1.0.0 release
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
// AUInputTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AUInput.Audio") struct AUInputAudioTests {
|
||||
|
||||
@Test func channelMustBeNonNegative() {
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
#expect(gen.channel == 0)
|
||||
}
|
||||
|
||||
@Test func computeReturnsSilenceWhenEngineHasNoInputs() throws {
|
||||
// Engine with zero input channels — AUInput.Audio should defensively
|
||||
// return zeros rather than read past the bus array.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = gen._computeSamples(graph: graph, count: 32)
|
||||
#expect(result.count == 1)
|
||||
#expect(result[0].prefix(32).allSatisfy { $0 == 0 })
|
||||
}
|
||||
|
||||
@Test func computeReadsFromHostInputBus() throws {
|
||||
// Engine with two input channels — engine.audioBuses[numOutputChannels
|
||||
// + ch] holds the staged host input. We seed those buses directly
|
||||
// and verify AUInput.Audio reads them.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let inputBusIdx: Int = engine.numOutputChannels
|
||||
for i: Int in 0..<32 {
|
||||
engine.audioBuses[inputBusIdx][i] = Float(i) * 0.1
|
||||
}
|
||||
for i: Int in 0..<32 {
|
||||
engine.audioBuses[inputBusIdx + 1][i] = -Float(i) * 0.1
|
||||
}
|
||||
|
||||
let leftIn: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let rightIn: AUInput.Audio = AUInput.Audio(channel: 1)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let leftResult: [[Double]] = leftIn._computeSamples(graph: graph, count: 32)
|
||||
let rightResult: [[Double]] = rightIn._computeSamples(graph: graph, count: 32)
|
||||
#expect(leftResult[0][10] == Double(Float(10) * 0.1))
|
||||
#expect(leftResult[0][31] == Double(Float(31) * 0.1))
|
||||
#expect(rightResult[0][10] == Double(-Float(10) * 0.1))
|
||||
#expect(rightResult[0][31] == Double(-Float(31) * 0.1))
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsAlwaysOne() {
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 5)
|
||||
#expect(gen.outputChannelCount == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// AUv3DriverTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test fixtures
|
||||
|
||||
/// Synth that writes a deterministic counter into each output channel: sample i
|
||||
/// of channel c receives the value `Double(sampleIndex + i + c * 10000)`. Lets
|
||||
/// tests verify the ring buffer preserves temporal + channel ordering.
|
||||
private final class CounterSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: CounterGen = CounterGen()
|
||||
output(bus: 0, source: gen[0])
|
||||
output(bus: 1, source: gen[1])
|
||||
}
|
||||
}
|
||||
|
||||
private final class CounterGen: GeneratorBase, AudioGenerator {
|
||||
private var _sampleIndex: Int = 0
|
||||
override init(channels: Int = 2) {
|
||||
super.init(channels: channels)
|
||||
}
|
||||
public override var outputChannelCount: Int { _result.count }
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = Double(_sampleIndex + i)
|
||||
_result[1][i] = Double(_sampleIndex + i + 10000)
|
||||
}
|
||||
_sampleIndex += count
|
||||
return _result
|
||||
}
|
||||
public func floatValue(graph: SynthGraph) -> Double {
|
||||
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Builds a heap-allocated AudioBufferList for `channels` mono Float channels,
|
||||
/// each `frames` long. Returns the buffer-list pointer + the per-channel storage
|
||||
/// arrays so the caller can inspect samples after `render`.
|
||||
private struct ABLFixture {
|
||||
let abl: UnsafeMutablePointer<AudioBufferList>
|
||||
let channelStorage: [UnsafeMutablePointer<Float>]
|
||||
let frames: Int
|
||||
let channels: Int
|
||||
|
||||
init(channels: Int, frames: Int) {
|
||||
self.channels = channels
|
||||
self.frames = frames
|
||||
let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels)
|
||||
let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout<AudioBufferList>.alignment)
|
||||
let abl: UnsafeMutablePointer<AudioBufferList> = raw.assumingMemoryBound(to: AudioBufferList.self)
|
||||
abl.pointee = AudioBufferList(mNumberBuffers: UInt32(channels),
|
||||
mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
|
||||
var storage: [UnsafeMutablePointer<Float>] = []
|
||||
let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl)
|
||||
for c: Int in 0..<channels {
|
||||
let ptr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: frames)
|
||||
for i: Int in 0..<frames { ptr[i] = 0 }
|
||||
storage.append(ptr)
|
||||
listPtr[c] = AudioBuffer(
|
||||
mNumberChannels: 1,
|
||||
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
|
||||
mData: UnsafeMutableRawPointer(ptr)
|
||||
)
|
||||
}
|
||||
self.abl = abl
|
||||
self.channelStorage = storage
|
||||
}
|
||||
|
||||
func channelSlice(_ c: Int) -> [Float] {
|
||||
let ptr: UnsafeMutablePointer<Float> = channelStorage[c]
|
||||
return Array(UnsafeBufferPointer(start: ptr, count: frames))
|
||||
}
|
||||
|
||||
func deallocate() {
|
||||
for p: UnsafeMutablePointer<Float> in channelStorage { p.deallocate() }
|
||||
UnsafeMutableRawPointer(abl).deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("AUv3Driver") struct AUv3DriverTests {
|
||||
|
||||
@Test func returnsUninitializedBeforeSetup() {
|
||||
let driver: AUv3Driver = AUv3Driver()
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 64)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == kAudioUnitErr_Uninitialized)
|
||||
}
|
||||
|
||||
@Test func rejectsFrameCountAboveMax() throws {
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 256)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
try engine.start()
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 512)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 512, outputData: fixture.abl)
|
||||
#expect(status == kAudioUnitErr_TooManyFramesToProcess)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func smallHostFrameCountDrivesMultipleEngineBlocks() throws {
|
||||
// Engine block 128; host requests 64 per call — two calls per engine block.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 64)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 64)
|
||||
defer { fixture.deallocate() }
|
||||
|
||||
// First render — engine produces one block (128 frames); ring delivers 64.
|
||||
var status: AUAudioUnitStatus = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let firstL: [Float] = fixture.channelSlice(0)
|
||||
let firstR: [Float] = fixture.channelSlice(1)
|
||||
#expect(firstL.first == 0)
|
||||
#expect(firstL.last == 63)
|
||||
#expect(firstR.first == 10000)
|
||||
#expect(firstR.last == 10063)
|
||||
|
||||
// Second render — pulls remaining 64 from the same engine block.
|
||||
status = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let secondL: [Float] = fixture.channelSlice(0)
|
||||
#expect(secondL.first == 64)
|
||||
#expect(secondL.last == 127)
|
||||
|
||||
// Third render — engine must advance another block.
|
||||
status = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let thirdL: [Float] = fixture.channelSlice(0)
|
||||
#expect(thirdL.first == 128)
|
||||
#expect(thirdL.last == 191)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func largeHostFrameCountPullsMultipleEngineBlocks() throws {
|
||||
// Host wants 1024 per call but engine block is 256 — 4 engine blocks per
|
||||
// render call.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 256, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 1024)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 1024, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let samples: [Float] = fixture.channelSlice(0)
|
||||
#expect(samples.first == 0)
|
||||
#expect(samples[256] == 256)
|
||||
#expect(samples[512] == 512)
|
||||
#expect(samples.last == 1023)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func alternatingFrameCountsPreserveContinuity() throws {
|
||||
// Hosts may switch frame counts mid-stream; the ring must keep sample
|
||||
// continuity intact.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let counts: [Int] = [1, 7, 64, 1, 200, 33, 511, 1]
|
||||
var nextExpected: Float = 0
|
||||
for count: Int in counts {
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: count)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: count, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let samples: [Float] = fixture.channelSlice(0)
|
||||
#expect(samples.first == nextExpected, "first mismatch at count=\(count)")
|
||||
#expect(samples.last == nextExpected + Float(count - 1), "last mismatch at count=\(count)")
|
||||
nextExpected += Float(count)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// AUv3RingBufferTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AUv3RingBuffer") struct AUv3RingBufferTests {
|
||||
|
||||
@Test func capacityRoundsUpToPowerOfTwo() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 1000)
|
||||
#expect(ring.capacity == 1024)
|
||||
}
|
||||
|
||||
@Test func capacityExactPowerOfTwoUnchanged() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 256)
|
||||
#expect(ring.capacity == 256)
|
||||
}
|
||||
|
||||
@Test func availableToReadStartsAtZero() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 128)
|
||||
#expect(ring.availableToRead == 0)
|
||||
#expect(ring.availableToWrite == 128)
|
||||
}
|
||||
|
||||
@Test func writeThenReadRoundTrip() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 128)
|
||||
let inL: [Float] = (0..<32).map { Float($0) }
|
||||
let inR: [Float] = (0..<32).map { Float(100 + $0) }
|
||||
ring.write(from: [inL, inR], count: 32)
|
||||
#expect(ring.availableToRead == 32)
|
||||
|
||||
var outL: [Float] = [Float](repeating: 0, count: 32)
|
||||
var outR: [Float] = [Float](repeating: 0, count: 32)
|
||||
outL.withUnsafeMutableBufferPointer { lBuf in
|
||||
outR.withUnsafeMutableBufferPointer { rBuf in
|
||||
guard let lBase: UnsafeMutablePointer<Float> = lBuf.baseAddress, let rBase: UnsafeMutablePointer<Float> = rBuf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 2)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = lBase
|
||||
ptrs[1] = rBase
|
||||
ring.read(into: ptrs, channelCount: 2, count: 32)
|
||||
}
|
||||
}
|
||||
#expect(outL == inL)
|
||||
#expect(outR == inR)
|
||||
#expect(ring.availableToRead == 0)
|
||||
}
|
||||
|
||||
@Test func writeAndReadWrapAround() {
|
||||
// capacity = 16; write 12, read 12 (advance indices), then write 12 (wraps).
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 16)
|
||||
let first: [Float] = (0..<12).map { Float($0) }
|
||||
ring.write(from: [first], count: 12)
|
||||
|
||||
var sink: [Float] = [Float](repeating: 0, count: 12)
|
||||
sink.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 12)
|
||||
}
|
||||
#expect(sink == first)
|
||||
|
||||
let second: [Float] = (100..<112).map { Float($0) }
|
||||
ring.write(from: [second], count: 12)
|
||||
var sink2: [Float] = [Float](repeating: 0, count: 12)
|
||||
sink2.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 12)
|
||||
}
|
||||
#expect(sink2 == second)
|
||||
}
|
||||
|
||||
@Test func resetClearsState() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 16)
|
||||
let data: [Float] = [1, 2, 3, 4]
|
||||
ring.write(from: [data], count: 4)
|
||||
#expect(ring.availableToRead == 4)
|
||||
ring.reset()
|
||||
#expect(ring.availableToRead == 0)
|
||||
#expect(ring.availableToWrite == 16)
|
||||
}
|
||||
|
||||
@Test func interleavedReadWritePreservesOrderingOverManyCycles() {
|
||||
// capacity = 32. Push N=7 samples then pull N=7, many times; values must
|
||||
// round-trip with stable ordering even though the indices wrap repeatedly.
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 32)
|
||||
var nextValue: Float = 0
|
||||
for cycle: Int in 0..<50 {
|
||||
let chunk: [Float] = (0..<7).map { _ in
|
||||
let v: Float = nextValue; nextValue += 1; return v
|
||||
}
|
||||
ring.write(from: [chunk], count: 7)
|
||||
var sink: [Float] = [Float](repeating: -1, count: 7)
|
||||
sink.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 7)
|
||||
}
|
||||
#expect(sink == chunk, "cycle \(cycle) mismatch: \(sink) vs \(chunk)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// LyrebirdAUParameterMappingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Fixtures
|
||||
|
||||
private class ParamSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.5
|
||||
@LiveParam var modIndex: Double = 1.25
|
||||
override func build() {
|
||||
output(bus: 0, source: 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
private final class EmptySynth: SynthesizerBase {
|
||||
override func build() {
|
||||
output(bus: 0, source: 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
private final class InheritedParamSynth: ParamSynth {
|
||||
@LiveParam var detune: Double = 0.0
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Suite("LyrebirdAUParameterMapping discovery") struct LyrebirdAUParameterDiscoveryTests {
|
||||
|
||||
@Test func discoversAllLiveParamsInDeclarationOrder() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries.count == 3)
|
||||
#expect(entries[0].name == "freq")
|
||||
#expect(entries[1].name == "amp")
|
||||
#expect(entries[2].name == "modIndex")
|
||||
#expect(entries[0].address == 0)
|
||||
#expect(entries[1].address == 1)
|
||||
#expect(entries[2].address == 2)
|
||||
}
|
||||
|
||||
@Test func discoversInitialValuesFromWrappers() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries[0].node.value == 440.0)
|
||||
#expect(entries[1].node.value == 0.5)
|
||||
#expect(entries[2].node.value == 1.25)
|
||||
}
|
||||
|
||||
@Test func emptySynthProducesEmptyEntries() {
|
||||
let synth: EmptySynth = EmptySynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func subclassParamsFollowBaseClassParams() {
|
||||
let synth: InheritedParamSynth = InheritedParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
// Mirror walks oldest-superclass first, so ParamSynth's three come before
|
||||
// the subclass's detune.
|
||||
let names: [String] = entries.map { $0.name }
|
||||
#expect(names == ["freq", "amp", "modIndex", "detune"])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUParameterMapping tree") struct LyrebirdAUParameterTreeTests {
|
||||
|
||||
@Test func buildsOneAUParameterPerSlot() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (tree, nodes) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let params: [AUParameter] = tree.allParameters
|
||||
#expect(params.count == 3)
|
||||
#expect(nodes.count == 3)
|
||||
let names: [String] = params.map { $0.identifier }
|
||||
#expect(names == ["freq", "amp", "modIndex"])
|
||||
}
|
||||
|
||||
@Test func paramValueSeededFromCurrentScalar() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
synth.freq = 1234.5 // overwrite default
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
#expect(freq?.value == AUValue(1234.5))
|
||||
}
|
||||
|
||||
@Test func metadataAppliesMinMaxUnitDisplayName() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let metadata: [String: LyrebirdAUParameterInfo] = [
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
|
||||
"amp": .init(min: 0, max: 1, unit: .linearGain),
|
||||
]
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(
|
||||
for: synth, metadata: metadata)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
let amp: AUParameter? = tree.parameter(withAddress: 1)
|
||||
#expect(freq?.minValue == 20)
|
||||
#expect(freq?.maxValue == 8000)
|
||||
#expect(freq?.unit == .hertz)
|
||||
#expect(freq?.displayName == "Frequency")
|
||||
#expect(amp?.minValue == 0)
|
||||
#expect(amp?.maxValue == 1)
|
||||
#expect(amp?.unit == .linearGain)
|
||||
}
|
||||
|
||||
@Test func defaultMetadataAppliesPermissiveBounds() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
#expect(freq?.minValue == AUValue(-lyrebirdAUParameterDefaultBound))
|
||||
#expect(freq?.maxValue == AUValue( lyrebirdAUParameterDefaultBound))
|
||||
#expect(freq?.unit == .generic)
|
||||
}
|
||||
|
||||
@Test func seededValueClampedToMetadataRange() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
synth.freq = 99_999.0 // way above max
|
||||
let metadata: [String: LyrebirdAUParameterInfo] = [
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz),
|
||||
]
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(
|
||||
for: synth, metadata: metadata)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
// AUParameter.value setter clamps writes, so the seeded value should be 8000.
|
||||
#expect(freq?.value == 8000)
|
||||
}
|
||||
|
||||
@Test func nodesDictionaryPointsToOriginalParameterNode() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (_, nodes) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
// Write through the node — synth.freq should update atomically.
|
||||
nodes[0]?._writeAtomicValue(2000.0)
|
||||
#expect(synth.freq == 2000.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// LyrebirdAUPresetRegistryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Fixture preset-codable generator
|
||||
|
||||
private final class FixturePresetGen: GeneratorBase, AudioGenerator, LyrebirdAUPresetCodable {
|
||||
|
||||
static let presetTypeID: String = "test.fixturePresetGen"
|
||||
|
||||
private let _amp: Double
|
||||
private let _freq: Double
|
||||
|
||||
init(amp: Double, freq: Double) {
|
||||
self._amp = amp
|
||||
self._freq = freq
|
||||
super.init()
|
||||
}
|
||||
|
||||
var presetEncodedParameters: [String: AUValue] {
|
||||
["amp": AUValue(_amp), "freq": AUValue(_freq)]
|
||||
}
|
||||
|
||||
static func presetMake(from parameters: [String: AUValue]) -> any Generator {
|
||||
FixturePresetGen(
|
||||
amp: Double(parameters["amp"] ?? 0),
|
||||
freq: Double(parameters["freq"] ?? 0)
|
||||
)
|
||||
}
|
||||
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count)
|
||||
for i: Int in 0..<count { _result[0][i] = _amp }
|
||||
return _result
|
||||
}
|
||||
|
||||
func floatValue(graph: SynthGraph) -> Double { _amp }
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUPresetSourceRegistry") struct LyrebirdAUPresetRegistryTests {
|
||||
|
||||
@Test func registerAndMakeRoundTrip() {
|
||||
defer { LyrebirdAUPresetSourceRegistry.unregister(typeID: FixturePresetGen.presetTypeID) }
|
||||
LyrebirdAUPresetSourceRegistry.register(FixturePresetGen.self)
|
||||
let descriptor: LyrebirdAUPresetSourceDescriptor = LyrebirdAUPresetSourceDescriptor(
|
||||
typeID: FixturePresetGen.presetTypeID,
|
||||
parameters: ["amp": 0.5, "freq": 440]
|
||||
)
|
||||
let made: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor)
|
||||
guard let typed: FixturePresetGen = made as? FixturePresetGen else {
|
||||
Issue.record("made-generator is not FixturePresetGen — got \(type(of: made))")
|
||||
return
|
||||
}
|
||||
#expect(typed.presetEncodedParameters["amp"] == AUValue(0.5))
|
||||
#expect(typed.presetEncodedParameters["freq"] == AUValue(440))
|
||||
}
|
||||
|
||||
@Test func unknownTypeIDReturnsNil() {
|
||||
let descriptor: LyrebirdAUPresetSourceDescriptor = LyrebirdAUPresetSourceDescriptor(typeID: "test.unknown")
|
||||
let made: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor)
|
||||
#expect(made == nil)
|
||||
}
|
||||
|
||||
@Test func unregisterRemovesType() {
|
||||
LyrebirdAUPresetSourceRegistry.register(FixturePresetGen.self)
|
||||
#expect(LyrebirdAUPresetSourceRegistry.registeredTypeIDs.contains(FixturePresetGen.presetTypeID))
|
||||
LyrebirdAUPresetSourceRegistry.unregister(typeID: FixturePresetGen.presetTypeID)
|
||||
#expect(!LyrebirdAUPresetSourceRegistry.registeredTypeIDs.contains(FixturePresetGen.presetTypeID))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// LyrebirdAUVoicePoolBindingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
private final class TestVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0
|
||||
@LiveParam var amp: Double = 0
|
||||
@LiveParam var gate: Double = 0
|
||||
override func build() { output(bus: 0, source: $freq * $amp * $gate) }
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUVoicePoolBinding") struct LyrebirdAUVoicePoolBindingTests {
|
||||
|
||||
@Test func noteOnAllocatesVoiceAndConfigures() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let pool: VoicePool<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 4,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = LyrebirdAUVoicePoolBinding(pool: pool) { voice, note, velocity in
|
||||
voice.freq = Double(note)
|
||||
voice.amp = velocity
|
||||
voice.gate = 1
|
||||
}
|
||||
binding.handle(message: .noteOn(channel: 0, note: 60, velocity: 100),
|
||||
sampleTime: 0)
|
||||
// Walk the voices array — exactly one voice should have freq == 60.
|
||||
let activeCount: Int = pool.voices.filter { $0.gate == 1 && $0.freq == 60 }.count
|
||||
#expect(activeCount == 1)
|
||||
let voice: TestVoice = try #require(pool.voices.first(where: { $0.freq == 60 }))
|
||||
#expect(abs(voice.amp - Double(100) / Double(midiVelocityMax)) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func noteOffRunsConfigureForAllVoices() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let pool: VoicePool<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 2,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
var noteOffCount: Int = 0
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = LyrebirdAUVoicePoolBinding(pool: pool) { voice, _, _ in
|
||||
voice.gate = 1
|
||||
} noteOff: { voice, _ in
|
||||
voice.gate = 0
|
||||
noteOffCount += 1
|
||||
}
|
||||
binding.handle(message: .noteOn(channel: 0, note: 60, velocity: 90), sampleTime: 0)
|
||||
binding.handle(message: .noteOff(channel: 0, note: 60, velocity: 0), sampleTime: 0)
|
||||
// Note-off configure fires once per voice (104c documented behaviour).
|
||||
#expect(noteOffCount == 2)
|
||||
#expect(pool.voices.allSatisfy { $0.gate == 0 })
|
||||
}
|
||||
|
||||
@Test func channelFilterRespectsValue() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let pool: VoicePool<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 2,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = LyrebirdAUVoicePoolBinding(
|
||||
pool: pool,
|
||||
channelFilter: 0,
|
||||
noteOn: { voice, note, _ in voice.freq = Double(note) }
|
||||
)
|
||||
binding.handle(message: .noteOn(channel: 1, note: 60, velocity: 100),
|
||||
sampleTime: 0)
|
||||
// Filtered out — no voice should have been touched.
|
||||
#expect(pool.voices.allSatisfy { $0.freq == 0 })
|
||||
binding.handle(message: .noteOn(channel: 0, note: 72, velocity: 100),
|
||||
sampleTime: 0)
|
||||
#expect(pool.voices.contains(where: { $0.freq == 72 }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// LyrebirdAudioUnitEffectTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
private final class PassthroughSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let left: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let right: AUInput.Audio = AUInput.Audio(channel: 1)
|
||||
output(bus: 0, source: left)
|
||||
output(bus: 1, source: right)
|
||||
}
|
||||
}
|
||||
|
||||
private final class PassthroughEffectAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase {
|
||||
PassthroughSynth()
|
||||
}
|
||||
public override class var lyrebirdInputChannels: Int { 2 }
|
||||
public override class var lyrebirdOutputChannels: Int { 2 }
|
||||
}
|
||||
|
||||
private func makeEffectDescription() -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_Effect,
|
||||
componentSubType: 0x4C425046, // 'LBPF'
|
||||
componentManufacturer: 0x524C5A53, // 'RLZS'
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit effect") struct LyrebirdAudioUnitEffectTests {
|
||||
|
||||
@Test func effectAUDeclaresInputAndOutputBuses() throws {
|
||||
let au: PassthroughEffectAU = try PassthroughEffectAU(componentDescription: makeEffectDescription())
|
||||
#expect(au.outputBusses.count == 1)
|
||||
#expect(au.inputBusses.count == 1)
|
||||
let inFormat: AVAudioFormat = au.inputBusses[0].format
|
||||
#expect(inFormat.channelCount == 2)
|
||||
}
|
||||
|
||||
@Test func effectAUEngineHasInputChannels() throws {
|
||||
let au: PassthroughEffectAU = try PassthroughEffectAU(componentDescription: makeEffectDescription())
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numInputChannels == 2)
|
||||
#expect(engine.numOutputChannels == 2)
|
||||
}
|
||||
|
||||
@Test func instrumentAUEngineHasNoInputChannels() throws {
|
||||
// Sanity check the default — instrument AUs must not allocate input buses.
|
||||
final class StubSynth: SynthesizerBase {
|
||||
override func build() { output(bus: 0, source: 0.0) }
|
||||
}
|
||||
final class StubInstrumentAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { StubSynth() }
|
||||
}
|
||||
let desc: AudioComponentDescription = AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: 0x53545542,
|
||||
componentManufacturer: 0x524C5A53,
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
let au: StubInstrumentAU = try StubInstrumentAU(componentDescription: desc)
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numInputChannels == 0)
|
||||
#expect(au.inputBusses.count == 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// LyrebirdAudioUnitMIDITests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("LyrebirdAudioUnit MIDI dispatch") struct LyrebirdAudioUnitMIDITests {
|
||||
|
||||
@Test func dispatchHandlesNilHeadGracefully() {
|
||||
var received: [MIDIMessage] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: nil) { msg, _ in
|
||||
received.append(msg)
|
||||
}
|
||||
#expect(received.isEmpty)
|
||||
}
|
||||
|
||||
@Test func dispatchSkipsCallWhenHandlerNil() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x90, data1: 60, data2: 100)
|
||||
defer { event.deallocate() }
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event, handler: nil)
|
||||
// No assertion needed — just verifies no crash.
|
||||
}
|
||||
|
||||
@Test func dispatchParsesNoteOnEvent() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x91, data1: 60, data2: 100)
|
||||
defer { event.deallocate() }
|
||||
var received: [MIDIMessage] = []
|
||||
var sampleTimes: [AUEventSampleTime] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event) { msg, time in
|
||||
received.append(msg)
|
||||
sampleTimes.append(time)
|
||||
}
|
||||
#expect(received.count == 1)
|
||||
if case .noteOn(let channel, let note, let velocity) = received[0] {
|
||||
#expect(channel == 1)
|
||||
#expect(note == 60)
|
||||
#expect(velocity == 100)
|
||||
} else {
|
||||
Issue.record("Expected .noteOn, got \(received[0])")
|
||||
}
|
||||
#expect(sampleTimes == [0])
|
||||
}
|
||||
|
||||
@Test func dispatchParsesNoteOffEvent() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x80, data1: 64, data2: 0)
|
||||
defer { event.deallocate() }
|
||||
var received: [MIDIMessage] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event) { msg, _ in
|
||||
received.append(msg)
|
||||
}
|
||||
#expect(received.count == 1)
|
||||
if case .noteOff(_, let note, _) = received[0] {
|
||||
#expect(note == 64)
|
||||
} else {
|
||||
Issue.record("Expected .noteOff, got \(received[0])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func dispatchWalksChainOfEvents() {
|
||||
// Chain: noteOn → noteOff. Link via head.next pointer.
|
||||
let e1: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x90, data1: 60, data2: 80, sampleTime: 0)
|
||||
let e2: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x80, data1: 60, data2: 0, sampleTime: 128)
|
||||
defer { e1.deallocate(); e2.deallocate() }
|
||||
// Patch e1.head.next to point at e2.
|
||||
let mutablePtr: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>(mutating: e1)
|
||||
mutablePtr.pointee.head.next = UnsafeMutablePointer<AURenderEvent>(mutating: e2)
|
||||
|
||||
var received: [MIDIMessage] = []
|
||||
var sampleTimes: [AUEventSampleTime] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: e1) { msg, time in
|
||||
received.append(msg)
|
||||
sampleTimes.append(time)
|
||||
}
|
||||
#expect(received.count == 2)
|
||||
#expect(sampleTimes == [0, 128])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Builds a single AURenderEvent on the heap with a MIDI payload. Caller owns
|
||||
/// the returned pointer and must `deallocate()` it when done.
|
||||
private func makeMIDIRenderEvent(
|
||||
status: UInt8,
|
||||
data1: UInt8,
|
||||
data2: UInt8,
|
||||
sampleTime: AUEventSampleTime = 0
|
||||
) -> UnsafePointer<AURenderEvent> {
|
||||
let ptr: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>.allocate(capacity: 1)
|
||||
var event: AURenderEvent = AURenderEvent()
|
||||
event.head.next = nil
|
||||
event.head.eventSampleTime = sampleTime
|
||||
event.head.eventType = .MIDI
|
||||
event.head.reserved = 0
|
||||
event.MIDI.eventType = .MIDI
|
||||
event.MIDI.reserved = 0
|
||||
event.MIDI.length = 3
|
||||
event.MIDI.cable = 0
|
||||
event.MIDI.data = (status, data1, data2)
|
||||
ptr.initialize(to: event)
|
||||
return UnsafePointer(ptr)
|
||||
}
|
||||
|
||||
private extension UnsafePointer where Pointee == AURenderEvent {
|
||||
func deallocate() {
|
||||
let mut: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>(mutating: self)
|
||||
mut.deinitialize(count: 1)
|
||||
mut.deallocate()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
// LyrebirdAudioUnitMultiBusTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Multi-output-bus fixture
|
||||
|
||||
private final class StemRenderSynth: SynthesizerBase {
|
||||
@LiveParam var gainA: Double = 0.5
|
||||
@LiveParam var gainB: Double = 0.5
|
||||
override func build() {
|
||||
// Bus 0 (main, 2ch): channels 0+1
|
||||
output(bus: 0, source: $gainA)
|
||||
output(bus: 1, source: $gainA)
|
||||
// Bus 1 (aux, 2ch): channels 2+3
|
||||
output(bus: 2, source: $gainB)
|
||||
output(bus: 3, source: $gainB)
|
||||
}
|
||||
}
|
||||
|
||||
private final class StemRenderAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { StemRenderSynth() }
|
||||
public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] {
|
||||
[
|
||||
.init(name: "Main", channelCount: 2),
|
||||
.init(name: "FX Send", channelCount: 2),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-input-bus (main + sidechain) fixture
|
||||
|
||||
private final class SidechainPassthrough: SynthesizerBase {
|
||||
override func build() {
|
||||
// Main input bus 0 → output bus 0 (passthrough)
|
||||
let mainL: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 0)
|
||||
let mainR: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 1)
|
||||
output(bus: 0, source: mainL)
|
||||
output(bus: 1, source: mainR)
|
||||
}
|
||||
}
|
||||
|
||||
private final class SidechainAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { SidechainPassthrough() }
|
||||
public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] {
|
||||
[.init(name: "Output", channelCount: 2)]
|
||||
}
|
||||
public override class var lyrebirdInputBusses: [LyrebirdAUBusSpec] {
|
||||
[
|
||||
.init(name: "Main In", channelCount: 2),
|
||||
.init(name: "Sidechain", channelCount: 2),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Single-bus back-compat fixture
|
||||
|
||||
private final class SingleBusSynth: SynthesizerBase {
|
||||
override func build() { output(bus: 0, source: 0.0) }
|
||||
}
|
||||
|
||||
private final class SingleBusAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { SingleBusSynth() }
|
||||
// No bus-spec overrides — must keep the default single-bus behaviour.
|
||||
}
|
||||
|
||||
private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: subtype,
|
||||
componentManufacturer: 0x524C5A53,
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit multi-bus — defaults") struct LyrebirdAudioUnitMultiBusDefaultTests {
|
||||
|
||||
@Test func singleBusAUKeeps104aShape() throws {
|
||||
let au: SingleBusAU = try SingleBusAU(componentDescription: makeAUDesc(subtype: 0x53424102))
|
||||
#expect(au.outputBusses.count == 1)
|
||||
#expect(au.inputBusses.count == 0)
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numOutputChannels == 2)
|
||||
#expect(engine.numInputChannels == 0)
|
||||
#expect(engine.auOutputBusOffsets == [0])
|
||||
#expect(engine.auInputBusOffsets == [])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit multi-bus — multi-output") struct LyrebirdAudioUnitMultiOutputBusTests {
|
||||
|
||||
@Test func twoOutputBussesAreExposed() throws {
|
||||
let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F42))
|
||||
#expect(au.outputBusses.count == 2)
|
||||
#expect(au.outputBusses[0].format.channelCount == 2)
|
||||
#expect(au.outputBusses[1].format.channelCount == 2)
|
||||
// Bus names are reflected via the format's channel layout name —
|
||||
// the spec name itself is internal, so just confirm bus instances exist.
|
||||
}
|
||||
|
||||
@Test func twoOutputBussesEngineLayout() throws {
|
||||
let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F43))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
// 2 + 2 channels across two output busses.
|
||||
#expect(engine.numOutputChannels == 4)
|
||||
// Bus 0 starts at engine channel 0; bus 1 at engine channel 2.
|
||||
#expect(engine.auOutputBusOffsets == [0, 2])
|
||||
}
|
||||
|
||||
@Test func asymmetricBusPullsDoNotCrash() throws {
|
||||
// AU spec lets a host pull bus 0 repeatedly without pulling bus 1.
|
||||
// Without the driver's saturation guard this would overflow bus 1's
|
||||
// ring buffer after `capacity / blockSize` engine advances.
|
||||
// Verify many pulls of bus 0 with zero pulls of bus 1 stay safe.
|
||||
let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x53415359))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
|
||||
let frames: Int = 64
|
||||
let fixture: ABLFixture = makeABL(channels: 2, frames: frames)
|
||||
defer { deallocateABL(fixture) }
|
||||
|
||||
var flags: AudioUnitRenderActionFlags = []
|
||||
var ts: AudioTimeStamp = AudioTimeStamp()
|
||||
ts.mFlags = .sampleTimeValid
|
||||
ts.mSampleTime = 0
|
||||
let block: AUInternalRenderBlock = au.internalRenderBlock
|
||||
|
||||
// 64 pulls of bus 0 — more than the ring capacity / blockSize. With
|
||||
// the saturation guard in place, the driver resets bus 1's ring
|
||||
// when it would overflow rather than tripping a precondition.
|
||||
for _ in 0..<64 {
|
||||
let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0,
|
||||
fixture.abl, nil, nil)
|
||||
#expect(status == noErr)
|
||||
ts.mSampleTime += Float64(frames)
|
||||
}
|
||||
// Now pull bus 1 once — should succeed (returns the freshest block,
|
||||
// not the long-stale data dropped by saturation).
|
||||
let fixtureB: ABLFixture = makeABL(channels: 2, frames: frames)
|
||||
defer { deallocateABL(fixtureB) }
|
||||
let statusB: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 1,
|
||||
fixtureB.abl, nil, nil)
|
||||
#expect(statusB == noErr)
|
||||
}
|
||||
|
||||
@Test func renderingRoutesEachBusIndependently() throws {
|
||||
let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F44))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let synth: StemRenderSynth = try #require(au.synthesizer as? StemRenderSynth)
|
||||
synth.gainA = 0.25
|
||||
synth.gainB = 0.75
|
||||
|
||||
let frames: Int = 64
|
||||
let fixtureA: ABLFixture = makeABL(channels: 2, frames: frames)
|
||||
let fixtureB: ABLFixture = makeABL(channels: 2, frames: frames)
|
||||
defer { deallocateABL(fixtureA); deallocateABL(fixtureB) }
|
||||
|
||||
var flags: AudioUnitRenderActionFlags = []
|
||||
var ts: AudioTimeStamp = AudioTimeStamp()
|
||||
ts.mFlags = .sampleTimeValid
|
||||
ts.mSampleTime = 0
|
||||
let block: AUInternalRenderBlock = au.internalRenderBlock
|
||||
|
||||
// Render multiple cycles so the @LiveParam ramp completes (default
|
||||
// engine blockSize 256, so ≥ 4 × 64-frame renders reach the
|
||||
// steady-state gain). Check the LAST sample of each bus's ABL on
|
||||
// the final cycle.
|
||||
let cycles: Int = 8
|
||||
for _ in 0..<cycles {
|
||||
let statusA: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0,
|
||||
fixtureA.abl, nil, nil)
|
||||
let statusB: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 1,
|
||||
fixtureB.abl, nil, nil)
|
||||
#expect(statusA == noErr)
|
||||
#expect(statusB == noErr)
|
||||
ts.mSampleTime += Float64(frames)
|
||||
}
|
||||
let lastA: Float = fixtureA.channelStorage[0][frames - 1]
|
||||
let lastB: Float = fixtureB.channelStorage[0][frames - 1]
|
||||
// Allow some tolerance for the ramp tail.
|
||||
#expect(abs(Double(lastA) - 0.25) < 0.05,
|
||||
"bus 0 final sample should be near 0.25, got \(lastA)")
|
||||
#expect(abs(Double(lastB) - 0.75) < 0.05,
|
||||
"bus 1 final sample should be near 0.75, got \(lastB)")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit multi-bus — sidechain input") struct LyrebirdAudioUnitSidechainTests {
|
||||
|
||||
@Test func twoInputBussesAreExposed() throws {
|
||||
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E32))
|
||||
#expect(au.inputBusses.count == 2)
|
||||
#expect(au.inputBusses[0].format.channelCount == 2)
|
||||
#expect(au.inputBusses[1].format.channelCount == 2)
|
||||
}
|
||||
|
||||
@Test func sidechainEngineOffsetMapPopulated() throws {
|
||||
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E33))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numInputChannels == 4)
|
||||
// Main In at engine bus 2, Sidechain at engine bus 4.
|
||||
#expect(engine.auInputBusOffsets == [2, 4])
|
||||
}
|
||||
|
||||
@Test func renderLoopDispatchesPerInputBusPullBlock() throws {
|
||||
// Drive the full internalRenderBlock → driver → _fillInputStagingFromHost
|
||||
// path with a synthetic pullInputBlock that fills bus 0 ABL with +1.0
|
||||
// and bus 1 ABL with -1.0. Verify the AU passes bus 0 samples through
|
||||
// to its output (SidechainPassthrough's build wires bus 0 → output).
|
||||
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E50))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
|
||||
let frames: Int = 64
|
||||
let fixture: ABLFixture = makeABL(channels: 2, frames: frames)
|
||||
defer { deallocateABL(fixture) }
|
||||
|
||||
// Synthetic pullInputBlock fills bus N's ABL based on the bus number.
|
||||
// Heap-allocated Int counters captured by raw pointer so the
|
||||
// @convention(block) closure can mutate them.
|
||||
let countMain: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.allocate(capacity: 1)
|
||||
let countSC: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.allocate(capacity: 1)
|
||||
countMain.initialize(to: 0)
|
||||
countSC.initialize(to: 0)
|
||||
defer {
|
||||
countMain.deinitialize(count: 1); countMain.deallocate()
|
||||
countSC.deinitialize(count: 1); countSC.deallocate()
|
||||
}
|
||||
let pull: AURenderPullInputBlock = { _, _, inFrames, inputBusNumber, inputData in
|
||||
switch inputBusNumber {
|
||||
case 0: countMain.pointee += 1
|
||||
case 1: countSC.pointee += 1
|
||||
default: break
|
||||
}
|
||||
let abl: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(inputData)
|
||||
let fillValue: Float = inputBusNumber == 0 ? 1.0 : -1.0
|
||||
for c: Int in 0..<abl.count {
|
||||
guard let raw: UnsafeMutableRawPointer = abl[c].mData else { continue }
|
||||
let dst: UnsafeMutablePointer<Float> = raw.assumingMemoryBound(to: Float.self)
|
||||
for i: Int in 0..<Int(inFrames) { dst[i] = fillValue }
|
||||
}
|
||||
return noErr
|
||||
}
|
||||
|
||||
var flags: AudioUnitRenderActionFlags = []
|
||||
var ts: AudioTimeStamp = AudioTimeStamp()
|
||||
ts.mFlags = .sampleTimeValid
|
||||
ts.mSampleTime = 0
|
||||
let block: AUInternalRenderBlock = au.internalRenderBlock
|
||||
|
||||
// 8 render cycles so the @LiveParam ramps complete and the
|
||||
// passthrough output converges on the input value.
|
||||
for _ in 0..<8 {
|
||||
let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0,
|
||||
fixture.abl, nil, pull)
|
||||
#expect(status == noErr)
|
||||
ts.mSampleTime += Float64(frames)
|
||||
}
|
||||
|
||||
// Output should track bus 0's +1.0 (main input passthrough), not
|
||||
// bus 1's -1.0 (sidechain).
|
||||
let lastSample: Float = fixture.channelStorage[0][frames - 1]
|
||||
#expect(abs(Double(lastSample) - 1.0) < 0.05,
|
||||
"main-input passthrough should converge on 1.0, got \(lastSample)")
|
||||
// Both input busses must be pulled at least once.
|
||||
#expect(countMain.pointee > 0,
|
||||
"main input bus pullInputBlock should be called")
|
||||
#expect(countSC.pointee > 0,
|
||||
"sidechain input bus pullInputBlock should be called")
|
||||
}
|
||||
|
||||
@Test func auInputBusIndexResolves() throws {
|
||||
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E34))
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
|
||||
// Seed engine input buses directly: main = +1 ramp; sidechain = -1 ramp.
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
engine.audioBuses[2][i] = Float(i)
|
||||
engine.audioBuses[3][i] = Float(i)
|
||||
engine.audioBuses[4][i] = -Float(i)
|
||||
engine.audioBuses[5][i] = -Float(i)
|
||||
}
|
||||
|
||||
let mainGen: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 0)
|
||||
let scGen: AUInput.Audio = AUInput.Audio(busIndex: 1, channel: 0)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let mainOut: [[Double]] = mainGen._computeSamples(graph: graph, count: 32)
|
||||
let scOut: [[Double]] = scGen._computeSamples(graph: graph, count: 32)
|
||||
#expect(mainOut[0][10] == Double(10))
|
||||
#expect(scOut[0][10] == Double(-10))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ABL helpers (mirrors AUv3DriverTests fixture)
|
||||
|
||||
private struct ABLFixture {
|
||||
let abl: UnsafeMutablePointer<AudioBufferList>
|
||||
let channelStorage: [UnsafeMutablePointer<Float>]
|
||||
}
|
||||
|
||||
private func makeABL(channels: Int, frames: Int) -> ABLFixture {
|
||||
let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels)
|
||||
let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: size,
|
||||
alignment: MemoryLayout<AudioBufferList>.alignment
|
||||
)
|
||||
let abl: UnsafeMutablePointer<AudioBufferList> = raw.assumingMemoryBound(to: AudioBufferList.self)
|
||||
let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl)
|
||||
listPtr.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(channels)
|
||||
var storage: [UnsafeMutablePointer<Float>] = []
|
||||
for c: Int in 0..<channels {
|
||||
let p: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: frames)
|
||||
for i: Int in 0..<frames { p[i] = 0 }
|
||||
storage.append(p)
|
||||
listPtr[c] = AudioBuffer(
|
||||
mNumberChannels: 1,
|
||||
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
|
||||
mData: UnsafeMutableRawPointer(p)
|
||||
)
|
||||
}
|
||||
return ABLFixture(abl: abl, channelStorage: storage)
|
||||
}
|
||||
|
||||
private func deallocateABL(_ fixture: ABLFixture) {
|
||||
for p: UnsafeMutablePointer<Float> in fixture.channelStorage { p.deallocate() }
|
||||
UnsafeMutableRawPointer(fixture.abl).deallocate()
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// LyrebirdAudioUnitPresetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
private final class PresetSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440
|
||||
@LiveParam var amp: Double = 0.5
|
||||
override func build() { output(bus: 0, source: $freq * $amp) }
|
||||
}
|
||||
|
||||
private final class PresetAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { PresetSynth() }
|
||||
public override class func factoryPresetsForLyrebird() -> [LyrebirdAUFactoryPreset] {
|
||||
[
|
||||
.init(name: "Bright", scalarValues: ["freq": 880, "amp": 0.8]),
|
||||
.init(name: "Quiet", scalarValues: ["freq": 220, "amp": 0.1]),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private func makeDesc() -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: 0x50525345,
|
||||
componentManufacturer: 0x524C5A53,
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit factory presets") struct LyrebirdAudioUnitFactoryPresetsTests {
|
||||
|
||||
@Test func factoryPresetsExposeAllNames() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let presets: [AUAudioUnitPreset] = try #require(au.factoryPresets)
|
||||
#expect(presets.map(\.name) == ["Bright", "Quiet"])
|
||||
#expect(presets.map(\.number) == [0, 1])
|
||||
}
|
||||
|
||||
@Test func selectingCurrentPresetAppliesScalars() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
let p0: AUAudioUnitPreset? = au.factoryPresets?.first
|
||||
au.currentPreset = p0
|
||||
// Preset scalars are AUValue (Float) — round-trip through Double will
|
||||
// pick up a small precision delta, so tolerance is applied.
|
||||
#expect(synth.freq == 880)
|
||||
#expect(abs(synth.amp - 0.8) < 1e-6)
|
||||
|
||||
let p1: AUAudioUnitPreset? = au.factoryPresets?.last
|
||||
au.currentPreset = p1
|
||||
#expect(synth.freq == 220)
|
||||
#expect(abs(synth.amp - 0.1) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func currentPresetSetterIsIdempotent() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let p0: AUAudioUnitPreset? = au.factoryPresets?.first
|
||||
au.currentPreset = p0
|
||||
au.currentPreset = p0
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
#expect(synth.freq == 880)
|
||||
}
|
||||
|
||||
@Test func nilCurrentPresetIsNoop() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
synth.freq = 1234
|
||||
au.currentPreset = nil
|
||||
// Nil should not overwrite the user-set scalar.
|
||||
#expect(synth.freq == 1234)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// LyrebirdAudioUnitTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test fixtures
|
||||
|
||||
private final class TestFMSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.5
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq * $amp)
|
||||
}
|
||||
}
|
||||
|
||||
private final class TestFMSynthAudioUnit: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase {
|
||||
TestFMSynth()
|
||||
}
|
||||
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
|
||||
[
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
|
||||
"amp": .init(min: 0, max: 1, unit: .linearGain),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private func makeDescription() -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: 0x4C425454, // 'LBTT'
|
||||
componentManufacturer: 0x524C5A53, // 'RLZS'
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Init / parameter tree
|
||||
|
||||
@Suite("LyrebirdAudioUnit init") struct LyrebirdAudioUnitInitTests {
|
||||
|
||||
@Test func initSucceedsAndPopulatesParameterTree() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let tree: AUParameterTree = try #require(au.parameterTree)
|
||||
let params: [AUParameter] = tree.allParameters
|
||||
#expect(params.count == 2)
|
||||
#expect(params.map(\.identifier) == ["freq", "amp"])
|
||||
#expect(params.first?.value == 440)
|
||||
}
|
||||
|
||||
@Test func parameterMetadataAppliesToTree() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let tree: AUParameterTree = try #require(au.parameterTree)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
#expect(freq?.minValue == 20)
|
||||
#expect(freq?.maxValue == 8000)
|
||||
#expect(freq?.unit == .hertz)
|
||||
}
|
||||
|
||||
@Test func writingAUParameterUpdatesSynthAtomic() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let tree: AUParameterTree = try #require(au.parameterTree)
|
||||
let freq: AUParameter = try #require(tree.parameter(withAddress: 0))
|
||||
freq.value = 1000
|
||||
let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth)
|
||||
#expect(synth.freq == 1000.0)
|
||||
}
|
||||
|
||||
@Test func readingAUParameterValueProviderReflectsSynth() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth)
|
||||
synth.freq = 2000.0
|
||||
let tree: AUParameterTree = try #require(au.parameterTree)
|
||||
let freq: AUParameter = try #require(tree.parameter(withAddress: 0))
|
||||
// The valueProvider is consulted on read after a non-tree write — refresh
|
||||
// via .value getter (AUParameter caches the last write but the provider
|
||||
// closure executes when the value is fetched via the implementor path).
|
||||
let resolved: AUValue? = freq.value(forKeyPath: "value") as? AUValue
|
||||
// The AU spec doesn't expose the provider directly; the more reliable
|
||||
// black-box assertion is that the tree-side write path is bidirectional
|
||||
// (see writingAUParameterUpdatesSynthAtomic). This test just sanity-checks
|
||||
// that .value remains in range after a backdoor write.
|
||||
_ = resolved
|
||||
#expect(freq.value >= 20 && freq.value <= 8000)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Resource lifecycle
|
||||
|
||||
@Suite("LyrebirdAudioUnit render resources") struct LyrebirdAudioUnitRenderResourceTests {
|
||||
|
||||
@Test func allocateAndDeallocateLifecycle() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
#expect(au.engine == nil)
|
||||
try au.allocateRenderResources()
|
||||
#expect(au.engine != nil)
|
||||
let firstEngine: SynthesisEngine? = au.engine
|
||||
#expect(firstEngine?.isRunning == true)
|
||||
au.deallocateRenderResources()
|
||||
#expect(au.engine == nil)
|
||||
}
|
||||
|
||||
@Test func reallocateRebuildsEngineAtNewSampleRate() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
// First allocate at default 44100.
|
||||
try au.allocateRenderResources()
|
||||
#expect(au.engine?.sampleRate == 44100)
|
||||
au.deallocateRenderResources()
|
||||
|
||||
// Set output bus to 48000.
|
||||
let bus: AUAudioUnitBus = au.outputBusses[0]
|
||||
let newFormat: AVAudioFormat = try #require(AVAudioFormat(
|
||||
standardFormatWithSampleRate: 48000,
|
||||
channels: bus.format.channelCount
|
||||
))
|
||||
try bus.setFormat(newFormat)
|
||||
try au.allocateRenderResources()
|
||||
#expect(au.engine?.sampleRate == 48000)
|
||||
au.deallocateRenderResources()
|
||||
}
|
||||
|
||||
@Test func renderProducesNonzeroOutputAfterAllocate() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
|
||||
// synth.freq * synth.amp = 440 * 0.5 = 220 — every output sample should be 220.
|
||||
let frames: Int = 64
|
||||
let channels: Int = 2
|
||||
let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels)
|
||||
let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: size,
|
||||
alignment: MemoryLayout<AudioBufferList>.alignment
|
||||
)
|
||||
defer { raw.deallocate() }
|
||||
let abl: UnsafeMutablePointer<AudioBufferList> = raw.assumingMemoryBound(to: AudioBufferList.self)
|
||||
let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl)
|
||||
listPtr.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(channels)
|
||||
var storage: [UnsafeMutablePointer<Float>] = []
|
||||
for c: Int in 0..<channels {
|
||||
let p: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: frames)
|
||||
for i: Int in 0..<frames { p[i] = -999 }
|
||||
storage.append(p)
|
||||
listPtr[c] = AudioBuffer(
|
||||
mNumberChannels: 1,
|
||||
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
|
||||
mData: UnsafeMutableRawPointer(p)
|
||||
)
|
||||
}
|
||||
defer { for p: UnsafeMutablePointer<Float> in storage { p.deallocate() } }
|
||||
|
||||
// Invoke the AU's render block directly (NRT-style — no host needed).
|
||||
let block: AUInternalRenderBlock = au.internalRenderBlock
|
||||
var flags: AudioUnitRenderActionFlags = []
|
||||
var ts: AudioTimeStamp = AudioTimeStamp()
|
||||
ts.mFlags = .sampleTimeValid
|
||||
ts.mSampleTime = 0
|
||||
let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0, abl, nil, nil)
|
||||
#expect(status == noErr)
|
||||
let samples: [Float] = Array(UnsafeBufferPointer(start: storage[0], count: frames))
|
||||
// Output is 220 on every sample once the synth has been added — the first
|
||||
// engine block applies the add event and runs the generator.
|
||||
let nonZero: Bool = samples.contains { $0 != 0 && $0 != -999 }
|
||||
#expect(nonZero, "render produced silence; samples: \(samples.prefix(8))")
|
||||
#expect(samples.last == 220, "expected 220 on last sample, got \(samples.last ?? .nan)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - fullState save / restore
|
||||
|
||||
@Suite("LyrebirdAudioUnit fullState") struct LyrebirdAudioUnitFullStateTests {
|
||||
|
||||
@Test func fullStateRoundTripPreservesScalarLiveParams() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth)
|
||||
synth.freq = 1234.5
|
||||
synth.amp = 0.75
|
||||
let state: [String : Any]? = au.fullState
|
||||
#expect(state != nil)
|
||||
|
||||
// Mutate, then restore via fullState setter.
|
||||
synth.freq = 100
|
||||
synth.amp = 0.0
|
||||
au.fullState = state
|
||||
#expect(synth.freq == 1234.5)
|
||||
#expect(synth.amp == 0.75)
|
||||
}
|
||||
|
||||
@Test func fullStateStoresUnderNamespacedKey() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let state: [String : Any] = try #require(au.fullState)
|
||||
#expect(state[lyrebirdAUFullStateKey] != nil)
|
||||
// Scalar values are nested under a sub-key inside the root payload.
|
||||
let payload: [String : Any] = try #require(state[lyrebirdAUFullStateKey] as? [String: Any])
|
||||
let values: [String : AUValue] = try #require(payload[lyrebirdAUFullStateScalarKey] as? [String: AUValue])
|
||||
#expect(values["freq"] == 440)
|
||||
#expect(values["amp"] == AUValue(0.5))
|
||||
}
|
||||
|
||||
@Test func fullStateRestoreUpdatesAUParameterValues() throws {
|
||||
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
|
||||
let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth)
|
||||
synth.freq = 555
|
||||
synth.amp = 0.25
|
||||
let saved: [String : Any]? = au.fullState
|
||||
|
||||
// Reset and restore.
|
||||
synth.freq = 1000
|
||||
synth.amp = 0.9
|
||||
au.fullState = saved
|
||||
let tree: AUParameterTree = try #require(au.parameterTree)
|
||||
let freq: AUParameter = try #require(tree.parameter(withAddress: 0))
|
||||
let amp: AUParameter = try #require(tree.parameter(withAddress: 1))
|
||||
#expect(freq.value == 555)
|
||||
#expect(amp.value == AUValue(0.25))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
// AdditiveSynthesizerTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AdditiveSynthesizer")
|
||||
struct AdditiveSynthesizerTests {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Make a frame buffer populated with all-zero magnitudes.
|
||||
private func makeZeroFrameBuffer(fftSize: Int = 64, frameCount: Int = 2) -> SpectralFrameBuffer {
|
||||
SpectralFrameBuffer(
|
||||
fftSize: fftSize,
|
||||
hopSize: fftSize / 4,
|
||||
frameCount: frameCount,
|
||||
sampleRate: 44100
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - 1. Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - 2. Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
// The pre-allocated buffer has lyrebirdDefaultResultBufferSize (512) slots; check first 64 are accessible.
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
// MARK: - 3. Silent when all magnitudes are zero
|
||||
|
||||
@Test func silentWhenAllMagnitudesZero() throws {
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
|
||||
// Buffer is zero-initialized by default — all magnitudes are 0.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(64)))
|
||||
#expect(rms < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: - 4. Non-silent with non-zero magnitude on bin 1
|
||||
|
||||
@Test func nonSilentWithNonZeroMagnitude() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
|
||||
)
|
||||
// Set bin 1 magnitude in frame 0 to 1.0 via direct _mag pointer access.
|
||||
// Layout: _mag[frame * halfSize + k] = magnitude for bin k in frame.
|
||||
let halfSize: Int = fftSize / 2 // 32
|
||||
fb._mag[0 * halfSize + 1] = 1.0
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(64)))
|
||||
#expect(rms > 1e-6)
|
||||
}
|
||||
|
||||
// MARK: - 5. Fan-out — same segment returns identical first-channel output
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
|
||||
)
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + 1] = 0.5
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
}
|
||||
|
||||
// MARK: - 6. State advances exactly once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
|
||||
)
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + 1] = 1.0
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Second call in same segment — must be cache hit.
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Phase advanced: block2 must differ from block1.
|
||||
#expect(block1a != block2)
|
||||
}
|
||||
|
||||
// MARK: - 7. maxPartials = 0 uses all bins
|
||||
|
||||
@Test func maxPartialsZeroUsesAllBins() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer(fftSize: fftSize)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, maxPartials: 0)
|
||||
// Internal _activePartials == halfSize - 1 == binCount
|
||||
let expectedActive: Int = fftSize / 2 - 1
|
||||
// Access via reflection is not possible; verify indirectly via output count matching
|
||||
// a known non-zero-magnitude bin at the highest active index.
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + expectedActive] = 1.0
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(64)))
|
||||
// If maxPartials==0 is honouring all bins, the highest bin contributes signal.
|
||||
#expect(rms > 0.0)
|
||||
}
|
||||
|
||||
// MARK: - 8. maxPartials cap
|
||||
|
||||
@Test func maxPartialsCap() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer(fftSize: fftSize)
|
||||
// With maxPartials=10, bin 11 should NOT contribute even when its magnitude is non-zero.
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + 11] = 1.0 // frame 0, bin 11
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// maxPartials=10: only bins 1..10 are active; bin 11 is beyond the cap → silence.
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0, maxPartials: 10)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(64)))
|
||||
#expect(rms < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: - 9. Position clamping — no crash on out-of-range positions
|
||||
|
||||
@Test func positionClampAbove() throws {
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// position = 2.0 > 1.0 — must clamp to last frame without crashing.
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 2.0)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1)
|
||||
}
|
||||
|
||||
@Test func positionClampBelow() throws {
|
||||
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// position = -0.5 < 0.0 — must clamp to first frame without crashing.
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: -0.5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1)
|
||||
}
|
||||
|
||||
// MARK: - 10. Anti-aliasing — bin above Nyquist is zeroed
|
||||
|
||||
@Test func antialiasingZerosBinAboveNyquist() throws {
|
||||
// At 44100 Hz playback, Nyquist = 22050 Hz.
|
||||
// With fftSize=64 and sampleRate=44100: freqPerBin = 44100/64 ≈ 689 Hz.
|
||||
// Bin 32 would be at 32 × 689 ≈ 22050 Hz — exactly at or above Nyquist.
|
||||
// Use a very small fftSize to make a bin clearly above Nyquist.
|
||||
// fftSize=8: halfSize=4, binCount=3, freqPerBin=44100/8=5512.5 Hz.
|
||||
// Bin 3 → 3 × 5512.5 = 16537.5 Hz (below Nyquist=22050) → NOT zeroed.
|
||||
// Use different sampleRate: recordSR matches but a bin whose k*freqPerBin > nyquist.
|
||||
// fftSize=8 at recordSR=44100: freqPerBin = 5512.5 Hz
|
||||
// bin 1 → 5512.5 Hz (below 22050) → active
|
||||
// bin 3 → 16537.5 Hz (below 22050) → active
|
||||
// To get above Nyquist: use a buffer recorded at 192000 Hz but played at 44100 Hz.
|
||||
// freqPerBin = 192000/8 = 24000 Hz
|
||||
// bin 1 → 24000 Hz > 22050 Hz → zeroed!
|
||||
let fftSize: Int = 8
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 2, frameCount: 2, sampleRate: 192000
|
||||
)
|
||||
let halfSize: Int = fftSize / 2 // 4
|
||||
// Set bin 1 of frame 0 to a non-zero magnitude.
|
||||
fb._mag[0 * halfSize + 1] = 1.0
|
||||
|
||||
// Play back at 44100 Hz — bin 1's frequency (192000/8 = 24000 Hz) > Nyquist (22050 Hz).
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(64)))
|
||||
// All bins are above Nyquist → output should be silence.
|
||||
#expect(rms < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: - 11. mulAdd — with mul:2.0 add:1.0, output is original × 2 + 1
|
||||
|
||||
@Test func mulAddApplied() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
|
||||
)
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + 1] = 0.5 // bin 1 has magnitude 0.5
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Plain generator (no mulAdd).
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let genPlain: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
let outPlain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
|
||||
// Generator with mul:2.0, add:1.0.
|
||||
let genMulAdd: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0, mul: 2.0, add: 1.0)
|
||||
let outMulAdd: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
|
||||
// Both generators share the same frame buffer and start from the same zero phase,
|
||||
// so their base outputs are identical. Verify the relationship holds sample-by-sample.
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = outPlain[i] * 2.0 + 1.0
|
||||
#expect(abs(outMulAdd[i] - expected) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 12. Integration — runs inside a Synthesizer on the engine without crash
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
let fftSize: Int = 64
|
||||
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
|
||||
)
|
||||
let halfSize: Int = fftSize / 2
|
||||
fb._mag[0 * halfSize + 1] = 0.5
|
||||
|
||||
final class AddSynth: SynthesizerBase {
|
||||
let fb: SpectralFrameBuffer
|
||||
init(fb: SpectralFrameBuffer) { self.fb = fb; super.init() }
|
||||
override func build() {
|
||||
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let synth: AddSynth = AddSynth(fb: fb)
|
||||
try engine.add(synth)
|
||||
|
||||
// Run a few blocks — must not crash.
|
||||
for _ in 0..<4 {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// AmbiAFormatConversionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiAFormat conversion (B↔A)")
|
||||
struct AmbiAFormatConversionTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func static4Row(_ a: Double, _ b: Double, _ c: Double, _ d: Double) -> GeneratorArray {
|
||||
return GeneratorArray([
|
||||
ConstantGeneratorInput(a) as any Generator,
|
||||
ConstantGeneratorInput(b),
|
||||
ConstantGeneratorInput(c),
|
||||
ConstantGeneratorInput(d)
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: - Output topology
|
||||
|
||||
@Test func bToAOutputCountIsFour() {
|
||||
let bToA: AmbiBToA = AmbiBToA(input: static4Row(1, 0, 0, 0))
|
||||
#expect(bToA.outputChannelCount == 4)
|
||||
let out: [[Double]] = bToA.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 4)
|
||||
}
|
||||
|
||||
@Test func aToBOutputCountIsFour() {
|
||||
let aToB: AmbiAToB = AmbiAToB(input: static4Row(1, 0, 0, 0))
|
||||
#expect(aToB.outputChannelCount == 4)
|
||||
let out: [[Double]] = aToB.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 4)
|
||||
}
|
||||
|
||||
// MARK: - Matrix correctness
|
||||
|
||||
@Test func bToAExpandsWOnlyEqually() {
|
||||
// W only → all 4 capsules get W·0.5.
|
||||
let bToA: AmbiBToA = AmbiBToA(input: static4Row(1.0, 0, 0, 0))
|
||||
let out: [[Double]] = bToA.calculatedSamples(graph: graph, count: 64)
|
||||
for row: Int in 0..<4 {
|
||||
#expect(abs(out[row][32] - 0.5) < 1e-12)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func bToAExpandsXAsFrontMinusBack() {
|
||||
// X only → LFU = +0.5, RFD = +0.5, LBD = −0.5, RBU = −0.5.
|
||||
let bToA: AmbiBToA = AmbiBToA(input: static4Row(0, 1.0, 0, 0))
|
||||
let out: [[Double]] = bToA.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 0.5) < 1e-12)
|
||||
#expect(abs(out[1][32] - 0.5) < 1e-12)
|
||||
#expect(abs(out[2][32] - (-0.5)) < 1e-12)
|
||||
#expect(abs(out[3][32] - (-0.5)) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func aToBExtractsWFromEqualCapsules() {
|
||||
// All 4 capsules = 1 → W = 0.5·4 = 2, X = Y = Z = 0.
|
||||
let aToB: AmbiAToB = AmbiAToB(input: static4Row(1, 1, 1, 1))
|
||||
let out: [[Double]] = aToB.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 2.0) < 1e-12)
|
||||
#expect(abs(out[1][32]) < 1e-12)
|
||||
#expect(abs(out[2][32]) < 1e-12)
|
||||
#expect(abs(out[3][32]) < 1e-12)
|
||||
}
|
||||
|
||||
// MARK: - Round trip
|
||||
|
||||
@Test func bToAToBIsIdentity() {
|
||||
// Round trip B → A → B should be identity (up to FP noise).
|
||||
// Use distinct W/X/Y/Z so any cross-talk surfaces.
|
||||
let original: GeneratorArray = static4Row(0.123, -0.456, 0.789, -0.234)
|
||||
let bToA: AmbiBToA = AmbiBToA(input: original)
|
||||
let aToB: AmbiAToB = AmbiAToB(input: bToA)
|
||||
let out: [[Double]] = aToB.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 0.123) < 1e-12)
|
||||
#expect(abs(out[1][32] - (-0.456)) < 1e-12)
|
||||
#expect(abs(out[2][32] - 0.789) < 1e-12)
|
||||
#expect(abs(out[3][32] - (-0.234)) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func aToBToAIsIdentity() {
|
||||
// Round trip A → B → A on distinct capsule values.
|
||||
let original: GeneratorArray = static4Row(0.21, -0.34, 0.55, -0.42)
|
||||
let aToB: AmbiAToB = AmbiAToB(input: original)
|
||||
let bToA: AmbiBToA = AmbiBToA(input: aToB)
|
||||
let out: [[Double]] = bToA.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 0.21) < 1e-12)
|
||||
#expect(abs(out[1][32] - (-0.34)) < 1e-12)
|
||||
#expect(abs(out[2][32] - 0.55) < 1e-12)
|
||||
#expect(abs(out[3][32] - (-0.42)) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let aToB: AmbiAToB = AmbiAToB(input: static4Row(1, 1, 1, 1), mul: 2.0, add: 0.1)
|
||||
let out: [[Double]] = aToB.calculatedSamples(graph: graph, count: 64)
|
||||
// W = 2.0 baseline. After mul·add: 2·2 + 0.1 = 4.1.
|
||||
#expect(abs(out[0][32] - 4.1) < 1e-12)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// AmbiDecoderMonoTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiDecoderMono")
|
||||
struct AmbiDecoderMonoTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func staticBFormat(w: Double, x: Double, y: Double, z: Double) -> GeneratorArray {
|
||||
return GeneratorArray([
|
||||
ConstantGeneratorInput(w) as any Generator,
|
||||
ConstantGeneratorInput(x),
|
||||
ConstantGeneratorInput(y),
|
||||
ConstantGeneratorInput(z)
|
||||
])
|
||||
}
|
||||
|
||||
/// Encoder math: for unit-amplitude source at (az, el), W = 1/√2, X = cos(az)·cos(el),
|
||||
/// Y = sin(az)·cos(el), Z = sin(el). Use this to drive virtual-mic tests.
|
||||
private func encodedSource(amplitude: Double, az: Double, el: Double) -> GeneratorArray {
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let cosEl: Double = cos(el)
|
||||
return staticBFormat(
|
||||
w: wScale * amplitude,
|
||||
x: cos(az) * cosEl * amplitude,
|
||||
y: sin(az) * cosEl * amplitude,
|
||||
z: sin(el) * amplitude
|
||||
)
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsOne() {
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: 0, el: 0),
|
||||
pattern: 1.0
|
||||
)
|
||||
#expect(dec.outputChannelCount == 1)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1)
|
||||
}
|
||||
|
||||
@Test func omniReturnsUnitGainForAnyDirection() {
|
||||
// pattern = 0 → pure omni; should return the source amplitude regardless of (az, el).
|
||||
for (az, el): (Double, Double) in [(0, 0), (.pi / 2, 0), (.pi, 0), (0, .pi / 2)] {
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 0.6, az: az, el: el),
|
||||
azimuth: 0, elevation: 0, pattern: 0
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 0.6) < 1e-12,
|
||||
"Omni at source (az=\(az), el=\(el)) should return 0.6; got \(out[0][32])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func cardioidOnAxisFullGain() {
|
||||
// pattern = 1, mic at (0, 0), source at (0, 0): out = (1-0.5)·W·√2 + 0.5·(1·1·1 + 0 + 0)
|
||||
// = 0.5 · 1 + 0.5 · 1 = 1.0 ✓
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: 0, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 1.0
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - 1.0) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func cardioidBehindIsNullToFP() {
|
||||
// Cardioid pointing forward, source directly behind (az=π): cos(π) = −1 →
|
||||
// directional term = 0.5·(−1) = −0.5. omni = 0.5·W·√2 = 0.5. Sum = 0.
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: .pi, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 1.0
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32]) < 1e-12,
|
||||
"Cardioid null behind should be 0; got \(out[0][32])")
|
||||
}
|
||||
|
||||
@Test func figureEightFrontBackOppositePolarity() {
|
||||
// pattern = 2 → pure figure-8. omni gain = 0. Front (az=0): +1; back (az=π): −1.
|
||||
let front: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: 0, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 2.0
|
||||
)
|
||||
let back: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: .pi, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 2.0
|
||||
)
|
||||
let frontOut: [[Double]] = front.calculatedSamples(graph: graph, count: 64)
|
||||
let backOut: [[Double]] = back.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(frontOut[0][32] - 1.0) < 1e-12)
|
||||
#expect(abs(backOut[0][32] - (-1.0)) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func figureEightSideNull() {
|
||||
// Figure-8 mic pointing forward, source at side (az=π/2): cos(π/2) = 0. Null.
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: .pi / 2, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 2.0
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32]) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let dec: AmbiDecoderMono = AmbiDecoderMono(
|
||||
input: encodedSource(amplitude: 1, az: 0, el: 0),
|
||||
azimuth: 0, elevation: 0, pattern: 1.0,
|
||||
mul: 2.0, add: 0.1
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
// On-axis cardioid = 1.0; mul·add → 1·2 + 0.1 = 2.1.
|
||||
#expect(abs(out[0][32] - 2.1) < 1e-12)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// AmbiDecoderStereoTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiDecoderStereo")
|
||||
struct AmbiDecoderStereoTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
/// Convenience: build a static B-format source from scalar W/X/Y/Z values.
|
||||
private func staticBFormat(w: Double, x: Double, y: Double, z: Double) -> GeneratorArray {
|
||||
return GeneratorArray([
|
||||
ConstantGeneratorInput(w) as any Generator,
|
||||
ConstantGeneratorInput(x),
|
||||
ConstantGeneratorInput(y),
|
||||
ConstantGeneratorInput(z)
|
||||
])
|
||||
}
|
||||
|
||||
@Test func outputCountIsTwoChannels() {
|
||||
let dec: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: 0.707, x: 1, y: 0, z: 0)
|
||||
)
|
||||
#expect(dec.outputChannelCount == 2)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2)
|
||||
}
|
||||
|
||||
@Test func frontSourceProducesBalancedLR() {
|
||||
// Encoder at az=0, el=0 → W=1/√2, X=1, Y=0, Z=0. With Y=0, L=R.
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let dec: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: wScale, x: 1, y: 0, z: 0)
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][32] - out[1][32]) < 1e-12,
|
||||
"Y=0 source must produce L == R")
|
||||
}
|
||||
|
||||
@Test func hardLeftSourceFavoursLeft() {
|
||||
// Source at az=π/2 → Y=1, X=0. L = W + 0.61, R = W − 0.61.
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let dec: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: wScale, x: 0, y: 1, z: 0)
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
let l: Double = out[0][32]
|
||||
let r: Double = out[1][32]
|
||||
#expect(l > r, "Left source must give L > R; got L=\(l) R=\(r)")
|
||||
#expect(abs(l - (wScale + 0.61)) < 1e-12)
|
||||
#expect(abs(r - (wScale - 0.61)) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func zSilentlyDropped() {
|
||||
// Pure Z (elevation = π/2) source: W=1/√2, Z=1, X=Y=0. Decoder uses no Z.
|
||||
// L = R = W. Increasing |Z| arbitrarily changes nothing.
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let decLowZ: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: wScale, x: 0, y: 0, z: 0)
|
||||
)
|
||||
let decHighZ: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: wScale, x: 0, y: 0, z: 1.0)
|
||||
)
|
||||
let outLow: [[Double]] = decLowZ.calculatedSamples(graph: graph, count: 64)
|
||||
let outHigh: [[Double]] = decHighZ.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(outLow[0][32] == outHigh[0][32])
|
||||
#expect(outLow[1][32] == outHigh[1][32])
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let dec: AmbiDecoderStereo = AmbiDecoderStereo(
|
||||
input: staticBFormat(w: 1, x: 0, y: 0, z: 0),
|
||||
mul: 2.0,
|
||||
add: 0.1
|
||||
)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
// L = R = W·1 + 0.35·0 + 0.61·0 = 1. After mul·add: 1·2 + 0.1 = 2.1.
|
||||
#expect(abs(out[0][32] - 2.1) < 1e-12)
|
||||
#expect(abs(out[1][32] - 2.1) < 1e-12)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// AmbiDecoderUHJTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiDecoderUHJ")
|
||||
struct AmbiDecoderUHJTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func staticStereo(l: Double, r: Double) -> GeneratorArray {
|
||||
return GeneratorArray([
|
||||
ConstantGeneratorInput(l) as any Generator,
|
||||
ConstantGeneratorInput(r)
|
||||
])
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsFour() {
|
||||
let dec: AmbiDecoderUHJ = AmbiDecoderUHJ(input: staticStereo(l: 1, r: 1))
|
||||
#expect(dec.outputChannelCount == 4)
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 4)
|
||||
}
|
||||
|
||||
@Test func zRowIsAlwaysSilent() {
|
||||
let dec: AmbiDecoderUHJ = AmbiDecoderUHJ(input: staticStereo(l: 0.7, r: -0.3))
|
||||
// Run several blocks; Z must remain exactly 0 throughout.
|
||||
for _: Int in 0..<8 {
|
||||
let out: [[Double]] = dec.calculatedSamples(
|
||||
graph: makeSynthGraph(engine: engine), count: 512
|
||||
)
|
||||
for s: Double in out[3].prefix(512) {
|
||||
#expect(s == 0, "Z row must be silent; saw \(s)")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func equalLREncodesMonoToWXOnly() {
|
||||
// L = R = const → only the symmetric W/X matrix terms survive (Y has L − R coefficient).
|
||||
let dec: AmbiDecoderUHJ = AmbiDecoderUHJ(input: staticStereo(l: 0.5, r: 0.5))
|
||||
for _: Int in 0..<32 {
|
||||
_ = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
// Y output should be near zero after Hilbert filters settle (L − R = 0 for in-phase
|
||||
// path, and 0.385·(L_im + R_im) cancels only if L and R are coherent — they ARE the
|
||||
// same constant, so both Hilbert filters produce identical lj and rj, leaving
|
||||
// Y = 0.5·(0.763·0 + 0.385·(lj + rj)) = 0.385·lj.
|
||||
// For DC L = R = 0.5, Hilbert settles both paths to 0.5, so Y → 0.385·0.5 ≈ 0.193·0.5
|
||||
// — non-zero but Y/W ratio is bounded. Verify W and X are dominant.
|
||||
let w: Double = out[0][500]
|
||||
let x: Double = out[1][500]
|
||||
let y: Double = out[2][500]
|
||||
#expect(abs(w) > abs(y), "W=\(w) should dominate Y=\(y) for centred-mono UHJ")
|
||||
#expect(abs(x) > 0, "X=\(x) must be nonzero")
|
||||
}
|
||||
|
||||
@Test func roundTripBToUHJToBPreservesEnergy() {
|
||||
// B-format → UHJ → B-format: W/X/Y energy should be approximately preserved
|
||||
// within the Hilbert cascade's design band (UHJ matrix is energy-preserving in
|
||||
// theory). Z always returns 0.
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let origBFormat: GeneratorArray = GeneratorArray([
|
||||
OscSin.Audio(freq: 1_000.0) as any Generator,
|
||||
ConstantGeneratorInput(wScale) as any Generator,
|
||||
ConstantGeneratorInput(0.7) as any Generator,
|
||||
ConstantGeneratorInput(0) as any Generator
|
||||
])
|
||||
// Note: GeneratorArray of mixed Generator types — W gets the 1 kHz sine,
|
||||
// X/Y constant. Verify decoder returns 4 finite rows with Z = 0.
|
||||
let encoded: AmbiEncoderUHJ = AmbiEncoderUHJ(input: origBFormat)
|
||||
let decoded: AmbiDecoderUHJ = AmbiDecoderUHJ(input: encoded)
|
||||
// Settle Hilbert filters in both stages (each adds ~16τ settling).
|
||||
for _: Int in 0..<64 {
|
||||
_ = decoded.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = decoded.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
// All four rows must be finite. Z row exactly 0.
|
||||
for row: Int in 0..<4 {
|
||||
for s: Double in out[row].prefix(512) {
|
||||
#expect(s.isFinite, "Row \(row) sample not finite")
|
||||
}
|
||||
}
|
||||
for s: Double in out[3].prefix(512) {
|
||||
#expect(s == 0, "Z row must be 0 after round trip")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func steadyStateEqualLRPinsCoefficients() {
|
||||
// Deterministic coefficient pin: with L = R = 1 DC, both Hilbert paths settle to
|
||||
// 1.0 on both channels. The decode matrix collapses to:
|
||||
// W = 0.5·(kWRe·(l + r) + kWIm·(lj − rj)) = 0.5·(kWRe·2 + 0) = kWRe
|
||||
// X = 0.5·(kXRe·(l + r) + kXIm·(rj − lj)) = 0.5·(kXRe·2 + 0) = kXRe
|
||||
// Y = 0.5·(kYRe·(l − r) + kYIm·(lj + rj)) = 0.5·(0 + kYIm·2) = kYIm
|
||||
// Z = 0
|
||||
// Any sign flip on the decode coefficients in AmbiUHJCoeffs.swift trips this.
|
||||
let dec: AmbiDecoderUHJ = AmbiDecoderUHJ(input: staticStereo(l: 1.0, r: 1.0))
|
||||
let settleBlocks: Int = 48
|
||||
for _: Int in 0..<settleBlocks {
|
||||
_ = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let expectedW: Double = uhjDecodeWRe // = 0.982
|
||||
let expectedX: Double = uhjDecodeXRe // = 0.419
|
||||
let expectedY: Double = uhjDecodeYIm // = 0.385 (quadrature-only contribution survives)
|
||||
#expect(abs(out[0][500] - expectedW) < 1e-3,
|
||||
"W steady-state for L=R=1 DC: expected ≈ \(expectedW), got \(out[0][500])")
|
||||
#expect(abs(out[1][500] - expectedX) < 1e-3,
|
||||
"X steady-state: expected ≈ \(expectedX), got \(out[1][500])")
|
||||
#expect(abs(out[2][500] - expectedY) < 1e-3,
|
||||
"Y steady-state: expected ≈ \(expectedY), got \(out[2][500])")
|
||||
#expect(out[3][500] == 0, "Z must be exactly 0")
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let dec: AmbiDecoderUHJ = AmbiDecoderUHJ(input: staticStereo(l: 1, r: 1), mul: 2.0, add: 0.1)
|
||||
for _: Int in 0..<32 {
|
||||
_ = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
// Z row should be 0·2 + 0.1 = 0.1 after mul/add.
|
||||
for s: Double in out[3].prefix(512) {
|
||||
#expect(abs(s - 0.1) < 1e-12, "Z (silent + mul/add): expected 0.1, got \(s)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// AmbiEncoder1ParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiEncoder1 parameter ramping")
|
||||
struct AmbiEncoder1ParameterRampingTests {
|
||||
|
||||
/// Audio-rate Generator drives azimuth — a constant 1.0 input source encoded
|
||||
/// with `azimuth = ConstantGeneratorInput(.pi / 2)` should yield X≈0, Y≈1
|
||||
/// throughout the block (no ramping, no parameter settle window — every
|
||||
/// sample sees the same azimuth).
|
||||
@Test func audioRateGeneratorDrivesAzimuth() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let enc: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
azimuth: ConstantGeneratorInput(.pi / 2),
|
||||
elevation: 0.0
|
||||
)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: g, count: 64)
|
||||
// Sample 0 should already be at π/2 (no ramp — Generator delivers
|
||||
// the constant per-sample directly).
|
||||
#expect(abs(out[1][0]) < 1e-12, "X at audio-rate az=π/2 should be 0 at sample 0")
|
||||
#expect(abs(out[2][0] - 1.0) < 1e-12, "Y at audio-rate az=π/2 should be 1 at sample 0")
|
||||
}
|
||||
|
||||
@Test func azimuthRampIsApplied() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let lastSampleIdx: Int = engine.blockSize - 1
|
||||
|
||||
// ParameterNode now drives azimuth via the new `any ValidGeneratorInput`
|
||||
// init parameter — same ramping semantics as the prior @LiveParam-backed
|
||||
// version, but the caller owns the node.
|
||||
let azNode: ParameterNode = ParameterNode(0.0)
|
||||
let enc: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
azimuth: azNode,
|
||||
elevation: 0.0
|
||||
)
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = enc.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Block 2: ramp azimuth to π/2 → X=0, Y=1 at last sample.
|
||||
azNode.value = .pi / 2
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = enc.calculatedSamples(graph: g2, count: 64)
|
||||
// First sample: az still near 0 → X≈1, Y≈0.
|
||||
// Last sample: az≈π/2 → X≈0, Y≈1.
|
||||
let xLast: Double = out2[1][lastSampleIdx] // X channel
|
||||
let yLast: Double = out2[2][lastSampleIdx] // Y channel
|
||||
#expect(abs(xLast) < 1e-4, "After azimuth=π/2 ramp: X should be ~0 at last sample")
|
||||
#expect(abs(yLast - 1.0) < 1e-4, "After azimuth=π/2 ramp: Y should be ~1 at last sample")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// AmbiEncoderStereoTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiEncoderStereo")
|
||||
struct AmbiEncoderStereoTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsFour() {
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(left: 1.0, right: 1.0)
|
||||
#expect(enc.outputChannelCount == 4)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 4)
|
||||
}
|
||||
|
||||
@Test func zRowIsAlwaysSilent() {
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(left: 0.7, right: -0.3, spread: .pi / 4)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
for s: Double in out[3].prefix(64) { #expect(s == 0) }
|
||||
}
|
||||
|
||||
@Test func spreadZeroMonoCentre() {
|
||||
// spread = 0 → cos = 1, sin = 0. Y row should be 0; W/X both ∝ (L + R).
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(left: 0.6, right: 0.4, spread: 0)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let sum: Double = 0.6 + 0.4
|
||||
#expect(abs(out[0][32] - wScale * sum) < 1e-12) // W
|
||||
#expect(abs(out[1][32] - sum) < 1e-12) // X = cos(0)·sum = sum
|
||||
#expect(abs(out[2][32]) < 1e-12) // Y = sin(0)·diff = 0
|
||||
}
|
||||
|
||||
@Test func spreadHalfPiHardLeftRight() {
|
||||
// spread = π/2 → cos = 0 (X silent), sin = 1. Y = L − R.
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(left: 1.0, right: 0.0, spread: .pi / 2)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
#expect(abs(out[0][32] - wScale * 1.0) < 1e-12) // W = (1/√2) × (1 + 0)
|
||||
#expect(abs(out[1][32]) < 1e-12) // X = 0
|
||||
#expect(abs(out[2][32] - 1.0) < 1e-12) // Y = 1 × (1 − 0)
|
||||
}
|
||||
|
||||
@Test func matchesTwoEncoder1ReferenceAtPiOver4() {
|
||||
// spread = π/4 with left=1, right=0 should match an AmbiEncoder1 at az=+π/4.
|
||||
let spread: Double = .pi / 4
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(left: 1.0, right: 0.0, spread: spread)
|
||||
let ref: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
azimuth: spread,
|
||||
elevation: 0
|
||||
)
|
||||
// Settle parameter ramps in both via several blocks.
|
||||
for _: Int in 0..<8 {
|
||||
_ = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 64)
|
||||
_ = ref.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 64)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let encOut: [[Double]] = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 64)
|
||||
let refOut: [[Double]] = ref.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 64)
|
||||
// Stereo encoder with right=0 should equal AmbiEncoder1 driven by left source at +spread.
|
||||
for row: Int in 0..<4 {
|
||||
#expect(abs(encOut[row][32] - refOut[row][32]) < 1e-10,
|
||||
"Row \(row) mismatch: \(encOut[row][32]) vs \(refOut[row][32])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(
|
||||
left: 0.5, right: 0.5, spread: 0, mul: 2.0, add: 0.1
|
||||
)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
// W = wScale · 1.0 = 0.707, after mul·add = 0.707·2 + 0.1 ≈ 1.514.
|
||||
#expect(abs(out[0][32] - (wScale * 1.0 * 2.0 + 0.1)) < 1e-12)
|
||||
// Z = 0 → mul·add = 0 + 0.1 = 0.1.
|
||||
#expect(abs(out[3][32] - 0.1) < 1e-12)
|
||||
}
|
||||
|
||||
/// Audio-rate Generator drives `spread`. With `spread = π/2` (constant
|
||||
/// signal), X row coefficient cos(π/2) ≈ 0 → X channel silent; Y row
|
||||
/// coefficient sin(π/2) = 1 → Y = (L − R). Pins the new
|
||||
/// `_spreadIsGenerator == true` per-sample code path.
|
||||
@Test func audioRateGeneratorDrivesSpread() {
|
||||
let enc: AmbiEncoderStereo = AmbiEncoderStereo(
|
||||
left: 1.0,
|
||||
right: 0.0,
|
||||
spread: ConstantGeneratorInput(.pi / 2)
|
||||
)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
// Sample 0 should already be at π/2 (Generator delivers constant
|
||||
// per-sample directly — no ramp window).
|
||||
#expect(abs(out[1][0]) < 1e-12, "X = cos(π/2)·(L+R) should be 0")
|
||||
#expect(abs(out[2][0] - 1.0) < 1e-12, "Y = sin(π/2)·(L−R) should be 1.0")
|
||||
// Z row stays silent regardless of spread path.
|
||||
#expect(abs(out[3][0]) < 1e-12, "Z row always silent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// AmbiEncoderUHJTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiEncoderUHJ")
|
||||
struct AmbiEncoderUHJTests {
|
||||
|
||||
private let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
private var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func staticBFormat(w: Double, x: Double, y: Double, z: Double) -> GeneratorArray {
|
||||
return GeneratorArray([
|
||||
ConstantGeneratorInput(w) as any Generator,
|
||||
ConstantGeneratorInput(x),
|
||||
ConstantGeneratorInput(y),
|
||||
ConstantGeneratorInput(z)
|
||||
])
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsTwo() {
|
||||
let enc: AmbiEncoderUHJ = AmbiEncoderUHJ(input: staticBFormat(w: 1, x: 0, y: 0, z: 0))
|
||||
#expect(enc.outputChannelCount == 2)
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2)
|
||||
}
|
||||
|
||||
@Test func zChannelDroppedSilently() {
|
||||
// Vary Z heavily — output L/R must be unchanged.
|
||||
let lowZ: AmbiEncoderUHJ = AmbiEncoderUHJ(input: staticBFormat(w: 0.5, x: 0.5, y: 0.5, z: 0))
|
||||
let highZ: AmbiEncoderUHJ = AmbiEncoderUHJ(input: staticBFormat(w: 0.5, x: 0.5, y: 0.5, z: 0.9))
|
||||
// Settle Hilbert filters.
|
||||
for _: Int in 0..<32 {
|
||||
_ = lowZ.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
_ = highZ.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let outLow: [[Double]] = lowZ.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let outHigh: [[Double]] = highZ.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
// Compare a late-block sample. Z shouldn't enter the UHJ output at all.
|
||||
#expect(abs(outLow[0][500] - outHigh[0][500]) < 1e-10,
|
||||
"Z must not affect L output")
|
||||
#expect(abs(outLow[1][500] - outHigh[1][500]) < 1e-10,
|
||||
"Z must not affect R output")
|
||||
}
|
||||
|
||||
@Test func frontSourceBalancesLAndREnergy() {
|
||||
// Encoded front-centre source (az=0, el=0) on a 1 kHz tone:
|
||||
// W = (1/√2)·sin(ωt), X = sin(ωt), Y = 0, Z = 0.
|
||||
// Y is the only L/R-asymmetric matrix term; with Y = 0 the energy should be
|
||||
// balanced (RMS(L) ≈ RMS(R)) once the Hilbert filters settle. Per-sample
|
||||
// equality does NOT hold — the wj/xj imaginary components have fixed signs
|
||||
// between L and R, so the instantaneous difference is non-zero, but RMS over
|
||||
// many cycles is the same.
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 1_000.0)
|
||||
// Build W = (1/√2)·source, X = 1·source using mul.
|
||||
let bformat: GeneratorArray = GeneratorArray([
|
||||
(osc * wScale) as any Generator,
|
||||
osc as any Generator,
|
||||
ConstantGeneratorInput(0) as any Generator,
|
||||
ConstantGeneratorInput(0) as any Generator
|
||||
])
|
||||
let enc: AmbiEncoderUHJ = AmbiEncoderUHJ(input: bformat)
|
||||
// Settle Hilbert filters.
|
||||
for _: Int in 0..<32 {
|
||||
_ = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
var rmsL: Double = 0
|
||||
var rmsR: Double = 0
|
||||
for i: Int in 0..<512 {
|
||||
rmsL += out[0][i] * out[0][i]
|
||||
rmsR += out[1][i] * out[1][i]
|
||||
}
|
||||
let ratio: Double = rmsL / rmsR
|
||||
// Energies should match to within ±10% (Hilbert phase error introduces ~7% mismatch
|
||||
// at 1 kHz under the Niemitalo cascade; hard-left pan would push the ratio well
|
||||
// outside this band).
|
||||
#expect(abs(ratio - 1.0) < 0.10,
|
||||
"Front source: RMS(L) / RMS(R) = \(ratio), expected ~1.0")
|
||||
}
|
||||
|
||||
@Test func panHardLeftFavoursLChannel() {
|
||||
// Encoded source at az=π/2: X=0, Y=1, W=1/√2. UHJ matrix L gets +Y, R gets −Y.
|
||||
// After settling, RMS(L) should exceed RMS(R).
|
||||
let wScale: Double = 1.0 / Double(2.0).squareRoot()
|
||||
let bformat: GeneratorArray = staticBFormat(w: wScale, x: 0, y: 1.0, z: 0)
|
||||
let enc: AmbiEncoderUHJ = AmbiEncoderUHJ(input: bformat)
|
||||
for _: Int in 0..<32 {
|
||||
_ = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
var rmsL: Double = 0
|
||||
var rmsR: Double = 0
|
||||
for i: Int in 0..<512 {
|
||||
rmsL += out[0][i] * out[0][i]
|
||||
rmsR += out[1][i] * out[1][i]
|
||||
}
|
||||
#expect(rmsL > rmsR, "Pan-hard-left: RMS(L)=\(rmsL) must exceed RMS(R)=\(rmsR)")
|
||||
}
|
||||
|
||||
@Test func steadyStateDCWWithZeroXYPinsCoefficients() {
|
||||
// Deterministic coefficient pin: with W = 1 DC and X = Y = Z = 0, both Hilbert
|
||||
// paths on W settle to 1.0 (each IIR all-pass section has unity DC magnitude;
|
||||
// 4 cascaded sections × π phase shift each = 4π = 0, so DC passes through with
|
||||
// gain +1). The UHJ matrix collapses to:
|
||||
// L = 0.5 · (uhjEncodeWRe · 1 − uhjEncodeWIm · 1) = 0.5 · (0.9397 − 0.342)
|
||||
// R = 0.5 · (uhjEncodeWRe · 1 + uhjEncodeWIm · 1) = 0.5 · (0.9397 + 0.342)
|
||||
// Any sign flip on `imagPart` or wrong constant in AmbiUHJCoeffs.swift will trip this.
|
||||
let bformat: GeneratorArray = staticBFormat(w: 1.0, x: 0, y: 0, z: 0)
|
||||
let enc: AmbiEncoderUHJ = AmbiEncoderUHJ(input: bformat)
|
||||
// Long settle for the slow IIR pole — Hilbert constants document ≥ 16τ for 1e-4.
|
||||
let settleBlocks: Int = 48
|
||||
for _: Int in 0..<settleBlocks {
|
||||
_ = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let expectedL: Double = 0.5 * (uhjEncodeWRe - uhjEncodeWIm)
|
||||
let expectedR: Double = 0.5 * (uhjEncodeWRe + uhjEncodeWIm)
|
||||
#expect(abs(out[0][500] - expectedL) < 1e-3,
|
||||
"L steady-state for W=1 DC: expected ≈ \(expectedL), got \(out[0][500])")
|
||||
#expect(abs(out[1][500] - expectedR) < 1e-3,
|
||||
"R steady-state for W=1 DC: expected ≈ \(expectedR), got \(out[1][500])")
|
||||
}
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let bformat: GeneratorArray = staticBFormat(w: 1, x: 0, y: 0, z: 0)
|
||||
let enc: AmbiEncoderUHJ = AmbiEncoderUHJ(input: bformat, mul: 2.0, add: 0.1)
|
||||
// Settle Hilbert filters (long pole).
|
||||
for _: Int in 0..<32 {
|
||||
_ = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = enc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
// Both channels: finite + offset by mul·add baseline (Hilbert settling around DC W input).
|
||||
#expect(out[0][500].isFinite)
|
||||
#expect(out[1][500].isFinite)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// AmbiSpeakerLayoutTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmbiSpeakerLayout")
|
||||
struct AmbiSpeakerLayoutTests {
|
||||
|
||||
private let azTolerance: Double = 1e-12
|
||||
private let elTolerance: Double = 1e-12
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func makeEngine(blockSize: Int = 64) throws -> SynthesisEngine {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
return engine
|
||||
}
|
||||
|
||||
private func ringStepRadians(_ n: Int) -> Double { 2.0 * .pi / Double(n) }
|
||||
|
||||
// MARK: - Ring layouts
|
||||
|
||||
@Test func quadDefaultHasFourHorizontalSpeakers() {
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.quad()
|
||||
#expect(speakers.count == 4)
|
||||
for sp: (az: Double, el: Double) in speakers {
|
||||
#expect(abs(sp.el) < elTolerance)
|
||||
}
|
||||
let step: Double = ringStepRadians(4)
|
||||
for (i, sp) in speakers.enumerated() {
|
||||
#expect(abs(sp.az - Double(i) * step) < azTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func quadWithOffsetRotatesEveryAzimuth() {
|
||||
let offset: Double = .pi / 4
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.quad(azimuthOffset: offset)
|
||||
let step: Double = ringStepRadians(4)
|
||||
for (i, sp) in speakers.enumerated() {
|
||||
#expect(abs(sp.az - (offset + Double(i) * step)) < azTolerance)
|
||||
#expect(abs(sp.el) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func hexagonHasSixHorizontalSpeakersEvenlySpaced() {
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.hexagon()
|
||||
#expect(speakers.count == 6)
|
||||
let step: Double = ringStepRadians(6)
|
||||
for i: Int in 1..<speakers.count {
|
||||
#expect(abs((speakers[i].az - speakers[i - 1].az) - step) < azTolerance)
|
||||
#expect(abs(speakers[i].el) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func octagonHasEightHorizontalSpeakersEvenlySpaced() {
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.octagon()
|
||||
#expect(speakers.count == 8)
|
||||
let step: Double = ringStepRadians(8)
|
||||
for i: Int in 1..<speakers.count {
|
||||
#expect(abs((speakers[i].az - speakers[i - 1].az) - step) < azTolerance)
|
||||
#expect(abs(speakers[i].el) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Double-ring layouts
|
||||
|
||||
@Test func cubeStacksTwoFourSpeakerRingsWithMirroredElevation() {
|
||||
let elevation: Double = .pi / 6
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.cube(elevation: elevation)
|
||||
#expect(speakers.count == 8)
|
||||
|
||||
for k: Int in 0..<4 {
|
||||
#expect(abs(speakers[k].el - elevation) < elTolerance)
|
||||
}
|
||||
for k: Int in 4..<8 {
|
||||
#expect(abs(speakers[k].el - (-elevation)) < elTolerance)
|
||||
}
|
||||
// Upper and lower rings share azimuths element-wise.
|
||||
for k: Int in 0..<4 {
|
||||
#expect(abs(speakers[k].az - speakers[k + 4].az) < azTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func cubeAzimuthOffsetAppliesToBothRings() {
|
||||
let offset: Double = .pi / 8
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.cube(
|
||||
elevation: .pi / 6, azimuthOffset: offset
|
||||
)
|
||||
let step: Double = ringStepRadians(4)
|
||||
for k: Int in 0..<4 {
|
||||
#expect(abs(speakers[k].az - (offset + Double(k) * step)) < azTolerance)
|
||||
#expect(abs(speakers[k + 4].az - (offset + Double(k) * step)) < azTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func doubleHexagonStacksTwoSixSpeakerRings() {
|
||||
let elevation: Double = .pi / 6
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.doubleHexagon(
|
||||
elevation: elevation
|
||||
)
|
||||
#expect(speakers.count == 12)
|
||||
for k: Int in 0..<6 {
|
||||
#expect(abs(speakers[k].el - elevation) < elTolerance)
|
||||
}
|
||||
for k: Int in 6..<12 {
|
||||
#expect(abs(speakers[k].el - (-elevation)) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func doubleOctagonStacksTwoEightSpeakerRings() {
|
||||
let elevation: Double = .pi / 6
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.doubleOctagon(
|
||||
elevation: elevation
|
||||
)
|
||||
#expect(speakers.count == 16)
|
||||
for k: Int in 0..<8 {
|
||||
#expect(abs(speakers[k].el - elevation) < elTolerance)
|
||||
}
|
||||
for k: Int in 8..<16 {
|
||||
#expect(abs(speakers[k].el - (-elevation)) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - stackedRings — general form
|
||||
|
||||
@Test func stackedRingsSingleLayerIgnoresElevation() {
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.stackedRings(
|
||||
vertices: 5, layers: 1, elevation: 0.3
|
||||
)
|
||||
#expect(speakers.count == 5)
|
||||
let step: Double = ringStepRadians(5)
|
||||
for (i, sp) in speakers.enumerated() {
|
||||
#expect(abs(sp.el) < elTolerance)
|
||||
#expect(abs(sp.az - Double(i) * step) < azTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func stackedRingsTwoLayersSplitsUpperAndLower() {
|
||||
let elevation: Double = 0.4
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.stackedRings(
|
||||
vertices: 7, layers: 2, elevation: elevation
|
||||
)
|
||||
#expect(speakers.count == 14)
|
||||
for k: Int in 0..<7 {
|
||||
#expect(abs(speakers[k].el - elevation) < elTolerance)
|
||||
#expect(abs(speakers[k + 7].el - (-elevation)) < elTolerance)
|
||||
#expect(abs(speakers[k].az - speakers[k + 7].az) < azTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func stackedRingsThreeLayersDistributesElevationEvenly() {
|
||||
let elevation: Double = 0.5
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.stackedRings(
|
||||
vertices: 4, layers: 3, elevation: elevation
|
||||
)
|
||||
#expect(speakers.count == 12)
|
||||
for k: Int in 0..<4 {
|
||||
#expect(abs(speakers[k].el - elevation) < elTolerance)
|
||||
}
|
||||
for k: Int in 4..<8 {
|
||||
#expect(abs(speakers[k].el - 0) < elTolerance)
|
||||
}
|
||||
for k: Int in 8..<12 {
|
||||
#expect(abs(speakers[k].el - (-elevation)) < elTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func stackedRingsFourLayersStepsEvenlyFromPlusToMinus() {
|
||||
let elevation: Double = 0.6
|
||||
let speakers: [(az: Double, el: Double)] = AmbiSpeakerLayout.stackedRings(
|
||||
vertices: 4, layers: 4, elevation: elevation
|
||||
)
|
||||
#expect(speakers.count == 16)
|
||||
let stepEl: Double = 2.0 * elevation / 3.0
|
||||
for layer: Int in 0..<4 {
|
||||
let expectedEl: Double = elevation - stepEl * Double(layer)
|
||||
for k: Int in 0..<4 {
|
||||
#expect(abs(speakers[layer * 4 + k].el - expectedEl) < elTolerance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AmbiDecoder1 integration smoke test
|
||||
|
||||
@Test func decoderAcceptsLayoutOutputForQuad() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let enc: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
azimuth: 0.0,
|
||||
elevation: 0.0
|
||||
)
|
||||
|
||||
let dec: AmbiDecoder1 = AmbiDecoder1(
|
||||
input: enc,
|
||||
speakers: AmbiSpeakerLayout.quad(azimuthOffset: .pi / 4)
|
||||
)
|
||||
#expect(dec.outputChannelCount == 4)
|
||||
|
||||
let out: [[Double]] = dec.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 4)
|
||||
for row: [Double] in out {
|
||||
for s: Double in row.prefix(64) {
|
||||
#expect(s.isFinite)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// AmplitudeFollowerParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AmplitudeFollower parameter ramping")
|
||||
struct AmplitudeFollowerParameterRampingTests {
|
||||
|
||||
@Test func attackTimeGeneratorInputIsRead() throws {
|
||||
// Verify that wiring a ParameterNode to attackTime does not crash and produces output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let attackNode: ParameterNode = ParameterNode(0.01)
|
||||
let releaseNode: ParameterNode = ParameterNode(0.1)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: signal, attackTime: attackNode,
|
||||
releaseTime: releaseNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = follower.calculatedSamples(graph: g, count: 64)
|
||||
#expect(out.count == 1, "AmplitudeFollower should produce 1 channel")
|
||||
let hasEnergy: Bool = (out.first ?? []).prefix(64).contains { $0 > 0 }
|
||||
#expect(hasEnergy, "AmplitudeFollower with sine input should produce non-zero output")
|
||||
}
|
||||
|
||||
@Test func controlAttackTimeGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let attackNode: ParameterNode = ParameterNode(0.01)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let follower: AmplitudeFollower.Control = AmplitudeFollower.Control(in: signal, attackTime: attackNode)
|
||||
|
||||
// Warm up one block to prime the follower.
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = follower.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Change attack time via the ParameterNode and verify no crash/invalid output.
|
||||
attackNode.value = 0.5
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = follower.calculatedSamples(graph: g2, count: 64)
|
||||
let samples: [Double] = Array((out2.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"AmplitudeFollower.Control output must remain finite after attackTime change")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
// AudioRateInputTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - DFT helper
|
||||
|
||||
/// Compute normalised DFT magnitude at a single frequency — O(N). Used for sideband detection.
|
||||
private func dftMagnitude(samples: [Double], freq: Double, sampleRate: Double) -> Double {
|
||||
let n: Int = samples.count
|
||||
guard n > 0 else { return 0 }
|
||||
var real: Double = 0.0
|
||||
var imag: Double = 0.0
|
||||
for i: Int in 0..<n {
|
||||
let phase: Double = 2.0 * Double.pi * freq * Double(i) / sampleRate
|
||||
real += Double(samples[i]) * cos(phase)
|
||||
imag -= Double(samples[i]) * sin(phase)
|
||||
}
|
||||
return sqrt(real * real + imag * imag) / Double(n)
|
||||
}
|
||||
|
||||
/// Collect `totalSamples` of output from a generator across multiple blocks.
|
||||
private func collectSamples(
|
||||
_ gen: any Generator,
|
||||
engine: SynthesisEngine,
|
||||
totalSamples: Int
|
||||
) -> [Double] {
|
||||
let blockSize: Int = engine.blockSize
|
||||
var output: [Double] = []
|
||||
output.reserveCapacity(totalSamples)
|
||||
while output.count < totalSamples {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let needed: Int = min(blockSize, totalSamples - output.count)
|
||||
let block: [Double] = gen.calculatedSamples(graph: g, count: blockSize)[0]
|
||||
output += block.prefix(needed)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// MARK: - AudioRateInput suite
|
||||
|
||||
@Suite("AudioRateInput")
|
||||
struct AudioRateInputTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
// MARK: OscSin
|
||||
|
||||
@Test func oscSinScalarAndConstantGeneratorInputMatch() {
|
||||
let count: Int = 64
|
||||
let oscScalar: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let oscConst: OscSin.Audio = OscSin.Audio(freq: ConstantGeneratorInput(440.0))
|
||||
let s1: [Double] = oscScalar.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let s2: [Double] = oscConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
for i: Int in 0..<count {
|
||||
#expect(abs(Double(s1[i]) - Double(s2[i])) < 1e-5,
|
||||
"sample \(i): scalar=\(s1[i]) const=\(s2[i])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func oscSinGeneratorFreqDiffersFromScalar() {
|
||||
let count: Int = 64
|
||||
let carrierFreq: Double = 440.0
|
||||
let modDepth: Double = 200.0
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
let fmOsc: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||||
let constOsc: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
|
||||
let fmSamples: [Double] = fmOsc.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = constOsc.calculatedSamples(graph: graph, count: count)[0]
|
||||
|
||||
let maxDiff: Double = (0..<count).map { abs(Double(fmSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||||
#expect(maxDiff > 0.01, "FM-modulated OscSin should differ from constant-freq version")
|
||||
}
|
||||
|
||||
@Test func oscSinGeneratorFreqRateIsAudio() {
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let carrier: OscSin.Audio = OscSin.Audio(freq: modulator * 200 + 440)
|
||||
#expect(carrier.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: OscTable
|
||||
|
||||
@Test func oscTableGeneratorFreqDiffersFromScalar() {
|
||||
let count: Int = 64
|
||||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
table.fillSine()
|
||||
let carrierFreq: Double = 440.0
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
let fmOsc: OscTable.Audio = OscTable.Audio(table: table, freq: modulator * 200 + carrierFreq)
|
||||
let constOsc: OscTable.Audio = OscTable.Audio(table: table, freq: carrierFreq)
|
||||
|
||||
let fmSamples: [Double] = fmOsc.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = constOsc.calculatedSamples(graph: graph, count: count)[0]
|
||||
|
||||
let maxDiff: Double = (0..<count).map { abs(Double(fmSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||||
#expect(maxDiff > 0.01, "FM-modulated OscTable should differ from constant-freq version")
|
||||
}
|
||||
|
||||
@Test func oscTableScalarAndConstantGeneratorMatch() {
|
||||
let count: Int = 64
|
||||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
table.fillSine()
|
||||
let oscScalar: OscTable.Audio = OscTable.Audio(table: table, freq: 440.0)
|
||||
let oscConst: OscTable.Audio = OscTable.Audio(table: table, freq: ConstantGeneratorInput(440.0))
|
||||
let s1: [Double] = oscScalar.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let s2: [Double] = oscConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
for i: Int in 0..<count {
|
||||
#expect(abs(Double(s1[i]) - Double(s2[i])) < 1e-4,
|
||||
"sample \(i): scalar=\(s1[i]) const=\(s2[i])")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Impulse
|
||||
|
||||
@Test func impulseGeneratorFreqProducesFiniteOutput() {
|
||||
let count: Int = 64
|
||||
let freqMod: BinaryOpGenerator = OscSin.Audio(freq: 4.0) * 2.0 + 4.0
|
||||
let imp: Impulse.Audio = Impulse.Audio(freq: freqMod)
|
||||
let samples: [Double] = imp.calculatedSamples(graph: graph, count: count)[0]
|
||||
#expect(samples.prefix(count).allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func impulseGeneratorFreqDiffersFromScalar() {
|
||||
let count: Int = 64
|
||||
let sampleRate: Double = Double(engine.sampleRate)
|
||||
let baseFreq: Double = sampleRate / 8 // fires every 8 samples at 1x
|
||||
let modDepth: Double = sampleRate / 32 // large enough to shift timing
|
||||
// OscSin completes a half-cycle over the block, sweeping freq up and back.
|
||||
// The varying phase accumulation produces different impulse positions than constant baseFreq.
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: sampleRate / 128.0)
|
||||
let impMod: Impulse.Audio = Impulse.Audio(freq: modulator * modDepth + baseFreq)
|
||||
let impConst: Impulse.Audio = Impulse.Audio(freq: baseFreq)
|
||||
let modSamples: [Double] = impMod.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = impConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
#expect(modSamples.prefix(count).allSatisfy { $0.isFinite })
|
||||
#expect(constSamples.prefix(count).allSatisfy { $0.isFinite })
|
||||
#expect(modSamples != constSamples,
|
||||
"audio-rate freq path should produce different impulse timing than scalar path")
|
||||
}
|
||||
|
||||
// MARK: FirstOrderSection
|
||||
|
||||
@Test func firstOrderSectionGeneratorCoefficientChangesOutput() {
|
||||
let count: Int = 64
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
// Audio-rate a0 modulated by a slow sine — should change the output vs constant a0
|
||||
let a0Mod: BinaryOpGenerator = OscSin.Audio(freq: 1.0) * 0.05 + 0.1 // a0 in [0.05, 0.15]
|
||||
let filterMod: FirstOrderSection = FirstOrderSection(input: signal, a0: a0Mod, a1: 0.0, b1: 0.9)
|
||||
let filterConst: FirstOrderSection = FirstOrderSection(input: OscSin.Audio(freq: 440.0), a0: 0.1, a1: 0.0, b1: 0.9)
|
||||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||||
#expect(maxDiff > 0.0, "Audio-rate coefficient filter should differ from constant-coefficient version")
|
||||
}
|
||||
|
||||
// MARK: SecondOrderSection
|
||||
|
||||
@Test func secondOrderSectionGeneratorCoefficientChangesOutput() {
|
||||
let count: Int = 64
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let a0Mod: BinaryOpGenerator = OscSin.Audio(freq: 2.0) * 0.1 + 0.5
|
||||
let filterMod: SecondOrderSection = SecondOrderSection(input: signal, a0: a0Mod, a1: 0.0, a2: 0.0, b1: 0.0, b2: 0.0)
|
||||
let filterConst: SecondOrderSection = SecondOrderSection(input: OscSin.Audio(freq: 440.0), a0: 0.5, a1: 0.0, a2: 0.0, b1: 0.0, b2: 0.0)
|
||||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||||
#expect(maxDiff > 0.0)
|
||||
}
|
||||
|
||||
// MARK: RBJBandPass
|
||||
|
||||
@Test func rbjBandPassGeneratorFreqChangesOutput() {
|
||||
let count: Int = 64
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let freqMod: BinaryOpGenerator = OscSin.Audio(freq: 1.0) * 200.0 + 1000.0 // sweeping 800–1200 Hz
|
||||
let filterMod: RBJBandPass.Audio = RBJBandPass.Audio(input: signal, freq: freqMod, bandwidth: 1.0)
|
||||
let filterConst: RBJBandPass.Audio = RBJBandPass.Audio(input: OscSin.Audio(freq: 440.0), freq: 1000.0, bandwidth: 1.0)
|
||||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||||
#expect(maxDiff > 0.0, "Audio-rate swept RBJ filter should differ from fixed-freq version")
|
||||
}
|
||||
|
||||
// MARK: DelayLine
|
||||
|
||||
@Test func delayLineGeneratorDelayProducesFiniteOutput() {
|
||||
let count: Int = 64
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let delayMod: BinaryOpGenerator = OscSin.Audio(freq: 2.0) * 0.005 + 0.01
|
||||
let delay: DelayLine = DelayLine(input: signal, maxDelay: 0.1, delay: delayMod, sampleRate: 44100)
|
||||
let samples: [Double] = delay.calculatedSamples(graph: graph, count: count)[0]
|
||||
#expect(samples.prefix(count).allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func delayLineGeneratorDelayDiffersFromScalar() {
|
||||
let count: Int = 64
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
// Use a large-amplitude modulator so the varying delay is clearly different from fixed
|
||||
let delayMod: ConstantGeneratorInput = ConstantGeneratorInput(0.005) // constant via Generator path
|
||||
let delayConst: Double = 0.005 as Double // literal scalar path
|
||||
let delayLineGen: DelayLine = DelayLine(input: signal, maxDelay: 0.1, delay: delayMod, sampleRate: 44100)
|
||||
let delayLineLit: DelayLine = DelayLine(input: OscSin.Audio(freq: 440.0), maxDelay: 0.1, delay: delayConst, sampleRate: 44100)
|
||||
let genSamples: [Double] = delayLineGen.calculatedSamples(graph: graph, count: count)[0]
|
||||
advanceBlock(engine)
|
||||
let litSamples: [Double] = delayLineLit.calculatedSamples(graph: graph, count: count)[0]
|
||||
// Both should produce finite, non-silent output (signal is passing through the delay)
|
||||
#expect(genSamples.prefix(count).allSatisfy { $0.isFinite })
|
||||
#expect(litSamples.prefix(count).allSatisfy { $0.isFinite })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FMSynthesis suite
|
||||
|
||||
@Suite("FMSynthesis")
|
||||
struct FMSynthesisTests {
|
||||
|
||||
let sampleRate: Double = 44100
|
||||
let blockSize: Int = 256
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 256, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
@Test func fmOutputDiffersFromConstantFrequencyOscillator() {
|
||||
let carrierFreq: Double = 440.0
|
||||
let modDepth: Double = 200.0
|
||||
let totalSamples: Int = 1024
|
||||
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
let fmCarrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||||
let constCarrier: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
|
||||
let fmSamples: [Double] = collectSamples(fmCarrier, engine: engine, totalSamples: totalSamples)
|
||||
let constSamples: [Double] = collectSamples(constCarrier, engine: engine, totalSamples: totalSamples)
|
||||
|
||||
let rmsSquared: Double = (0..<totalSamples).map {
|
||||
pow(Double(fmSamples[$0]) - Double(constSamples[$0]), 2)
|
||||
}.reduce(0, +)
|
||||
let rmsDiff: Double = sqrt(rmsSquared / Double(totalSamples))
|
||||
|
||||
// FM with modIndex ≈ 0.45 produces sidebands with ~22% amplitude → significant RMS difference
|
||||
#expect(rmsDiff > 0.05, "FM output should differ substantially from constant-freq version (rmsDiff=\(rmsDiff))")
|
||||
}
|
||||
|
||||
@Test func fmHasEnergyAtSidebandFrequency() {
|
||||
// modIndex = 1.0 → J_1(1.0) ≈ 0.44 (strong first sideband)
|
||||
let carrierFreq: Double = 441.0 // 100 samples/cycle at 44100 Hz
|
||||
let modulatorFreq: Double = 441.0
|
||||
let modDepth: Double = 441.0 // modIndex = depth / carrier = 1.0
|
||||
|
||||
let totalSamples: Int = 8820 // 88.2 cycles at 100 samples/cycle
|
||||
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: modulatorFreq)
|
||||
let fmCarrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||||
let constCarrier: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||||
|
||||
let fmSamples: [Double] = collectSamples(fmCarrier, engine: engine, totalSamples: totalSamples)
|
||||
let constSamples: [Double] = collectSamples(constCarrier, engine: engine, totalSamples: totalSamples)
|
||||
|
||||
// First upper sideband at carrier + modulator = 882 Hz
|
||||
let sidebandFreq: Double = 882.0
|
||||
let fmSidebandMag: Double = dftMagnitude(samples: fmSamples, freq: sidebandFreq, sampleRate: sampleRate)
|
||||
let constSidebandMag: Double = dftMagnitude(samples: constSamples, freq: sidebandFreq, sampleRate: sampleRate)
|
||||
|
||||
// FM should have strong sideband energy (J_1(1.0) ≈ 0.44 → expect > 0.1)
|
||||
#expect(fmSidebandMag > 0.1,
|
||||
"FM output should contain sideband energy at \(sidebandFreq) Hz (mag=\(fmSidebandMag))")
|
||||
// Constant sine should have negligible energy at sideband frequency
|
||||
#expect(constSidebandMag < 0.05,
|
||||
"Constant-freq sine should have no sideband energy (mag=\(constSidebandMag))")
|
||||
}
|
||||
|
||||
@Test func fmSynthExampleBuilds() {
|
||||
// Smoke-test the canonical FM synthesis example.
|
||||
class FMSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let modulatorFreq: Double = 440.0
|
||||
let carrierFreq: Double = 440.0
|
||||
let modDepth: Double = 200.0
|
||||
let modulator: OscSin.Audio = OscSin.Audio(freq: modulatorFreq)
|
||||
let carrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||||
output(bus: 0, source: carrier * 0.3)
|
||||
output(bus: 1, source: carrier * 0.3)
|
||||
}
|
||||
}
|
||||
let synth: FMSynth = FMSynth()
|
||||
synth.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
// BinaryOpGeneratorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Multi-channel test fixture — emits a fixed scalar per channel.
|
||||
/// Used to verify channel-aware broadcasting in BinaryOpGenerator.
|
||||
fileprivate final class StereoConstantGen: GeneratorBase, AudioGenerator {
|
||||
let leftValue: Double
|
||||
let rightValue: Double
|
||||
public override var outputChannelCount: Int { 2 }
|
||||
|
||||
init(left: Double, right: Double) {
|
||||
self.leftValue = left
|
||||
self.rightValue = right
|
||||
super.init(channels: 2)
|
||||
}
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = leftValue
|
||||
_result[1][i] = rightValue
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
/// 3-channel test fixture used to verify 3×3 element-wise composition.
|
||||
fileprivate final class TripleConstantGen: GeneratorBase, AudioGenerator {
|
||||
public override var outputChannelCount: Int { 3 }
|
||||
|
||||
init(_ a: Double, _ b: Double, _ c: Double) {
|
||||
super.init(channels: 3)
|
||||
for i: Int in 0..<_result[0].count {
|
||||
_result[0][i] = a
|
||||
_result[1][i] = b
|
||||
_result[2][i] = c
|
||||
}
|
||||
}
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
/// 4-channel test fixture used to verify Pan4-shape (4-row) broadcast paths.
|
||||
fileprivate final class QuadConstantGen: GeneratorBase, AudioGenerator {
|
||||
public override var outputChannelCount: Int { 4 }
|
||||
|
||||
init(_ a: Double, _ b: Double, _ c: Double, _ d: Double) {
|
||||
super.init(channels: 4)
|
||||
for i: Int in 0..<_result[0].count {
|
||||
_result[0][i] = a
|
||||
_result[1][i] = b
|
||||
_result[2][i] = c
|
||||
_result[3][i] = d
|
||||
}
|
||||
}
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("BinaryOpGenerator")
|
||||
struct BinaryOpGeneratorTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph {
|
||||
makeSynthGraph(engine: engine)
|
||||
}
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func multiplyTwoConstants() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (2.0 as Double) * ConstantAudioGen(3.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 6.0 })
|
||||
}
|
||||
|
||||
@Test func addTwoConstants() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(1.0) + (0.5 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 1.5 })
|
||||
}
|
||||
|
||||
@Test func subtractConstants() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(1.0) - (0.25 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.75 })
|
||||
}
|
||||
|
||||
@Test func divideConstants() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(4.0) / (2.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 2.0 })
|
||||
}
|
||||
|
||||
@Test func resultRateIsAudio() {
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(1.0) * ConstantAudioGen(1.0)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func countIsRespected() {
|
||||
let count: Int = 4
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(1.0) + (0.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
// The pre-allocated result buffer is sized to lyrebirdDefaultResultBufferSize;
|
||||
// only the first `count` elements are valid for this call.
|
||||
#expect(samples[0].count >= count)
|
||||
for i: Int in 0..<count {
|
||||
#expect(samples[0][i] == 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func floatValueUsesOp() {
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(3.0) * (2.0 as Double)
|
||||
#expect(gen.floatValue(graph: graph) == 6.0)
|
||||
}
|
||||
|
||||
@Test func chainedOps() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (ConstantAudioGen(2.0) * (3.0 as Double)) + (1.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 7.0 })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-channel broadcast
|
||||
|
||||
@Suite("BinaryOpGenerator multi-channel broadcast")
|
||||
struct BinaryOpGeneratorMultiChannelTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph {
|
||||
makeSynthGraph(engine: engine)
|
||||
}
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test("stereo × scalar produces 2-row result, both channels scaled")
|
||||
func stereoTimesScalar() {
|
||||
let count: Int = 8
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let gen: BinaryOpGenerator = stereo * (0.5 as Double)
|
||||
#expect(gen.outputChannelCount == 2)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples.count == 2)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.5 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 1.0 })
|
||||
}
|
||||
|
||||
@Test("scalar × stereo produces 2-row result")
|
||||
func scalarTimesStereo() {
|
||||
let count: Int = 8
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let gen: BinaryOpGenerator = (3.0 as Double) * stereo
|
||||
#expect(gen.outputChannelCount == 2)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 3.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 6.0 })
|
||||
}
|
||||
|
||||
@Test("mono generator + stereo generator broadcasts mono to both channels")
|
||||
func monoPlusStereoBroadcasts() {
|
||||
let count: Int = 8
|
||||
let mono: ConstantAudioGen = ConstantAudioGen(10.0)
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let gen: BinaryOpGenerator = mono + stereo
|
||||
#expect(gen.outputChannelCount == 2)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 11.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 12.0 })
|
||||
}
|
||||
|
||||
@Test("stereo + mono broadcasts mono on rhs")
|
||||
func stereoPlusMonoBroadcasts() {
|
||||
let count: Int = 8
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let mono: ConstantAudioGen = ConstantAudioGen(10.0)
|
||||
let gen: BinaryOpGenerator = stereo + mono
|
||||
#expect(gen.outputChannelCount == 2)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 11.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 12.0 })
|
||||
}
|
||||
|
||||
@Test("stereo + stereo is element-wise")
|
||||
func stereoPlusStereoElementWise() {
|
||||
let count: Int = 8
|
||||
let a: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let b: StereoConstantGen = StereoConstantGen(left: 10.0, right: 20.0)
|
||||
let gen: BinaryOpGenerator = a + b
|
||||
#expect(gen.outputChannelCount == 2)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 11.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 22.0 })
|
||||
}
|
||||
|
||||
@Test("stereo × stereo element-wise")
|
||||
func stereoTimesStereoElementWise() {
|
||||
let count: Int = 8
|
||||
let a: StereoConstantGen = StereoConstantGen(left: 2.0, right: 3.0)
|
||||
let b: StereoConstantGen = StereoConstantGen(left: 4.0, right: 5.0)
|
||||
let gen: BinaryOpGenerator = a * b
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 8.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 15.0 })
|
||||
}
|
||||
|
||||
@Test("ChannelSelect on multi-row BinaryOpGenerator extracts correct channel")
|
||||
func channelSelectOnBinaryOp() {
|
||||
let count: Int = 8
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 1.0, right: 2.0)
|
||||
let scaled: BinaryOpGenerator = stereo * (0.5 as Double)
|
||||
let right: ChannelSelect.Audio = scaled.channel(1)
|
||||
let samples: [[Double]] = right.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 1.0 })
|
||||
}
|
||||
|
||||
@Test("floatValue on N-row BinaryOpGenerator returns channel-0 sample-0")
|
||||
func floatValueReturnsFirstChannelFirstSample() {
|
||||
let stereo: StereoConstantGen = StereoConstantGen(left: 7.0, right: 100.0)
|
||||
let gen: BinaryOpGenerator = stereo * (2.0 as Double)
|
||||
#expect(gen.floatValue(graph: graph) == 14.0)
|
||||
}
|
||||
|
||||
@Test("outputChannelCount is max of operands")
|
||||
func outputChannelCountMaxOfOperands() {
|
||||
let stereoA: StereoConstantGen = StereoConstantGen(left: 1, right: 2)
|
||||
let stereoB: StereoConstantGen = StereoConstantGen(left: 3, right: 4)
|
||||
let monoA: ConstantAudioGen = ConstantAudioGen(1.0)
|
||||
let monoB: ConstantAudioGen = ConstantAudioGen(2.0)
|
||||
#expect((stereoA * monoA).outputChannelCount == 2)
|
||||
#expect((monoA * stereoA).outputChannelCount == 2)
|
||||
#expect((stereoA * stereoB).outputChannelCount == 2)
|
||||
#expect((monoA * monoB).outputChannelCount == 1)
|
||||
#expect((stereoA * (0.5 as Double)).outputChannelCount == 2)
|
||||
}
|
||||
|
||||
@Test("3-channel × 3-channel element-wise")
|
||||
func tripleTimesTripleElementWise() {
|
||||
let count: Int = 8
|
||||
let a: TripleConstantGen = TripleConstantGen(1.0, 2.0, 3.0)
|
||||
let b: TripleConstantGen = TripleConstantGen(10.0, 20.0, 30.0)
|
||||
let gen: BinaryOpGenerator = a * b
|
||||
#expect(gen.outputChannelCount == 3)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 10.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 40.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 90.0 })
|
||||
}
|
||||
|
||||
@Test("scalar × 3-channel broadcasts")
|
||||
func scalarTimesTriple() {
|
||||
let count: Int = 8
|
||||
let triple: TripleConstantGen = TripleConstantGen(1.0, 2.0, 3.0)
|
||||
let gen: BinaryOpGenerator = triple * (10.0 as Double)
|
||||
#expect(gen.outputChannelCount == 3)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 10.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 20.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 30.0 })
|
||||
}
|
||||
|
||||
@Test("mono + 4-channel broadcasts mono to all four channels")
|
||||
func monoPlusQuadBroadcasts() {
|
||||
let count: Int = 8
|
||||
let mono: ConstantAudioGen = ConstantAudioGen(100.0)
|
||||
let quad: QuadConstantGen = QuadConstantGen(1.0, 2.0, 3.0, 4.0)
|
||||
let gen: BinaryOpGenerator = mono + quad
|
||||
#expect(gen.outputChannelCount == 4)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples.count == 4)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 101.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 102.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 103.0 })
|
||||
#expect(samples[3].prefix(count).allSatisfy { $0 == 104.0 })
|
||||
}
|
||||
|
||||
@Test("4-channel × scalar scales every channel")
|
||||
func quadTimesScalar() {
|
||||
let count: Int = 8
|
||||
let quad: QuadConstantGen = QuadConstantGen(1.0, 2.0, 3.0, 4.0)
|
||||
let gen: BinaryOpGenerator = quad * (0.5 as Double)
|
||||
#expect(gen.outputChannelCount == 4)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.5 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 1.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 1.5 })
|
||||
#expect(samples[3].prefix(count).allSatisfy { $0 == 2.0 })
|
||||
}
|
||||
|
||||
@Test("4-channel + 4-channel element-wise (matches Pan4 + Pan4 shape)")
|
||||
func quadPlusQuadElementWise() {
|
||||
let count: Int = 8
|
||||
let a: QuadConstantGen = QuadConstantGen(1.0, 2.0, 3.0, 4.0)
|
||||
let b: QuadConstantGen = QuadConstantGen(10.0, 20.0, 30.0, 40.0)
|
||||
let gen: BinaryOpGenerator = a + b
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 11.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 22.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 33.0 })
|
||||
#expect(samples[3].prefix(count).allSatisfy { $0 == 44.0 })
|
||||
}
|
||||
|
||||
// The 2 × 3 mismatch trap (`precondition` at `BinaryOpGenerator.init`) is correctness-
|
||||
// critical but cannot be tested via Swift Testing — `precondition` terminates the
|
||||
// process rather than throwing. The trap's behavior is exercised manually and verified
|
||||
// by code review. The construction `StereoConstantGen() * TripleConstantGen()` would
|
||||
// trap with the message "BinaryOpGenerator: incompatible channel counts (2 vs 3) ...".
|
||||
}
|
||||
|
||||
// MARK: - Existential operator overloads (any ValidGeneratorInput op any ValidGeneratorInput)
|
||||
|
||||
@Suite("BinaryOpGenerator existential operators")
|
||||
struct BinaryOpGeneratorExistentialTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph {
|
||||
makeSynthGraph(engine: engine)
|
||||
}
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// These tests cover the `any ValidGeneratorInput op any ValidGeneratorInput` overloads.
|
||||
// All four operators are exercised with an existential-typed LHS so the compiler
|
||||
// cannot resolve to a stdlib or concrete-Generator overload.
|
||||
|
||||
@Test("existential * scalar produces correct output")
|
||||
func existentialTimesScalar() {
|
||||
let count: Int = 8
|
||||
let freq: any ValidGeneratorInput = 440.0
|
||||
let scaled: Double = 1.5
|
||||
let gen: BinaryOpGenerator = freq * scaled // (any ValidGeneratorInput) * (Double as any ValidGeneratorInput)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 440.0 * 1.5
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("existential + scalar produces correct output")
|
||||
func existentialPlusScalar() {
|
||||
let count: Int = 8
|
||||
let freq: any ValidGeneratorInput = 440.0
|
||||
let gen: BinaryOpGenerator = freq + (10.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 450.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("existential - scalar produces correct output")
|
||||
func existentialMinusScalar() {
|
||||
let count: Int = 8
|
||||
let freq: any ValidGeneratorInput = 440.0
|
||||
let gen: BinaryOpGenerator = freq - (40.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 400.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("existential / scalar produces correct output")
|
||||
func existentialDividedByScalar() {
|
||||
let count: Int = 8
|
||||
let freq: any ValidGeneratorInput = 440.0
|
||||
let gen: BinaryOpGenerator = freq / (2.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 220.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("existential op existential both non-generator produces BinaryOpGenerator")
|
||||
func existentialOpExistential() {
|
||||
let count: Int = 8
|
||||
let a: any ValidGeneratorInput = 3.0
|
||||
let b: any ValidGeneratorInput = 4.0
|
||||
let gen: BinaryOpGenerator = a * b
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 12.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
/// Regression guard: concrete `Double op Double` must still resolve to `Double`
|
||||
/// (stdlib overload), not `BinaryOpGenerator`. If the existential overloads above
|
||||
/// introduced ambiguity, this line would fail to compile with a type error.
|
||||
@Test("Double op Double still resolves to Double (stdlib wins)")
|
||||
func doubleOpDoubleRemainsDouble() {
|
||||
let a: Double = 440.0
|
||||
let b: Double = 1.5
|
||||
// These must be Double, not BinaryOpGenerator.
|
||||
// If our overloads caused ambiguity, the type annotations below would fail to compile.
|
||||
let product: Double = a * b
|
||||
let sum: Double = a + b
|
||||
let diff: Double = a - b
|
||||
let quot: Double = a / b
|
||||
#expect(product == 440.0 * 1.5)
|
||||
#expect(sum == 440.0 + 1.5)
|
||||
#expect(diff == 440.0 - 1.5)
|
||||
#expect(quot == 440.0 / 1.5)
|
||||
}
|
||||
|
||||
@Test("existential op produces a BinaryOpGenerator that is a Generator")
|
||||
func existentialOpResultIsGenerator() {
|
||||
let freq: any ValidGeneratorInput = 440.0
|
||||
let gen: BinaryOpGenerator = freq * (2.0 as Double)
|
||||
// The result must conform to Generator so it can be wired into a signal graph.
|
||||
#expect(gen is any Generator)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ConstantGeneratorInput
|
||||
|
||||
@Suite("ConstantGeneratorInput")
|
||||
struct ConstantGeneratorInputTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph {
|
||||
makeSynthGraph(engine: engine)
|
||||
}
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test("calculatedSamples returns all-constant block")
|
||||
func calculatedSamplesIsConstant() {
|
||||
let constantValue: Double = 440.0
|
||||
let count: Int = 8
|
||||
let gen: ConstantGeneratorInput = ConstantGeneratorInput(constantValue)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == constantValue })
|
||||
}
|
||||
|
||||
@Test("floatValue returns the constant directly")
|
||||
func floatValueReturnsConstant() {
|
||||
let constantValue: Double = 220.0
|
||||
let gen: ConstantGeneratorInput = ConstantGeneratorInput(constantValue)
|
||||
#expect(gen.floatValue(graph: graph) == constantValue)
|
||||
}
|
||||
|
||||
@Test("rate is audio")
|
||||
func rateIsAudio() {
|
||||
let gen: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test("needsInterpolation is false")
|
||||
func needsInterpolationIsFalse() {
|
||||
let gen: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
// ConstantGeneratorInput is an AudioGenerator → needsInterpolation() == false.
|
||||
#expect(gen.needsInterpolation() == false)
|
||||
}
|
||||
|
||||
@Test("ConstantGeneratorInput * scalar resolves via Category A overload")
|
||||
func constGenInputTimesScalar() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantGeneratorInput(440.0) * (2.0 as Double)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 880.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("ConstantGeneratorInput + OscSin wires correctly")
|
||||
func constGenInputPlusOscSin() {
|
||||
// Verifies ConstantGeneratorInput participates in the Generator op Generator path.
|
||||
let count: Int = 8
|
||||
let offset: ConstantGeneratorInput = ConstantGeneratorInput(100.0)
|
||||
let osc: ConstantAudioGen = ConstantAudioGen(440.0)
|
||||
let gen: BinaryOpGenerator = offset + osc // Generator + Generator → BinaryOpGenerator
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let expected: Double = 540.0
|
||||
#expect(samples[0].prefix(count).allSatisfy { abs($0 - expected) < 1e-9 })
|
||||
}
|
||||
|
||||
@Test("fan-out cache: calculatedSamples called twice returns same block")
|
||||
func fanOutCacheHit() {
|
||||
let count: Int = 8
|
||||
let gen: ConstantGeneratorInput = ConstantGeneratorInput(440.0)
|
||||
let first: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
let second: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
// Same segment serial → cache hit → identical buffer reference returned.
|
||||
for i: Int in 0..<count {
|
||||
#expect(first[0][i] == second[0][i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// BowedStringTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("BowedString")
|
||||
struct BowedStringTests {
|
||||
|
||||
// MARK: - Test fixture
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
let testMaxDelayTime: Double = 0.05
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
#expect(bowed.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = bowed.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Silent at zero excitation
|
||||
|
||||
@Test func silentAtZeroExcitation() {
|
||||
// With bowVelocity = 0 and zero-initialised delay lines, output must be near zero.
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
bowVelocity: 0.0,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = bowed.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-6 }
|
||||
#expect(allNearZero, "Output must be near zero with bowVelocity = 0")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent with excitation
|
||||
|
||||
@Test func nonSilentWithExcitation() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: 0.5,
|
||||
bowForce: 3.0,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
// Render several blocks to allow waveguide to build up.
|
||||
var lastSamples: [Double] = []
|
||||
for _ in 0..<10 {
|
||||
let out: [[Double]] = bowed.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
lastSamples = Array(out[0].prefix(512))
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let rms: Double = rmsValue(lastSamples)
|
||||
#expect(rms > 0, "BowedString must produce non-zero output with bowVelocity > 0")
|
||||
#expect(lastSamples.allSatisfy { $0.isFinite }, "All samples must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out single evaluation
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out1: [[Double]] = bowed.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = bowed.calculatedSamples(graph: graph, count: 512)
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - State advances across blocks
|
||||
|
||||
@Test func stateAdvancesAcrossBlocks() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
bowVelocity: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
_ = bowed.calculatedSamples(graph: graph, count: 512)
|
||||
_ = bowed.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block2: [[Double]] = bowed.calculatedSamples(graph: graph2, count: 512)
|
||||
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples must be finite after block advance")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let bowed1: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: ConstantGeneratorInput(0.5),
|
||||
bowForce: ConstantGeneratorInput(3.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let bowed2: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: ConstantGeneratorInput(0.5),
|
||||
bowForce: ConstantGeneratorInput(3.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out1: [Double] = Array(bowed1.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(bowed2.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
var relationshipHolds: Bool = true
|
||||
for i: Int in 0..<512 {
|
||||
let expected: Double = out1[i] * 2.0 + 1.0
|
||||
if abs(out2[i] - expected) > 1e-10 {
|
||||
relationshipHolds = false
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(relationshipHolds, "mul:2.0 add:1.0 must produce output × 2 + 1")
|
||||
}
|
||||
|
||||
// MARK: - Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class BowedSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: 0.5,
|
||||
sampleRate: 44100,
|
||||
maxDelayTime: 0.05
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: bowed))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: BowedSynth = BowedSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Finite after many blocks
|
||||
|
||||
@Test func finiteAfterManyBlocks() {
|
||||
let bowed: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: 0.5,
|
||||
bowForce: 3.0,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let blockCount: Int = 200
|
||||
var allFinite: Bool = true
|
||||
for _ in 0..<blockCount {
|
||||
let out: [[Double]] = bowed.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
if !samples.allSatisfy({ $0.isFinite }) {
|
||||
allFinite = false
|
||||
break
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allFinite, "BowedString must produce finite output for 200 blocks")
|
||||
}
|
||||
|
||||
// MARK: - Bow position affects tone
|
||||
|
||||
@Test func bowPositionAffectsTone() {
|
||||
// Warm up two instances with different bow positions; output must differ.
|
||||
let bowed1: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: 0.5,
|
||||
bowPosition: 0.05,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let bowed2: BowedString.Audio = BowedString.Audio(
|
||||
freq: 220.0,
|
||||
bowVelocity: 0.5,
|
||||
bowPosition: 0.4,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
// Run warm-up blocks to let waveguides develop.
|
||||
let warmupBlocks: Int = 20
|
||||
for b: Int in 0..<warmupBlocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = bowed1.calculatedSamples(graph: g, count: 512)
|
||||
_ = bowed2.calculatedSamples(graph: g, count: 512)
|
||||
advanceBlock(engine)
|
||||
_ = b
|
||||
}
|
||||
let gFinal: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [Double] = Array(bowed1.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(bowed2.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let identical: Bool = out1 == out2
|
||||
#expect(!identical, "Different bowPosition values must produce different output buffers")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
// BufferReadTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("BufferRead")
|
||||
struct BufferReadTests {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
func makeEngine(blockSize: Int = 16) throws -> SynthesisEngine {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
return engine
|
||||
}
|
||||
|
||||
/// Fill buffer frames with their index value per channel.
|
||||
/// ch 0: frame index value; ch 1: frame index + 100.0; etc.
|
||||
func makeRampBuffer(frames: Int, channelCount: Int = 1) -> LyrebirdBuffer {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: channelCount)
|
||||
for frame: Int in 0..<frames {
|
||||
for ch: Int in 0..<channelCount {
|
||||
buf.write(Double(frame) + Double(ch) * 100.0,
|
||||
frame: frame, channel: ch)
|
||||
}
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// MARK: - Audio — position semantics
|
||||
|
||||
@Test func audioPositionZeroReturnsFirstFrame() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 2)
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.0, interpolation: .none)
|
||||
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
for i: Int in 0..<16 {
|
||||
#expect(abs(out[0][i] - 0.0) < 1e-9,
|
||||
"ch0 sample \(i): expected 0.0, got \(out[0][i])")
|
||||
#expect(abs(out[1][i] - 100.0) < 1e-9,
|
||||
"ch1 sample \(i): expected 100.0, got \(out[1][i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioPositionOneReturnsLastFrame() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let frames: Int = 32
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: frames, channelCount: 2)
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 1.0, interpolation: .none)
|
||||
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
let lastFrame: Double = Double(frames - 1)
|
||||
for i: Int in 0..<16 {
|
||||
#expect(abs(out[0][i] - lastFrame) < 1e-9,
|
||||
"ch0 sample \(i): expected \(lastFrame), got \(out[0][i])")
|
||||
#expect(abs(out[1][i] - (lastFrame + 100.0)) < 1e-9,
|
||||
"ch1 sample \(i): expected \(lastFrame + 100.0), got \(out[1][i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioPositionHalfReturnsLinearMidpoint() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// 3-frame buffer: [0.0, 1.0, 2.0]
|
||||
// position=0.5 → frameF = 0.5 * 2.0 = 1.0 → exactly frame 1 = 1.0
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 3)
|
||||
buf.write(0.0, frame: 0, channel: 0)
|
||||
buf.write(1.0, frame: 1, channel: 0)
|
||||
buf.write(2.0, frame: 2, channel: 0)
|
||||
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.5, interpolation: .linear)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
#expect(abs(out[0][0] - 1.0) < 1e-9,
|
||||
"expected midpoint 1.0, got \(out[0][0])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioLinearInterpolationBetweenFrames() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// 2-frame buffer: [0.0, 10.0]
|
||||
// position=0.25 → frameF = 0.25 * 1.0 = 0.25 → lerp(0, 10, 0.25) = 2.5
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 2)
|
||||
buf.write(0.0, frame: 0, channel: 0)
|
||||
buf.write(10.0, frame: 1, channel: 0)
|
||||
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.25, interpolation: .linear)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
#expect(abs(out[0][0] - 2.5) < 1e-9,
|
||||
"expected 2.5, got \(out[0][0])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioStereoBothChannelsReadAtSamePosition() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let frames: Int = 16
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: frames, channelCount: 2)
|
||||
// position=0.5 → frameF = 0.5 * 15 = 7.5 → lerp(7, 8, 0.5) = 7.5 for ch0
|
||||
// → lerp(107, 108, 0.5) = 107.5 for ch1
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.5, interpolation: .linear)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
#expect(abs(out[0][0] - 7.5) < 1e-9,
|
||||
"ch0 expected 7.5, got \(out[0][0])")
|
||||
#expect(abs(out[1][0] - 107.5) < 1e-9,
|
||||
"ch1 expected 107.5, got \(out[1][0])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioInvalidBufferOutputsZero() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 16)
|
||||
buf.invalidate()
|
||||
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.5)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
for i: Int in 0..<16 {
|
||||
#expect(abs(out[0][i]) < 1e-9,
|
||||
"sample \(i): expected 0, got \(out[0][i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func audioMulAddApplied() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// buffer value at position=0.0 is 0.0 → (0.0 * 2.0) + 1.0 = 1.0
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 8)
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.0,
|
||||
interpolation: .none, mul: 2.0, add: 1.0)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
#expect(abs(out[0][0] - 1.0) < 1e-9,
|
||||
"expected (0*2)+1=1.0, got \(out[0][0])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Control variant
|
||||
|
||||
@Test func controlPositionZeroReturnsFirstFrame() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 2)
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf, position: 0.0, interpolation: .none)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
// Control ramps from 0→target. Initial _rampTargets = [0,0], target = [0, 100].
|
||||
// ch0 ramps 0→0, ch1 ramps 0→100. Last sample of ch1 should be 100.
|
||||
#expect(abs(out[0][15] - 0.0) < 1e-9,
|
||||
"ch0 last sample: expected 0.0, got \(out[0][15])")
|
||||
#expect(abs(out[1][15] - 100.0) < 1e-9,
|
||||
"ch1 last sample: expected 100.0, got \(out[1][15])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlMatchesAudioAtSamePosition() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// 10-frame mono buffer filled with frame index values.
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 10)
|
||||
let pos: Double = 0.5 // frameF = 0.5 * 9 = 4.5 → lerp(4, 5, 0.5) = 4.5
|
||||
|
||||
let audioReader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: pos, interpolation: .linear)
|
||||
let controlReader: BufferRead.Control = BufferRead.Control(buffer: buf, position: pos, interpolation: .linear)
|
||||
|
||||
let audioOut: [[Double]] = audioReader.calculatedSamples(graph: graph, count: 1)
|
||||
let controlOut: [[Double]] = controlReader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
// Audio gives exact result; Control last sample = target = same value.
|
||||
#expect(abs(audioOut[0][0] - 4.5) < 1e-9,
|
||||
"audio: expected 4.5, got \(audioOut[0][0])")
|
||||
#expect(abs(controlOut[0][0] - 4.5) < 1e-9,
|
||||
"control: expected 4.5, got \(controlOut[0][0])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlInvalidBufferOutputsZero() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 16)
|
||||
buf.invalidate()
|
||||
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf, position: 0.5)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
for i: Int in 0..<16 {
|
||||
#expect(abs(out[0][i]) < 1e-9,
|
||||
"sample \(i): expected 0, got \(out[0][i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlMulAddApplied() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// buffer value at position=1.0 is 9.0 for a 10-frame buffer.
|
||||
// _rampTargets starts at 0, ramps to 9.0 over 16 samples.
|
||||
// last sample = (9.0 * 2.0) + 1.0 = 19.0
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 10)
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf, position: 1.0,
|
||||
interpolation: .none, mul: 2.0, add: 1.0)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
#expect(abs(out[0][15] - 19.0) < 1e-9,
|
||||
"expected (9*2)+1=19.0 at last sample, got \(out[0][15])")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Generator-input position (exercises _position.calculatedSamples / floatValue paths)
|
||||
|
||||
@Test func audioPositionDrivenByGenerator() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// 5-frame mono buffer: [0, 10, 20, 30, 40]
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 5)
|
||||
for f: Int in 0..<5 { buf.write(Double(f) * 10.0, frame: f, channel: 0) }
|
||||
|
||||
// Closure drives position: sample 0 → 0.0, sample 1 → 0.5, sample 2 → 1.0
|
||||
var sampleIndex: Int = 0
|
||||
let positions: [Double] = [0.0, 0.5, 1.0]
|
||||
let posGen: Closure = Closure { _, _ in
|
||||
let v: Double = sampleIndex < positions.count ? positions[sampleIndex] : 0.0
|
||||
sampleIndex += 1
|
||||
return v
|
||||
}
|
||||
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: posGen, interpolation: .linear)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 3)
|
||||
|
||||
// pos=0.0 → frameF=0.0 → 0.0
|
||||
#expect(abs(out[0][0] - 0.0) < 1e-9, "pos=0.0: expected 0.0, got \(out[0][0])")
|
||||
// pos=0.5 → frameF=2.0 → exactly frame 2 = 20.0
|
||||
#expect(abs(out[0][1] - 20.0) < 1e-9, "pos=0.5: expected 20.0, got \(out[0][1])")
|
||||
// pos=1.0 → frameF=4.0 → frame 4 = 40.0
|
||||
#expect(abs(out[0][2] - 40.0) < 1e-9, "pos=1.0: expected 40.0, got \(out[0][2])")
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlPositionDrivenByGenerator() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// 5-frame mono buffer: [0, 10, 20, 30, 40]
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 5)
|
||||
for f: Int in 0..<5 { buf.write(Double(f) * 10.0, frame: f, channel: 0) }
|
||||
|
||||
// Closure returns 0.75: frameF = 0.75 * 4 = 3.0 → frame 3 = 30.0
|
||||
let posGen: Closure = Closure { _, _ in 0.75 }
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf, position: posGen, interpolation: .none)
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 1)
|
||||
|
||||
// Ramps from 0 → 30.0; count=1 so last sample = target = 30.0
|
||||
#expect(abs(out[0][0] - 30.0) < 1e-9, "expected 30.0, got \(out[0][0])")
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Rate checks
|
||||
|
||||
@Test func audioRateIsAudio() {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16)
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf)
|
||||
#expect(reader.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func controlRateIsControl() {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16)
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf)
|
||||
#expect(reader.rate == .control)
|
||||
}
|
||||
|
||||
// MARK: - Live buffer swap
|
||||
|
||||
/// Drain freeQueue synchronously so swapped-out buffer refs can be released
|
||||
/// without waiting on the 5ms background timer.
|
||||
private func drainFreeQueue(_ engine: SynthesisEngine) {
|
||||
// Drain both the engine's free queue (for synth/group releases) and the
|
||||
// RTBufferSlot kill queue (for displaced buffer releases).
|
||||
while let ref: Unmanaged<AnyObject> = engine.freeQueue.dequeue() {
|
||||
ref.release()
|
||||
}
|
||||
_ = engine.drainBufferSwapKillQueue()
|
||||
}
|
||||
|
||||
@Test func audioSetBufferReadsFromNewBuffer() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let first: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 1) // value == frame index
|
||||
let second: LyrebirdBuffer = LyrebirdBuffer(count: 32, channelCount: 1)
|
||||
second.fill(with: 42.0)
|
||||
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: first, position: 0.5, interpolation: .none)
|
||||
|
||||
let before: [[Double]] = reader.calculatedSamples(graph: graph, count: 8)
|
||||
// first buffer at position 0.5 = frame 15 (index 15 in 32-frame ramp) → 15.0
|
||||
for i: Int in 0..<8 {
|
||||
#expect(abs(before[0][i] - 15.0) < 1e-9, "before-swap sample \(i): expected 15.0, got \(before[0][i])")
|
||||
}
|
||||
|
||||
reader.setBuffer(second, engine: engine)
|
||||
advanceBlock(engine)
|
||||
|
||||
let after: [[Double]] = reader.calculatedSamples(graph: graph, count: 8)
|
||||
for i: Int in 0..<8 {
|
||||
#expect(abs(after[0][i] - 42.0) < 1e-9, "after-swap sample \(i): expected 42.0, got \(after[0][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func audioSetBufferToNilOutputsSilence() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 1)
|
||||
let reader: BufferRead.Audio = BufferRead.Audio(buffer: buf, position: 0.5, interpolation: .none)
|
||||
|
||||
reader.setBuffer(nil, engine: engine)
|
||||
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 8)
|
||||
for i: Int in 0..<8 {
|
||||
#expect(out[0][i] == 0.0, "expected silence at sample \(i), got \(out[0][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func audioSetBufferEnqueuesPreviousBufferRef() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let reader: BufferRead.Audio
|
||||
do {
|
||||
let first: LyrebirdBuffer = LyrebirdBuffer(count: 16, channelCount: 1)
|
||||
weakRef = first
|
||||
reader = BufferRead.Audio(buffer: first)
|
||||
}
|
||||
#expect(weakRef != nil, "Reader's slot must keep the initial buffer alive")
|
||||
|
||||
reader.setBuffer(nil, engine: engine)
|
||||
// Trigger a compute pass so the slot drains pending and pushes the displaced
|
||||
// buffer to engine.bufferSwapKillQueue.
|
||||
_ = reader.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
#expect(weakRef != nil, "Buffer enqueued but not yet released")
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Buffer should be deallocated after freeQueue drain")
|
||||
_ = reader
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlSetBufferReadsFromNewBuffer() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 4)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let first: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 1)
|
||||
let second: LyrebirdBuffer = LyrebirdBuffer(count: 32, channelCount: 1)
|
||||
second.fill(with: 7.5)
|
||||
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: first, position: 1.0, interpolation: .none)
|
||||
|
||||
// Warm the ramp so previousOutputValue tracks the first buffer.
|
||||
_ = reader.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
_ = reader.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
|
||||
reader.setBuffer(second, engine: engine)
|
||||
|
||||
// After the swap, target becomes 7.5; with count=4, last sample = 7.5.
|
||||
let after: [[Double]] = reader.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(abs(after[0][3] - 7.5) < 1e-9, "last-block sample should reach 7.5, got \(after[0][3])")
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func controlSetBufferToNilOutputsSilence() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32, channelCount: 1)
|
||||
let reader: BufferRead.Control = BufferRead.Control(buffer: buf, position: 1.0)
|
||||
|
||||
reader.setBuffer(nil, engine: engine)
|
||||
|
||||
let out: [[Double]] = reader.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(out[0][i] == 0.0, "expected silence at sample \(i), got \(out[0][i])")
|
||||
}
|
||||
#expect(reader.previousOutputValue == 0.0)
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
// BufferSlotAdoptionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Live-buffer-swap tests for Phase-C RTBufferSlot adoption sites.
|
||||
/// Per-generator tests verify (1) swap takes effect on the next block, (2) swap to nil
|
||||
/// silences output, (3) the previously installed buffer is released after the engine's
|
||||
/// freeQueue drains.
|
||||
@Suite("BufferSlot adoption — Phase C")
|
||||
struct BufferSlotAdoptionTests {
|
||||
|
||||
/// Drain freeQueue synchronously (mirrors SynthesisEngine.stop() loop) so the
|
||||
/// swapped-out retained buffer ref is released without waiting on the background
|
||||
/// timer.
|
||||
private func drainFreeQueue(_ engine: SynthesisEngine) {
|
||||
// Drain both the engine's free queue (for synth/group releases) and the
|
||||
// RTBufferSlot kill queue (for displaced buffer releases).
|
||||
while let ref: Unmanaged<AnyObject> = engine.freeQueue.dequeue() {
|
||||
ref.release()
|
||||
}
|
||||
_ = engine.drainBufferSwapKillQueue()
|
||||
}
|
||||
|
||||
// MARK: - OscTable
|
||||
|
||||
@Test func oscTableSetTableSwitchesWaveform() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let tableSize: Int = 8
|
||||
let tableA: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||
tableA.fill { i, _ in Double(i) }
|
||||
let tableB: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||
tableB.fill(with: 42.0)
|
||||
|
||||
// Step exactly one table entry per sample so each sample reads a different
|
||||
// frame. Freq = sampleRate / tableSize.
|
||||
let osc: OscTable.Audio = OscTable.Audio(
|
||||
table: tableA,
|
||||
freq: 44100.0 / Double(tableSize),
|
||||
interpolation: .none
|
||||
)
|
||||
|
||||
let before: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(before[0][i] - Double(i)) < 1e-9, "before sample \(i): expected \(i), got \(before[0][i])")
|
||||
}
|
||||
|
||||
osc.setTable(tableB, engine: engine)
|
||||
advanceBlock(engine)
|
||||
|
||||
let after: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(after[0][i] - 42.0) < 1e-9, "after sample \(i): expected 42.0, got \(after[0][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func oscTableSetTableToNilOutputsSilence() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
||||
table.fill { i, _ in Double(i) }
|
||||
let osc: OscTable.Audio = OscTable.Audio(table: table, freq: 44100.0 / 8.0, interpolation: .none)
|
||||
osc.setTable(nil, engine: engine)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(out[0][i] == 0.0, "expected silence at \(i), got \(out[0][i])")
|
||||
}
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func oscTableSetTableEnqueuesPreviousTable() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let osc: OscTable.Audio
|
||||
do {
|
||||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
||||
weakRef = table
|
||||
osc = OscTable.Audio(table: table, freq: 1.0)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
osc.setTable(nil, engine: engine)
|
||||
// Trigger a compute pass so the slot drains its pending swap and pushes the
|
||||
// displaced buffer to engine.bufferSwapKillQueue.
|
||||
_ = osc.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Initial table should be deallocated after drain")
|
||||
_ = osc
|
||||
}
|
||||
|
||||
// MARK: - PlayBuffer
|
||||
|
||||
@Test func playBufferSetBufferSwitchesSource() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let bufA: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
||||
bufA.fill { i, _ in Double(i) } // 0,1,2,…,7
|
||||
let bufB: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
||||
bufB.fill(with: 99.0)
|
||||
|
||||
let player: PlayBuffer.Audio = PlayBuffer.Audio(buffer: bufA, loop: true, interpolation: .none, rate: 1.0)
|
||||
let before: [[Double]] = player.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(before[0][i] - Double(i)) < 1e-9, "before sample \(i): expected \(i), got \(before[0][i])")
|
||||
}
|
||||
|
||||
player.setBuffer(bufB, engine: engine)
|
||||
advanceBlock(engine)
|
||||
|
||||
let after: [[Double]] = player.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(after[0][i] - 99.0) < 1e-9, "after sample \(i): expected 99.0, got \(after[0][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func playBufferSetBufferToNilOutputsSilence() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
||||
buf.fill { i, _ in Double(i) }
|
||||
let player: PlayBuffer.Audio = PlayBuffer.Audio(buffer: buf, loop: true)
|
||||
player.setBuffer(nil, engine: engine)
|
||||
let out: [[Double]] = player.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(out[0][i] == 0.0)
|
||||
}
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
// MARK: - SpectralBinDelay
|
||||
|
||||
@Test func spectralBinDelaySetDelayTimesEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let fftSize: Int = 64
|
||||
let halfSize: Int = fftSize / 2
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let bd: SpectralBinDelay
|
||||
let spectralBuf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||||
do {
|
||||
let dts: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
|
||||
let fbs: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
|
||||
weakRef = dts
|
||||
bd = SpectralBinDelay(
|
||||
fftSize: fftSize, hopSize: 16, maxDelaySeconds: 0.1,
|
||||
sampleRate: 44100, delayTimes: dts, feedbacks: fbs
|
||||
)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
bd.setDelayTimes(nil, engine: engine)
|
||||
bd.process(spectral: spectralBuf, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old delay-times buffer should be released after drain")
|
||||
_ = bd
|
||||
}
|
||||
|
||||
@Test func spectralBinDelaySetFeedbacksAcceptsValidBuffer() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let fftSize: Int = 64
|
||||
let halfSize: Int = fftSize / 2
|
||||
let dts: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
|
||||
let fbs: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
|
||||
let bd: SpectralBinDelay = SpectralBinDelay(
|
||||
fftSize: fftSize, hopSize: 16, maxDelaySeconds: 0.1,
|
||||
sampleRate: 44100, delayTimes: dts, feedbacks: fbs
|
||||
)
|
||||
let fbs2: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
|
||||
fbs2.fill(with: 0.5)
|
||||
bd.setFeedbacks(fbs2, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
_ = bd
|
||||
}
|
||||
|
||||
// MARK: - SpectralMagnitudeMap
|
||||
|
||||
@Test func spectralMagnitudeMapSetBufferEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let map: SpectralMagnitudeMap
|
||||
do {
|
||||
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 16)
|
||||
curve.fill { i, n in Double(i) / Double(n - 1) }
|
||||
weakRef = curve
|
||||
map = SpectralMagnitudeMap(buffer: curve)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
let next: LyrebirdBuffer = LyrebirdBuffer(count: 16)
|
||||
next.fill(with: 0.25)
|
||||
map.setBuffer(next, engine: engine)
|
||||
// Trigger a process pass with non-zero magnitudes so map.process reaches the
|
||||
// slot.load(engine:) path that drains pending and pushes the old curve.
|
||||
let spectralBuf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
spectralBuf[magnitude: 5] = 1.0
|
||||
map.process(spectral: spectralBuf, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old transfer curve should be released after drain")
|
||||
_ = map
|
||||
}
|
||||
|
||||
// MARK: - ResonatorBank
|
||||
|
||||
@Test func resonatorBankSetBufferRequiresMatchingShape() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 4, channelCount: 3) // bankSize = 4
|
||||
for k: Int in 0..<4 {
|
||||
buf.setValue(440.0 * Double(k + 1), frame: k, channel: 0)
|
||||
buf.setValue(0.5, frame: k, channel: 1)
|
||||
buf.setValue(0.1, frame: k, channel: 2)
|
||||
}
|
||||
let bank: ResonatorBank.Audio = ResonatorBank.Audio(input: 0.0 as Double, buffer: buf)
|
||||
// Same shape — should swap cleanly.
|
||||
let next: LyrebirdBuffer = LyrebirdBuffer(count: 4, channelCount: 3)
|
||||
for k: Int in 0..<4 {
|
||||
next.setValue(330.0 * Double(k + 1), frame: k, channel: 0)
|
||||
next.setValue(0.5, frame: k, channel: 1)
|
||||
next.setValue(0.05, frame: k, channel: 2)
|
||||
}
|
||||
bank.setBuffer(next, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
// Swap to nil silences.
|
||||
bank.setBuffer(nil, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
_ = bank
|
||||
}
|
||||
|
||||
@Test func resonatorBankSetBufferEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let bank: ResonatorBank.Audio
|
||||
do {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 2, channelCount: 3)
|
||||
for k: Int in 0..<2 {
|
||||
buf.setValue(440.0, frame: k, channel: 0)
|
||||
buf.setValue(0.5, frame: k, channel: 1)
|
||||
buf.setValue(0.1, frame: k, channel: 2)
|
||||
}
|
||||
weakRef = buf
|
||||
bank = ResonatorBank.Audio(input: 0.0 as Double, buffer: buf)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
bank.setBuffer(nil, engine: engine)
|
||||
_ = bank.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old mode-table buffer should be released after drain")
|
||||
_ = bank
|
||||
}
|
||||
|
||||
// MARK: - BufferGrain
|
||||
|
||||
@Test func bufferGrainSetBufferEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let grain: BufferGrain
|
||||
do {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
weakRef = buf
|
||||
grain = BufferGrain(buffer: buf)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
grain.setBuffer(nil, engine: engine)
|
||||
_ = grain.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old grain source should be released after drain")
|
||||
_ = grain
|
||||
}
|
||||
|
||||
@Test func bufferGrainSetWindowFallsBackToHanningOnNil() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
let win: LyrebirdBuffer = LyrebirdBuffer(count: 256)
|
||||
win.fill(with: 0.5)
|
||||
let grain: BufferGrain = BufferGrain(buffer: buf, window: win)
|
||||
grain.setWindow(nil, engine: engine)
|
||||
drainFreeQueue(engine)
|
||||
_ = grain
|
||||
}
|
||||
|
||||
// MARK: - SineGrain / FMGrain / InputGrain — window swap
|
||||
|
||||
@Test func sineGrainSetWindowEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let grain: SineGrain
|
||||
do {
|
||||
let win: LyrebirdBuffer = LyrebirdBuffer(count: 256)
|
||||
win.fill(with: 0.5)
|
||||
weakRef = win
|
||||
grain = SineGrain(window: win)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
grain.setWindow(nil, engine: engine)
|
||||
_ = grain.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old window should be released after drain")
|
||||
_ = grain
|
||||
}
|
||||
|
||||
@Test func fmGrainSetWindowEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let grain: FMGrain
|
||||
do {
|
||||
let win: LyrebirdBuffer = LyrebirdBuffer(count: 256)
|
||||
win.fill(with: 0.5)
|
||||
weakRef = win
|
||||
grain = FMGrain(window: win)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
grain.setWindow(nil, engine: engine)
|
||||
_ = grain.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil)
|
||||
_ = grain
|
||||
}
|
||||
|
||||
@Test func inputGrainSetWindowEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let grain: InputGrain
|
||||
do {
|
||||
let win: LyrebirdBuffer = LyrebirdBuffer(count: 256)
|
||||
win.fill(with: 0.5)
|
||||
weakRef = win
|
||||
grain = InputGrain(input: 0.0 as Double, window: win)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
grain.setWindow(nil, engine: engine)
|
||||
_ = grain.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil)
|
||||
_ = grain
|
||||
}
|
||||
|
||||
// MARK: - VectorOscillator
|
||||
|
||||
@Test func vectorOscillatorSetBufferASwitchesCorner() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let size: Int = 8
|
||||
let a: LyrebirdBuffer = LyrebirdBuffer(count: size); a.fill(with: 1.0)
|
||||
let b: LyrebirdBuffer = LyrebirdBuffer(count: size); b.fill(with: 1.0)
|
||||
let c: LyrebirdBuffer = LyrebirdBuffer(count: size); c.fill(with: 1.0)
|
||||
let d: LyrebirdBuffer = LyrebirdBuffer(count: size); d.fill(with: 1.0)
|
||||
let osc: VectorOscillator.Audio = VectorOscillator.Audio(
|
||||
bufferA: a, bufferB: b, bufferC: c, bufferD: d,
|
||||
freq: 0.0, x: 0.0, y: 0.0, interpolation: .none
|
||||
)
|
||||
// x=0, y=0 → reads bufferA. All ones → output is 1.0.
|
||||
let before: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(before[0][i] - 1.0) < 1e-9, "before swap: expected 1.0, got \(before[0][i])")
|
||||
}
|
||||
// Swap A to a buffer of zeros — output should drop to 0.
|
||||
let a2: LyrebirdBuffer = LyrebirdBuffer(count: size); a2.fill(with: 0.0)
|
||||
osc.setBufferA(a2, engine: engine)
|
||||
advanceBlock(engine)
|
||||
let after: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(abs(after[0][i] - 0.0) < 1e-9, "after swap: expected 0.0, got \(after[0][i])")
|
||||
}
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func vectorOscillatorSetCornerToNilSilencesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let size: Int = 8
|
||||
let a: LyrebirdBuffer = LyrebirdBuffer(count: size); a.fill(with: 1.0)
|
||||
let b: LyrebirdBuffer = LyrebirdBuffer(count: size); b.fill(with: 1.0)
|
||||
let c: LyrebirdBuffer = LyrebirdBuffer(count: size); c.fill(with: 1.0)
|
||||
let d: LyrebirdBuffer = LyrebirdBuffer(count: size); d.fill(with: 1.0)
|
||||
let osc: VectorOscillator.Audio = VectorOscillator.Audio(bufferA: a, bufferB: b, bufferC: c, bufferD: d,
|
||||
freq: 0.0, x: 0.5, y: 0.5)
|
||||
osc.setBufferB(nil, engine: engine)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
for i: Int in 0..<4 {
|
||||
#expect(out[0][i] == 0.0)
|
||||
}
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
// MARK: - TimeStretch
|
||||
|
||||
@Test func timeStretchSetBufferEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let ts: TimeStretch.Audio
|
||||
do {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
weakRef = buf
|
||||
ts = TimeStretch.Audio(buffer: buf)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
ts.setBuffer(nil, engine: engine)
|
||||
_ = ts.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil)
|
||||
_ = ts
|
||||
}
|
||||
|
||||
@Test func timeStretchSetWindowEnqueuesPrevious() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
weak var weakRef: LyrebirdBuffer?
|
||||
let ts: TimeStretch.Audio
|
||||
do {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||||
let win: LyrebirdBuffer = LyrebirdBuffer(count: 256)
|
||||
win.fill(with: 0.5)
|
||||
weakRef = win
|
||||
ts = TimeStretch.Audio(buffer: buf, window: win)
|
||||
}
|
||||
#expect(weakRef != nil)
|
||||
ts.setWindow(nil, engine: engine)
|
||||
_ = ts.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 1)
|
||||
drainFreeQueue(engine)
|
||||
#expect(weakRef == nil, "Old window should be released after drain")
|
||||
_ = ts
|
||||
}
|
||||
|
||||
// MARK: - OscTable.Control + PlayBuffer.Control (Control-variant swap coverage)
|
||||
|
||||
@Test func oscTableControlSetTableSwitchesWaveform() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let tableSize: Int = 8
|
||||
let tableA: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||
tableA.fill(with: 1.0)
|
||||
let tableB: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||
tableB.fill(with: -1.0)
|
||||
|
||||
// freq=0 → phase doesn't advance → output ramps toward table value at phase 0.
|
||||
let osc: OscTable.Control = OscTable.Control(table: tableA, freq: 0.0, interpolation: .none)
|
||||
|
||||
// Warm ramp toward 1.0.
|
||||
for _ in 0..<3 {
|
||||
_ = osc.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
osc.setTable(tableB, engine: engine)
|
||||
advanceBlock(engine)
|
||||
|
||||
// After swap + several blocks the ramp converges toward -1.0.
|
||||
var lastVal: Double = 0
|
||||
for _ in 0..<8 {
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
lastVal = out[0][3]
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(abs(lastVal - (-1.0)) < 1e-6, "control ramp should reach -1.0 after swap, got \(lastVal)")
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func playBufferControlSetBufferReadsFromNewBuffer() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let bufA: LyrebirdBuffer = LyrebirdBuffer(count: 8); bufA.fill(with: 1.0)
|
||||
let bufB: LyrebirdBuffer = LyrebirdBuffer(count: 8); bufB.fill(with: -1.0)
|
||||
let player: PlayBuffer.Control = PlayBuffer.Control(buffer: bufA, loop: true, rate: 0.0)
|
||||
|
||||
// Warm ramp toward 1.0.
|
||||
for _ in 0..<3 {
|
||||
_ = player.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
player.setBuffer(bufB, engine: engine)
|
||||
advanceBlock(engine)
|
||||
|
||||
var lastVal: Double = 0
|
||||
for _ in 0..<8 {
|
||||
let out: [[Double]] = player.calculatedSamples(graph: graph, count: 4)
|
||||
lastVal = out[0][3]
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(abs(lastVal - (-1.0)) < 1e-6, "control ramp should reach -1.0 after swap, got \(lastVal)")
|
||||
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
|
||||
@Test func playBufferControlSetBufferToNilOutputsSilence() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 8); buf.fill(with: 1.0)
|
||||
let player: PlayBuffer.Control = PlayBuffer.Control(buffer: buf, loop: true, rate: 0.0)
|
||||
player.setBuffer(nil, engine: engine)
|
||||
// Drive blocks; ramp converges toward 0.
|
||||
var lastVal: Double = 0
|
||||
for _ in 0..<8 {
|
||||
let out: [[Double]] = player.calculatedSamples(graph: graph, count: 4)
|
||||
lastVal = out[0][3]
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(abs(lastVal) < 1e-6, "control ramp should reach 0 after swap-to-nil, got \(lastVal)")
|
||||
engine.stop()
|
||||
drainFreeQueue(engine)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// HRIRFileTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test Data helpers
|
||||
|
||||
/// Appends a `UInt32` in little-endian byte order.
|
||||
private func appendLE32(_ v: UInt32, to data: inout Data) {
|
||||
var le: UInt32 = v.littleEndian
|
||||
withUnsafeBytes(of: &le) { data.append(contentsOf: $0) }
|
||||
}
|
||||
|
||||
/// Appends a `Double` (as its bit pattern) in little-endian byte order.
|
||||
private func appendLEDouble(_ v: Double, to data: inout Data) {
|
||||
var le: UInt64 = v.bitPattern.littleEndian
|
||||
withUnsafeBytes(of: &le) { data.append(contentsOf: $0) }
|
||||
}
|
||||
|
||||
/// Appends an `Int16` in little-endian byte order.
|
||||
private func appendLE16(_ v: Int16, to data: inout Data) {
|
||||
var le: Int16 = v.littleEndian
|
||||
withUnsafeBytes(of: &le) { data.append(contentsOf: $0) }
|
||||
}
|
||||
|
||||
/// Builds a minimal valid `.lbhr` blob with the given header values and
|
||||
/// writes it to a temporary URL. Returns both the URL and the `Data`.
|
||||
/// Caller is responsible for cleanup via `FileManager.default.removeItem(at:)`.
|
||||
private func makeMinimalLBHR(
|
||||
magic: [UInt8] = [0x4C, 0x42, 0x48, 0x52], // "LBHR"
|
||||
version: UInt32 = 1,
|
||||
sampleRate: UInt32 = 44_100,
|
||||
irLength: UInt32 = 4,
|
||||
positionCount: UInt32 = 1
|
||||
) throws -> (url: URL, data: Data) {
|
||||
let tmpURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("test-\(UUID().uuidString).lbhr")
|
||||
|
||||
var bytes: Data = Data()
|
||||
bytes.append(contentsOf: magic)
|
||||
appendLE32(version, to: &bytes)
|
||||
appendLE32(sampleRate, to: &bytes)
|
||||
appendLE32(irLength, to: &bytes)
|
||||
appendLE32(positionCount, to: &bytes)
|
||||
appendLE32(0, to: &bytes) // reserved
|
||||
|
||||
// Position table entries: one per positionCount.
|
||||
for i: Int in 0..<Int(positionCount) {
|
||||
appendLEDouble(0.0, to: &bytes) // azimuth
|
||||
appendLEDouble(0.0, to: &bytes) // elevation
|
||||
appendLE32(UInt32(i * 2 * Int(irLength)), to: &bytes) // sampleOffset
|
||||
appendLE32(0, to: &bytes) // reserved
|
||||
}
|
||||
|
||||
// Samples: positionCount × 2 × irLength × i16 (all zeros).
|
||||
let sampleCount: Int = Int(positionCount) * 2 * Int(irLength)
|
||||
for _ in 0..<sampleCount {
|
||||
appendLE16(0, to: &bytes)
|
||||
}
|
||||
|
||||
try bytes.write(to: tmpURL)
|
||||
return (tmpURL, bytes)
|
||||
}
|
||||
|
||||
// MARK: - Suite
|
||||
|
||||
@Suite("HRIRFile")
|
||||
struct HRIRFileTests {
|
||||
|
||||
// MARK: - Negative tests: invalid files are rejected
|
||||
|
||||
@Test func invalidMagicIsRejected() throws {
|
||||
let (url, validData) = try makeMinimalLBHR()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
// Corrupt the first magic byte.
|
||||
var bad: Data = validData
|
||||
bad[0] = 0x00
|
||||
try bad.write(to: url)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: url)
|
||||
Issue.record("Expected .invalidMagic error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.invalidMagic {
|
||||
// expected
|
||||
} catch {
|
||||
Issue.record("Expected .invalidMagic, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func truncatedFileIsRejected() throws {
|
||||
let tmpURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("truncated-\(UUID().uuidString).lbhr")
|
||||
defer { try? FileManager.default.removeItem(at: tmpURL) }
|
||||
|
||||
// Write only the magic — not even the full header.
|
||||
let short: Data = Data([0x4C, 0x42, 0x48, 0x52])
|
||||
try short.write(to: tmpURL)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: tmpURL)
|
||||
Issue.record("Expected .truncated error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.truncated {
|
||||
// expected
|
||||
} catch {
|
||||
Issue.record("Expected .truncated, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func wrongVersionIsRejected() throws {
|
||||
let (url, data) = try makeMinimalLBHR(version: 99)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try data.write(to: url)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: url)
|
||||
Issue.record("Expected .unsupportedVersion error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.unsupportedVersion(let v) {
|
||||
#expect(v == 99)
|
||||
} catch {
|
||||
Issue.record("Expected .unsupportedVersion, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func positionCountZeroIsRejected() throws {
|
||||
let (url, data) = try makeMinimalLBHR(positionCount: 0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try data.write(to: url)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: url)
|
||||
Issue.record("Expected .invalidPositionCount error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.invalidPositionCount(let n) {
|
||||
#expect(n == 0)
|
||||
} catch {
|
||||
Issue.record("Expected .invalidPositionCount, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func irLengthZeroIsRejected() throws {
|
||||
let (url, data) = try makeMinimalLBHR(irLength: 0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try data.write(to: url)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: url)
|
||||
Issue.record("Expected .invalidIRLength error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.invalidIRLength(let n) {
|
||||
#expect(n == 0)
|
||||
} catch {
|
||||
Issue.record("Expected .invalidIRLength, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func sampleRateZeroIsRejected() throws {
|
||||
let (url, data) = try makeMinimalLBHR(sampleRate: 0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try data.write(to: url)
|
||||
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: url)
|
||||
Issue.record("Expected .invalidSampleRate error, but load succeeded")
|
||||
} catch HRIRFile.LoadError.invalidSampleRate(let r) {
|
||||
#expect(r == 0)
|
||||
} catch {
|
||||
Issue.record("Expected .invalidSampleRate, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func nonexistentFileThrowsIOError() {
|
||||
let missing: URL = URL(fileURLWithPath: "/tmp/does-not-exist-\(UUID().uuidString).lbhr")
|
||||
do {
|
||||
_ = try HRIRFile.load(contentsOf: missing)
|
||||
Issue.record("Expected .ioError for nonexistent file, but load succeeded")
|
||||
} catch HRIRFile.LoadError.ioError {
|
||||
// expected
|
||||
} catch {
|
||||
Issue.record("Expected .ioError, got \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Round-trip sanity: known values survive load unchanged
|
||||
|
||||
@Test func minimalValidFileParsesCorrectly() throws {
|
||||
let tmpURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("valid-\(UUID().uuidString).lbhr")
|
||||
defer { try? FileManager.default.removeItem(at: tmpURL) }
|
||||
|
||||
let testIRLength: UInt32 = 4
|
||||
let testPositionCount: UInt32 = 1
|
||||
|
||||
var bytes: Data = Data()
|
||||
bytes.append(contentsOf: [0x4C, 0x42, 0x48, 0x52]) // "LBHR"
|
||||
appendLE32(1, to: &bytes) // version
|
||||
appendLE32(44_100, to: &bytes) // sampleRate
|
||||
appendLE32(testIRLength, to: &bytes) // irLength
|
||||
appendLE32(testPositionCount, to: &bytes) // positionCount
|
||||
appendLE32(0, to: &bytes) // reserved
|
||||
|
||||
// Position: azimuth = π/2 (left), elevation = 0.
|
||||
let testAzimuth: Double = Double.pi / 2.0
|
||||
appendLEDouble(testAzimuth, to: &bytes)
|
||||
appendLEDouble(0.0, to: &bytes)
|
||||
appendLE32(0, to: &bytes) // sampleOffset
|
||||
appendLE32(0, to: &bytes) // reserved
|
||||
|
||||
// L IR: [32767, -32768, 16384, -16384]
|
||||
let lSamples: [Int16] = [32767, -32768, 16384, -16384]
|
||||
for s: Int16 in lSamples { appendLE16(s, to: &bytes) }
|
||||
// R IR: [0, 32767, -32767, 1]
|
||||
let rSamples: [Int16] = [0, 32767, -32767, 1]
|
||||
for s: Int16 in rSamples { appendLE16(s, to: &bytes) }
|
||||
|
||||
try bytes.write(to: tmpURL)
|
||||
|
||||
let hrir: HRIRFile = try HRIRFile.load(contentsOf: tmpURL)
|
||||
#expect(hrir.sampleRate == 44_100)
|
||||
#expect(hrir.irLength == Int(testIRLength))
|
||||
#expect(hrir.positions.count == 1)
|
||||
#expect(abs(hrir.positions[0].azimuth - testAzimuth) < 1e-12)
|
||||
#expect(abs(hrir.positions[0].elevation) < 1e-12)
|
||||
|
||||
// Verify float conversion: 32767 / 32768.0 and -32768 / 32768.0 = -1.0.
|
||||
let expectedL0: Float = Float(Int16(32767)) / 32768.0
|
||||
let expectedL1: Float = Float(Int16(-32768)) / 32768.0
|
||||
#expect(hrir.irs[0][0][0] == expectedL0)
|
||||
#expect(hrir.irs[0][0][1] == expectedL1)
|
||||
#expect(hrir.irs[0][1][0] == 0.0)
|
||||
let expectedR1: Float = Float(Int16(32767)) / 32768.0
|
||||
#expect(hrir.irs[0][1][1] == expectedR1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// BusAllocatorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("BusAllocator")
|
||||
struct BusAllocatorTests {
|
||||
|
||||
// makeTestEngine: 2 out + 2 in → hardware audio buses 0–3 are reserved
|
||||
// First allocatable audio bus is 4.
|
||||
|
||||
// MARK: - AudioBus allocation
|
||||
|
||||
@Test func allocateAudioBusReturnsBusAfterHardwareReservation() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(numOutputChannels: 2, numInputChannels: 2)
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(bus.index >= 4, "First allocatable bus must be after hardware buses 0–3")
|
||||
#expect(bus.channelCount == 1)
|
||||
}
|
||||
|
||||
@Test func allocateAudioBusContiguousMultiChannel() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(numOutputChannels: 2, numInputChannels: 2)
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 4)
|
||||
#expect(bus.channelCount == 4)
|
||||
// All 4 channels must be contiguous starting at bus.index
|
||||
let bus2: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(bus2.index == bus.index + 4, "Next allocation must start right after the 4-channel block")
|
||||
}
|
||||
|
||||
@Test func releaseAudioBusAllowsReuse() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(numOutputChannels: 2, numInputChannels: 2)
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let idx: Int = bus.index
|
||||
engine.busAllocator.releaseAudioBus(bus)
|
||||
let reused: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(reused.index == idx, "Released bus must be reused on next allocation")
|
||||
}
|
||||
|
||||
@Test func hardwareBusesArePreReserved() throws {
|
||||
// With 2 out + 2 in, buses 0–3 are hardware. Allocating a 4-channel block at index 0
|
||||
// must not succeed — the allocator should skip past the reserved range.
|
||||
let engine: SynthesisEngine = makeTestEngine(numOutputChannels: 2, numInputChannels: 2)
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(bus.index >= 4, "Allocator must not return hardware buses 0–3")
|
||||
}
|
||||
|
||||
@Test func allocateAudioBusThrowsWhenPoolExhausted() throws {
|
||||
// Small pool: 4 buses, all reserved as hardware → no free buses remain
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
numAudioBuses: 4
|
||||
)
|
||||
#expect(throws: BusAllocatorError.noFreeBus(channelCount: 1)) {
|
||||
try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func allocateAudioBusThrowsWhenNoContiguousBlock() throws {
|
||||
// Pool of 6 with 4 hardware → 2 free (buses 4 and 5). Requesting 3 must throw.
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
numAudioBuses: 6
|
||||
)
|
||||
#expect(throws: BusAllocatorError.noFreeBus(channelCount: 3)) {
|
||||
try engine.busAllocator.allocateAudioBus(channelCount: 3)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ControlBus allocation
|
||||
|
||||
@Test func allocateControlBusRoundTrip() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
#expect(bus.index >= 0 && bus.index < engine.numControlBuses)
|
||||
#expect(bus.channelCount == 1)
|
||||
engine.busAllocator.releaseControlBus(bus)
|
||||
let reused: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
#expect(reused.index == bus.index, "Released control bus must be reused on next allocation")
|
||||
}
|
||||
|
||||
@Test func allocateControlBusThrowsWhenPoolExhausted() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(numControlBuses: 2)
|
||||
let b1: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
let b2: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
_ = b1; _ = b2
|
||||
#expect(throws: BusAllocatorError.noFreeBus(channelCount: 1)) {
|
||||
try engine.busAllocator.allocateControlBus()
|
||||
}
|
||||
}
|
||||
|
||||
@Test func allocateControlBusMultiChannelContiguous() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 3)
|
||||
#expect(bus.channelCount == 3)
|
||||
let next: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 1)
|
||||
#expect(next.index == bus.index + 3, "Next allocation must start right after the 3-channel block")
|
||||
}
|
||||
|
||||
@Test func allocateControlBusMultiChannelReleaseAllowsReuse() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
|
||||
let start: Int = bus.index
|
||||
engine.busAllocator.releaseControlBus(bus)
|
||||
let reused: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
|
||||
#expect(reused.index == start, "Released multi-channel control bus must be reused")
|
||||
}
|
||||
|
||||
@Test func allocateControlBusThrowsWhenNoContiguousBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(numControlBuses: 3)
|
||||
// Allocate buses 0 and 2, leave bus 1 free → no 2-channel contiguous block starting at 0 or 2
|
||||
let b0: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 1)
|
||||
let b1: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 1)
|
||||
let b2: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 1)
|
||||
engine.busAllocator.releaseControlBus(b1)
|
||||
_ = b0; _ = b2
|
||||
#expect(throws: BusAllocatorError.noFreeBus(channelCount: 2)) {
|
||||
try engine.busAllocator.allocateControlBus(channelCount: 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func multiChannelControlBusInOutRoundTrip() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
|
||||
let src: Pan2 = Pan2(input: ConstantGeneratorInput(1.0 as Double), pan: 0.0)
|
||||
let outGen: Out.Control = Out.Control(bus: bus, source: src)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
// Pan2 at pan=0 gives equal power split; both control buses should be non-zero
|
||||
let v0: Float = engine.controlBuses[bus.index]
|
||||
let v1: Float = engine.controlBuses[bus.index + 1]
|
||||
#expect(v0 > 0, "Control bus channel 0 must receive Pan2 left output")
|
||||
#expect(v1 > 0, "Control bus channel 1 must receive Pan2 right output")
|
||||
|
||||
// In.Control(bus:) with multi-channel ControlBus reads both channels
|
||||
let inGen: In.Control = In.Control(bus: bus)
|
||||
#expect(inGen.channels == 2, "In.Control(bus: ControlBus) must inherit channelCount")
|
||||
}
|
||||
|
||||
// MARK: - In/Out overloads with AudioBus / ControlBus
|
||||
|
||||
@Test func inAudioWithAudioBusReadsCorrectBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
// Write a known value to the allocated bus
|
||||
let expected: Float = 0.75
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
engine.audioBuses[bus.index][i] = expected
|
||||
}
|
||||
|
||||
let gen: In.Audio = In.Audio(bus: bus)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
#expect(out.count == 1)
|
||||
#expect(out[0].prefix(engine.blockSize).allSatisfy { abs($0 - Double(expected)) < 1e-6 },
|
||||
"In.Audio(bus: AudioBus) must read from the allocated bus index")
|
||||
}
|
||||
|
||||
@Test func outAudioWithAudioBusWritesCorrectBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let signal: ConstantGeneratorInput = ConstantGeneratorInput(0.5 as Double)
|
||||
|
||||
let outGen: Out.Audio = Out.Audio(bus: bus, source: signal)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
let busValue: Float = Float(engine.audioBuses[bus.index][0])
|
||||
#expect(abs(busValue - 0.5) < 1e-4,
|
||||
"Out.Audio(bus:AudioBus, source:) must write to the allocated bus index")
|
||||
}
|
||||
|
||||
@Test func inControlWithControlBusReadsCorrectBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
engine.controlBuses[bus.index] = 0.42
|
||||
|
||||
let gen: In.Control = In.Control(bus: bus)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let fv: Double = gen.floatValue(graph: graph)
|
||||
#expect(abs(fv - 0.42) < 1e-5,
|
||||
"In.Control(bus: ControlBus) must read the current engine control bus value")
|
||||
}
|
||||
|
||||
@Test func outAudioChannelClampingPreventsAdjacentBusWrite() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Allocate a 1-channel bus; the next bus is separately allocated so a spill would corrupt it.
|
||||
let bus1ch: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let adjacentBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(adjacentBus.index == bus1ch.index + 1, "Adjacent allocation must be contiguous")
|
||||
|
||||
// 2-channel source writing to a 1-channel AudioBus — channel 1 must be clamped.
|
||||
let stereoSource: Pan2 = Pan2(input: ConstantGeneratorInput(1.0 as Double), pan: 0.0)
|
||||
let outGen: Out.Audio = Out.Audio(bus: bus1ch, source: stereoSource)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
let adjacentSum: Float = engine.audioBuses[adjacentBus.index].prefix(engine.blockSize).reduce(0, +)
|
||||
#expect(adjacentSum == 0,
|
||||
"Out.Audio(bus:AudioBus, source:) must not write beyond bus.channelCount")
|
||||
}
|
||||
|
||||
@Test func outControlWithControlBusWritesCorrectBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
let signal: ConstantGeneratorInput = ConstantGeneratorInput(0.77 as Double)
|
||||
|
||||
let outGen: Out.Control = Out.Control(bus: bus, source: signal)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
let busValue: Float = engine.controlBuses[bus.index]
|
||||
#expect(abs(busValue - 0.77) < 1e-4,
|
||||
"Out.Control(bus:ControlBus, source:) must write to the allocated control bus index")
|
||||
}
|
||||
|
||||
@Test func multiChannelAudioBusConvenienceInit() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||
engine.audioBuses[bus.index][0] = 0.1
|
||||
engine.audioBuses[bus.index + 1][0] = 0.9
|
||||
|
||||
let gens: GeneratorArray = In.Audio.multi(bus: bus)
|
||||
#expect(gens.generators.count == 2, "In.Audio.multi(bus:) must return one generator per channel")
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let ch0: [[Double]] = gens[0].calculatedSamples(graph: graph, count: 1)
|
||||
advanceBlock(engine)
|
||||
let ch1: [[Double]] = gens[1].calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(ch0[0][0] - 0.1) < 1e-5, "Channel 0 must read bus.index")
|
||||
#expect(abs(ch1[0][0] - 0.9) < 1e-5, "Channel 1 must read bus.index + 1")
|
||||
}
|
||||
|
||||
// MARK: - ValidBus protocol
|
||||
|
||||
@Test func intConformsToValidBusWithIndexSelf() {
|
||||
let bus: any ValidBus = 7
|
||||
#expect(bus.index == 7)
|
||||
#expect(bus.channelCount == Int.max, "Int bus must report Int.max channelCount")
|
||||
}
|
||||
|
||||
@Test func audioBusConformsToValidBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let ab: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 3)
|
||||
let vb: any ValidBus = ab
|
||||
#expect(vb.index == ab.index)
|
||||
#expect(vb.channelCount == 3)
|
||||
}
|
||||
|
||||
@Test func controlBusConformsToValidBus() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let cb: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
|
||||
let vb: any ValidBus = cb
|
||||
#expect(vb.index == cb.index)
|
||||
#expect(vb.channelCount == 2)
|
||||
}
|
||||
|
||||
@Test func inAudioWithIntBusSingleChannel() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let gen: In.Audio = In.Audio(bus: 4 as Int)
|
||||
#expect(gen.channels == 1, "Int bus must produce 1-channel In.Audio")
|
||||
#expect(gen.bus == 4)
|
||||
}
|
||||
|
||||
@Test func inControlWithIntBusSingleChannel() {
|
||||
let gen: In.Control = In.Control(bus: 10 as Int)
|
||||
#expect(gen.channels == 1, "Int bus must produce 1-channel In.Control")
|
||||
#expect(gen.bus == 10)
|
||||
}
|
||||
|
||||
@Test func outAudioIntBusWritesAllSourceChannels() throws {
|
||||
// Int bus has channelCount = Int.max, so all source channels must pass through.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let stereo: Pan2 = Pan2(input: ConstantGeneratorInput(1.0 as Double), pan: 0.0)
|
||||
// Write to buses 4 and 5 via plain Int; both should be non-zero.
|
||||
let outGen: Out.Audio = Out.Audio(bus: 4 as Int, source: stereo)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
let sum4: Float = engine.audioBuses[4].prefix(engine.blockSize).reduce(0, +)
|
||||
let sum5: Float = engine.audioBuses[5].prefix(engine.blockSize).reduce(0, +)
|
||||
#expect(sum4 > 0, "Int bus must not clamp channel 0")
|
||||
#expect(sum5 > 0, "Int bus must not clamp channel 1 (no channelCount limit)")
|
||||
}
|
||||
|
||||
@Test func outAudioAudioBusClampsToChannelCount() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let bus1ch: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let adjacent: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
#expect(adjacent.index == bus1ch.index + 1)
|
||||
|
||||
let stereo: Pan2 = Pan2(input: ConstantGeneratorInput(1.0 as Double), pan: 0.0)
|
||||
let outGen: Out.Audio = Out.Audio(bus: bus1ch, source: stereo)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outGen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
|
||||
let spillSum: Float = engine.audioBuses[adjacent.index].prefix(engine.blockSize).reduce(0, +)
|
||||
#expect(spillSum == 0, "AudioBus channelCount must clamp writes — adjacent bus must be silent")
|
||||
}
|
||||
|
||||
@Test func synthesizerBaseOutputAcceptsAudioBus() throws {
|
||||
final class BusSynth: SynthesizerBase {
|
||||
let bus: AudioBus
|
||||
init(bus: AudioBus) { self.bus = bus; super.init() }
|
||||
override func build() {
|
||||
output(bus: bus, source: 0.5 as Double)
|
||||
}
|
||||
}
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let ab: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let synth: BusSynth = BusSynth(bus: ab)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.audioBuses[ab.index][0] - 0.5) < 1e-6,
|
||||
"output(bus: AudioBus, source:) must write to the allocated bus")
|
||||
}
|
||||
|
||||
@Test func synthesizerBaseControlOutputAcceptsControlBus() throws {
|
||||
final class CtrlSynth: SynthesizerBase {
|
||||
let bus: ControlBus
|
||||
init(bus: ControlBus) { self.bus = bus; super.init() }
|
||||
override func build() {
|
||||
controlOutput(bus: bus, source: 0.33 as Double)
|
||||
}
|
||||
}
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let cb: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
let synth: CtrlSynth = CtrlSynth(bus: cb)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.controlBuses[cb.index] - 0.33) < 1e-6,
|
||||
"controlOutput(bus: ControlBus, source:) must write to the allocated bus")
|
||||
}
|
||||
|
||||
@Test func synthesizerBaseInputAcceptsAudioBus() throws {
|
||||
// Write 0.7 to bus, then read it back via input(bus: AudioBus)
|
||||
final class ReadSynth: SynthesizerBase {
|
||||
let src: Int; let dst: AudioBus
|
||||
init(src: Int, dst: AudioBus) { self.src = src; self.dst = dst; super.init() }
|
||||
override func build() {
|
||||
output(bus: dst, source: input(bus: src))
|
||||
}
|
||||
}
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
// Pre-seed srcBus via another synth that writes 0.7
|
||||
final class WriteSynth: SynthesizerBase {
|
||||
let b: AudioBus; init(b: AudioBus) { self.b = b; super.init() }
|
||||
override func build() { output(bus: b, source: 0.7 as Double) }
|
||||
}
|
||||
// engine.add uses addToHead: last-added evaluates first.
|
||||
// Add reader first (tail), then writer (head) so writer evaluates before reader.
|
||||
try engine.add(ReadSynth(src: srcBus.index, dst: dstBus)) // reader first → tail
|
||||
try engine.add(WriteSynth(b: srcBus)) // writer last → head
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.audioBuses[dstBus.index][0] - 0.7) < 1e-5,
|
||||
"input(bus: AudioBus) must read from the allocated bus")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// BusErgonomicsTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test synthesizers
|
||||
|
||||
/// Uses `output(bus:source:)` to write a constant to bus 0.
|
||||
private final class SingleOutputSynth: SynthesizerBase {
|
||||
let value: Double
|
||||
let bus: Int
|
||||
init(value: Double, bus: Int = 0) {
|
||||
self.value = value
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(bus: bus, source: value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses `output(buses:source:)` to write a constant to a range of audio buses.
|
||||
private final class MultiOutputSynth: SynthesizerBase {
|
||||
let value: Double
|
||||
let buses: Range<Int>
|
||||
init(value: Double, buses: Range<Int>) {
|
||||
self.value = value
|
||||
self.buses = buses
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(buses: buses, source: value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses `controlOutput(bus:source:)` to write a constant to a control bus.
|
||||
private final class ControlOutputSynth: SynthesizerBase {
|
||||
let value: Double
|
||||
let bus: Int
|
||||
init(value: Double, bus: Int = 0) {
|
||||
self.value = value
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
controlOutput(bus: bus, source: value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses `input(bus:)` to read an audio bus and routes it to another bus.
|
||||
private final class InputRoutingSynth: SynthesizerBase {
|
||||
let sourceBus: Int
|
||||
let destBus: Int
|
||||
init(sourceBus: Int, destBus: Int) {
|
||||
self.sourceBus = sourceBus
|
||||
self.destBus = destBus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(bus: destBus, source: input(bus: sourceBus))
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses `controlInput(bus:)` to read a control bus and routes it to an audio bus.
|
||||
private final class ControlInputRoutingSynth: SynthesizerBase {
|
||||
let controlBusIndex: Int
|
||||
let audioBusIndex: Int
|
||||
init(controlBusIndex: Int, audioBusIndex: Int) {
|
||||
self.controlBusIndex = controlBusIndex
|
||||
self.audioBusIndex = audioBusIndex
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(bus: audioBusIndex, source: controlInput(bus: controlBusIndex))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Suite("Bus Ergonomics — SynthesizerBase convenience helpers")
|
||||
struct BusErgonomicsTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: output(bus:source:)
|
||||
|
||||
@Test func outputBusWritesToCorrectBus() throws {
|
||||
let synth: SingleOutputSynth = SingleOutputSynth(value: 0.5, bus: 0)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
#expect(abs(engine.audioBuses[0][i] - 0.5) < 1e-6,
|
||||
"bus 0 sample \(i) should be 0.5")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func outputBusDoesNotWriteToOtherBuses() throws {
|
||||
let synth: SingleOutputSynth = SingleOutputSynth(value: 0.7, bus: 2)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// Bus 2 should have the value
|
||||
#expect(abs(engine.audioBuses[2][0] - 0.7) < 1e-6)
|
||||
// Bus 0 should remain 0
|
||||
#expect(engine.audioBuses[0][0] == 0.0)
|
||||
}
|
||||
|
||||
// MARK: output(buses:source:)
|
||||
|
||||
@Test func outputBusesWritesToAllBusesInRange() throws {
|
||||
let synth: MultiOutputSynth = MultiOutputSynth(value: 0.3, buses: 0..<4)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
for bus: Int in 0..<4 {
|
||||
#expect(abs(engine.audioBuses[bus][0] - 0.3) < 1e-6,
|
||||
"bus \(bus) sample 0 should be 0.3")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func outputBusesDoesNotWriteOutsideRange() throws {
|
||||
let synth: MultiOutputSynth = MultiOutputSynth(value: 0.6, buses: 1..<3)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// Bus 0 untouched
|
||||
#expect(engine.audioBuses[0][0] == 0.0)
|
||||
// Buses 1 and 2 written
|
||||
#expect(abs(engine.audioBuses[1][0] - 0.6) < 1e-6)
|
||||
#expect(abs(engine.audioBuses[2][0] - 0.6) < 1e-6)
|
||||
// Bus 3 untouched
|
||||
#expect(engine.audioBuses[3][0] == 0.0)
|
||||
}
|
||||
|
||||
@Test func outputBusesCreatesIndependentInstances() throws {
|
||||
// Each bus should have exactly the source value — not double-accumulated.
|
||||
// If instances were shared, bus writes would accumulate onto each other incorrectly.
|
||||
let synth: MultiOutputSynth = MultiOutputSynth(value: 0.4, buses: 0..<2)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.audioBuses[0][0] - 0.4) < 1e-6,
|
||||
"bus 0 should be 0.4, not 0.8 (would be 0.8 if same Out instance accumulated twice)")
|
||||
#expect(abs(engine.audioBuses[1][0] - 0.4) < 1e-6,
|
||||
"bus 1 should be 0.4, not 0.8")
|
||||
}
|
||||
|
||||
// MARK: controlOutput(bus:source:)
|
||||
|
||||
@Test func controlOutputWritesToCorrectControlBus() throws {
|
||||
let synth: ControlOutputSynth = ControlOutputSynth(value: 1.5, bus: 3)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.controlBuses[3] - 1.5) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func controlOutputDoesNotWriteToOtherBuses() throws {
|
||||
let synth: ControlOutputSynth = ControlOutputSynth(value: 0.9, bus: 5)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(abs(engine.controlBuses[5] - 0.9) < 1e-6)
|
||||
#expect(engine.controlBuses[0] == 0.0)
|
||||
}
|
||||
|
||||
// MARK: input(bus:)
|
||||
|
||||
@Test func inputReturnsWorkingInGenerator() throws {
|
||||
// Write a known value to bus 4; processBlock zeroes audio buses before evaluating,
|
||||
// so the writer (sourceSynth) must evaluate before the reader (routingSynth).
|
||||
// engine.add uses addToHead: the last-added synth evaluates first.
|
||||
// Add reader first (tail), then writer (head) so writer evaluates before reader.
|
||||
let sourceSynth: SingleOutputSynth = SingleOutputSynth(value: 0.25, bus: 4)
|
||||
let routingSynth: InputRoutingSynth = InputRoutingSynth(sourceBus: 4, destBus: 6)
|
||||
try engine.add(routingSynth) // reader first → tail
|
||||
try engine.add(sourceSynth) // writer last → head (evaluates before routingSynth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
#expect(abs(engine.audioBuses[6][i] - 0.25) < 1e-6,
|
||||
"bus 6 sample \(i) should be 0.25 (routed from bus 4)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: controlInput(bus:)
|
||||
|
||||
@Test func controlInputReturnsWorkingControlInGenerator() throws {
|
||||
engine.controlBuses[2] = Float(0.8)
|
||||
let synth: ControlInputRoutingSynth = ControlInputRoutingSynth(controlBusIndex: 2, audioBusIndex: 7)
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// ControlIn interpolates from 0.0 to 0.8; last sample should equal the bus value.
|
||||
let lastSample: Float = engine.audioBuses[7][engine.blockSize - 1]
|
||||
#expect(abs(Double(lastSample) - 0.8) < 1e-5,
|
||||
"last sample of bus 7 should reach control bus value 0.8")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
// ButterworthFilterTests.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 (mirrors RBJFilterTests)
|
||||
|
||||
private func bwDftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double {
|
||||
let n: Int = samples.count
|
||||
guard n > 0 else { return 0 }
|
||||
var re: Double = 0.0, im = 0.0
|
||||
for i: Int in 0..<n {
|
||||
let phase: Double = 2.0 * Double.pi * freq * Double(i) / sampleRate
|
||||
re += Double(samples[i]) * cos(phase)
|
||||
im -= Double(samples[i]) * sin(phase)
|
||||
}
|
||||
return sqrt(re * re + im * im) / Double(n)
|
||||
}
|
||||
|
||||
private func rms(_ samples: [Double]) -> Double {
|
||||
guard !samples.isEmpty else { return 0 }
|
||||
return sqrt(samples.map { Double($0) * Double($0) }.reduce(0, +) / Double(samples.count))
|
||||
}
|
||||
|
||||
// MARK: - ButterworthFilterTests
|
||||
|
||||
@Suite("ButterworthFilters")
|
||||
struct ButterworthFilterTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: Butterworth Q values
|
||||
|
||||
@Test func order2HasOneBiquadWithCorrectQ() {
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: ConstantGeneratorInput(0.0), freq: 1000.0, order: 2)
|
||||
#expect(lpf.order == 2)
|
||||
#expect(lpf.butterworthQs.count == 1)
|
||||
// Q for order-2 Butterworth = 1/√2 ≈ 0.7071
|
||||
#expect(abs(Double(lpf.butterworthQs[0]) - 1.0 / sqrt(2.0)) < 0.001)
|
||||
}
|
||||
|
||||
@Test func order4HasTwoBiquadsWithCorrectQs() {
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: ConstantGeneratorInput(0.0), freq: 1000.0, order: 4)
|
||||
#expect(lpf.butterworthQs.count == 2)
|
||||
// k=1: Q_1 = -1/(2·cos(5π/8)) ≈ 1.3066; k=2: Q_2 = -1/(2·cos(7π/8)) ≈ 0.5412
|
||||
#expect(abs(Double(lpf.butterworthQs[0]) - 1.3066) < 0.002)
|
||||
#expect(abs(Double(lpf.butterworthQs[1]) - 0.5412) < 0.002)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMax() {
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: ConstantGeneratorInput(0.0), freq: 1000.0, order: 99)
|
||||
#expect(lpf.order == maxButterworthOrder)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMin() {
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: ConstantGeneratorInput(0.0), freq: 1000.0, order: 0)
|
||||
#expect(lpf.order == 1)
|
||||
}
|
||||
|
||||
// MARK: Order 2 LPF — −3 dB at cutoff
|
||||
|
||||
@Test func order2LPFMinus3dBAtCutoff() throws {
|
||||
// A 2nd-order Butterworth LPF has gain = 1/√2 at its cutoff frequency by definition.
|
||||
// Feed a sine at cutoff, measure steady-state RMS.
|
||||
// Input RMS for sine amplitude 1.0 = 0.707. After −3 dB: output RMS ≈ 0.707 × 0.707 ≈ 0.5.
|
||||
let cutoff: Double = 1000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: cutoff)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: cutoff, order: 2)
|
||||
let all: [Double] = collectBlocks(lpf, engine: engine, blocks: 50)
|
||||
let steady: [Double] = Array(all.suffix(32 * engine.blockSize))
|
||||
let measuredRMS: Double = rms(steady)
|
||||
// Allow ±3 dB tolerance around 0.5: [0.354, 0.707]
|
||||
#expect(measuredRMS > 0.32 && measuredRMS < 0.75)
|
||||
}
|
||||
|
||||
// MARK: Order 4 vs Order 2 — steeper rolloff
|
||||
|
||||
@Test func order4RolloffSteeperThan2ndAtTwiceCutoff() throws {
|
||||
// At 2× the cutoff, −24 dB/oct (order 4) attenuates more than −12 dB/oct (order 2).
|
||||
let cutoff: Double = 800.0
|
||||
let testFreq: Double = cutoff * 2
|
||||
|
||||
let sine2: OscSin.Audio = OscSin.Audio(freq: testFreq)
|
||||
let lpf2: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine2, freq: cutoff, order: 2)
|
||||
let samples2: [Double] = collectBlocks(lpf2, engine: engine, blocks: 50)
|
||||
let tail2: [Double] = Array(samples2.suffix(32 * engine.blockSize))
|
||||
let rms2: Double = rms(tail2)
|
||||
|
||||
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try engine2.start()
|
||||
let sine4: OscSin.Audio = OscSin.Audio(freq: testFreq)
|
||||
let lpf4: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine4, freq: cutoff, order: 4)
|
||||
let samples4: [Double] = collectBlocks(lpf4, engine: engine2, blocks: 50)
|
||||
let tail4: [Double] = Array(samples4.suffix(32 * engine2.blockSize))
|
||||
let rms4: Double = rms(tail4)
|
||||
|
||||
#expect(rms4 < rms2)
|
||||
}
|
||||
|
||||
// MARK: HPF — passes high, attenuates DC
|
||||
|
||||
@Test func order2HPFAttenuatesDC() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: dc, freq: 1000.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
let last: [Double] = Array(samples.suffix(engine.blockSize))
|
||||
let mean: Double = last.map { abs(Double($0)) }.reduce(0, +) / Double(last.count)
|
||||
#expect(mean < 0.05)
|
||||
}
|
||||
|
||||
@Test func order2HPFPassesHighFreq() {
|
||||
let sineHigh: OscSin.Audio = OscSin.Audio(freq: 8000.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: sineHigh, freq: 1000.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
let mag: Double = bwDftMag(samples: samples, freq: 8000, sampleRate: sr)
|
||||
#expect(mag > 0.15)
|
||||
}
|
||||
|
||||
// MARK: Order 1 — first-order section only
|
||||
|
||||
@Test func order1LPFPassesDC() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: dc, freq: 1000.0, order: 1)
|
||||
#expect(lpf.butterworthQs.isEmpty) // no biquad stages for order 1
|
||||
let samples: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
let last: [Double] = Array(samples.suffix(engine.blockSize))
|
||||
let mean: Double = last.map { Double($0) }.reduce(0, +) / Double(last.count)
|
||||
#expect(abs(mean - 1.0) < 0.05) // DC gain ≈ 1.0
|
||||
}
|
||||
|
||||
@Test func order1LPFAttenuatesHighFreq() {
|
||||
let sineHigh: OscSin.Audio = OscSin.Audio(freq: 8000.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sineHigh, freq: 500.0, order: 1)
|
||||
let samples: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
let mag: Double = bwDftMag(samples: samples, freq: 8000, sampleRate: sr)
|
||||
#expect(mag < 0.05)
|
||||
}
|
||||
|
||||
@Test func order1HPFAttenuatesDC() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: dc, freq: 1000.0, order: 1)
|
||||
let samples: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
let last: [Double] = Array(samples.suffix(engine.blockSize))
|
||||
let mean: Double = last.map { abs(Double($0)) }.reduce(0, +) / Double(last.count)
|
||||
#expect(mean < 0.05)
|
||||
}
|
||||
|
||||
// MARK: Order 7 — 3 biquads + first-order section
|
||||
|
||||
@Test func order7LPFNoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: 2000.0, order: 7)
|
||||
#expect(lpf.butterworthQs.count == 3) // ⌊7/2⌋ = 3 biquad stages
|
||||
let samples: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(!samples.allSatisfy { $0 == 0 }) // non-trivial output
|
||||
}
|
||||
|
||||
@Test func order7HPFNoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 8000.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: sine, freq: 500.0, order: 7)
|
||||
let samples: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(!samples.allSatisfy { $0 == 0 })
|
||||
}
|
||||
|
||||
// MARK: Audio-rate freq modulation
|
||||
|
||||
@Test func lpfAudioRateFreqModNoCrash() {
|
||||
// freq driven by a slow LFO — exercises the block-boundary interpolation path
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 1.0) // slow modulation
|
||||
let freqGen: BinaryOpGenerator = lfo * 500.0 + 1000.0 // sweeps 500–1500 Hz
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: freqGen, order: 4)
|
||||
let samples: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func hpfAudioRateFreqModNoCrash() {
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 1.0)
|
||||
let freqGen: BinaryOpGenerator = lfo * 500.0 + 1000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 8000.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: sine, freq: freqGen, order: 4)
|
||||
let samples: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
// MARK: Fan-out cache
|
||||
|
||||
@Test func lpfParticipatesInFanOutCache() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: 1000.0, order: 2)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let r1: [[Double]] = lpf.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
let r2: [[Double]] = lpf.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
|
||||
}
|
||||
|
||||
// MARK: Deterministic first-sample tests
|
||||
|
||||
@Test func order1LPFFirstSampleMatchesFormula() {
|
||||
// Step input (all 1.0s), initial state = 0. First output = b0 of the FO section.
|
||||
// Bilinear LP: omega = tan(pi*freq/sr), b0 = omega/(omega+1).
|
||||
let freq: Double = 500.0
|
||||
let omega: Double = tan(.pi * freq / sr)
|
||||
let expectedFirstSample: Double = omega / (omega + 1.0)
|
||||
|
||||
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: input, freq: freq, order: 1)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = lpf.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10)
|
||||
}
|
||||
|
||||
@Test func order2LPFFirstSampleMatchesFormula() {
|
||||
// Step input, initial state = 0. For order-2 LP (one biquad, no FO section),
|
||||
// first output = nb0 (normalised by a0). RBJ LP: nb0 = (1-cos(w0))/2 / (1+alpha)
|
||||
// where alpha = sin(w0)/(2*Q) and Q = 1/sqrt(2) for Butterworth order 2.
|
||||
let freq: Double = 1000.0
|
||||
let q: Double = 1.0 / sqrt(2.0)
|
||||
let w0: Double = 2.0 * .pi * freq / sr
|
||||
let sinW0: Double = sin(w0)
|
||||
let cosW0: Double = cos(w0)
|
||||
let alpha: Double = sinW0 / (2.0 * q)
|
||||
let a0: Double = 1.0 + alpha
|
||||
let expectedFirstSample: Double = ((1.0 - cosW0) / 2.0) / a0
|
||||
|
||||
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: input, freq: freq, order: 2)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = lpf.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10)
|
||||
}
|
||||
|
||||
@Test func order1HPFFirstTwoSamplesMatchFormula() {
|
||||
// Step input [1,1,...], initial state = 0.
|
||||
// Bilinear HP: omega = tan(pi*freq/sr), b0 = 1/(omega+1), b1 = -b0, na1 = (1-omega)/(omega+1)
|
||||
// y[0] = b0 * x[0] = b0
|
||||
// y[1] = b0*x[1] + b1*x[0] - na1*y[0] = b0 + (-b0)*1 - na1*b0 = -na1*b0
|
||||
let freq: Double = 500.0
|
||||
let omega: Double = tan(.pi * freq / sr)
|
||||
let b0hp: Double = 1.0 / (omega + 1.0)
|
||||
let na1hp: Double = (1.0 - omega) / (omega + 1.0)
|
||||
let expectedSample0: Double = b0hp
|
||||
let expectedSample1: Double = -na1hp * b0hp
|
||||
|
||||
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: input, freq: freq, order: 1)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = hpf.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(abs(Double(samples[0][0]) - expectedSample0) < 1e-10)
|
||||
#expect(abs(Double(samples[0][1]) - expectedSample1) < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: All even orders compile and run
|
||||
|
||||
@Test func allEvenOrdersLPFRunWithoutCrash() throws {
|
||||
let evenOrders: [Int] = [2, 4, 6, 8]
|
||||
for order: Int in evenOrders {
|
||||
let eng: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try eng.start()
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: 1000.0, order: order)
|
||||
let samples: [Double] = collectBlocks(lpf, engine: eng, blocks: 10)
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "order \(order) produced non-finite output")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func allOddOrdersLPFRunWithoutCrash() throws {
|
||||
let oddOrders: [Int] = [1, 3, 5, 7]
|
||||
for order: Int in oddOrders {
|
||||
let eng: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try eng.start()
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: 1000.0, order: order)
|
||||
let samples: [Double] = collectBlocks(lpf, engine: eng, blocks: 10)
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "order \(order) produced non-finite output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ButterworthBandPassTests
|
||||
|
||||
@Suite("ButterworthBandPass")
|
||||
struct ButterworthBandPassTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func butterworthQsMatchLP() {
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 300.0, highFreq: 3000.0, order: 4)
|
||||
#expect(bp.butterworthQs.count == 2)
|
||||
#expect(abs(Double(bp.butterworthQs[0]) - 1.3066) < 0.002)
|
||||
#expect(abs(Double(bp.butterworthQs[1]) - 0.5412) < 0.002)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMax() {
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 300.0, highFreq: 3000.0, order: 99)
|
||||
#expect(bp.order == maxButterworthOrder)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMin() {
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 300.0, highFreq: 3000.0, order: 0)
|
||||
#expect(bp.order == 1)
|
||||
}
|
||||
|
||||
@Test func passesMidBandSine() {
|
||||
// A sine at 1 kHz should pass through a 300–3000 Hz BPF (inside band).
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine, lowFreq: 300.0, highFreq: 3000.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 50)
|
||||
let mag: Double = bwDftMag(samples: Array(samples.suffix(32 * engine.blockSize)),
|
||||
freq: 1000, sampleRate: sr)
|
||||
#expect(mag > 0.1)
|
||||
}
|
||||
|
||||
@Test func attenuatesDC() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: dc, lowFreq: 300.0, highFreq: 3000.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 30)
|
||||
let last: [Double] = Array(samples.suffix(engine.blockSize))
|
||||
let mean: Double = last.map { abs(Double($0)) }.reduce(0, +) / Double(last.count)
|
||||
#expect(mean < 0.05)
|
||||
}
|
||||
|
||||
@Test func attenuatesHighFreqAboveBand() {
|
||||
let sineHigh: OscSin.Audio = OscSin.Audio(freq: 12000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sineHigh, lowFreq: 300.0, highFreq: 3000.0, order: 4)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 30)
|
||||
let mag: Double = bwDftMag(samples: Array(samples.suffix(16 * engine.blockSize)),
|
||||
freq: 12000, sampleRate: sr)
|
||||
#expect(mag < 0.05)
|
||||
}
|
||||
|
||||
@Test func attenuatesLowFreqBelowBand() {
|
||||
let sineLow: OscSin.Audio = OscSin.Audio(freq: 50.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sineLow, lowFreq: 500.0, highFreq: 3000.0, order: 4)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 50)
|
||||
let mag: Double = bwDftMag(samples: Array(samples.suffix(32 * engine.blockSize)),
|
||||
freq: 50, sampleRate: sr)
|
||||
#expect(mag < 0.05)
|
||||
}
|
||||
|
||||
@Test func order4RolloffSteeperThanOrder2() throws {
|
||||
// At a frequency well outside the band, order-4 attenuates more than order-2.
|
||||
let testFreq: Double = 10000.0
|
||||
let sine2: OscSin.Audio = OscSin.Audio(freq: testFreq)
|
||||
let bp2: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine2, lowFreq: 300.0, highFreq: 3000.0, order: 2)
|
||||
let s2: [Double] = collectBlocks(bp2, engine: engine, blocks: 30)
|
||||
let mag2: Double = bwDftMag(samples: Array(s2.suffix(16 * engine.blockSize)),
|
||||
freq: testFreq, sampleRate: sr)
|
||||
|
||||
let engine4: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try engine4.start()
|
||||
let sine4: OscSin.Audio = OscSin.Audio(freq: testFreq)
|
||||
let bp4: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine4, lowFreq: 300.0, highFreq: 3000.0, order: 4)
|
||||
let s4: [Double] = collectBlocks(bp4, engine: engine4, blocks: 30)
|
||||
let mag4: Double = bwDftMag(samples: Array(s4.suffix(16 * engine4.blockSize)),
|
||||
freq: testFreq, sampleRate: sr)
|
||||
|
||||
#expect(mag4 < mag2)
|
||||
}
|
||||
|
||||
@Test func order1NoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine, lowFreq: 300.0, highFreq: 3000.0, order: 1)
|
||||
#expect(bp.butterworthQs.isEmpty)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(!samples.allSatisfy { $0 == 0 })
|
||||
}
|
||||
|
||||
@Test func order7NoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine, lowFreq: 300.0, highFreq: 3000.0, order: 7)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(!samples.allSatisfy { $0 == 0 })
|
||||
}
|
||||
|
||||
@Test func audioRateFreqModNoCrash() {
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5)
|
||||
let lowGen: BinaryOpGenerator = lfo * 100.0 + 400.0
|
||||
let highGen: BinaryOpGenerator = lfo * 200.0 + 2000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine, lowFreq: lowGen, highFreq: highGen, order: 2)
|
||||
let samples: [Double] = collectBlocks(bp, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func participatesInFanOutCache() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: sine, lowFreq: 300.0, highFreq: 3000.0, order: 2)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let r1: [[Double]] = bp.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
let r2: [[Double]] = bp.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
|
||||
}
|
||||
|
||||
@Test func order1BPFFirstSampleMatchesFormula() {
|
||||
// order=1 BPF: HP-FO writes _scratch[0]=b0_hp, LP-FO reads _scratch → result[0]=b0_lp*b0_hp.
|
||||
// b0_hp = 1/(omega_hp+1) where omega_hp = tan(pi*lowFreq/sr)
|
||||
// b0_lp = omega_lp/(omega_lp+1) where omega_lp = tan(pi*highFreq/sr)
|
||||
let lowFreq: Double = 300.0
|
||||
let highFreq: Double = 3000.0
|
||||
let omega_hp: Double = tan(.pi * lowFreq / sr)
|
||||
let omega_lp: Double = tan(.pi * highFreq / sr)
|
||||
let b0_hp: Double = 1.0 / (omega_hp + 1.0)
|
||||
let b0_lp: Double = omega_lp / (omega_lp + 1.0)
|
||||
let expectedFirstSample: Double = b0_lp * b0_hp
|
||||
|
||||
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let bp: ButterworthBandPass.Audio = ButterworthBandPass.Audio(input: input, lowFreq: lowFreq, highFreq: highFreq, order: 1)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = bp.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ButterworthBandRejectTests
|
||||
|
||||
@Suite("ButterworthBandReject")
|
||||
struct ButterworthBandRejectTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func butterworthQsMatchLP() {
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 800.0, highFreq: 1200.0, order: 4)
|
||||
#expect(br.butterworthQs.count == 2)
|
||||
#expect(abs(Double(br.butterworthQs[0]) - 1.3066) < 0.002)
|
||||
#expect(abs(Double(br.butterworthQs[1]) - 0.5412) < 0.002)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMax() {
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 800.0, highFreq: 1200.0, order: 99)
|
||||
#expect(br.order == maxButterworthOrder)
|
||||
}
|
||||
|
||||
@Test func orderClampedToMin() {
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: ConstantGeneratorInput(0.0),
|
||||
lowFreq: 800.0, highFreq: 1200.0, order: 0)
|
||||
#expect(br.order == 1)
|
||||
}
|
||||
|
||||
@Test func passesDC() {
|
||||
// DC must pass through a band-reject filter (it's below the stop band).
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: dc, lowFreq: 800.0, highFreq: 1200.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 30)
|
||||
let last: [Double] = Array(samples.suffix(engine.blockSize))
|
||||
let mean: Double = last.map { Double($0) }.reduce(0, +) / Double(last.count)
|
||||
#expect(abs(mean - 1.0) < 0.1)
|
||||
}
|
||||
|
||||
@Test func passesHighFreq() {
|
||||
let sineHigh: OscSin.Audio = OscSin.Audio(freq: 8000.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sineHigh, lowFreq: 800.0, highFreq: 1200.0, order: 2)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 30)
|
||||
let mag: Double = bwDftMag(samples: Array(samples.suffix(16 * engine.blockSize)),
|
||||
freq: 8000, sampleRate: sr)
|
||||
#expect(mag > 0.1)
|
||||
}
|
||||
|
||||
@Test func attenuatesMidBandSine() {
|
||||
// With widely-separated cutoffs (300/3000 Hz), 1000 Hz sits deep in the stop band.
|
||||
// LP at 300 Hz attenuates 1000 Hz by ~1/sqrt(1+(10/3)^8) ≈ 0.025;
|
||||
// HP at 3000 Hz attenuates 1000 Hz by ~1/sqrt(1+3^8) ≈ 0.012.
|
||||
// Their phase-summed output at 1000 Hz should be well below 0.05.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 1000.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 300.0, highFreq: 3000.0, order: 4)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 50)
|
||||
let mag: Double = bwDftMag(samples: Array(samples.suffix(32 * engine.blockSize)),
|
||||
freq: 1000, sampleRate: sr)
|
||||
#expect(mag < 0.05)
|
||||
}
|
||||
|
||||
@Test func order1NoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 800.0, highFreq: 1200.0, order: 1)
|
||||
#expect(br.butterworthQs.isEmpty)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func order7NoCrashAndFiniteOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 800.0, highFreq: 1200.0, order: 7)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func audioRateFreqModNoCrash() {
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5)
|
||||
let lowGen: BinaryOpGenerator = lfo * 100.0 + 700.0
|
||||
let highGen: BinaryOpGenerator = lfo * 100.0 + 1300.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: lowGen, highFreq: highGen, order: 2)
|
||||
let samples: [Double] = collectBlocks(br, engine: engine, blocks: 20)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func participatesInFanOutCache() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 800.0, highFreq: 1200.0, order: 2)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let r1: [[Double]] = br.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
let r2: [[Double]] = br.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
|
||||
}
|
||||
|
||||
@Test func order1BRFFirstSampleMatchesFormula() {
|
||||
// order=1 BRF: LP-FO writes _lpResult[0]=b0_lp, HP-FO writes _result[0][0]=b0_hp.
|
||||
// Final sum: result[0] += lpResult[0] → b0_lp + b0_hp.
|
||||
// b0_lp = omega_lp/(omega_lp+1) where omega_lp = tan(pi*lowFreq/sr) (LP cutoff)
|
||||
// b0_hp = 1/(omega_hp+1) where omega_hp = tan(pi*highFreq/sr) (HP cutoff)
|
||||
let lowFreq: Double = 800.0
|
||||
let highFreq: Double = 1200.0
|
||||
let omega_lp: Double = tan(.pi * lowFreq / sr)
|
||||
let omega_hp: Double = tan(.pi * highFreq / sr)
|
||||
let b0_lp: Double = omega_lp / (omega_lp + 1.0)
|
||||
let b0_hp: Double = 1.0 / (omega_hp + 1.0)
|
||||
let expectedFirstSample: Double = b0_lp + b0_hp
|
||||
|
||||
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: input, lowFreq: lowFreq, highFreq: highFreq, order: 1)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = br.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10)
|
||||
}
|
||||
|
||||
@Test func allEvenOrdersRunWithoutCrash() throws {
|
||||
for order: Int in [2, 4, 6, 8] {
|
||||
let eng: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try eng.start()
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 800.0, highFreq: 1200.0, order: order)
|
||||
let samples: [Double] = collectBlocks(br, engine: eng, blocks: 10)
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "order \(order) produced non-finite output")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func allOddOrdersRunWithoutCrash() throws {
|
||||
for order: Int in [1, 3, 5, 7] {
|
||||
let eng: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
|
||||
try eng.start()
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let br: ButterworthBandReject.Audio = ButterworthBandReject.Audio(input: sine, lowFreq: 800.0, highFreq: 1200.0, order: order)
|
||||
let samples: [Double] = collectBlocks(br, engine: eng, blocks: 10)
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "order \(order) produced non-finite output")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: vDSP path correctness
|
||||
|
||||
@Test func lpfOrder4StableWithCorrectSteadyState() throws {
|
||||
let cutoff: Double = 1000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: cutoff)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: cutoff, order: 4)
|
||||
let all: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
#expect(all.allSatisfy { $0.isFinite }, "LPF (order 4) produced non-finite output")
|
||||
// At cutoff: gain ≈ 1/√2 → RMS of amplitude-1 sine ≈ 0.5
|
||||
let steady: [Double] = Array(all.suffix(8 * engine.blockSize))
|
||||
let measuredRMS: Double = rms(steady)
|
||||
#expect(measuredRMS > 0.30 && measuredRMS < 0.80,
|
||||
"LPF (order 4) RMS \(measuredRMS) out of expected range")
|
||||
}
|
||||
|
||||
@Test func hpfOrder4StableWithCorrectSteadyState() throws {
|
||||
let cutoff: Double = 1000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: cutoff)
|
||||
let hpf: ButterworthHighPass.Audio = ButterworthHighPass.Audio(input: sine, freq: cutoff, order: 4)
|
||||
let all: [Double] = collectBlocks(hpf, engine: engine, blocks: 20)
|
||||
#expect(all.allSatisfy { $0.isFinite }, "HPF (order 4) produced non-finite output")
|
||||
let steady: [Double] = Array(all.suffix(8 * engine.blockSize))
|
||||
let measuredRMS: Double = rms(steady)
|
||||
#expect(measuredRMS > 0.30 && measuredRMS < 0.80,
|
||||
"HPF (order 4) RMS \(measuredRMS) out of expected range")
|
||||
}
|
||||
|
||||
@Test func oddOrderLPFOrder3BelowCutoffPassesSignal() throws {
|
||||
let cutoff: Double = 1000.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0)
|
||||
let lpf: ButterworthLowPass.Audio = ButterworthLowPass.Audio(input: sine, freq: cutoff, order: 3)
|
||||
let all: [Double] = collectBlocks(lpf, engine: engine, blocks: 20)
|
||||
#expect(all.allSatisfy { $0.isFinite }, "LPF (order 3) produced non-finite output")
|
||||
let steady: [Double] = Array(all.suffix(8 * engine.blockSize))
|
||||
let measuredRMS: Double = rms(steady)
|
||||
#expect(measuredRMS > 0.50, "LPF (order 3) below cutoff RMS \(measuredRMS) unexpectedly low")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// CPUStatsTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("CPU Statistics")
|
||||
final class CPUStatsTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
deinit {
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func averageCPUNonNegativeAfterOneBlock() {
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.averageCPU >= 0.0)
|
||||
}
|
||||
|
||||
@Test func peakCPUAtLeastAverageCPU() {
|
||||
for _ in 0..<10 {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
#expect(engine.peakCPU >= engine.averageCPU)
|
||||
}
|
||||
|
||||
@Test func peakNonDecreasingWithoutReset() {
|
||||
// Reset first so the auto-reset timer (5 s) cannot fire mid-assertion.
|
||||
engine.resetPeakCPU()
|
||||
var lastPeak: Double = 0.0
|
||||
for _ in 0..<20 {
|
||||
engine.processBlock(inputSamples: [])
|
||||
let peak: Double = engine.peakCPU
|
||||
#expect(peak >= lastPeak)
|
||||
lastPeak = peak
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetPeakSetsZero() {
|
||||
for _ in 0..<5 {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
engine.resetPeakCPU()
|
||||
#expect(engine.peakCPU == 0.0)
|
||||
}
|
||||
|
||||
@Test func peakReseededAfterReset() {
|
||||
for _ in 0..<5 {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
engine.resetPeakCPU()
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.peakCPU > 0.0)
|
||||
}
|
||||
|
||||
@Test func averageCPUConverges() {
|
||||
let blockCount: Int = 50
|
||||
var readings: [Double] = []
|
||||
for _ in 0..<blockCount {
|
||||
engine.processBlock(inputSamples: [])
|
||||
readings.append(engine.averageCPU)
|
||||
}
|
||||
let tail: Array<Double>.SubSequence = readings.suffix(10)
|
||||
let mean: Double = tail.reduce(0, +) / Double(tail.count)
|
||||
// Guard against near-zero mean (e.g. mock driver with negligible block cost).
|
||||
guard mean > 1e-9 else { return }
|
||||
for v: Double in tail {
|
||||
#expect(abs(v - mean) < mean * 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// ChannelSelectTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("ChannelSelect")
|
||||
struct ChannelSelectTests {
|
||||
|
||||
func makeEngine() throws -> SynthesisEngine {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
return engine
|
||||
}
|
||||
|
||||
// MARK: - ChannelSelect.Audio basics
|
||||
|
||||
@Test func audioExtractsChannel0FromPan2HardLeft() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: -1.0)
|
||||
let left: ChannelSelect.Audio = pan[0]
|
||||
let right: ChannelSelect.Audio = pan[1]
|
||||
|
||||
let lOut: [[Double]] = left.calculatedSamples(graph: graph, count: 64)
|
||||
let rOut: [[Double]] = right.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(lOut.count == 1, "ChannelSelect must return exactly 1 channel")
|
||||
#expect(rOut.count == 1, "ChannelSelect must return exactly 1 channel")
|
||||
#expect(abs(lOut[0][0] - 1.0) < 1e-6, "Hard-left pan: left channel should be 1.0")
|
||||
#expect(abs(rOut[0][0]) < 1e-6, "Hard-left pan: right channel should be 0.0")
|
||||
}
|
||||
|
||||
@Test func audioExtractsChannel1FromPan2HardRight() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: 1.0)
|
||||
let left: ChannelSelect.Audio = pan[0]
|
||||
let right: ChannelSelect.Audio = pan[1]
|
||||
|
||||
let lOut: [[Double]] = left.calculatedSamples(graph: graph, count: 64)
|
||||
let rOut: [[Double]] = right.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(abs(lOut[0][0]) < 1e-6, "Hard-right pan: left channel should be 0.0")
|
||||
#expect(abs(rOut[0][0] - 1.0) < 1e-6, "Hard-right pan: right channel should be 1.0")
|
||||
}
|
||||
|
||||
@Test func audioOutOfRangeChannelReturnsSilence() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: 0.0)
|
||||
let oob: ChannelSelect.Audio = pan[99]
|
||||
let out: [[Double]] = oob.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(out.count == 1, "Out-of-range ChannelSelect must return 1-channel buffer")
|
||||
#expect(out[0].prefix(64).allSatisfy { $0 == 0.0 }, "Out-of-range channel must be silent")
|
||||
}
|
||||
|
||||
@Test func audioResultIsSingleChannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(0.5), pan: 0.0)
|
||||
for ch: Int in 0..<2 {
|
||||
let out: [[Double]] = pan[ch].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
#expect(out.count == 1, "Channel \(ch) selector must return exactly 1 outer channel")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Named aliases on Pan2
|
||||
|
||||
@Test func pan2LeftAliasMatchesSubscript0() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: -0.5)
|
||||
let viaSubscript: [[Double]] = pan[0].calculatedSamples(graph: graph, count: 64)
|
||||
let viaAlias: [[Double]] = pan.left.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(viaSubscript[0][0] == viaAlias[0][0],
|
||||
"pan.left must produce the same value as pan[0]")
|
||||
}
|
||||
|
||||
@Test func pan2RightAliasMatchesSubscript1() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: 0.7)
|
||||
let viaSubscript: [[Double]] = pan[1].calculatedSamples(graph: graph, count: 64)
|
||||
let viaAlias: [[Double]] = pan.right.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(viaSubscript[0][0] == viaAlias[0][0],
|
||||
"pan.right must produce the same value as pan[1]")
|
||||
}
|
||||
|
||||
// MARK: - Named aliases on Pan4 subclass (PanAz)
|
||||
|
||||
@Test func pan4NamedAliasesMatchSubscripts() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Pan4 itself is an open base class with no inputs; pick a concrete
|
||||
// subclass to exercise the inherited channel-alias extension. PanAz at
|
||||
// az = -π/4 hard-pans to LF (x = -1, y = +1).
|
||||
let pan: PanAz = PanAz(input: ConstantGeneratorInput(1.0))
|
||||
pan.azimuth = -.pi / 4
|
||||
|
||||
let aliases: [ChannelSelect.Audio] = [
|
||||
pan.frontLeft, pan.frontRight, pan.rearRight, pan.rearLeft
|
||||
]
|
||||
// Run alias and subscript in the SAME segment so the fan-out cache ensures
|
||||
// the panner evaluates once and both channel selectors read from the same
|
||||
// output buffer. With per-sample azimuth evaluation, alias and subscript
|
||||
// must share the same underlying evaluation — different segments would
|
||||
// produce different ramp positions.
|
||||
for (ch, alias) in aliases.enumerated() {
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let viaAlias: [[Double]] = alias.calculatedSamples(graph: graph, count: 64)
|
||||
let viaSubscript: [[Double]] = pan[ch].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
#expect(viaAlias[0][0] == viaSubscript[0][0],
|
||||
"PanAz named alias ch\(ch) must match pan[\(ch)] in the same segment")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Named aliases on FreqTracker
|
||||
|
||||
@Test func freqTrackerFreqAliasIsSingleChannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0))
|
||||
let out: [[Double]] = tracker.freq.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1, "tracker.freq must return 1 channel")
|
||||
}
|
||||
|
||||
@Test func freqTrackerConfidenceAliasIsSingleChannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0))
|
||||
let out: [[Double]] = tracker.confidence.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1, "tracker.confidence must return 1 channel")
|
||||
}
|
||||
|
||||
@Test func freqTrackerFreqAliasMatchesSubscript0() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0))
|
||||
let via0: [[Double]] = tracker[0].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
let viaAlias: [[Double]] = tracker.freq.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(via0[0][0] == viaAlias[0][0],
|
||||
"tracker.freq must match tracker[0]")
|
||||
}
|
||||
|
||||
@Test func freqTrackerConfidenceAliasMatchesSubscript1() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0))
|
||||
let via1: [[Double]] = tracker[1].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
let viaAlias: [[Double]] = tracker.confidence.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(via1[0][0] == viaAlias[0][0],
|
||||
"tracker.confidence must match tracker[1]")
|
||||
}
|
||||
|
||||
// MARK: - .channel(n) method is equivalent to subscript
|
||||
|
||||
@Test func channelMethodEqualsSubscript() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: -0.3)
|
||||
let via0: [[Double]] = pan[0].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
let viaMethod: [[Double]] = pan.channel(0).calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(via0[0][0] == viaMethod[0][0],
|
||||
"pan[0] and pan.channel(0) must produce the same value")
|
||||
}
|
||||
|
||||
// MARK: - GeneratorArray subscript
|
||||
|
||||
@Test func generatorArraySubscriptIsSingleChannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let oscs: GeneratorArray = expand([440.0, 880.0] as [any ValidGeneratorInput]) {
|
||||
OscSin.Audio(freq: $0)
|
||||
}
|
||||
let ch0: [[Double]] = oscs[0].calculatedSamples(graph: graph, count: 64)
|
||||
#expect(ch0.count == 1, "GeneratorArray[0] must return 1-channel output")
|
||||
}
|
||||
|
||||
@Test func generatorArraySubscriptMatchesDirectChannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
// GeneratorArray with a hard-panned source: channel 0 = 1.0, channel 1 = 0.0
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: -1.0)
|
||||
let arr: GeneratorArray = GeneratorArray([pan]) // 1-generator array, 2-channel source
|
||||
// arr[0] selects channel 0 of the GeneratorArray (which is channel 0 of Pan2's first channel)
|
||||
let direct: [[Double]] = pan[0].calculatedSamples(graph: graph, count: 64)
|
||||
advanceBlock(engine)
|
||||
let viaArr: [[Double]] = arr[0].calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(abs(direct[0][0] - 1.0) < 1e-6, "Pan2 ch0 hard-left should be 1.0")
|
||||
#expect(viaArr.count == 1, "GeneratorArray[0] must return 1-channel output")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out cache: shared source evaluates once per segment
|
||||
|
||||
@Test func sharedPan2EvaluatesOnceWithTwoChannelSelectors() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let pan: Pan2 = Pan2(input: ConstantGeneratorInput(1.0), pan: -1.0)
|
||||
let left: ChannelSelect.Audio = pan.left
|
||||
let right: ChannelSelect.Audio = pan.right
|
||||
|
||||
// Both selectors call pan.calculatedSamples in the same segment.
|
||||
// The segment-serial cache ensures pan._computeSamples fires once.
|
||||
// Verify: left = 1.0, right = 0.0 — consistent data, no double evaluation.
|
||||
let lOut: [[Double]] = left.calculatedSamples(graph: graph, count: 64)
|
||||
let rOut: [[Double]] = right.calculatedSamples(graph: graph, count: 64)
|
||||
|
||||
#expect(abs(lOut[0][0] - 1.0) < 1e-6, "Left channel should be 1.0 (hard-left)")
|
||||
#expect(abs(rOut[0][0]) < 1e-6, "Right channel should be 0.0 (hard-left)")
|
||||
}
|
||||
|
||||
// MARK: - ChannelSelect.Control ramp interpolation
|
||||
|
||||
@Test func controlRampInterpolatesFromPreviousToTarget() throws {
|
||||
// ChannelSelect.Control follows the same ramp pattern as In.Control.
|
||||
// Use a 2-value source: block 1 constant 0.0, block 2 constant 1.0.
|
||||
// ChannelSelect.Control should ramp from 0→1 across the second block.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let defer_: () -> () = { engine.stop() }
|
||||
defer { defer_() }
|
||||
|
||||
// Build a 2-channel source that holds block-rate values.
|
||||
// We use a constant source for simplicity: both channels always 1.0.
|
||||
let src: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let sel: ChannelSelect.Control = ChannelSelect.Control(source: src, channel: 0)
|
||||
|
||||
// Block 1: previousOutputValue starts at 0.0, target = 1.0 → ramp 0→1.
|
||||
let graph1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let b1: [[Double]] = sel._computeSamples(graph: graph1, count: 64)
|
||||
|
||||
// Ramp from 0 to 1 over 64 samples: last sample should be very close to 1.0.
|
||||
#expect(b1[0][0] < b1[0][63], "Ramp should increase from first to last sample")
|
||||
#expect(abs(b1[0][63] - 1.0) < 1e-6, "Ramp last sample should reach target 1.0")
|
||||
|
||||
// Block 2: previousOutputValue is now 1.0, target still 1.0 → flat at 1.0.
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let b2: [[Double]] = sel._computeSamples(graph: graph2, count: 64)
|
||||
#expect(abs(b2[0][0] - 1.0) < 1e-6, "Second block should be flat at 1.0")
|
||||
#expect(abs(b2[0][63] - 1.0) < 1e-6, "Second block last sample should be 1.0")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// ChorusTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Chorus")
|
||||
struct ChorusTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic first sample
|
||||
|
||||
@Test func firstSampleDeterministic() {
|
||||
// input=0.5, depth=0, rate=0, mix=0.5 → first sample = 0.25 on both channels.
|
||||
// Delay line starts all-zero; wet = 0; output = 0.5*(1-0.5) + 0*0.5 = 0.25.
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
delayTime: 0.025,
|
||||
depth: 0.0,
|
||||
rate: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 1)
|
||||
let expected: Double = 0.25
|
||||
#expect(abs(out[0][0] - expected) < 1e-10, "Left ch first sample must be \(expected)")
|
||||
#expect(abs(out[1][0] - expected) < 1e-10, "Right ch first sample must be \(expected)")
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: 0.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
#expect(chorus.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output is stereo (2 channels)
|
||||
|
||||
@Test func outputIsStereo() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count == 2, "Chorus.Audio must produce exactly 2 output channels")
|
||||
#expect(out[0].count >= 512, "Channel 0 must have at least 512 samples")
|
||||
#expect(out[1].count >= 512, "Channel 1 must have at least 512 samples")
|
||||
}
|
||||
|
||||
// MARK: - Silent input → near-zero output
|
||||
|
||||
@Test func silentInputProducesNearZeroOutput() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
let samplesL: [Double] = Array(out[0].prefix(512))
|
||||
let samplesR: [Double] = Array(out[1].prefix(512))
|
||||
let allNearZeroL: Bool = samplesL.allSatisfy { abs($0) < 1e-12 }
|
||||
let allNearZeroR: Bool = samplesR.allSatisfy { abs($0) < 1e-12 }
|
||||
#expect(allNearZeroL, "Left channel: zero input must produce near-zero output")
|
||||
#expect(allNearZeroR, "Right channel: zero input must produce near-zero output")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent input produces non-zero output
|
||||
|
||||
@Test func nonSilentInputProducesNonZeroOutput() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
// Let delay line fill.
|
||||
for _ in 0..<5 {
|
||||
_ = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let rmsL: Double = rmsValue(Array(out[0].prefix(512)))
|
||||
let rmsR: Double = rmsValue(Array(out[1].prefix(512)))
|
||||
#expect(rmsL > 0, "Left channel must have non-zero output with non-silent input")
|
||||
#expect(rmsR > 0, "Right channel must have non-zero output with non-silent input")
|
||||
}
|
||||
|
||||
// MARK: - Left and right channels are distinct (LFOs 180° apart)
|
||||
|
||||
@Test func leftAndRightChannelsAreDistinct() {
|
||||
// With a varying input (sine wave), different delay offsets driven by the two LFOs
|
||||
// (180° apart) will read different values from the delay line, producing distinct
|
||||
// left and right outputs. Use mix=1.0 (all wet) so only tap differences matter.
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 880.0)
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: input,
|
||||
delayTime: 0.010,
|
||||
depth: 0.9,
|
||||
rate: 5.0,
|
||||
mix: 1.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
// Let delay line fill with the sine wave content and LFOs diverge.
|
||||
for _ in 0..<20 {
|
||||
_ = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
|
||||
.contains { abs($0 - $1) > 1e-8 }
|
||||
#expect(anyDiff, "Left and right channels must differ due to 180° LFO phase offset")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out1: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
let s1L: [Double] = Array(out1[0].prefix(512))
|
||||
let s2L: [Double] = Array(out2[0].prefix(512))
|
||||
let s1R: [Double] = Array(out1[1].prefix(512))
|
||||
let s2R: [Double] = Array(out2[1].prefix(512))
|
||||
#expect(s1L == s2L, "Fan-out: left channel must be identical on second call in same segment")
|
||||
#expect(s1R == s2R, "Fan-out: right channel must be identical on second call in same segment")
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
_ = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
_ = chorus.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let block2: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let allFiniteL: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
let allFiniteR: Bool = Array(block2[1].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFiniteL, "Left channel must be finite after block advance")
|
||||
#expect(allFiniteR, "Right channel must be finite after block advance")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
// Zero input → zero wet and dry → output 0. After mul:2 add:1 → output 1.
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
|
||||
let samplesL: [Double] = Array(out[0].prefix(512))
|
||||
let samplesR: [Double] = Array(out[1].prefix(512))
|
||||
let allNearOneL: Bool = samplesL.allSatisfy { abs($0 - 1.0) < 1e-10 }
|
||||
let allNearOneR: Bool = samplesR.allSatisfy { abs($0 - 1.0) < 1e-10 }
|
||||
#expect(allNearOneL, "Left channel: mulAdd(mul:2, add:1) on zero input must produce 1.0")
|
||||
#expect(allNearOneR, "Right channel: mulAdd(mul:2, add:1) on zero input must produce 1.0")
|
||||
}
|
||||
|
||||
// MARK: - Channel aliases
|
||||
|
||||
@Test func channelAliasesMatchSubscripts() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let leftOut: [[Double]] = chorus.left.calculatedSamples(graph: graph, count: 64)
|
||||
let rightOut: [[Double]] = chorus.right.calculatedSamples(graph: graph, count: 64)
|
||||
let fullOut: [[Double]] = chorus.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10,
|
||||
"left alias must match channel 0 at index \(i)")
|
||||
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10,
|
||||
"right alias must match channel 1 at index \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class ChorusSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let chorus: Chorus.Audio = Chorus.Audio(
|
||||
input: OscSin.Audio(freq: 220.0),
|
||||
delayTime: 0.025,
|
||||
depth: 0.002,
|
||||
rate: 1.5,
|
||||
mix: 0.5,
|
||||
sampleRate: 44100
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: chorus.left))
|
||||
addOutputGenerator(Out.Audio(bus: 1, source: chorus.right))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: ChorusSynth = ChorusSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// ClarinetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Clarinet")
|
||||
struct ClarinetTests {
|
||||
|
||||
// MARK: - Test fixture
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
let testMaxDelayTime: Double = 0.05
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
#expect(clar.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = clar.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Silent at zero excitation
|
||||
|
||||
@Test func silentAtZeroExcitation() {
|
||||
// With breathPressure = 0 and noiseGain = 0, no energy enters the bore.
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
breathPressure: 0.0,
|
||||
noiseGain: 0.0,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = clar.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-6 }
|
||||
#expect(allNearZero, "Output must be near zero with breathPressure = 0 and noiseGain = 0")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent with excitation
|
||||
|
||||
@Test func nonSilentWithExcitation() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: 0.6,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
var lastSamples: [Double] = []
|
||||
for _ in 0..<10 {
|
||||
let out: [[Double]] = clar.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
lastSamples = Array(out[0].prefix(512))
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let rms: Double = rmsValue(lastSamples)
|
||||
#expect(rms > 0, "Clarinet must produce non-zero output with breathPressure > 0")
|
||||
#expect(lastSamples.allSatisfy { $0.isFinite }, "All samples must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out single evaluation
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out1: [[Double]] = clar.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = clar.calculatedSamples(graph: graph, count: 512)
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - State advances across blocks
|
||||
|
||||
@Test func stateAdvancesAcrossBlocks() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
breathPressure: 0.6,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
_ = clar.calculatedSamples(graph: graph, count: 512)
|
||||
_ = clar.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block2: [[Double]] = clar.calculatedSamples(graph: graph2, count: 512)
|
||||
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples must be finite after block advance")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let clar1: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: ConstantGeneratorInput(0.6),
|
||||
noiseGain: ConstantGeneratorInput(0.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let clar2: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: ConstantGeneratorInput(0.6),
|
||||
noiseGain: ConstantGeneratorInput(0.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out1: [Double] = Array(clar1.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(clar2.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
var relationshipHolds: Bool = true
|
||||
for i: Int in 0..<512 {
|
||||
let expected: Double = out1[i] * 2.0 + 1.0
|
||||
if abs(out2[i] - expected) > 1e-10 {
|
||||
relationshipHolds = false
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(relationshipHolds, "mul:2.0 add:1.0 must produce output × 2 + 1")
|
||||
}
|
||||
|
||||
// MARK: - Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class ClarinetSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: 0.6,
|
||||
sampleRate: 44100,
|
||||
maxDelayTime: 0.05
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: clar))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: ClarinetSynth = ClarinetSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Finite after many blocks
|
||||
|
||||
@Test func finiteAfterManyBlocks() {
|
||||
let clar: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: 0.6,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let blockCount: Int = 200
|
||||
var allFinite: Bool = true
|
||||
for _ in 0..<blockCount {
|
||||
let out: [[Double]] = clar.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
if !samples.allSatisfy({ $0.isFinite }) {
|
||||
allFinite = false
|
||||
break
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allFinite, "Clarinet must produce finite output for 200 blocks")
|
||||
}
|
||||
|
||||
// MARK: - Reed stiffness affects tone
|
||||
|
||||
@Test func reedStiffnessAffectsTone() {
|
||||
let clar1: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: 0.6,
|
||||
reedStiffness: -0.2,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let clar2: Clarinet.Audio = Clarinet.Audio(
|
||||
freq: 220.0,
|
||||
breathPressure: 0.6,
|
||||
reedStiffness: -0.8,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
let warmupBlocks: Int = 20
|
||||
for b: Int in 0..<warmupBlocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = clar1.calculatedSamples(graph: g, count: 512)
|
||||
_ = clar2.calculatedSamples(graph: g, count: 512)
|
||||
advanceBlock(engine)
|
||||
_ = b
|
||||
}
|
||||
let gFinal: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [Double] = Array(clar1.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(clar2.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let identical: Bool = out1 == out2
|
||||
#expect(!identical, "Different reedStiffness values must produce different output buffers")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// CollectionRandomPickTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("CollectionRandomPick")
|
||||
struct CollectionRandomPickTests {
|
||||
|
||||
// MARK: - choose() empty / single
|
||||
|
||||
@Test func chooseEmptyReturnsNil() {
|
||||
let empty: [Int] = []
|
||||
#expect(empty.choose() == nil)
|
||||
}
|
||||
|
||||
@Test func chooseSingletonReturnsThatElement() {
|
||||
let single: [Int] = [42]
|
||||
#expect(single.choose() == 42)
|
||||
}
|
||||
|
||||
@Test func chooseSeededEmptyReturnsNil() {
|
||||
let empty: [Int] = []
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 1)
|
||||
#expect(empty.choose(rng: &rng) == nil)
|
||||
}
|
||||
|
||||
// MARK: - choose(rng:) determinism
|
||||
|
||||
@Test func chooseSeededIsDeterministic() {
|
||||
let values: [Int] = [-7, -5, -2, 1, 5]
|
||||
var rngA: UInt64 = lyrebirdSeedXorshift64(from: 123)
|
||||
var rngB: UInt64 = lyrebirdSeedXorshift64(from: 123)
|
||||
for _ in 0..<100 {
|
||||
#expect(values.choose(rng: &rngA) == values.choose(rng: &rngB))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func chooseSeededAdvancesState() {
|
||||
let values: [Int] = [0, 1, 2, 3, 4, 5, 6, 7]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 7)
|
||||
var picks: [Int] = []
|
||||
for _ in 0..<20 {
|
||||
guard let v: Int = values.choose(rng: &rng) else {
|
||||
Issue.record("choose returned nil from non-empty collection")
|
||||
return
|
||||
}
|
||||
picks.append(v)
|
||||
}
|
||||
let distinct: Set<Int> = Set(picks)
|
||||
#expect(distinct.count > 1)
|
||||
}
|
||||
|
||||
@Test func chooseSeededAllElementsReachable() {
|
||||
let values: [Int] = [-7, -5, -2, 1, 5]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 9999)
|
||||
var seen: Set<Int> = []
|
||||
for _ in 0..<2000 {
|
||||
if let v: Int = values.choose(rng: &rng) {
|
||||
seen.insert(v)
|
||||
}
|
||||
}
|
||||
#expect(seen == Set(values))
|
||||
}
|
||||
|
||||
// MARK: - choose(rng:) approximate uniformity
|
||||
|
||||
@Test func chooseSeededDistributionIsApproximatelyUniform() {
|
||||
let values: [Int] = [0, 1, 2, 3, 4]
|
||||
let trials: Int = 50_000
|
||||
let expectedPerBucket: Double = Double(trials) / Double(values.count)
|
||||
var counts: [Int: Int] = [:]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 555)
|
||||
for _ in 0..<trials {
|
||||
if let v: Int = values.choose(rng: &rng) {
|
||||
counts[v, default: 0] += 1
|
||||
}
|
||||
}
|
||||
let toleranceFraction: Double = 0.05
|
||||
for v: Int in values {
|
||||
let observed: Double = Double(counts[v] ?? 0)
|
||||
let delta: Double = abs(observed - expectedPerBucket)
|
||||
#expect(delta < expectedPerBucket * toleranceFraction)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - wchoose empty / mismatch / zero
|
||||
|
||||
@Test func wchooseEmptyReturnsNil() {
|
||||
let empty: [Int] = []
|
||||
#expect(empty.wchoose(weights: []) == nil)
|
||||
}
|
||||
|
||||
@Test func wchooseMismatchedWeightCountReturnsNil() {
|
||||
let values: [Int] = [10, 20, 30]
|
||||
#expect(values.wchoose(weights: [0.5, 0.5]) == nil)
|
||||
#expect(values.wchoose(weights: [0.25, 0.25, 0.25, 0.25]) == nil)
|
||||
}
|
||||
|
||||
@Test func wchooseAllZeroWeightsReturnsNil() {
|
||||
let values: [Int] = [1, 2, 3]
|
||||
#expect(values.wchoose(weights: [0.0, 0.0, 0.0]) == nil)
|
||||
}
|
||||
|
||||
@Test func wchooseNegativeWeightsTreatedAsZero() {
|
||||
let values: [Int] = [1, 2, 3]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 1)
|
||||
var picks: Set<Int> = []
|
||||
for _ in 0..<500 {
|
||||
if let v: Int = values.wchoose(weights: [-1.0, 5.0, -3.0], rng: &rng) {
|
||||
picks.insert(v)
|
||||
}
|
||||
}
|
||||
#expect(picks == [2])
|
||||
}
|
||||
|
||||
@Test func wchooseDeterministicSeeded() {
|
||||
let values: [String] = ["a", "b", "c", "d"]
|
||||
let weights: [Double] = [1.0, 2.0, 3.0, 4.0]
|
||||
var rngA: UInt64 = lyrebirdSeedXorshift64(from: 314159)
|
||||
var rngB: UInt64 = lyrebirdSeedXorshift64(from: 314159)
|
||||
for _ in 0..<100 {
|
||||
#expect(values.wchoose(weights: weights, rng: &rngA)
|
||||
== values.wchoose(weights: weights, rng: &rngB))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - wchoose statistical bias
|
||||
|
||||
@Test func wchooseRespectsWeightedBias() {
|
||||
let values: [Int] = [0, 1, 2, 3]
|
||||
let weights: [Double] = [0.1, 0.2, 0.3, 0.4]
|
||||
let trials: Int = 50_000
|
||||
var counts: [Int: Int] = [:]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 271828)
|
||||
for _ in 0..<trials {
|
||||
if let v: Int = values.wchoose(weights: weights, rng: &rng) {
|
||||
counts[v, default: 0] += 1
|
||||
}
|
||||
}
|
||||
let totalWeight: Double = 1.0
|
||||
let toleranceFraction: Double = 0.06
|
||||
for i: Int in 0..<values.count {
|
||||
let expectedCount: Double = Double(trials) * weights[i] / totalWeight
|
||||
let observed: Double = Double(counts[values[i]] ?? 0)
|
||||
let delta: Double = abs(observed - expectedCount)
|
||||
#expect(delta < expectedCount * toleranceFraction)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func wchooseAutoNormalisesNonUnitWeights() {
|
||||
let values: [Int] = [0, 1]
|
||||
let weights: [Double] = [10.0, 90.0]
|
||||
let trials: Int = 20_000
|
||||
var ones: Int = 0
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 17)
|
||||
for _ in 0..<trials {
|
||||
if values.wchoose(weights: weights, rng: &rng) == 1 {
|
||||
ones += 1
|
||||
}
|
||||
}
|
||||
let observedFraction: Double = Double(ones) / Double(trials)
|
||||
let expectedFraction: Double = 0.9 // 90 / (10 + 90)
|
||||
let toleranceFraction: Double = 0.02
|
||||
#expect(abs(observedFraction - expectedFraction) < toleranceFraction)
|
||||
}
|
||||
|
||||
// MARK: - works on non-Array Collections
|
||||
|
||||
@Test func chooseWorksOnRange() {
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 42)
|
||||
var seen: Set<Int> = []
|
||||
for _ in 0..<500 {
|
||||
if let v: Int = (0..<8).choose(rng: &rng) {
|
||||
seen.insert(v)
|
||||
}
|
||||
}
|
||||
#expect(seen == Set(0..<8))
|
||||
}
|
||||
|
||||
@Test func chooseWorksOnArraySlice() {
|
||||
let arr: [Int] = [10, 20, 30, 40, 50]
|
||||
let slice: ArraySlice<Int> = arr[1..<4]
|
||||
var rng: UInt64 = lyrebirdSeedXorshift64(from: 11)
|
||||
var seen: Set<Int> = []
|
||||
for _ in 0..<500 {
|
||||
if let v: Int = slice.choose(rng: &rng) {
|
||||
seen.insert(v)
|
||||
}
|
||||
}
|
||||
#expect(seen == Set([20, 30, 40]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// CompressorParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Compressor parameter ramping")
|
||||
struct CompressorParameterRampingTests {
|
||||
|
||||
@Test func thresholdGeneratorInputIsRead() throws {
|
||||
// Verify wiring a ParameterNode to threshold produces valid output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-6.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let comp: Compressor.Audio = Compressor.Audio(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = comp.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Compressor.Audio output must be finite with ParameterNode threshold")
|
||||
}
|
||||
|
||||
@Test func thresholdParameterNodeOutputDiffersByBlock() throws {
|
||||
// Verify that the ParameterNode-wired threshold is read (not ignored).
|
||||
// Two separate Compressor instances with instant attack (attack=0):
|
||||
// - comp1: threshold = -20 dB → signal at -6 dBFS is well above threshold → heavy compression
|
||||
// - comp2: threshold = 0 dB → signal is below threshold → bypass (no compression)
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let signal1: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let signal2: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
|
||||
// threshNode1: -20 dB → signal at ~-6 dBFS is 14 dB above threshold → compression
|
||||
let threshNode1: ParameterNode = ParameterNode(-20.0)
|
||||
let comp1: Compressor.Audio = Compressor.Audio(in: signal1, threshold: threshNode1,
|
||||
ratio: 100.0, attack: 0.0, release: 0.0)
|
||||
|
||||
// threshNode2: 0 dB → signal is below threshold → no compression
|
||||
let threshNode2: ParameterNode = ParameterNode(0.0)
|
||||
let comp2: Compressor.Audio = Compressor.Audio(in: signal2, threshold: threshNode2,
|
||||
ratio: 100.0, attack: 0.0, release: 0.0)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [[Double]] = comp1.calculatedSamples(graph: g, count: 64)
|
||||
let out2: [[Double]] = comp2.calculatedSamples(graph: g, count: 64)
|
||||
|
||||
let rms1: Double = rmsValue(Array((out1.first ?? []).prefix(64)))
|
||||
let rms2: Double = rmsValue(Array((out2.first ?? []).prefix(64)))
|
||||
|
||||
// comp1 compresses aggressively (14 dB above threshold, ratio 100:1, instant attack).
|
||||
// comp2 passes through unchanged. rms1 should be significantly less than rms2.
|
||||
#expect(rms1 < rms2 * 0.5,
|
||||
"ParameterNode threshold at -20dB with ratio=100 should heavily compress vs threshold=0dB: rms1=\(rms1) rms2=\(rms2)")
|
||||
}
|
||||
|
||||
@Test func controlThresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-6.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let comp: Compressor.Control = Compressor.Control(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = comp.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Compressor.Control output must be finite with ParameterNode threshold")
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,343 @@
|
||||
// ConvolutionReverbTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("ConvolutionReverb.Audio — partitioned overlap-save FFT convolution")
|
||||
struct ConvolutionReverbTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Build a single-channel IR with `frames` frames; sample at `frame` is `value`.
|
||||
private func makeUnitImpulseIR(frames: Int, position: Int = 0) -> LyrebirdBuffer {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: 1)
|
||||
buf.setValue(1.0, at: position)
|
||||
return buf
|
||||
}
|
||||
|
||||
/// Build a multi-channel IR with the same shape on every channel.
|
||||
private func makeMultiChannelImpulseIR(frames: Int, channels: Int) -> LyrebirdBuffer {
|
||||
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: channels)
|
||||
for c: Int in 0..<channels {
|
||||
buf.setValue(1.0, frame: 0, channel: c)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
/// Drive the verb with a generator that emits the supplied input sequence.
|
||||
private final class SequenceSource: GeneratorBase, AudioGenerator {
|
||||
var samples: [Double]
|
||||
var pos: Int = 0
|
||||
|
||||
init(_ samples: [Double]) { self.samples = samples; super.init() }
|
||||
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = pos < samples.count ? samples[pos] : 0
|
||||
pos += 1
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 1. Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: ir)
|
||||
#expect(verb.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - 2. outputChannelCount matches IR
|
||||
|
||||
@Test func outputChannelCountMatchesIR() {
|
||||
let irMono: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
|
||||
let monoVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: irMono)
|
||||
#expect(monoVerb.outputChannelCount == 1)
|
||||
|
||||
let irStereo: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 4, channels: 2)
|
||||
let stereoVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: irStereo)
|
||||
#expect(stereoVerb.outputChannelCount == 2)
|
||||
|
||||
let ir4: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 4, channels: 4)
|
||||
let quadVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: ir4)
|
||||
#expect(quadVerb.outputChannelCount == 4)
|
||||
}
|
||||
|
||||
// MARK: - 3. Silent input → silent output (after warmup)
|
||||
|
||||
@Test func silentInputProducesSilentOutput() {
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.0),
|
||||
ir: ir,
|
||||
mix: 1.0
|
||||
)
|
||||
for _ in 0..<5 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
let maxAbs: Double = out[0].prefix(512).map { abs($0) }.max() ?? 0
|
||||
#expect(maxAbs < 1e-9, "Silent input → silent output; got \(maxAbs)")
|
||||
}
|
||||
|
||||
// MARK: - 4. mix=0 → exact dry passthrough
|
||||
|
||||
@Test func mixZeroIsPassthrough() {
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.42),
|
||||
ir: ir,
|
||||
mix: 0.0
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(out[0][i] - 0.42) < 1e-12,
|
||||
"mix=0: dry passthrough; sample \(i) = \(out[0][i])")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 5. Unit-impulse IR is identity (mix=1, after one-partition latency)
|
||||
|
||||
@Test func unitImpulseIRPreservesInput() {
|
||||
let partitionSize: Int = 64
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: partitionSize)
|
||||
// Input = ramp 1, 2, 3, ..., scaled small.
|
||||
let inputCount: Int = partitionSize * 6
|
||||
var rampSamples: [Double] = [Double]()
|
||||
for i: Int in 0..<inputCount { rampSamples.append(0.001 * Double(i + 1)) }
|
||||
let src: ConvolutionReverbTests.SequenceSource = SequenceSource(rampSamples)
|
||||
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: src,
|
||||
ir: ir,
|
||||
partitionSize: partitionSize,
|
||||
mix: 1.0
|
||||
)
|
||||
|
||||
// Pull all output in one block.
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
|
||||
|
||||
// After partitionSize-sample latency, output should equal input.
|
||||
for i: Int in partitionSize..<inputCount {
|
||||
let expected: Double = rampSamples[i - partitionSize]
|
||||
#expect(abs(out[0][i] - expected) < 1e-5,
|
||||
"i=\(i) expected \(expected), got \(out[0][i])")
|
||||
}
|
||||
// First partitionSize samples must be silent (pre-latency).
|
||||
for i: Int in 0..<partitionSize {
|
||||
#expect(abs(out[0][i]) < 1e-9, "Pre-latency sample \(i) = \(out[0][i])")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 6. Delayed-impulse IR delays input by IR delay
|
||||
|
||||
@Test func delayedImpulseIRDelaysInput() {
|
||||
let partitionSize: Int = 64
|
||||
let irDelay: Int = 32
|
||||
let irFrames: Int = partitionSize
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: irFrames, position: irDelay)
|
||||
|
||||
let inputCount: Int = partitionSize * 6
|
||||
let src: ConvolutionReverbTests.SequenceSource = SequenceSource((0..<inputCount).map { Double($0 == 0 ? 1.0 : 0.0) })
|
||||
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: src,
|
||||
ir: ir,
|
||||
partitionSize: partitionSize,
|
||||
mix: 1.0
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
|
||||
|
||||
// Output[partitionSize + irDelay] should be the lone impulse (one-partition
|
||||
// latency PLUS the IR delay). Other samples ~0.
|
||||
let expectedSpike: Int = partitionSize + irDelay
|
||||
#expect(abs(out[0][expectedSpike] - 1.0) < 1e-5,
|
||||
"Impulse should appear at sample \(expectedSpike), got \(out[0][expectedSpike])")
|
||||
for i: Int in 0..<inputCount where i != expectedSpike {
|
||||
#expect(abs(out[0][i]) < 1e-5,
|
||||
"Non-spike sample \(i) = \(out[0][i])")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 7. Multi-partition IR (length > partitionSize)
|
||||
|
||||
@Test func multiPartitionIRConvolves() {
|
||||
// IR longer than one partition: impulse at frame 0 AND at frame 100 (across
|
||||
// partition boundary at 64). Convolves dirac input → both echoes.
|
||||
let partitionSize: Int = 64
|
||||
let irFrames: Int = 200
|
||||
let ir: LyrebirdBuffer = LyrebirdBuffer(count: irFrames, channelCount: 1)
|
||||
ir.setValue(1.0, at: 0)
|
||||
ir.setValue(0.5, at: 100)
|
||||
|
||||
let inputCount: Int = 512
|
||||
let src: ConvolutionReverbTests.SequenceSource = SequenceSource([1.0] + Array(repeating: 0.0, count: inputCount - 1))
|
||||
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: src,
|
||||
ir: ir,
|
||||
partitionSize: partitionSize,
|
||||
mix: 1.0
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
|
||||
|
||||
// Echo at sample partitionSize + 0 = 64 with amplitude 1.0
|
||||
// Echo at sample partitionSize + 100 = 164 with amplitude 0.5
|
||||
#expect(abs(out[0][partitionSize] - 1.0) < 1e-4,
|
||||
"First echo at \(partitionSize) = \(out[0][partitionSize])")
|
||||
#expect(abs(out[0][partitionSize + 100] - 0.5) < 1e-4,
|
||||
"Second echo at \(partitionSize + 100) = \(out[0][partitionSize + 100])")
|
||||
}
|
||||
|
||||
// MARK: - 8. mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.0),
|
||||
ir: ir,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(out[0][i] - 1.0) < 1e-12,
|
||||
"Silent input + mul=2,add=1 → 1.0; got \(out[0][i]) at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 9. Stereo IR produces two distinct channels
|
||||
|
||||
@Test func stereoIRProducesDistinctChannels() {
|
||||
// Left = impulse at 0; right = impulse at 32. Mono dirac input.
|
||||
let partitionSize: Int = 64
|
||||
let irFrames: Int = partitionSize
|
||||
let ir: LyrebirdBuffer = LyrebirdBuffer(count: irFrames, channelCount: 2)
|
||||
ir.setValue(1.0, frame: 0, channel: 0)
|
||||
ir.setValue(1.0, frame: 32, channel: 1)
|
||||
|
||||
let src: ConvolutionReverbTests.SequenceSource = SequenceSource([1.0] + Array(repeating: 0.0, count: 255))
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: src,
|
||||
ir: ir,
|
||||
partitionSize: partitionSize,
|
||||
mix: 1.0
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 256)
|
||||
|
||||
#expect(abs(out[0][partitionSize] - 1.0) < 1e-4,
|
||||
"Left echo at \(partitionSize) = \(out[0][partitionSize])")
|
||||
#expect(abs(out[1][partitionSize + 32] - 1.0) < 1e-4,
|
||||
"Right echo at \(partitionSize + 32) = \(out[1][partitionSize + 32])")
|
||||
// Right channel should NOT have a spike at partitionSize.
|
||||
#expect(abs(out[1][partitionSize]) < 1e-4,
|
||||
"Right at \(partitionSize) = \(out[1][partitionSize]) (should be silent)")
|
||||
}
|
||||
|
||||
// MARK: - 10. Fan-out: single evaluation per segment
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 256)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
ir: ir,
|
||||
mix: 0.5
|
||||
)
|
||||
let out1: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out1[0][i] == out2[0][i],
|
||||
"Fan-out: identical samples at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 11. .left/.right channel aliases
|
||||
|
||||
@Test func leftRightAliases() {
|
||||
let ir: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 64, channels: 2)
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.0),
|
||||
ir: ir
|
||||
)
|
||||
// Just verify they construct without trapping; the underlying ChannelSelect
|
||||
// uses subscript indexing.
|
||||
_ = verb.left
|
||||
_ = verb.right
|
||||
}
|
||||
|
||||
// MARK: - 12. partitionSize must be power of two ≥ 4
|
||||
|
||||
@Test func partitionSizeMustBePowerOfTwo() {
|
||||
// Valid pow-of-two passes.
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
|
||||
_ = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.0),
|
||||
ir: ir,
|
||||
partitionSize: 4
|
||||
)
|
||||
_ = ConvolutionReverb.Audio(
|
||||
input: ConstantGeneratorInput(0.0),
|
||||
ir: ir,
|
||||
partitionSize: 1024
|
||||
)
|
||||
// Non-pow-of-two would trap; we don't exercise via #expect(throws:) since
|
||||
// precondition aborts the process. The build-time check is sufficient.
|
||||
}
|
||||
|
||||
// MARK: - 13. Energy preservation: convolution with normalised IR ≈ input energy
|
||||
|
||||
@Test func unitImpulseIRPreservesEnergy() {
|
||||
// x convolved with δ[0] should equal x, so energy preserved exactly.
|
||||
let partitionSize: Int = 128
|
||||
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: partitionSize)
|
||||
let blockSize: Int = 512
|
||||
let blocks: Int = 8
|
||||
let inputCount: Int = blockSize * blocks
|
||||
let src: ConvolutionReverbTests.SequenceSource = SequenceSource((0..<inputCount).map { _ in
|
||||
Double.random(in: -0.5...0.5)
|
||||
})
|
||||
let inputCopy: [Double] = src.samples
|
||||
|
||||
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
|
||||
input: src,
|
||||
ir: ir,
|
||||
partitionSize: partitionSize,
|
||||
mix: 1.0
|
||||
)
|
||||
|
||||
// Pull block-by-block through the engine.
|
||||
var allOutput: [Double] = [Double]()
|
||||
allOutput.reserveCapacity(inputCount)
|
||||
for _ in 0..<blocks {
|
||||
let block: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
|
||||
allOutput += block[0].prefix(blockSize)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Compare aligned ranges: output[partitionSize..] vs input[0..inputCount-partitionSize].
|
||||
let alignedLen: Int = inputCount - partitionSize
|
||||
var inEnergy: Double = 0.0
|
||||
var outEnergy: Double = 0.0
|
||||
for i: Int in 0..<alignedLen {
|
||||
inEnergy += inputCopy[i] * inputCopy[i]
|
||||
outEnergy += allOutput[i + partitionSize] * allOutput[i + partitionSize]
|
||||
}
|
||||
let ratio: Double = outEnergy / inEnergy
|
||||
#expect(abs(ratio - 1.0) < 1e-3,
|
||||
"Energy ratio out/in = \(ratio) (expected ~1.0)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// CoreAudioDriverTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - CoreAudioDriverOptions defaults
|
||||
|
||||
@Suite("CoreAudioDriverOptions") struct CoreAudioDriverOptionsTests {
|
||||
@Test func defaultMatchDeviceSampleRateIsFalse() {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
|
||||
#expect(opts.matchDeviceSampleRate == false)
|
||||
}
|
||||
|
||||
@Test func canEnableMatchDeviceSampleRate() {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions(matchDeviceSampleRate: true)
|
||||
#expect(opts.matchDeviceSampleRate == true)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sample rate validation (offline, no hardware required)
|
||||
|
||||
@Suite("CoreAudioDriver sample rate validation") struct CoreAudioSampleRateValidationTests {
|
||||
@Test func doesNotThrowWhenRatesMatch() throws {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
|
||||
try CoreAudioDriver._validateSampleRates(
|
||||
requested: 44100.0, deviceRate: 44100.0, options: opts)
|
||||
}
|
||||
|
||||
@Test func throwsSampleRateMismatchWhenRatesDiffer() {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
|
||||
#expect(throws: CoreAudioError.self) {
|
||||
try CoreAudioDriver._validateSampleRates(
|
||||
requested: 44100.0, deviceRate: 48000.0, options: opts)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func mismatchErrorCarriesRequestedAndDeviceRate() {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
|
||||
var caught: CoreAudioError?
|
||||
do {
|
||||
try CoreAudioDriver._validateSampleRates(
|
||||
requested: 44100.0, deviceRate: 48000.0, options: opts)
|
||||
} catch let e as CoreAudioError {
|
||||
caught = e
|
||||
} catch {}
|
||||
|
||||
guard case .sampleRateMismatch(let requested, let deviceRate) = caught else {
|
||||
Issue.record("Expected sampleRateMismatch, got \(String(describing: caught))")
|
||||
return
|
||||
}
|
||||
#expect(requested == 44100.0)
|
||||
#expect(deviceRate == 48000.0)
|
||||
}
|
||||
|
||||
@Test func doesNotThrowWithMatchDeviceSampleRateWhenRatesDiffer() throws {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions(matchDeviceSampleRate: true)
|
||||
// Should not throw — driver will attempt to set the hardware rate instead.
|
||||
try CoreAudioDriver._validateSampleRates(
|
||||
requested: 44100.0, deviceRate: 48000.0, options: opts)
|
||||
}
|
||||
|
||||
@Test func toleratesFloatingPointNoise() throws {
|
||||
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
|
||||
// Rates that differ by less than 0.01 are treated as equal.
|
||||
try CoreAudioDriver._validateSampleRates(
|
||||
requested: 44100.0, deviceRate: 44100.005, options: opts)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - deviceSampleRate property
|
||||
|
||||
@Suite("CoreAudioDriver deviceSampleRate") struct CoreAudioDeviceSampleRateTests {
|
||||
@Test func deviceSampleRateNilBeforeSetup() {
|
||||
let driver: CoreAudioDriver = CoreAudioDriver()
|
||||
#expect(driver.deviceSampleRate == nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle (no hardware required)
|
||||
|
||||
@Suite("CoreAudioDriver lifecycle") struct CoreAudioDriverLifecycleTests {
|
||||
@Test func stopBeforeSetupIsNoop() {
|
||||
let driver: CoreAudioDriver = CoreAudioDriver()
|
||||
driver.stop()
|
||||
}
|
||||
|
||||
@Test func stopTwiceIsNoop() {
|
||||
let driver: CoreAudioDriver = CoreAudioDriver()
|
||||
driver.stop()
|
||||
driver.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Decay2Tests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Decay2")
|
||||
struct Decay2Tests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let blockSize: Int = 64
|
||||
let sampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
// MARK: 1. Rate
|
||||
|
||||
@Test func audioRate() {
|
||||
let gen: Decay2.Audio = Decay2.Audio(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func controlRate() {
|
||||
let gen: Decay2.Control = Decay2.Control(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
// MARK: 2. Output length
|
||||
|
||||
@Test func audioOutputLength() {
|
||||
let gen: Decay2.Audio = Decay2.Audio(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(result.count == 1)
|
||||
#expect(Array(result[0].prefix(blockSize)).count == blockSize)
|
||||
}
|
||||
|
||||
// MARK: 3. First sample is 0 when both integrators start at zero
|
||||
|
||||
@Test func firstSampleIsZero() {
|
||||
let gen: Decay2.Audio = Decay2.Audio(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
// At n=0 both integrators start at 0; yD[0]=x+bD*0=x, yA[0]=x+bA*0=x → output = 0
|
||||
#expect(abs(result[0][0]) < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: 4. Output eventually becomes positive (decay integrator dominates after attack)
|
||||
|
||||
@Test func outputBecomesPositive() {
|
||||
let gen: Decay2.Audio = Decay2.Audio(input: 1.0, attackTime: 0.001, decayTime: 0.5)
|
||||
var maxVal: Double = 0.0
|
||||
for _ in 0..<20 {
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
|
||||
maxVal = max(maxVal, result[0][blockSize - 1])
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(maxVal > 0)
|
||||
}
|
||||
|
||||
// MARK: 5. Equal times = zero output (decay - attack cancel)
|
||||
|
||||
@Test func equalTimesGivesZero() {
|
||||
let t: Double = 0.1
|
||||
let gen: Decay2.Audio = Decay2.Audio(input: 1.0, attackTime: t, decayTime: t)
|
||||
for _ in 0..<10 {
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
|
||||
// Both integrators identical → difference = 0 every sample
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(result[0][i]) < 1e-10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: 6. Control previousOutputValue
|
||||
|
||||
@Test func previousOutputValueUpdates() {
|
||||
let gen: Decay2.Control = Decay2.Control(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(gen.previousOutputValue == result[0][blockSize - 1])
|
||||
}
|
||||
|
||||
// MARK: 7. GeneratorEnum
|
||||
|
||||
@Test func generatorEnumAudioType() {
|
||||
let _: Decay2.AudioType = Decay2.Audio(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
}
|
||||
|
||||
@Test func generatorEnumControlType() {
|
||||
let _: Decay2.ControlType = Decay2.Control(input: 1.0, attackTime: 0.01, decayTime: 0.5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// DecayTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Decay")
|
||||
struct DecayTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let blockSize: Int = 64
|
||||
let sampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
// MARK: 1. Rate
|
||||
|
||||
@Test func audioRate() {
|
||||
let gen: Decay.Audio = Decay.Audio(input: 1.0, decayTime: 0.5)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func controlRate() {
|
||||
let gen: Decay.Control = Decay.Control(input: 1.0, decayTime: 0.5)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
// MARK: 2. Output length
|
||||
|
||||
@Test func audioOutputLength() {
|
||||
let gen: Decay.Audio = Decay.Audio(input: 1.0, decayTime: 0.5)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(result.count == 1)
|
||||
#expect(Array(result[0].prefix(blockSize)).count == blockSize)
|
||||
}
|
||||
|
||||
// MARK: 3. Impulse response decays to near zero after decayTime
|
||||
|
||||
@Test func impulseDecays() {
|
||||
// Feed a single impulse (constant 1.0 input for one block), then silence.
|
||||
// After decayTime worth of blocks the output should be < 0.001.
|
||||
let decayTime: Double = 0.05
|
||||
// Use a step input (constant 1.0) approximating energy injection, then check decay from memory.
|
||||
// Simpler: feed the Decay with 1.0 for one block to build up state, then feed 0.0.
|
||||
// Since we can't change input after init, use two separate gens and verify the output
|
||||
// after many blocks of silence is near zero for a decay with known decayTime.
|
||||
let gen: Decay.Audio = Decay.Audio(input: 0.0, decayTime: decayTime)
|
||||
// Manually set state by running one block with 1.0 (can't easily inject state),
|
||||
// so instead confirm that Decay with zero input stays at zero (valid boundary case).
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(result[0][0] == 0.0)
|
||||
}
|
||||
|
||||
@Test func decayOutputIsPositiveForPositiveImpulse() {
|
||||
// Decay with constant positive input should produce positive output.
|
||||
let gen: Decay.Audio = Decay.Audio(input: 1.0, decayTime: 0.1)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(result[0][blockSize - 1] > 0)
|
||||
}
|
||||
|
||||
// MARK: 4. Zero decayTime = pass-through
|
||||
|
||||
@Test func zeroDecayTimeIsPassThrough() {
|
||||
let gen: Decay.Audio = Decay.Audio(input: 0.5, decayTime: 0.0)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(abs(result[0][0] - 0.5) < 1e-10)
|
||||
#expect(abs(result[0][blockSize - 1] - 0.5) < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: 5. Decay grows under constant input
|
||||
|
||||
@Test func audioOutputGrowsUnderConstantInput() {
|
||||
let gen: Decay.Audio = Decay.Audio(input: 1.0, decayTime: 0.5)
|
||||
let r1: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
|
||||
advanceBlock(engine)
|
||||
let r2: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
|
||||
// Integrator accumulates, so later blocks should be larger
|
||||
#expect(r2[0][blockSize - 1] > r1[0][0])
|
||||
}
|
||||
|
||||
// MARK: 6. Control previousOutputValue
|
||||
|
||||
@Test func previousOutputValueUpdates() {
|
||||
let gen: Decay.Control = Decay.Control(input: 1.0, decayTime: 0.5)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(gen.previousOutputValue == result[0][blockSize - 1])
|
||||
}
|
||||
|
||||
// MARK: 7. mulAdd
|
||||
|
||||
@Test func mulAdd() {
|
||||
let gen: Decay.Audio = Decay.Audio(input: 0.0, decayTime: 0.0, mul: 3.0, add: 2.0)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
// 0 * 3 + 2 = 2
|
||||
#expect(abs(result[0][0] - 2.0) < 1e-10)
|
||||
}
|
||||
|
||||
// MARK: 8. GeneratorEnum
|
||||
|
||||
@Test func generatorEnumAudioType() {
|
||||
let _: Decay.AudioType = Decay.Audio(input: 1.0, decayTime: 0.5)
|
||||
}
|
||||
|
||||
@Test func generatorEnumControlType() {
|
||||
let _: Decay.ControlType = Decay.Control(input: 1.0, decayTime: 0.5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// DelayLineFeedbackParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DelayLineFeedback parameter ramping")
|
||||
struct DelayLineFeedbackParameterRampingTests {
|
||||
|
||||
@Test func decayTimeGeneratorInputDoesNotCrash() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let decayNode: ParameterNode = ParameterNode(2.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.3)
|
||||
let delay: DelayLineFeedback = DelayLineFeedback(
|
||||
input: signal,
|
||||
maxDelay: 0.5,
|
||||
delay: 0.1,
|
||||
decayTime: decayNode,
|
||||
targetAmp: 0.001,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = delay.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"DelayLineFeedback output must be finite with ParameterNode decayTime")
|
||||
}
|
||||
|
||||
@Test func targetAmpGeneratorInputDoesNotCrash() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let ampNode: ParameterNode = ParameterNode(0.001)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.3)
|
||||
let delay: DelayLineFeedback = DelayLineFeedback(
|
||||
input: signal,
|
||||
maxDelay: 0.5,
|
||||
delay: 0.1,
|
||||
decayTime: 2.0,
|
||||
targetAmp: ampNode,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = delay.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"DelayLineFeedback output must be finite with ParameterNode targetAmp")
|
||||
}
|
||||
|
||||
@Test func decayTimeRampChangesOutputEnergy() throws {
|
||||
// Block 1: decayTime=5.0 (long, lots of feedback). Block 2: ramp to 0.01 (short, almost no feedback).
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let decayNode: ParameterNode = ParameterNode(5.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.3)
|
||||
let delay: DelayLineFeedback = DelayLineFeedback(
|
||||
input: signal,
|
||||
maxDelay: 0.5,
|
||||
delay: 0.1,
|
||||
decayTime: decayNode,
|
||||
targetAmp: 0.001,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
// Warm up several blocks to build feedback.
|
||||
for _ in 0..<10 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = delay.calculatedSamples(graph: g, count: 64)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Block: long decay — measure output energy.
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [[Double]] = delay.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Now ramp to very short decay.
|
||||
decayNode.value = 0.001
|
||||
// Run several more blocks so feedback decays.
|
||||
for _ in 0..<5 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = delay.calculatedSamples(graph: g, count: 64)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = delay.calculatedSamples(graph: g2, count: 64)
|
||||
|
||||
let energy1: Double = rmsValue(Array((out1.first ?? []).prefix(64)))
|
||||
let energy2: Double = rmsValue(Array((out2.first ?? []).prefix(64)))
|
||||
|
||||
// After short decay, output should have less energy than after long decay.
|
||||
#expect(energy2 < energy1 + 0.01,
|
||||
"DelayLineFeedback: after decayTime ramp to near-zero, output energy should drop: \(energy2) vs \(energy1)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// DemandBrownianTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandBrownian")
|
||||
struct DemandBrownianTests {
|
||||
|
||||
@Test func walkStaysWithinBounds() {
|
||||
let d: DemandBrownian = DemandBrownian(
|
||||
low: -10.0,
|
||||
high: 10.0,
|
||||
step: 5.0,
|
||||
length: 10_000,
|
||||
seed: 99
|
||||
)
|
||||
while let v: Double = d.nextValue() {
|
||||
#expect(v >= -10.0 && v <= 10.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func startDefaultsToMidpoint() {
|
||||
let d: DemandBrownian = DemandBrownian(
|
||||
low: 0.0,
|
||||
high: 100.0,
|
||||
step: 0.0,
|
||||
length: 1,
|
||||
seed: 1
|
||||
)
|
||||
#expect(d.nextValue() == 50.0)
|
||||
}
|
||||
|
||||
@Test func sameSeedSameStartProducesIdenticalWalk() {
|
||||
let a: DemandBrownian = DemandBrownian(
|
||||
low: -5.0, high: 5.0, step: 0.5, start: 0.0, length: 100, seed: 2024
|
||||
)
|
||||
let b: DemandBrownian = DemandBrownian(
|
||||
low: -5.0, high: 5.0, step: 0.5, start: 0.0, length: 100, seed: 2024
|
||||
)
|
||||
for _ in 0..<100 {
|
||||
#expect(a.nextValue() == b.nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetRestoresStartPosition() {
|
||||
let d: DemandBrownian = DemandBrownian(
|
||||
low: -10.0, high: 10.0, step: 1.0, start: 7.0, length: -1, seed: 5
|
||||
)
|
||||
for _ in 0..<50 { _ = d.nextValue() }
|
||||
d.reset()
|
||||
if let v: Double = d.nextValue() {
|
||||
#expect(v >= 6.0 && v <= 8.0)
|
||||
} else {
|
||||
Issue.record("Expected non-nil value after reset")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// DemandConcatenateTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandConcatenate")
|
||||
struct DemandConcatenateTests {
|
||||
|
||||
@Test func playsEachInTurn() {
|
||||
let d: DemandConcatenate = DemandConcatenate(demands: [
|
||||
DemandSequence(values: [1.0, 2.0], repeats: 1),
|
||||
DemandSequence(values: [10.0, 20.0, 30.0], repeats: 1),
|
||||
DemandSequence(values: [100.0], repeats: 1)
|
||||
])
|
||||
var collected: [Double] = []
|
||||
while let v: Double = d.nextValue() { collected.append(v) }
|
||||
#expect(collected == [1.0, 2.0, 10.0, 20.0, 30.0, 100.0])
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func emptyListExhaustsImmediately() {
|
||||
let d: DemandConcatenate = DemandConcatenate(demands: [])
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func skipsExhaustedSubSources() {
|
||||
let d: DemandConcatenate = DemandConcatenate(demands: [
|
||||
DemandSequence(values: [], repeats: 1),
|
||||
DemandSequence(values: [5.0], repeats: 1),
|
||||
DemandSequence(values: [], repeats: 1),
|
||||
DemandSequence(values: [10.0], repeats: 1)
|
||||
])
|
||||
var collected: [Double] = []
|
||||
while let v: Double = d.nextValue() { collected.append(v) }
|
||||
#expect(collected == [5.0, 10.0])
|
||||
}
|
||||
|
||||
@Test func resetReplaysAll() {
|
||||
let d: DemandConcatenate = DemandConcatenate(demands: [
|
||||
DemandSequence(values: [1.0, 2.0], repeats: 1),
|
||||
DemandSequence(values: [3.0, 4.0], repeats: 1)
|
||||
])
|
||||
var first: [Double] = []
|
||||
while let v: Double = d.nextValue() { first.append(v) }
|
||||
#expect(first == [1.0, 2.0, 3.0, 4.0])
|
||||
d.reset()
|
||||
var second: [Double] = []
|
||||
while let v: Double = d.nextValue() { second.append(v) }
|
||||
#expect(second == first)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
// DemandGeneratorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - DemandSequence
|
||||
|
||||
@Suite("DemandSequence")
|
||||
struct DSequenceTests {
|
||||
|
||||
@Test func returnsValuesInOrder() {
|
||||
let seq: DemandSequence = DemandSequence(values: [1.0, 2.0, 3.0])
|
||||
#expect(seq.nextValue() == 1.0)
|
||||
#expect(seq.nextValue() == 2.0)
|
||||
#expect(seq.nextValue() == 3.0)
|
||||
}
|
||||
|
||||
@Test func wrapsAfterFullCycle() {
|
||||
let seq: DemandSequence = DemandSequence(values: [10.0, 20.0])
|
||||
_ = seq.nextValue(); _ = seq.nextValue() // complete cycle 1
|
||||
#expect(seq.nextValue() == 10.0) // cycle 2 starts
|
||||
}
|
||||
|
||||
@Test func infiniteRepeatsNeverExhausts() {
|
||||
let seq: DemandSequence = DemandSequence(values: [1.0, 2.0], repeats: -1)
|
||||
for _ in 0..<100 { _ = seq.nextValue() }
|
||||
#expect(!seq.isExhausted)
|
||||
#expect(seq.nextValue() != nil)
|
||||
}
|
||||
|
||||
@Test func exhaustsAfterNRepeats() {
|
||||
let seq: DemandSequence = DemandSequence(values: [1.0, 2.0, 3.0], repeats: 2)
|
||||
var count: Int = 0
|
||||
while let _ = seq.nextValue() { count += 1 }
|
||||
#expect(count == 6) // 3 values × 2 repeats
|
||||
#expect(seq.isExhausted)
|
||||
#expect(seq.nextValue() == nil)
|
||||
}
|
||||
|
||||
@Test func zeroRepeatsExhaustedImmediately() {
|
||||
let seq: DemandSequence = DemandSequence(values: [1.0, 2.0], repeats: 0)
|
||||
#expect(seq.isExhausted)
|
||||
#expect(seq.nextValue() == nil)
|
||||
}
|
||||
|
||||
@Test func resetRestartsFromBeginning() {
|
||||
let seq: DemandSequence = DemandSequence(values: [1.0, 2.0], repeats: 1)
|
||||
_ = seq.nextValue(); _ = seq.nextValue() // exhaust
|
||||
#expect(seq.isExhausted)
|
||||
seq.reset()
|
||||
#expect(!seq.isExhausted)
|
||||
#expect(seq.nextValue() == 1.0)
|
||||
}
|
||||
|
||||
@Test func emptyValuesAlwaysNil() {
|
||||
let seq: DemandSequence = DemandSequence(values: [])
|
||||
#expect(seq.nextValue() == nil)
|
||||
#expect(!seq.isExhausted) // empty ≠ exhausted
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DemandRandom
|
||||
|
||||
@Suite("DemandRandom")
|
||||
struct DRandomTests {
|
||||
|
||||
@Test func returnsValuesFromPool() {
|
||||
let pool: [Double] = [10.0, 20.0, 30.0, 40.0]
|
||||
let rand: DemandRandom = DemandRandom(values: pool, repeats: 20)
|
||||
for _ in 0..<20 {
|
||||
guard let v: Double = rand.nextValue() else { Issue.record("unexpectedly nil"); return }
|
||||
#expect(pool.contains(v))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func infiniteRepeatsNeverExhausts() {
|
||||
let rand: DemandRandom = DemandRandom(values: [1.0, 2.0, 3.0], repeats: -1)
|
||||
for _ in 0..<100 { _ = rand.nextValue() }
|
||||
#expect(!rand.isExhausted)
|
||||
#expect(rand.nextValue() != nil)
|
||||
}
|
||||
|
||||
@Test func exhaustsAfterNResponses() {
|
||||
let rand: DemandRandom = DemandRandom(values: [1.0, 2.0, 3.0], repeats: 5)
|
||||
var count: Int = 0
|
||||
while let _ = rand.nextValue() { count += 1 }
|
||||
#expect(count == 5)
|
||||
#expect(rand.isExhausted)
|
||||
}
|
||||
|
||||
@Test func resetRestartsResponseCount() {
|
||||
let rand: DemandRandom = DemandRandom(values: [1.0, 2.0], repeats: 3)
|
||||
for _ in 0..<3 { _ = rand.nextValue() }
|
||||
#expect(rand.isExhausted)
|
||||
rand.reset()
|
||||
#expect(!rand.isExhausted)
|
||||
var count: Int = 0
|
||||
while let _ = rand.nextValue() { count += 1 }
|
||||
#expect(count == 3)
|
||||
}
|
||||
|
||||
@Test func deterministicWithSameSeed() {
|
||||
let seed: UInt64 = 12345
|
||||
let r1: DemandRandom = DemandRandom(values: [1.0, 2.0, 3.0, 4.0, 5.0], repeats: 10, seed: seed)
|
||||
let r2: DemandRandom = DemandRandom(values: [1.0, 2.0, 3.0, 4.0, 5.0], repeats: 10, seed: seed)
|
||||
for _ in 0..<10 {
|
||||
#expect(r1.nextValue() == r2.nextValue())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Demand.Audio
|
||||
|
||||
@Suite("Demand.Audio")
|
||||
struct DemandAudioTests {
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let d: Demand.Audio = Demand.Audio(trig: 0.0, demand: DemandSequence(values: [1.0]))
|
||||
#expect(d.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func holdsZeroBeforeFirstTrigger() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
let d: Demand.Audio = Demand.Audio(trig: 0.0, demand: DemandSequence(values: [10.0, 20.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 16)[0]
|
||||
for s: Double in samples { #expect(s == 0.0) }
|
||||
}
|
||||
|
||||
@Test func advancesOnRisingEdge() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
// Trigger goes high at sample 4, stays high.
|
||||
let trig: Closure = Closure { _, i in i >= 4 ? 1.0 : 0.0 }
|
||||
let d: Demand.Audio = Demand.Audio(trig: trig, demand: DemandSequence(values: [99.0, 200.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 16)[0]
|
||||
// Samples 0-3: 0 (no trigger), sample 4+: 99.0
|
||||
for i: Int in 0..<4 { #expect(samples[i] == 0.0) }
|
||||
for i: Int in 4..<16 { #expect(samples[i] == 99.0) }
|
||||
}
|
||||
|
||||
@Test func multipleTriggersInOneBlock() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
// Two rising edges: at sample 2 (2-3 high) and sample 8 (8-9 high).
|
||||
let trig: Closure = Closure { _, i in
|
||||
(i == 2 || i == 3 || i == 8 || i == 9) ? 1.0 : 0.0
|
||||
}
|
||||
let d: Demand.Audio = Demand.Audio(trig: trig, demand: DemandSequence(values: [10.0, 20.0, 30.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 16)[0]
|
||||
#expect(samples[0] == 0.0) // before first trigger
|
||||
#expect(samples[2] == 10.0) // first trigger → 10
|
||||
#expect(samples[7] == 10.0) // still holding 10
|
||||
#expect(samples[8] == 20.0) // second trigger → 20
|
||||
}
|
||||
|
||||
@Test func holdsLastValueAfterExhaustion() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
// Trigger rises at sample 0 (prevTrig = 0 initially), stays high.
|
||||
let trig: Closure = Closure { _, _ in 1.0 }
|
||||
let d: Demand.Audio = Demand.Audio(trig: trig, demand: DemandSequence(values: [42.0], repeats: 1))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 16)[0]
|
||||
// Rising edge at sample 0 → 42.0. DemandSequence exhausted. No further rising edges (stays high).
|
||||
for s: Double in samples.prefix(16) { #expect(s == 42.0) }
|
||||
|
||||
// Advance to next block; trig stays high → no new rising edge → still 42.0.
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples2: [Double] = d.calculatedSamples(graph: graph2, count: 16)[0]
|
||||
for s: Double in samples2.prefix(16) { #expect(s == 42.0) }
|
||||
}
|
||||
|
||||
@Test func resetInputClearsHeldValue() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var block: Int = 0
|
||||
// Block 0: trigger at sample 0 → held = 77.0.
|
||||
// Block 1: reset at sample 0, no trigger → held clears to 0.
|
||||
let trig: Closure = Closure { _, i in block == 0 && i == 0 ? 1.0 : 0.0 }
|
||||
let reset: Closure = Closure { _, i in block == 1 && i == 0 ? 1.0 : 0.0 }
|
||||
let d: Demand.Audio = Demand.Audio(trig: trig, reset: reset, demand: DemandSequence(values: [77.0, 88.0]))
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let s1: [Double] = d.calculatedSamples(graph: g1, count: 8)[0]
|
||||
#expect(s1[0] == 77.0)
|
||||
|
||||
block = 1
|
||||
advanceBlock(engine)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let s2: [Double] = d.calculatedSamples(graph: g2, count: 8)[0]
|
||||
// reset fired at sample 0 → _heldValue = 0; seq also reset to index 0.
|
||||
for s: Double in s2 { #expect(s == 0.0) }
|
||||
}
|
||||
|
||||
@Test func resetThenTriggerSameSample() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
let seq: DemandSequence = DemandSequence(values: [10.0, 20.0, 30.0])
|
||||
// Consume first value so reset effect is observable.
|
||||
_ = seq.nextValue() // 10.0 consumed; seq at index 1
|
||||
|
||||
// Reset and trigger both cross at sample 0 simultaneously.
|
||||
let combined: Closure = Closure { _, i in i == 0 ? 1.0 : 0.0 }
|
||||
let d: Demand.Audio = Demand.Audio(trig: combined, reset: combined, demand: seq)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 16)[0]
|
||||
// reset fires first → seq.reset() → index back to 0
|
||||
// trigger then pulls → 10.0 (first value again, not 20.0)
|
||||
#expect(samples[0] == 10.0)
|
||||
}
|
||||
|
||||
@Test func blockBoundaryTrigger() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var trigHigh: Bool = false
|
||||
let trig: Closure = Closure { _, _ in trigHigh ? 1.0 : 0.0 }
|
||||
let d: Demand.Audio = Demand.Audio(trig: trig, demand: DemandSequence(values: [55.0]))
|
||||
|
||||
// Block 1: trig = 0 → _prevTrig persists as 0 on d after this block.
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let s1: [Double] = d.calculatedSamples(graph: g1, count: 8)[0]
|
||||
for s: Double in s1.prefix(8) { #expect(s == 0.0) }
|
||||
|
||||
// Block 2: trig goes high from sample 0. Same instance d — _prevTrig = 0 → rising edge.
|
||||
trigHigh = true
|
||||
advanceBlock(engine)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let s2: [Double] = d.calculatedSamples(graph: g2, count: 8)[0]
|
||||
// _prevTrig = 0 (carried from block 1), trig[0] = 1 → edge detected on same instance.
|
||||
#expect(s2[0] == 55.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Demand.Control
|
||||
|
||||
@Suite("Demand.Control")
|
||||
struct DemandControlTests {
|
||||
|
||||
@Test func rateIsControl() {
|
||||
let d: Demand.Control = Demand.Control(trig: 0.0, demand: DemandSequence(values: [1.0]))
|
||||
#expect(d.rate == .control)
|
||||
}
|
||||
|
||||
@Test func holdsZeroBeforeFirstTrigger() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
let d: Demand.Control = Demand.Control(trig: 0.0, demand: DemandSequence(values: [10.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: graph, count: 16)
|
||||
#expect(d.previousOutputValue == 0.0)
|
||||
}
|
||||
|
||||
@Test func advancesOnRisingEdgeMidBlock() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
// Trigger crosses at sample 8.
|
||||
let trig: Closure = Closure { _, i in i >= 8 ? 1.0 : 0.0 }
|
||||
let d: Demand.Control = Demand.Control(trig: trig, demand: DemandSequence(values: [100.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: graph, count: 16)
|
||||
// Rising edge mid-block → heldValue = 100.0 → previousOutputValue = 100.0
|
||||
#expect(d.previousOutputValue == 100.0)
|
||||
}
|
||||
|
||||
@Test func outputIsRampToNewValue() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
|
||||
// trig always high → rising edge at sample 0 (prevTrig = 0 initially).
|
||||
// _rampTarget = 0, _heldValue becomes 40.0. Ramp 0 → 40 over 4 samples.
|
||||
let trig: Closure = Closure { _, _ in 1.0 }
|
||||
let d: Demand.Control = Demand.Control(trig: trig, demand: DemandSequence(values: [40.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [Double] = d.calculatedSamples(graph: graph, count: 4)[0]
|
||||
#expect(samples[0] == 10.0)
|
||||
#expect(samples[1] == 20.0)
|
||||
#expect(samples[2] == 30.0)
|
||||
#expect(samples[3] == 40.0)
|
||||
}
|
||||
|
||||
@Test func holdsAfterExhaustion() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
// Rising edge at sample 0 → 7.0. DemandSequence exhausted. Trig stays high → no new edge.
|
||||
let trig: Closure = Closure { _, _ in 1.0 }
|
||||
let d: Demand.Control = Demand.Control(trig: trig, demand: DemandSequence(values: [7.0], repeats: 1))
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: g1, count: 8)
|
||||
#expect(d.previousOutputValue == 7.0)
|
||||
|
||||
advanceBlock(engine)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: g2, count: 8)
|
||||
#expect(d.previousOutputValue == 7.0)
|
||||
}
|
||||
|
||||
@Test func resetClearsHeldValueAndRamps() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
|
||||
// Reset at sample 0 (prevReset = 0 initially) → demand.reset(), heldValue = 0.
|
||||
// Ramp: _rampTarget = 0, _heldValue = 0 → flat at 0.
|
||||
let resetSig: Closure = Closure { _, _ in 1.0 }
|
||||
let d: Demand.Control = Demand.Control(trig: 0.0, reset: resetSig, demand: DemandSequence(values: [50.0]))
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(d.previousOutputValue == 0.0)
|
||||
}
|
||||
|
||||
@Test func floatValueDoesNotAdvanceSequence() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
// Single puller owns the sequence. trig always-high → rising edge at sample 0.
|
||||
let d: Demand.Control = Demand.Control(
|
||||
trig: Closure { _, _ in 1.0 },
|
||||
demand: DemandSequence(values: [11.0, 22.0, 33.0])
|
||||
)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// floatValue returns previousOutputValue (0) without calling nextValue on seq.
|
||||
let fv: Double = d.floatValue(graph: graph)
|
||||
#expect(fv == 0.0)
|
||||
// calculatedSamples triggers on the same block → must pull 11.0, not 22.0.
|
||||
_ = d.calculatedSamples(graph: graph, count: 8)
|
||||
#expect(d.previousOutputValue == 11.0)
|
||||
}
|
||||
|
||||
@Test func resetThenTriggerSameBlock() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
let seq: DemandSequence = DemandSequence(values: [10.0, 20.0, 30.0])
|
||||
// Advance seq past first value so reset effect is observable.
|
||||
_ = seq.nextValue() // 10.0 consumed; seq at index 1
|
||||
|
||||
// Reset fires at sample 2, trigger at sample 6 (both are rising edges from 0).
|
||||
let reset: Closure = Closure { _, i in i == 2 ? 1.0 : 0.0 }
|
||||
let trig: Closure = Closure { _, i in i == 6 ? 1.0 : 0.0 }
|
||||
let d: Demand.Control = Demand.Control(trig: trig, reset: reset, demand: seq)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = d.calculatedSamples(graph: graph, count: 16)
|
||||
// reset fires first (sample 2) → seq.reset(), heldValue = 0, didTrigger cleared.
|
||||
// trigger fires after (sample 6) → pulls 10.0 (first value of fresh sequence).
|
||||
#expect(d.previousOutputValue == 10.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// DemandGeometricTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandGeometric")
|
||||
struct DemandGeometricTests {
|
||||
|
||||
@Test func emitsGeometricSequence() {
|
||||
let d: DemandGeometric = DemandGeometric(start: 1.0, ratio: 2.0, length: 4)
|
||||
#expect(d.nextValue() == 1.0)
|
||||
#expect(d.nextValue() == 2.0)
|
||||
#expect(d.nextValue() == 4.0)
|
||||
#expect(d.nextValue() == 8.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func fractionalRatioDecays() {
|
||||
let d: DemandGeometric = DemandGeometric(start: 100.0, ratio: 0.5, length: 3)
|
||||
#expect(d.nextValue() == 100.0)
|
||||
#expect(d.nextValue() == 50.0)
|
||||
#expect(d.nextValue() == 25.0)
|
||||
}
|
||||
|
||||
@Test func resetRestoresInitialValue() {
|
||||
let d: DemandGeometric = DemandGeometric(start: 3.0, ratio: 2.0, length: -1)
|
||||
for _ in 0..<5 { _ = d.nextValue() }
|
||||
d.reset()
|
||||
#expect(d.nextValue() == 3.0)
|
||||
#expect(d.nextValue() == 6.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// DemandNonRepeatingRandomTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandNonRepeatingRandom")
|
||||
struct DemandNonRepeatingRandomTests {
|
||||
|
||||
@Test func neverRepeatsSameIndexConsecutively() {
|
||||
let d: DemandNonRepeatingRandom = DemandNonRepeatingRandom(
|
||||
values: [1.0, 2.0, 3.0, 4.0, 5.0],
|
||||
repeats: 1_000,
|
||||
seed: 42
|
||||
)
|
||||
var prev: Double? = nil
|
||||
while let v: Double = d.nextValue() {
|
||||
if let p: Double = prev {
|
||||
#expect(v != p, "Consecutive repeat: \(p) → \(v)")
|
||||
}
|
||||
prev = v
|
||||
}
|
||||
}
|
||||
|
||||
@Test func singleValueAlwaysReturnsThatValue() {
|
||||
let d: DemandNonRepeatingRandom = DemandNonRepeatingRandom(
|
||||
values: [7.0],
|
||||
repeats: 5,
|
||||
seed: 1
|
||||
)
|
||||
for _ in 0..<5 { #expect(d.nextValue() == 7.0) }
|
||||
#expect(d.nextValue() == nil)
|
||||
}
|
||||
|
||||
@Test func sameSeedProducesIdenticalSequence() {
|
||||
let a: DemandNonRepeatingRandom = DemandNonRepeatingRandom(
|
||||
values: [10.0, 20.0, 30.0, 40.0], repeats: 50, seed: 99
|
||||
)
|
||||
let b: DemandNonRepeatingRandom = DemandNonRepeatingRandom(
|
||||
values: [10.0, 20.0, 30.0, 40.0], repeats: 50, seed: 99
|
||||
)
|
||||
for _ in 0..<50 {
|
||||
#expect(a.nextValue() == b.nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetClearsExhaustionAndLastPick() {
|
||||
let d: DemandNonRepeatingRandom = DemandNonRepeatingRandom(
|
||||
values: [1.0, 2.0, 3.0], repeats: 3, seed: 1
|
||||
)
|
||||
for _ in 0..<3 { _ = d.nextValue() }
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() != nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// DemandSeriesTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandSeries")
|
||||
struct DemandSeriesTests {
|
||||
|
||||
@Test func emitsArithmeticSequence() {
|
||||
let d: DemandSeries = DemandSeries(start: 0.0, step: 2.0, length: 4)
|
||||
#expect(d.nextValue() == 0.0)
|
||||
#expect(d.nextValue() == 2.0)
|
||||
#expect(d.nextValue() == 4.0)
|
||||
#expect(d.nextValue() == 6.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func infiniteLengthNeverExhausts() {
|
||||
let d: DemandSeries = DemandSeries(start: 1.0, step: 1.0, length: -1)
|
||||
for _ in 0..<1_000 { _ = d.nextValue() }
|
||||
#expect(!d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func resetRestartsFromStart() {
|
||||
let d: DemandSeries = DemandSeries(start: 5.0, step: 1.0, length: 2)
|
||||
_ = d.nextValue(); _ = d.nextValue()
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() == 5.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// DemandShuffleTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandShuffle")
|
||||
struct DemandShuffleTests {
|
||||
|
||||
@Test func returnsAllValuesExactlyOncePerCycle() {
|
||||
let d: DemandShuffle = DemandShuffle(
|
||||
values: [1.0, 2.0, 3.0, 4.0, 5.0],
|
||||
repeats: 1,
|
||||
seed: 42
|
||||
)
|
||||
var collected: [Double] = []
|
||||
while let v: Double = d.nextValue() { collected.append(v) }
|
||||
#expect(collected.sorted() == [1.0, 2.0, 3.0, 4.0, 5.0])
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func samePermutationReplaysOnReset() {
|
||||
let d: DemandShuffle = DemandShuffle(
|
||||
values: [1.0, 2.0, 3.0, 4.0],
|
||||
repeats: -1,
|
||||
seed: 7
|
||||
)
|
||||
let first: [Double] = (0..<4).compactMap { _ in d.nextValue() }
|
||||
d.reset()
|
||||
let second: [Double] = (0..<4).compactMap { _ in d.nextValue() }
|
||||
#expect(first == second)
|
||||
}
|
||||
|
||||
@Test func sameSeedProducesSamePermutation() {
|
||||
let a: DemandShuffle = DemandShuffle(values: [10.0, 20.0, 30.0, 40.0], repeats: 1, seed: 99)
|
||||
let b: DemandShuffle = DemandShuffle(values: [10.0, 20.0, 30.0, 40.0], repeats: 1, seed: 99)
|
||||
for _ in 0..<4 {
|
||||
#expect(a.nextValue() == b.nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetClearsExhaustion() {
|
||||
let d: DemandShuffle = DemandShuffle(
|
||||
values: [1.0, 2.0, 3.0],
|
||||
repeats: 1,
|
||||
seed: 5
|
||||
)
|
||||
while d.nextValue() != nil {}
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() != nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// DemandStutterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandStutter")
|
||||
struct DemandStutterTests {
|
||||
|
||||
@Test func repeatsEachValueByCount() {
|
||||
let d: DemandStutter = DemandStutter(
|
||||
demand: DemandSequence(values: [10.0, 20.0, 30.0], repeats: 1),
|
||||
count: 2
|
||||
)
|
||||
var collected: [Double] = []
|
||||
while let v: Double = d.nextValue() { collected.append(v) }
|
||||
#expect(collected == [10.0, 10.0, 20.0, 20.0, 30.0, 30.0])
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func countOneIsPassThrough() {
|
||||
let d: DemandStutter = DemandStutter(
|
||||
demand: DemandSequence(values: [1.0, 2.0, 3.0], repeats: 1),
|
||||
count: 1
|
||||
)
|
||||
var collected: [Double] = []
|
||||
while let v: Double = d.nextValue() { collected.append(v) }
|
||||
#expect(collected == [1.0, 2.0, 3.0])
|
||||
}
|
||||
|
||||
@Test func upstreamExhaustionLatchesEngine() {
|
||||
let d: DemandStutter = DemandStutter(
|
||||
demand: DemandSequence(values: [5.0], repeats: 1),
|
||||
count: 3
|
||||
)
|
||||
#expect(d.nextValue() == 5.0)
|
||||
#expect(d.nextValue() == 5.0)
|
||||
#expect(d.nextValue() == 5.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func resetRestartsUpstreamAndCount() {
|
||||
let d: DemandStutter = DemandStutter(
|
||||
demand: DemandSequence(values: [7.0, 8.0], repeats: 1),
|
||||
count: 2
|
||||
)
|
||||
while d.nextValue() != nil {} // drain to trigger latch
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() == 7.0)
|
||||
#expect(d.nextValue() == 7.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// DemandSwitchTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandSwitch")
|
||||
struct DemandSwitchTests {
|
||||
|
||||
@Test func pullsByIndex() {
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [
|
||||
DemandSequence(values: [1.0, 2.0, 3.0], repeats: -1),
|
||||
DemandSequence(values: [10.0, 20.0, 30.0], repeats: -1)
|
||||
],
|
||||
index: DemandSequence(values: [0.0, 1.0, 0.0, 1.0], repeats: 1)
|
||||
)
|
||||
#expect(d.nextValue() == 1.0)
|
||||
#expect(d.nextValue() == 10.0)
|
||||
#expect(d.nextValue() == 2.0)
|
||||
#expect(d.nextValue() == 20.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func indexExhaustionLatches() {
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [DemandSequence(values: [100.0], repeats: -1)],
|
||||
index: DemandSequence(values: [0.0], repeats: 1)
|
||||
)
|
||||
#expect(d.nextValue() == 100.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func subSourceExhaustionLatches() {
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [DemandSequence(values: [7.0, 8.0], repeats: 1)],
|
||||
index: DemandSequence(values: [0.0], repeats: -1)
|
||||
)
|
||||
#expect(d.nextValue() == 7.0)
|
||||
#expect(d.nextValue() == 8.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func outOfRangeIndexLatches() {
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [DemandSequence(values: [1.0], repeats: -1)],
|
||||
index: DemandSequence(values: [0.0, 99.0], repeats: 1)
|
||||
)
|
||||
#expect(d.nextValue() == 1.0)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func negativeFractionalIndexFloorsToLatch() {
|
||||
// Index -0.5 floors to -1 (out of range) and latches, rather than
|
||||
// truncating toward zero (which would silently pick demands[0]).
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [DemandSequence(values: [42.0], repeats: -1)],
|
||||
index: DemandSequence(values: [-0.5], repeats: 1)
|
||||
)
|
||||
#expect(d.nextValue() == nil)
|
||||
#expect(d.isExhausted)
|
||||
}
|
||||
|
||||
@Test func resetRestartsAll() {
|
||||
let d: DemandSwitch = DemandSwitch(
|
||||
demands: [
|
||||
DemandSequence(values: [1.0, 2.0], repeats: -1),
|
||||
DemandSequence(values: [10.0, 20.0], repeats: -1)
|
||||
],
|
||||
index: DemandSequence(values: [0.0, 1.0], repeats: 1)
|
||||
)
|
||||
_ = d.nextValue(); _ = d.nextValue(); _ = d.nextValue()
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() == 1.0)
|
||||
#expect(d.nextValue() == 10.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// DemandUniformRandomTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandUniformRandom")
|
||||
struct DemandUniformRandomTests {
|
||||
|
||||
@Test func samplesStayWithinRange() {
|
||||
let d: DemandUniformRandom = DemandUniformRandom(
|
||||
low: -5.0,
|
||||
high: 5.0,
|
||||
length: 1_000,
|
||||
seed: 42
|
||||
)
|
||||
var count: Int = 0
|
||||
while let v: Double = d.nextValue() {
|
||||
#expect(v >= -5.0 && v <= 5.0)
|
||||
count += 1
|
||||
}
|
||||
#expect(count == 1_000)
|
||||
}
|
||||
|
||||
@Test func sameSeedProducesIdenticalSequence() {
|
||||
let a: DemandUniformRandom = DemandUniformRandom(low: 0.0, high: 1.0, length: 50, seed: 99)
|
||||
let b: DemandUniformRandom = DemandUniformRandom(low: 0.0, high: 1.0, length: 50, seed: 99)
|
||||
for _ in 0..<50 {
|
||||
#expect(a.nextValue() == b.nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetClearsExhaustion() {
|
||||
let d: DemandUniformRandom = DemandUniformRandom(low: 0.0, high: 1.0, length: 3, seed: 7)
|
||||
for _ in 0..<3 { _ = d.nextValue() }
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() != nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// DemandWeightedRandomTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("DemandWeightedRandom")
|
||||
struct DemandWeightedRandomTests {
|
||||
|
||||
@Test func zeroWeightValueNeverPicked() {
|
||||
let d: DemandWeightedRandom = DemandWeightedRandom(
|
||||
values: [1.0, 2.0, 3.0],
|
||||
weights: [1.0, 0.0, 1.0],
|
||||
repeats: 2_000,
|
||||
seed: 42
|
||||
)
|
||||
while let v: Double = d.nextValue() {
|
||||
#expect(v != 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func biasedDistributionFavoursHighWeight() {
|
||||
// 9:1 ratio → ~90 % of picks favour the first value.
|
||||
let n: Int = 5_000
|
||||
let d: DemandWeightedRandom = DemandWeightedRandom(
|
||||
values: [100.0, 200.0],
|
||||
weights: [9.0, 1.0],
|
||||
repeats: n,
|
||||
seed: 99
|
||||
)
|
||||
var lowCount: Int = 0
|
||||
while let v: Double = d.nextValue() {
|
||||
if v == 100.0 { lowCount += 1 }
|
||||
}
|
||||
let fraction: Double = Double(lowCount) / Double(n)
|
||||
#expect(abs(fraction - 0.9) < 0.03)
|
||||
}
|
||||
|
||||
@Test func sameSeedProducesIdenticalSequence() {
|
||||
let a: DemandWeightedRandom = DemandWeightedRandom(
|
||||
values: [10.0, 20.0, 30.0],
|
||||
weights: [1.0, 2.0, 3.0],
|
||||
repeats: 50,
|
||||
seed: 77
|
||||
)
|
||||
let b: DemandWeightedRandom = DemandWeightedRandom(
|
||||
values: [10.0, 20.0, 30.0],
|
||||
weights: [1.0, 2.0, 3.0],
|
||||
repeats: 50,
|
||||
seed: 77
|
||||
)
|
||||
for _ in 0..<50 {
|
||||
#expect(a.nextValue() == b.nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@Test func resetClearsExhaustion() {
|
||||
let d: DemandWeightedRandom = DemandWeightedRandom(
|
||||
values: [1.0, 2.0],
|
||||
weights: [1.0, 1.0],
|
||||
repeats: 3,
|
||||
seed: 13
|
||||
)
|
||||
for _ in 0..<3 { _ = d.nextValue() }
|
||||
#expect(d.isExhausted)
|
||||
d.reset()
|
||||
#expect(!d.isExhausted)
|
||||
#expect(d.nextValue() != nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// DenormalHandlingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - denormalsToZero helper
|
||||
|
||||
@Suite("denormalsToZero")
|
||||
struct DenormalsToZeroTests {
|
||||
|
||||
@Test func zeroIsUnchanged() {
|
||||
#expect(denormalsToZero(0.0) == 0.0)
|
||||
}
|
||||
|
||||
@Test func normalPositiveValueIsUnchanged() {
|
||||
let x: Double = 0.5
|
||||
#expect(denormalsToZero(x) == x)
|
||||
}
|
||||
|
||||
@Test func normalNegativeValueIsUnchanged() {
|
||||
let x: Double = -0.5
|
||||
#expect(denormalsToZero(x) == x)
|
||||
}
|
||||
|
||||
@Test func valueBelowThresholdIsFlushedToZero() {
|
||||
// 1e-31 is strictly below the 1e-30 threshold.
|
||||
#expect(denormalsToZero(1e-31 as Double) == 0.0)
|
||||
#expect(denormalsToZero(-1e-31 as Double) == 0.0)
|
||||
}
|
||||
|
||||
@Test func actualDoubleSubnormalIsFlushedToZero() {
|
||||
let subnormal: Double = Double.leastNonzeroMagnitude // ~5e-324, a true Double subnormal
|
||||
#expect(subnormal.isSubnormal)
|
||||
#expect(denormalsToZero(subnormal) == 0.0)
|
||||
}
|
||||
|
||||
@Test func valueExactlyAtThresholdPassesThrough() {
|
||||
// abs(1e-30) is NOT < 1e-30, so it must pass through unchanged.
|
||||
let x: Double = 1e-30
|
||||
#expect(denormalsToZero(x) == x)
|
||||
}
|
||||
|
||||
@Test func largeValueIsUnchanged() {
|
||||
let x: Double = 1e10
|
||||
#expect(denormalsToZero(x) == x)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FTZ + filter subnormal guard: no subnormals in output with FTZ active
|
||||
|
||||
// These tests call enableFlushToZero() to simulate the RT-thread context that
|
||||
// CoreAudioDriver.render() establishes before each processBlock call. With FTZ set,
|
||||
// any computation that would produce a subnormal result is flushed to zero by the
|
||||
// hardware, so filter outputs and delay-line writes must never be subnormal.
|
||||
|
||||
@Suite("FirstOrderSection — no subnormals under FTZ")
|
||||
struct FirstOrderSectionFTZTests {
|
||||
|
||||
/// Feed a subnormal-magnitude signal through a near-resonant one-pole filter.
|
||||
/// With FTZ active the hardware flushes subnormal products to zero; the
|
||||
/// denormalsToZero guard on the state variables provides a second line of defence.
|
||||
@Test func outputIsNeverSubnormalWithSubnormalInput() throws {
|
||||
enableFlushToZero()
|
||||
|
||||
let blockSize: Int = 64
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// Subnormal Double as input — without FTZ this would propagate subnormals.
|
||||
let tinyInput: Double = Double.leastNonzeroMagnitude
|
||||
let filter: FirstOrderSection = FirstOrderSection(input: tinyInput, a0: 1.0, a1: 0.0, b1: 0.9999)
|
||||
|
||||
for _ in 0..<500 {
|
||||
let samples: [[Double]] = filter.calculatedSamples(graph: graph, count: blockSize)
|
||||
let block: Array<Double>.SubSequence = samples[0].prefix(blockSize)
|
||||
for sample: Double in block {
|
||||
#expect(!sample.isSubnormal,
|
||||
"FirstOrderSection produced a subnormal output with FTZ active")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("SecondOrderSection — no subnormals under FTZ")
|
||||
struct SecondOrderSectionFTZTests {
|
||||
|
||||
@Test func outputIsNeverSubnormalWithSubnormalInput() throws {
|
||||
enableFlushToZero()
|
||||
|
||||
let blockSize: Int = 64
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let tinyInput: Double = Double.leastNonzeroMagnitude
|
||||
let filter: SecondOrderSection = SecondOrderSection(
|
||||
input: tinyInput, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.9999, b2: 0.0
|
||||
)
|
||||
|
||||
for _ in 0..<500 {
|
||||
let samples: [[Double]] = filter.calculatedSamples(graph: graph, count: blockSize)
|
||||
let block: Array<Double>.SubSequence = samples[0].prefix(blockSize)
|
||||
for sample: Double in block {
|
||||
#expect(!sample.isSubnormal,
|
||||
"SecondOrderSection produced a subnormal output with FTZ active")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("RBJBandPass — no subnormals under FTZ")
|
||||
struct RBJBandPassFTZTests {
|
||||
|
||||
@Test func outputIsNeverSubnormalWithSubnormalInput() throws {
|
||||
enableFlushToZero()
|
||||
|
||||
let blockSize: Int = 64
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let tinyInput: Double = Double.leastNonzeroMagnitude
|
||||
let filter: RBJBandPass.Audio = RBJBandPass.Audio(input: tinyInput, freq: 440.0, bandwidth: 1.0)
|
||||
|
||||
for _ in 0..<500 {
|
||||
let samples: [[Double]] = filter.calculatedSamples(graph: graph, count: blockSize)
|
||||
let block: Array<Double>.SubSequence = samples[0].prefix(blockSize)
|
||||
for sample: Double in block {
|
||||
#expect(!sample.isSubnormal,
|
||||
"RBJBandPass produced a subnormal output with FTZ active")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("DelayLineFeedback — no subnormals under FTZ")
|
||||
struct DelayLineFeedbackFTZTests {
|
||||
|
||||
@Test func outputIsNeverSubnormalWithSubnormalInput() throws {
|
||||
enableFlushToZero()
|
||||
|
||||
let blockSize: Int = 64
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let tinyInput: Double = Double.leastNonzeroMagnitude
|
||||
let delay: DelayLineFeedback = DelayLineFeedback(
|
||||
input: tinyInput,
|
||||
maxDelay: 0.1,
|
||||
delay: 0.01,
|
||||
decayTime: 10.0,
|
||||
targetAmp: 0.001,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
for _ in 0..<500 {
|
||||
let samples: [[Double]] = delay.calculatedSamples(graph: graph, count: blockSize)
|
||||
let block: Array<Double>.SubSequence = samples[0].prefix(blockSize)
|
||||
for sample: Double in block {
|
||||
#expect(!sample.isSubnormal,
|
||||
"DelayLineFeedback produced a subnormal output with FTZ active")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// LyrebirdMessageCenterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@Suite("LyrebirdMessageCenter")
|
||||
@MainActor
|
||||
struct LyrebirdMessageCenterTests {
|
||||
|
||||
@Test("post stores message at the given tier")
|
||||
func testPost() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter()
|
||||
center.post(.info, "hello")
|
||||
#expect(center.messages.count == 1)
|
||||
let m: LyrebirdMessage = center.messages[0]
|
||||
#expect(m.tier == .info)
|
||||
#expect(m.text == "hello")
|
||||
#expect(m.source == nil)
|
||||
}
|
||||
|
||||
@Test("convenience methods route to the correct tier")
|
||||
func testConvenienceTiers() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter()
|
||||
center.info("a")
|
||||
center.warning("b", source: "src")
|
||||
center.error("c")
|
||||
|
||||
#expect(center.messages.count == 3)
|
||||
#expect(center.messages[0].tier == .info)
|
||||
#expect(center.messages[1].tier == .warning)
|
||||
#expect(center.messages[1].source == "src")
|
||||
#expect(center.messages[2].tier == .error)
|
||||
}
|
||||
|
||||
@Test("ring prunes oldest when over capacity")
|
||||
func testCapacityPrune() {
|
||||
let cap: Int = 4
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter(capacity: cap)
|
||||
for i: Int in 0..<10 {
|
||||
center.info("msg \(i)")
|
||||
}
|
||||
#expect(center.messages.count == cap)
|
||||
// After pruning, the oldest retained should be "msg 6" (indices 6..9).
|
||||
#expect(center.messages.first?.text == "msg 6")
|
||||
#expect(center.messages.last?.text == "msg 9")
|
||||
}
|
||||
|
||||
@Test("reducing capacity prunes immediately")
|
||||
func testReduceCapacityPrunes() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter(capacity: 10)
|
||||
for i: Int in 0..<8 {
|
||||
center.info("msg \(i)")
|
||||
}
|
||||
#expect(center.messages.count == 8)
|
||||
|
||||
center.capacity = 3
|
||||
#expect(center.messages.count == 3)
|
||||
#expect(center.messages.first?.text == "msg 5")
|
||||
#expect(center.messages.last?.text == "msg 7")
|
||||
}
|
||||
|
||||
@Test("clear empties the ring")
|
||||
func testClear() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter()
|
||||
center.info("x")
|
||||
center.warning("y")
|
||||
#expect(center.messages.count == 2)
|
||||
center.clear()
|
||||
#expect(center.messages.isEmpty)
|
||||
}
|
||||
|
||||
@Test("each posted message has a unique id and a non-future timestamp")
|
||||
func testMessageIdentityAndTimestamp() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter()
|
||||
let before: Date = Date()
|
||||
center.info("a")
|
||||
center.info("b")
|
||||
let after: Date = Date()
|
||||
|
||||
#expect(center.messages.count == 2)
|
||||
#expect(center.messages[0].id != center.messages[1].id)
|
||||
#expect(center.messages[0].timestamp >= before)
|
||||
#expect(center.messages[1].timestamp <= after)
|
||||
}
|
||||
|
||||
@Test("posting with capacity 1 keeps only the newest message")
|
||||
func testCapacityOneKeepsNewest() {
|
||||
let center: LyrebirdMessageCenter = LyrebirdMessageCenter(capacity: 1)
|
||||
center.info("first")
|
||||
center.warning("second")
|
||||
center.error("third")
|
||||
#expect(center.messages.count == 1)
|
||||
#expect(center.messages[0].text == "third")
|
||||
#expect(center.messages[0].tier == .error)
|
||||
}
|
||||
|
||||
@Test("LyrebirdMessageTier.allCases covers info/warning/error in that order")
|
||||
func testTierAllCases() {
|
||||
#expect(LyrebirdMessageTier.allCases == [.info, .warning, .error])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
// DiskInOutTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func writeTempWAV(channels: [[Float]], sampleRate: Double = 44100) throws -> URL {
|
||||
precondition(!channels.isEmpty)
|
||||
let frameCount: Int = channels[0].count
|
||||
let nch: UInt32 = UInt32(channels.count)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
|
||||
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||||
let float32BitsPerChannel: UInt32 = 32
|
||||
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: float32ByteSize * nch,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: float32ByteSize * nch,
|
||||
mChannelsPerFrame: nch,
|
||||
mBitsPerChannel: float32BitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
var ref: ExtAudioFileRef?
|
||||
guard ExtAudioFileCreateWithURL(url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
||||
AudioFileFlags.eraseFile.rawValue, &ref) == noErr,
|
||||
let ref: ExtAudioFileRef else { throw DiskInError.cannotOpenFile(-1) }
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
||||
|
||||
var interleaved: [Float] = [Float](repeating: 0, count: frameCount * channels.count)
|
||||
for f: Int in 0..<frameCount {
|
||||
for ch: Int in 0..<channels.count {
|
||||
interleaved[f * channels.count + ch] = channels[ch][f]
|
||||
}
|
||||
}
|
||||
interleaved.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: nch,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileWrite(ref, UInt32(frameCount), &bl)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
private func readWAVSamples(url: URL, channelCount: Int,
|
||||
sampleRate: Double = 44100) throws -> [[Float]] {
|
||||
var ref: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(url as CFURL, &ref) == noErr, let ref: ExtAudioFileRef else { return [] }
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
|
||||
// Query total frame count
|
||||
var frameCount: Int64 = 0
|
||||
var propSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||||
ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileLengthFrames,
|
||||
&propSize, &frameCount)
|
||||
|
||||
let nch: UInt32 = UInt32(channelCount)
|
||||
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||||
let float32BitsPerChannel: UInt32 = 32
|
||||
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: float32ByteSize * nch,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: float32ByteSize * nch,
|
||||
mChannelsPerFrame: nch,
|
||||
mBitsPerChannel: float32BitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
||||
|
||||
var interleaved: [Float] = [Float](repeating: 0, count: Int(frameCount) * channelCount)
|
||||
var frames: UInt32 = UInt32(frameCount)
|
||||
interleaved.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: nch,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(ref, &frames, &bl)
|
||||
}
|
||||
|
||||
let n: Int = Int(frames)
|
||||
var result: [[Float]] = Array(repeating: [Float](repeating: 0, count: n), count: channelCount)
|
||||
for f: Int in 0..<n {
|
||||
for ch: Int in 0..<channelCount {
|
||||
result[ch][f] = interleaved[f * channelCount + ch]
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private func makeNRTEngine(outputURL: URL, duration: Double,
|
||||
blockSize: Int = 512, sampleRate: Double = 44100,
|
||||
numOutputChannels: Int = 2) -> SynthesisEngine {
|
||||
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: duration)
|
||||
return SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: numOutputChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 64,
|
||||
numControlBuses: 256,
|
||||
driver: driver
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Suite("DiskIn / DiskOut")
|
||||
struct DiskInOutTests {
|
||||
|
||||
// MARK: - DiskIn basic read
|
||||
|
||||
@Test func diskInReadsDCSignal() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let frameCount: Int = 512
|
||||
let dcValue: Float = 0.6
|
||||
let wavURL: URL = try writeTempWAV(channels: [[Float](repeating: dcValue, count: frameCount)],
|
||||
sampleRate: sampleRate)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
||||
sampleRate: sampleRate, bufferFrames: 512)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class MonoPlayer: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
init(_ d: DiskIn.Audio) { di = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: di)
|
||||
output(bus: 1, source: di[0])
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(frameCount) / sampleRate)
|
||||
try engine.add(MonoPlayer(diskIn))
|
||||
try engine.start()
|
||||
|
||||
// Read bus 0 output from the CAF file
|
||||
var fileRef: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
||||
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output file"); return }
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
||||
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt)
|
||||
|
||||
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
||||
var framesRead: UInt32 = UInt32(frameCount)
|
||||
buf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
||||
}
|
||||
|
||||
// Frames are interleaved L/R; check L (bus 0) — skip first sample (ramp-up)
|
||||
let leftSamples: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
||||
#expect(leftSamples.allSatisfy { abs(Double($0) - Double(dcValue)) < 0.01 })
|
||||
}
|
||||
|
||||
// MARK: - DiskIn stereo read
|
||||
|
||||
@Test func diskInReadsStereoChannels() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let frameCount: Int = 512
|
||||
let wavURL: URL = try writeTempWAV(
|
||||
channels: [[Float](repeating: 0.3, count: frameCount),
|
||||
[Float](repeating: 0.7, count: frameCount)],
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 2,
|
||||
sampleRate: sampleRate, bufferFrames: 512)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class StereoPlayer: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
init(_ d: DiskIn.Audio) { di = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: di[0])
|
||||
output(bus: 1, source: di[1])
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(frameCount) / sampleRate)
|
||||
try engine.add(StereoPlayer(diskIn))
|
||||
try engine.start()
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
||||
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
||||
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt)
|
||||
|
||||
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
||||
var framesRead: UInt32 = UInt32(frameCount)
|
||||
buf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
||||
}
|
||||
|
||||
let left: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
||||
let right: [Float] = stride(from: 3, to: Int(framesRead) * 2 - 1, by: 2).map { buf[$0] }
|
||||
#expect(left.allSatisfy { abs($0 - 0.3) < 0.01 })
|
||||
#expect(right.allSatisfy { abs($0 - 0.7) < 0.01 })
|
||||
}
|
||||
|
||||
// MARK: - DiskIn loop
|
||||
|
||||
@Test func diskInLoopWrapsAtEOF() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let fileFrames: Int = 256 // short file — shorter than one render block
|
||||
let renderFrames: Int = 512 // render two file-lengths
|
||||
|
||||
// Ramp 0→1 over fileFrames so we can detect wrapping
|
||||
let ramp: [Float] = (0..<fileFrames).map { Float($0) / Float(fileFrames - 1) }
|
||||
let wavURL: URL = try writeTempWAV(channels: [ramp], sampleRate: sampleRate)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
||||
sampleRate: sampleRate, loop: true,
|
||||
bufferFrames: 256)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class LoopPlayer: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
init(_ d: DiskIn.Audio) { di = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: di)
|
||||
output(bus: 1, source: di)
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(LoopPlayer(diskIn))
|
||||
try engine.start()
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
||||
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
||||
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt)
|
||||
|
||||
var buf: [Float] = [Float](repeating: 0, count: renderFrames * 2)
|
||||
var framesRead: UInt32 = UInt32(renderFrames)
|
||||
buf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
||||
}
|
||||
|
||||
// The file wraps: second half of output should start near 0 again (not stay at 1).
|
||||
// Check that the final sample is NOT close to 1.0 (it would be if no looping occurred).
|
||||
let lastLeft: Float = buf[(Int(framesRead) - 1) * 2]
|
||||
let midLeft: Float = buf[fileFrames * 2] // sample at the wrap point in the output
|
||||
|
||||
// After looping, the midpoint should be somewhere between 0 and 1 (near the start of ramp),
|
||||
// not still at the end (1.0).
|
||||
#expect(midLeft < 0.5)
|
||||
// Verify we rendered something (not all silence)
|
||||
let hasSignal: Bool = buf.prefix(Int(framesRead) * 2).contains { $0 > 0.01 }
|
||||
#expect(hasSignal)
|
||||
_ = lastLeft // suppress unused-variable warning
|
||||
}
|
||||
|
||||
// MARK: - DiskIn EOF triggers doneAction
|
||||
|
||||
@Test func diskInEOFSetsFreeNodeFlag() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let fileFrames: Int = 512
|
||||
let wavURL: URL = try writeTempWAV(
|
||||
channels: [[Float](repeating: 0.5, count: fileFrames)],
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
||||
sampleRate: sampleRate,
|
||||
doneAction: .freeNode,
|
||||
bufferFrames: 512)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class EOFPlayer: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
init(_ d: DiskIn.Audio) { di = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: di)
|
||||
output(bus: 1, source: di)
|
||||
}
|
||||
}
|
||||
|
||||
// Render more than the file length so EOF is definitely reached.
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(fileFrames * 3) / sampleRate)
|
||||
try engine.add(EOFPlayer(diskIn))
|
||||
try engine.start()
|
||||
|
||||
// needsFree should be true after rendering past EOF.
|
||||
#expect(diskIn.needsFree)
|
||||
}
|
||||
|
||||
// MARK: - DiskIn multi-buffer (exercises BG refill path)
|
||||
|
||||
@Test func diskInReadsAcrossBufferBoundaries() throws {
|
||||
let sampleRate: Double = 44100
|
||||
// bufferFrames > fileFrames/2 so both halves are filled synchronously in init,
|
||||
// avoiding BG-timing races in the NRT renderer. The half-swap path is still
|
||||
// exercised (readPos crosses bufferFrames at sample 2048).
|
||||
let blockSize: Int = 512 // NRT default
|
||||
let bufferFrames: Int = 2048 // must be power-of-two, > fileFrames/2 = 1280
|
||||
let fileFrames: Int = blockSize * 5 // 2560 frames — spans into the second half
|
||||
let dcValue: Float = 0.42
|
||||
|
||||
let wavURL: URL = try writeTempWAV(
|
||||
channels: [[Float](repeating: dcValue, count: fileFrames)],
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
||||
sampleRate: sampleRate,
|
||||
doneAction: .freeNode,
|
||||
bufferFrames: bufferFrames)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class LongPlayer: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
init(_ d: DiskIn.Audio) { di = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: di)
|
||||
output(bus: 1, source: di)
|
||||
}
|
||||
}
|
||||
|
||||
// Render at least 2 extra blocks beyond the file so EOF detection completes
|
||||
// even when fileFrames is an exact multiple of bufferFrames.
|
||||
let renderFrames: Int = fileFrames + 2 * bufferFrames
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(LongPlayer(diskIn))
|
||||
try engine.start()
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
||||
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
||||
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt)
|
||||
|
||||
let readFrames: Int = fileFrames
|
||||
var buf: [Float] = [Float](repeating: 0, count: readFrames * 2)
|
||||
var framesRead: UInt32 = UInt32(readFrames)
|
||||
buf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
||||
}
|
||||
|
||||
let leftSamples: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
||||
#expect(leftSamples.allSatisfy { abs(Double($0) - Double(dcValue)) < 0.02 })
|
||||
#expect(diskIn.needsFree)
|
||||
}
|
||||
|
||||
// MARK: - DiskOut round-trip
|
||||
|
||||
@Test func diskOutWritesAndDiskInReadsBack() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let renderFrames: Int = 512
|
||||
let testValue: Float = 0.55
|
||||
|
||||
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: diskOutURL)
|
||||
try? FileManager.default.removeItem(at: nrtOutURL)
|
||||
}
|
||||
|
||||
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
||||
channelCount: 1,
|
||||
url: diskOutURL,
|
||||
sampleRate: sampleRate,
|
||||
format: .wav,
|
||||
bufferFrames: 512)
|
||||
|
||||
final class RecordSynth: SynthesizerBase {
|
||||
let d: DiskOut.Audio
|
||||
init(_ d: DiskOut.Audio) { self.d = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: d)
|
||||
output(bus: 1, source: d)
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(RecordSynth(diskOut))
|
||||
try engine.start()
|
||||
diskOut.close()
|
||||
|
||||
// Verify diskOut wrote the expected value to disk.
|
||||
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
||||
sampleRate: sampleRate)
|
||||
#expect(channels.count == 1)
|
||||
let samples: [Float] = channels[0]
|
||||
#expect(samples.count >= 1)
|
||||
// Skip first sample (may be zero due to startup); check the rest.
|
||||
let interior: [Float] = Array(samples.dropFirst())
|
||||
#expect(interior.allSatisfy { abs(Double($0) - Double(testValue)) < 0.01 })
|
||||
}
|
||||
|
||||
// MARK: - DiskOut stereo round-trip
|
||||
|
||||
@Test func diskOutStereoRoundTrip() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let renderFrames: Int = 512
|
||||
|
||||
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: diskOutURL)
|
||||
try? FileManager.default.removeItem(at: nrtOutURL)
|
||||
}
|
||||
|
||||
// Write a sine-wave file, then record its stereo pan output via DiskOut.
|
||||
let fileFrames: Int = 512
|
||||
let sine: [Float] = (0..<fileFrames).map { Float(sin(2 * Double.pi * 440 * Double($0) / sampleRate)) }
|
||||
let wavURL: URL = try writeTempWAV(channels: [sine], sampleRate: sampleRate)
|
||||
defer { try? FileManager.default.removeItem(at: wavURL) }
|
||||
|
||||
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
||||
sampleRate: sampleRate, bufferFrames: 512)
|
||||
// Pan to stereo: L=diskIn * 0.4, R=diskIn * 0.8
|
||||
let leftSrc: BinaryOpGenerator = diskIn * (0.4 as Double)
|
||||
let rightSrc: BinaryOpGenerator = diskIn * (0.8 as Double)
|
||||
// Interleave both channels into a single 2-ch generator via BinaryOpGenerator
|
||||
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: leftSrc,
|
||||
channelCount: 1,
|
||||
url: diskOutURL,
|
||||
sampleRate: sampleRate,
|
||||
format: .wav,
|
||||
bufferFrames: 512)
|
||||
|
||||
final class StereoRec: SynthesizerBase {
|
||||
let di: DiskIn.Audio
|
||||
let dol: DiskOut.Audio
|
||||
let rightSrc: any ValidGeneratorInput
|
||||
init(di: DiskIn.Audio, dol: DiskOut.Audio, rightSrc: any ValidGeneratorInput) {
|
||||
self.di = di; self.dol = dol; self.rightSrc = rightSrc
|
||||
}
|
||||
override func build() {
|
||||
output(bus: 0, source: dol)
|
||||
output(bus: 1, source: rightSrc)
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(StereoRec(di: diskIn, dol: diskOut, rightSrc: rightSrc))
|
||||
try engine.start()
|
||||
diskOut.close()
|
||||
|
||||
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
||||
sampleRate: sampleRate)
|
||||
// DiskOut recorded the left channel (diskIn * 0.4). Verify it's non-zero
|
||||
// and roughly matches the scaled sine.
|
||||
let samples: [Float] = channels[0]
|
||||
let nonZeroCount: Int = samples.filter { abs($0) > 0.001 }.count
|
||||
#expect(nonZeroCount > fileFrames / 4)
|
||||
}
|
||||
|
||||
// MARK: - Two concurrent DiskIn instances
|
||||
|
||||
@Test func twoConcurrentDiskInInstances() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let frameCount: Int = 512
|
||||
|
||||
let wavA: URL = try writeTempWAV(channels: [[Float](repeating: 0.2, count: frameCount)],
|
||||
sampleRate: sampleRate)
|
||||
let wavB: URL = try writeTempWAV(channels: [[Float](repeating: 0.8, count: frameCount)],
|
||||
sampleRate: sampleRate)
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: wavA)
|
||||
try? FileManager.default.removeItem(at: wavB)
|
||||
}
|
||||
|
||||
let diskInA: DiskIn.Audio = try DiskIn.Audio(url: wavA, channelCount: 1,
|
||||
sampleRate: sampleRate, bufferFrames: 512)
|
||||
let diskInB: DiskIn.Audio = try DiskIn.Audio(url: wavB, channelCount: 1,
|
||||
sampleRate: sampleRate, bufferFrames: 512)
|
||||
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: outURL) }
|
||||
|
||||
final class DualPlayer: SynthesizerBase {
|
||||
let a: DiskIn.Audio
|
||||
let b: DiskIn.Audio
|
||||
init(a: DiskIn.Audio, b: DiskIn.Audio) { self.a = a; self.b = b }
|
||||
override func build() {
|
||||
output(bus: 0, source: a) // 0.2 on left
|
||||
output(bus: 1, source: b) // 0.8 on right
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
||||
duration: Double(frameCount) / sampleRate)
|
||||
try engine.add(DualPlayer(a: diskInA, b: diskInB))
|
||||
try engine.start()
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
||||
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
||||
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0
|
||||
)
|
||||
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt)
|
||||
|
||||
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
||||
var framesRead: UInt32 = UInt32(frameCount)
|
||||
buf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base))
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
||||
}
|
||||
|
||||
let left: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
||||
let right: [Float] = stride(from: 3, to: Int(framesRead) * 2 - 1, by: 2).map { buf[$0] }
|
||||
#expect(left.allSatisfy { abs($0 - 0.2) < 0.01 })
|
||||
#expect(right.allSatisfy { abs($0 - 0.8) < 0.01 })
|
||||
}
|
||||
|
||||
// MARK: - DiskOut no-op after close
|
||||
|
||||
@Test func diskOutCloseIsIdempotent() throws {
|
||||
let sampleRate: Double = 44100
|
||||
let outURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let nrtURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: outURL)
|
||||
try? FileManager.default.removeItem(at: nrtURL)
|
||||
}
|
||||
|
||||
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: 0.0 as Double,
|
||||
channelCount: 1,
|
||||
url: outURL,
|
||||
sampleRate: sampleRate,
|
||||
format: .wav,
|
||||
bufferFrames: 512)
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtURL, duration: 0.01)
|
||||
final class Sink: SynthesizerBase {
|
||||
let d: DiskOut.Audio
|
||||
init(_ d: DiskOut.Audio) { self.d = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: d)
|
||||
output(bus: 1, source: d)
|
||||
}
|
||||
}
|
||||
try engine.add(Sink(diskOut))
|
||||
try engine.start()
|
||||
diskOut.close()
|
||||
diskOut.close() // second call must not crash or deadlock
|
||||
#expect(FileManager.default.fileExists(atPath: outURL.path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// DynamicsTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func rmsD(_ samples: [Double]) -> Double {
|
||||
guard !samples.isEmpty else { return 0 }
|
||||
return sqrt(samples.map { Double($0) * Double($0) }.reduce(0, +) / Double(samples.count))
|
||||
}
|
||||
|
||||
/// Drive a 2-channel generator for `blocks` blocks; returns (ch0, ch1) flat arrays.
|
||||
private func collect2ch(
|
||||
_ gen: any Generator,
|
||||
engine: SynthesisEngine,
|
||||
blocks: Int
|
||||
) -> ([Double], [Double]) {
|
||||
let bs: Int = engine.blockSize
|
||||
var ch0: [Double] = []
|
||||
var ch1: [Double] = []
|
||||
ch0.reserveCapacity(blocks * bs)
|
||||
ch1.reserveCapacity(blocks * bs)
|
||||
for _ in 0..<blocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = gen.calculatedSamples(graph: g, count: bs)
|
||||
ch0 += (result.count > 0 ? result[0] : [Double](repeating: 0, count: bs)).prefix(bs)
|
||||
ch1 += (result.count > 1 ? result[1] : [Double](repeating: 0, count: bs)).prefix(bs)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
return (ch0, ch1)
|
||||
}
|
||||
|
||||
// MARK: - AmplitudeFollower Tests
|
||||
|
||||
@Suite("AmplitudeFollower")
|
||||
struct AmplitudeFollowerTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func silenceOutputsZero() {
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: ConstantGeneratorInput(0.0))
|
||||
let samples: [Double] = collectBlocks(follower, engine: engine, blocks: 10)
|
||||
#expect(samples.allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
|
||||
@Test func steadySineConvergesToAmplitude() {
|
||||
// A 440 Hz sine at amplitude 0.5. Follower should converge near 0.5.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.01, releaseTime: 0.01)
|
||||
let all: [Double] = collectBlocks(follower, engine: engine, blocks: 200)
|
||||
// Check steady-state tail.
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
// Sine amplitude 0.5 → follower should stabilise around ~0.3–0.5 (peak tracks ~0.5).
|
||||
#expect(avg > 0.2 && avg < 0.55)
|
||||
}
|
||||
|
||||
@Test func impulseThenDecay() {
|
||||
// Single block at 1.0 then silence. Follower should rise then decay.
|
||||
let const: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: const,
|
||||
attackTime: 0.001, releaseTime: 0.5)
|
||||
// Hot block (amplitude 1.0).
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let hot: [Double] = follower.calculatedSamples(graph: g1, count: engine.blockSize)[0]
|
||||
advanceBlock(engine)
|
||||
// Check last valid sample (index blockSize-1), not hot.last which is element [511].
|
||||
let lastValidSample: Double = hot[engine.blockSize - 1]
|
||||
#expect(lastValidSample > 0.5)
|
||||
|
||||
// Now silence input.
|
||||
let silence: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let follower2: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: silence,
|
||||
attackTime: 0.001, releaseTime: 0.5)
|
||||
// Pre-heat follower2 to a high value by running one block with amplitude 1.
|
||||
let constIn: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let follower3: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: constIn,
|
||||
attackTime: 0.0, releaseTime: 0.5)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let _ = follower3.calculatedSamples(graph: g2, count: engine.blockSize)
|
||||
advanceBlock(engine)
|
||||
// Now feed silence — amplitude should decrease.
|
||||
let silenceGen: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let follower4: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: silenceGen,
|
||||
attackTime: 0.0, releaseTime: 0.5)
|
||||
let g3: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let decaying: [Double] = follower4.calculatedSamples(graph: g3, count: engine.blockSize)[0]
|
||||
// Fresh follower starts at 0 and stays 0 with silence.
|
||||
#expect(decaying.allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
|
||||
@Test func attackFasterThanRelease() {
|
||||
// With zero attack and long release, the follower immediately follows peaks up.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.8)
|
||||
let fastAtk: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.0, releaseTime: 2.0)
|
||||
let all: [Double] = collectBlocks(fastAtk, engine: engine, blocks: 10)
|
||||
// With instant attack, peak should reach near 0.8 very quickly.
|
||||
let peak: Double = all.max() ?? 0
|
||||
#expect(peak > 0.7)
|
||||
}
|
||||
|
||||
@Test func controlVariantBlockRatePeak() throws {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let ctrl: AmplitudeFollower.Control = AmplitudeFollower.Control(in: sine, attackTime: 0.001, releaseTime: 0.001)
|
||||
let all: [Double] = collectBlocks(ctrl, engine: engine, blocks: 100)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 20))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(avg > 0.2 && avg < 0.6)
|
||||
}
|
||||
|
||||
@Test func generatorEnumConformance() {
|
||||
// Verify GeneratorEnum typealiases compile and construct.
|
||||
let _: AmplitudeFollower.Audio = AmplitudeFollower.AudioType(in: 0.0)
|
||||
let _: AmplitudeFollower.Control = AmplitudeFollower.ControlType(in: 0.0)
|
||||
}
|
||||
|
||||
@Test func zeroAttackInstantaneousRise() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 1.0)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.0, releaseTime: 0.1)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = follower.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
// First non-zero sine sample should already be tracked (instant attack).
|
||||
let nonZero: [Double] = block.filter { $0 > 0.001 }
|
||||
#expect(!nonZero.isEmpty)
|
||||
}
|
||||
|
||||
/// Phase 174 — denormal flush moved to once-per-block. Pre-heat the smoother
|
||||
/// to ~1.0 with a loud DC input, then switch to a tiny-but-nonzero input
|
||||
/// (1e-20) with very fast release — `_prevAmp` drops several orders of
|
||||
/// magnitude per block, sweeping through the denormal regime that the
|
||||
/// once-per-block flush is responsible for catching. Output must stay
|
||||
/// finite + bounded over the full render.
|
||||
///
|
||||
/// We construct two followers (preheat + measurement) because input is
|
||||
/// captured at init; the pre-heat is solely to prove the smoother had
|
||||
/// genuine non-zero state before we observed it converge. The measurement
|
||||
/// follower's `_prevAmp` starts at 0; with a tiny input + fast release it
|
||||
/// rises slowly toward 1e-20, then would normally drift through the
|
||||
/// denormal band but for the once-per-block `denormalsToZero` flush.
|
||||
@Test func denormalCadenceAmplitudeFollower() {
|
||||
// Pre-heat sanity check — distinct follower; validates the smoother
|
||||
// tracks a non-zero level (no assertion needed beyond non-finite check).
|
||||
let driven: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let preheat: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: driven, attackTime: 0.001, releaseTime: 0.001)
|
||||
for _: Int in 0..<32 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = preheat.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
for v: Double in block { #expect(v.isFinite) }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Measurement follower — tiny non-zero input + tiny release time. Output
|
||||
// converges toward 1e-20 (a denormal-adjacent value) over the render.
|
||||
let tiny: ConstantGeneratorInput = ConstantGeneratorInput(1e-20)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: tiny, attackTime: 1e-5, releaseTime: 1e-5)
|
||||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||||
var sawNonFinite: Bool = false
|
||||
var maxObserved: Double = 0.0
|
||||
for _: Int in 0..<blocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = follower.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
for v: Double in block {
|
||||
if !v.isFinite { sawNonFinite = true }
|
||||
if v > maxObserved { maxObserved = v }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(!sawNonFinite, "AmplitudeFollower output must remain finite")
|
||||
#expect(maxObserved < 1.0, "envelope of tiny input must remain bounded")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FreqTracker Tests
|
||||
|
||||
@Suite("FreqTracker")
|
||||
struct FreqTrackerTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100.0
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func silenceOutputsZeroConfidence() {
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0),
|
||||
fftSize: 512, hopSize: 256)
|
||||
let (_, conf) = collect2ch(tracker, engine: engine, blocks: 20)
|
||||
let tailConf: [Double] = Array(conf.suffix(engine.blockSize * 5))
|
||||
let avgConf: Double = tailConf.reduce(Double(0), +) / Double(tailConf.count)
|
||||
// Silence → near-zero confidence.
|
||||
#expect(avgConf < 0.2)
|
||||
}
|
||||
|
||||
@Test func pureA440FreqTracked() {
|
||||
// Use smaller fftSize for faster convergence in tests.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.8)
|
||||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||||
minFreq: 60.0, maxFreq: 3000.0)
|
||||
// Render enough blocks to warm up (need hopSize × 4 samples at minimum).
|
||||
let warmUpBlocks: Int = (512 / engine.blockSize) + 10
|
||||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: warmUpBlocks)
|
||||
// Check the tail.
|
||||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
|
||||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||||
if !nonZero.isEmpty {
|
||||
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
|
||||
#expect(avgFreq > 420.0 && avgFreq < 460.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func twoChannelOutput() {
|
||||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0), fftSize: 256, hopSize: 128)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = tracker.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(result.count == 2)
|
||||
// Buffers are pre-allocated to 512; at least blockSize valid samples in each.
|
||||
#expect(result[0].count >= engine.blockSize)
|
||||
#expect(result[1].count >= engine.blockSize)
|
||||
}
|
||||
|
||||
@Test func confidenceHighForPureSine() {
|
||||
let freq: Double = 440.0
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: freq, mul: 0.9)
|
||||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||||
minFreq: 60.0, maxFreq: 3000.0)
|
||||
// Warm up and check confidence.
|
||||
let blocks: Int = (1024 / engine.blockSize) + 20
|
||||
let (_, conf) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||||
let tail: [Double] = Array(conf.suffix(engine.blockSize * 10))
|
||||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||||
if !nonZero.isEmpty {
|
||||
let maxConf: Double = nonZero.max() ?? 0
|
||||
#expect(maxConf > 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func fftSizePreconditionPowerOfTwo() {
|
||||
// Valid: power of 2 ≥ 64.
|
||||
let t: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0), fftSize: 64)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = t.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
#expect(result.count == 2)
|
||||
}
|
||||
|
||||
@Test func outOfRangeFreqReturnsZero() {
|
||||
// A 440 Hz sine with maxFreq = 200 Hz — should report 0 Hz (out of range).
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||||
minFreq: 60.0, maxFreq: 200.0)
|
||||
let blocks: Int = (1024 / engine.blockSize) + 20
|
||||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 10))
|
||||
// 440 Hz is above maxFreq → should output 0.
|
||||
let above: [Double] = tail.filter { $0 > 250.0 }
|
||||
#expect(above.isEmpty)
|
||||
}
|
||||
|
||||
@Test func differentPitch880Hz() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 880.0, mul: 0.8)
|
||||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 256,
|
||||
minFreq: 60.0, maxFreq: 3000.0)
|
||||
let blocks: Int = (1024 / engine.blockSize) + 30
|
||||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||||
let nonZero: [Double] = freqs.filter { $0 > 400.0 } // filter out subharmonic at 440 Hz
|
||||
if !nonZero.isEmpty {
|
||||
let avgFreq: Double = nonZero.suffix(engine.blockSize * 5).reduce(Double(0), +)
|
||||
/ Double(min(engine.blockSize * 5, nonZero.count))
|
||||
#expect(avgFreq > 800.0 && avgFreq < 960.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - LookAheadLimiter Tests
|
||||
|
||||
@Suite("LookAheadLimiter")
|
||||
struct LookAheadLimiterTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100.0
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func lowAmplitudePassesThrough() {
|
||||
// Signal well below maxAmplitude should pass through with gain ≈ 1.
|
||||
// Compare RMS (not sample-by-sample — look-ahead delay shifts phase).
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.3)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: 1.0,
|
||||
lookAheadTime: 0.005, sampleRate: sr)
|
||||
let limited: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||||
let tail: [Double] = Array(limited.suffix(engine.blockSize * 50))
|
||||
let rmsLimited: Double = rmsD(tail)
|
||||
// 100 Hz sine at amplitude 0.3 → RMS ≈ 0.212. No limiting expected.
|
||||
#expect(rmsLimited > 0.18 && rmsLimited < 0.25)
|
||||
}
|
||||
|
||||
@Test func peakNeverExceedsMaxAmplitude() {
|
||||
// Loud signal — limiter must clamp absolute peak to ≤ maxAmplitude.
|
||||
let maxAmp: Double = 0.5
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 2.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.01, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||||
// Allow small margin for release tail.
|
||||
let violators: [Double] = samples.filter { abs(Double($0)) > maxAmp + 0.001 }
|
||||
#expect(violators.isEmpty)
|
||||
}
|
||||
|
||||
@Test func delayedBylookAheadSamples() {
|
||||
// An impulse at sample 0 should appear delayed by lookAheadSamples.
|
||||
let lookAheadTime: Double = 0.002
|
||||
let lookAheadSamples: Int = Int(lookAheadTime * sr)
|
||||
let impulse: Impulse.Audio = Impulse.Audio(freq: 0.0) // fires once at t=0 (never repeats if freq=0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: impulse, maxAmplitude: 2.0,
|
||||
lookAheadTime: lookAheadTime, sampleRate: sr)
|
||||
let blocks: Int = (lookAheadSamples / engine.blockSize) + 5
|
||||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: blocks)
|
||||
// First `lookAheadSamples` outputs should be zero (before the impulse arrives).
|
||||
let prefix: [Double] = Array(samples.prefix(lookAheadSamples))
|
||||
#expect(prefix.allSatisfy { abs($0) < 0.001 })
|
||||
}
|
||||
|
||||
@Test func zeroLookAheadStillLimits() {
|
||||
let maxAmp: Double = 0.4
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.5)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.0, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||||
// May briefly overshoot on first cycle without look-ahead — allow small margin.
|
||||
let steadyTail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||||
let violators: [Double] = steadyTail.filter { abs(Double($0)) > maxAmp + 0.01 }
|
||||
#expect(violators.isEmpty)
|
||||
}
|
||||
|
||||
@Test func dcSignalLimitedToMaxAmplitude() {
|
||||
// DC at 2.0 should be limited to 1.0.
|
||||
let maxAmp: Double = 1.0
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.005, sampleRate: sr)
|
||||
// After warm-up (look-ahead fills), output should be ≈ 1.0.
|
||||
let warmUpSamples: Int = Int(0.005 * sr) + engine.blockSize
|
||||
let warmUpBlocks: Int = warmUpSamples / engine.blockSize + 2
|
||||
let all: [Double] = collectBlocks(limiter, engine: engine, blocks: warmUpBlocks + 20)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 10))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(Double(avg) - maxAmp) < 0.05)
|
||||
}
|
||||
|
||||
@Test func customMaxAmplitude() {
|
||||
let maxAmp: Double = 0.25
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.005, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 200)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let peak: Double = tail.map { abs(Double($0)) }.max() ?? 0
|
||||
#expect(peak <= maxAmp + 0.001)
|
||||
}
|
||||
|
||||
/// DC at 2.0, maxAmplitude=1.0, lookAheadTime=0 (no delay).
|
||||
/// windowPeak = 2.0, requiredGain = 0.5 (instantaneous attack).
|
||||
/// Steady-state output = 2.0 × 0.5 = 1.0.
|
||||
@Test func exactLimitingOfKnownDCSignal() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: 1.0,
|
||||
lookAheadTime: 0.0, sampleRate: sr)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = limiter.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
// With instant attack and DC, every sample after the first should be exactly 1.0.
|
||||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||||
#expect(abs(steadySample - 1.0) < 0.001)
|
||||
}
|
||||
|
||||
/// Phase 173a — zero-look-ahead fast path is a pure peak follower (no ring, no deque).
|
||||
/// A loud transient must clamp on the same sample (instantaneous attack), and after
|
||||
/// the transient passes the gain must release back toward 1.0.
|
||||
@Test func zeroLookAheadPeakFollowerInstantClamp() {
|
||||
// Loud DC step at maxAmp=0.5 → instantaneous gain 0.5/2.0 = 0.25 → output = 0.5.
|
||||
let maxAmp: Double = 0.5
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.0, sampleRate: sr)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = limiter.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
// Every sample (including the first) is clamped to maxAmp.
|
||||
let peak: Double = block.map { abs(Double($0)) }.max() ?? 0
|
||||
#expect(peak <= maxAmp + 1e-9)
|
||||
// Steady state hits maxAmp exactly.
|
||||
#expect(abs(Double(block[engine.blockSize - 1]) - maxAmp) < 1e-9)
|
||||
}
|
||||
|
||||
/// Phase 173a — denormal flush moved to once-per-block (was per-sample).
|
||||
/// Sustained extreme reduction (tiny maxAmp on loud DC) drives `_gain` toward a
|
||||
/// very small value; the once-per-block flush must keep it from becoming a
|
||||
/// denormal that would slow down the RT path. Render long enough (~2 s) to
|
||||
/// flush many blocks and verify the output stream never produces NaN / inf
|
||||
/// and remains bounded.
|
||||
@Test func sustainedExtremeReductionStaysFinite() {
|
||||
let maxAmp: Double = 1e-30 // extreme; gain → ~5e-31 in steady state
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.005, sampleRate: sr)
|
||||
// ~2 seconds at blockSize 64 / sr 44100 → ~1378 blocks.
|
||||
let blocks: Int = (Int(sr * 2.0) / engine.blockSize) + 1
|
||||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: blocks)
|
||||
let badSamples: [Double] = samples.filter { !$0.isFinite }
|
||||
#expect(badSamples.isEmpty)
|
||||
// Output magnitudes stay near maxAmp once the look-ahead window warms up.
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let tailMax: Double = tail.map { abs($0) }.max() ?? 0
|
||||
#expect(tailMax < maxAmp * 10.0) // generous bound; really we want "small"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Compressor Tests
|
||||
|
||||
@Suite("Compressor")
|
||||
struct CompressorTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func signalBelowThresholdUnchanged() {
|
||||
// Signal at -20 dBFS, threshold at -6 dB → no compression.
|
||||
let amp: Float = Float(pow(10.0, -20.0 / 20.0)) // ≈ 0.1
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||||
let comp: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 4.0,
|
||||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||||
let samples: [Double] = collectBlocks(comp, engine: engine, blocks: 50)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||||
let rmsOut: Double = rmsD(tail)
|
||||
let rmsIn: Double = Double(amp) / sqrt(2.0) // sine RMS
|
||||
// Output RMS should be very close to input RMS (no compression).
|
||||
#expect(abs(rmsOut - rmsIn) < 0.01)
|
||||
}
|
||||
|
||||
@Test func signalAboveThresholdCompressed() {
|
||||
// Signal at 0 dBFS (amplitude 1.0), threshold at -6 dB, ratio 4:1, instant attack.
|
||||
// Expected: 6 dB over threshold → 6/4 = 1.5 dB output above threshold → gain ≈ -4.5 dB.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||||
let comp: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 4.0,
|
||||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||||
let samples: [Double] = collectBlocks(comp, engine: engine, blocks: 100)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||||
let peak: Double = tail.map { abs($0) }.max() ?? 0
|
||||
// Peak should be reduced below 1.0.
|
||||
#expect(Double(peak) < 0.9)
|
||||
}
|
||||
|
||||
@Test func makeupGainBoostsOutput() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||||
let noMakeup: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 1.0,
|
||||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||||
let withMakeup: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: 0.5),
|
||||
threshold: -6.0, ratio: 1.0,
|
||||
attack: 0.0, release: 0.0, makeupGain: 6.0)
|
||||
let ref: [Double] = collectBlocks(noMakeup, engine: engine, blocks: 50)
|
||||
let boosted: [Double] = collectBlocks(withMakeup, engine: engine, blocks: 50)
|
||||
let rmsRef: Double = rmsD(ref)
|
||||
let rmsBoosted: Double = rmsD(boosted)
|
||||
// +6 dB makeup ≈ ×2 amplitude → roughly 2× RMS.
|
||||
#expect(rmsBoosted > rmsRef * 1.7)
|
||||
}
|
||||
|
||||
@Test func controlVariantMatchesAudioWithinTolerance() {
|
||||
let sine1: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||||
let sine2: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||||
let audioComp: Compressor.Audio = Compressor.Audio(in: sine1, threshold: -6.0, ratio: 4.0,
|
||||
attack: 0.005, release: 0.1)
|
||||
let ctrlComp: Compressor.Control = Compressor.Control(in: sine2, threshold: -6.0, ratio: 4.0,
|
||||
attack: 0.005, release: 0.1)
|
||||
let audioOut: [Double] = collectBlocks(audioComp, engine: engine, blocks: 100)
|
||||
let ctrlOut: [Double] = collectBlocks(ctrlComp, engine: engine, blocks: 100)
|
||||
let rmsAudio: Double = rmsD(audioOut)
|
||||
let rmsCtrl: Double = rmsD(ctrlOut)
|
||||
// Control and audio should be within 3 dB of each other.
|
||||
let ratio: Double = max(rmsAudio, rmsCtrl) / (min(rmsAudio, rmsCtrl) + 1e-9)
|
||||
#expect(ratio < 1.5)
|
||||
}
|
||||
|
||||
@Test func softKneeSmoothsTransition() {
|
||||
// With a soft knee, the gain reduction should start before the threshold.
|
||||
// A signal right at threshold with soft knee should have some reduction vs none.
|
||||
let threshDB: Double = -12.0
|
||||
let amp: Float = Float(pow(10.0, threshDB / 20.0))
|
||||
let sineHard: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: Double(amp)),
|
||||
threshold: threshDB, ratio: 4.0,
|
||||
attack: 0.0, release: 0.0, kneeWidth: 0.0)
|
||||
let sineSoft: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: Double(amp)),
|
||||
threshold: threshDB, ratio: 4.0,
|
||||
attack: 0.0, release: 0.0, kneeWidth: 6.0)
|
||||
let hardOut: [Double] = collectBlocks(sineHard, engine: engine, blocks: 50)
|
||||
let softOut: [Double] = collectBlocks(sineSoft, engine: engine, blocks: 50)
|
||||
// At threshold, both should produce similar (not wildly different) output.
|
||||
let rmsHard: Double = rmsD(hardOut)
|
||||
let rmsSoft: Double = rmsD(softOut)
|
||||
let ratio: Double = max(rmsHard, rmsSoft) / (min(rmsHard, rmsSoft) + 1e-9)
|
||||
#expect(ratio < 2.0)
|
||||
}
|
||||
|
||||
@Test func generatorEnumConformance() {
|
||||
let _: Compressor.Audio = Compressor.AudioType(in: 0.0)
|
||||
let _: Compressor.Control = Compressor.ControlType(in: 0.0)
|
||||
}
|
||||
|
||||
/// DC at 0 dBFS (1.0), threshold=-6 dB, ratio=4:1, instant attack/release.
|
||||
/// gain_dB = (0 − (−6)) × (1/4 − 1) = 6 × (−0.75) = −4.5 dB
|
||||
/// target = 10^(−4.5/20) ≈ 0.5957.
|
||||
/// With attack=0, _prevGain collapses to target on first sample → steady-state output = target.
|
||||
@Test func exactGainForKnownDCInput() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let comp: Compressor.Audio = Compressor.Audio(in: dc, threshold: -6.0, ratio: 4.0,
|
||||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = comp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
let expectedGain: Double = pow(10.0, -4.5 / 20.0)
|
||||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||||
// Steady-state DC output = 1.0 × gain = expectedGain.
|
||||
#expect(abs(steadySample - expectedGain) < 0.001)
|
||||
}
|
||||
|
||||
/// Phase 174 — once-per-block denormal flush survives sustained extreme reduction.
|
||||
/// 1.0 DC at threshold=-60 dB ratio=20:1 with makeup -40 dB drives gain very low;
|
||||
/// output must stay finite + bounded over ~2 s.
|
||||
@Test func denormalCadenceCompressor() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||||
let comp: Compressor.Audio = Compressor.Audio(
|
||||
in: dc, threshold: -60.0, ratio: 20.0,
|
||||
attack: 0.001, release: 0.001,
|
||||
kneeWidth: 0.0, makeupGain: -40.0)
|
||||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||||
var sawNonFinite: Bool = false
|
||||
var maxAbs: Double = 0.0
|
||||
for _: Int in 0..<blocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = comp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
for v: Double in block {
|
||||
if !v.isFinite { sawNonFinite = true }
|
||||
let a: Double = abs(v)
|
||||
if a > maxAbs { maxAbs = a }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(!sawNonFinite, "Compressor output must remain finite")
|
||||
#expect(maxAbs < 1.0, "heavily-reduced output must stay below input level")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Expander Tests
|
||||
|
||||
@Suite("Expander")
|
||||
struct ExpanderTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func signalAboveThresholdUnchanged() {
|
||||
// Signal at 0 dBFS, threshold at -40 dB → above threshold, no expansion.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||||
let exp: Expander.Audio = Expander.Audio(in: sine, threshold: -40.0, ratio: 0.0,
|
||||
attack: 0.0, release: 0.0)
|
||||
let samples: [Double] = collectBlocks(exp, engine: engine, blocks: 50)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||||
let rmsOut: Double = rmsD(tail)
|
||||
// Input RMS ≈ 0.707. Output should be close.
|
||||
#expect(rmsOut > 0.6)
|
||||
}
|
||||
|
||||
@Test func gateRatioBelowThresholdSilences() {
|
||||
// Signal at -40 dBFS, threshold at -20 dB, ratio 0.0 (gate).
|
||||
let amp: Float = Float(pow(10.0, -40.0 / 20.0)) // −40 dBFS
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||||
let gate: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 0.0,
|
||||
attack: 0.0, release: 0.0)
|
||||
let samples: [Double] = collectBlocks(gate, engine: engine, blocks: 50)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||||
let rmsOut: Double = rmsD(tail)
|
||||
// Gate should suppress signal significantly (≤ −20 dB relative to input).
|
||||
#expect(rmsOut < Double(amp) * 0.2)
|
||||
}
|
||||
|
||||
@Test func expansionReducesLowLevelSignal() {
|
||||
// Signal 20 dB below threshold. With ratio 0.5, gain_dB = 20 × (0.5 − 1) = −10 dB.
|
||||
let amp: Float = Float(pow(10.0, -40.0 / 20.0)) // −40 dBFS
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||||
let expander: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 0.5,
|
||||
attack: 0.0, release: 0.0)
|
||||
let samples: [Double] = collectBlocks(expander, engine: engine, blocks: 50)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||||
let rmsOut: Double = rmsD(tail)
|
||||
// Output should be lower than input.
|
||||
#expect(rmsOut < Double(amp) * 0.8)
|
||||
}
|
||||
|
||||
@Test func controlVariantMatchesAudioWithinTolerance() {
|
||||
// Use signal well above threshold so both variants see no expansion.
|
||||
let sine1: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||||
let sine2: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||||
let audioExp: Expander.Audio = Expander.Audio(in: sine1, threshold: -40.0, ratio: 0.5,
|
||||
attack: 0.005, release: 0.1)
|
||||
let ctrlExp: Expander.Control = Expander.Control(in: sine2, threshold: -40.0, ratio: 0.5,
|
||||
attack: 0.005, release: 0.1)
|
||||
let audioOut: [Double] = collectBlocks(audioExp, engine: engine, blocks: 100)
|
||||
let ctrlOut: [Double] = collectBlocks(ctrlExp, engine: engine, blocks: 100)
|
||||
let rmsAudio: Double = rmsD(audioOut)
|
||||
let rmsCtrl: Double = rmsD(ctrlOut)
|
||||
let ratio: Double = max(rmsAudio, rmsCtrl) / (min(rmsAudio, rmsCtrl) + 1e-9)
|
||||
#expect(ratio < 1.5)
|
||||
}
|
||||
|
||||
@Test func generatorEnumConformance() {
|
||||
let _: Expander.Audio = Expander.AudioType(in: 0.0)
|
||||
let _: Expander.Control = Expander.ControlType(in: 0.0)
|
||||
}
|
||||
|
||||
@Test func bypassRatioOneNoChange() {
|
||||
// ratio = 1.0 → gain_dB = 0 at all levels, output equals input.
|
||||
let amp: Double = 0.02
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: amp)
|
||||
let bypass: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 1.0,
|
||||
attack: 0.0, release: 0.0)
|
||||
let samples: [Double] = collectBlocks(bypass, engine: engine, blocks: 50)
|
||||
let rmsOut: Double = rmsD(samples)
|
||||
let rmsIn: Double = Double(amp) / sqrt(2.0)
|
||||
#expect(abs(rmsOut - rmsIn) < 0.005)
|
||||
}
|
||||
|
||||
/// DC at −40 dBFS (0.01), threshold=−20 dB, ratio=0.5, instant.
|
||||
/// diff = −40 − (−20) = −20 dB. gain_dB = −20 × (1/0.5 − 1) = −20 × 1 = −20 dB.
|
||||
/// target = 10^(−20/20) = 0.1. output = 0.01 × 0.1 = 0.001.
|
||||
@Test func exactGainForKnownDCInput() {
|
||||
let inputAmp: Double = 0.01 // −40 dBFS
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(inputAmp)
|
||||
let expander: Expander.Audio = Expander.Audio(in: dc, threshold: -20.0, ratio: 0.5,
|
||||
attack: 0.0, release: 0.0)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = expander.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
let expectedOutput: Double = inputAmp * 0.1 // gain = −20 dB = 0.1 linear
|
||||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||||
#expect(abs(steadySample - expectedOutput) < 0.0001)
|
||||
}
|
||||
|
||||
/// Phase 174 — once-per-block denormal flush survives the gate path.
|
||||
/// ratio=0 (hard gate) on a sub-threshold signal drives gain → 1e-6 (−120 dB
|
||||
/// floor); output must stay finite + bounded over ~2 s.
|
||||
@Test func denormalCadenceExpander() {
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.001) // −60 dBFS
|
||||
let exp: Expander.Audio = Expander.Audio(
|
||||
in: dc, threshold: -20.0, ratio: 0.0,
|
||||
attack: 0.001, release: 0.001, kneeWidth: 0.0)
|
||||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||||
var sawNonFinite: Bool = false
|
||||
var maxAbs: Double = 0.0
|
||||
for _: Int in 0..<blocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block: [Double] = exp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||||
for v: Double in block {
|
||||
if !v.isFinite { sawNonFinite = true }
|
||||
let a: Double = abs(v)
|
||||
if a > maxAbs { maxAbs = a }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(!sawNonFinite, "Expander output must remain finite")
|
||||
#expect(maxAbs < 0.001, "gated output must stay near silence")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// EngineHostTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Phase 197 — `EngineHost` facade coverage.
|
||||
@Suite("EngineHost (Phase 197)")
|
||||
struct EngineHostTests {
|
||||
|
||||
// MARK: - Test helpers
|
||||
|
||||
/// Build a fresh `SynthesisEngineConfig` suitable for unit tests
|
||||
/// (small block size, offline driver, zero input channels).
|
||||
private func makeConfig() -> SynthesisEngineConfig {
|
||||
SynthesisEngineConfig(
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: 16,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - 197.1 makeEngine
|
||||
|
||||
@Test func makeEngineRegistersUnderRole() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
let engine: SynthesisEngine = try host.makeEngine(
|
||||
role: .nrtRender(slot: 0),
|
||||
config: makeConfig()
|
||||
)
|
||||
|
||||
#expect(host.engineCount == 1)
|
||||
#expect(host.engine(for: .nrtRender(slot: 0)) === engine)
|
||||
#expect(host.role(for: engine) == .nrtRender(slot: 0))
|
||||
}
|
||||
|
||||
@Test func makeEngineMultipleRolesDistinctEngines() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
let a: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
let b: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
|
||||
let c: SynthesisEngine = try host.makeEngine(role: .auxiliary(name: "analysis"), config: makeConfig())
|
||||
|
||||
#expect(host.engineCount == 3)
|
||||
#expect(a.identifier != b.identifier)
|
||||
#expect(b.identifier != c.identifier)
|
||||
#expect(a.identifier != c.identifier)
|
||||
}
|
||||
|
||||
@Test func makeEngineDuplicateRoleThrows() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
|
||||
var caught: EngineHostError? = nil
|
||||
do {
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
} catch let error as EngineHostError {
|
||||
caught = error
|
||||
}
|
||||
#expect(caught != nil)
|
||||
if case .duplicateRole(let role) = caught {
|
||||
#expect(role == .nrtRender(slot: 0))
|
||||
} else {
|
||||
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase 197 re-review fix: pre-check throw must not leak the
|
||||
/// host lock. If `_validateRoleUnlocked` threw without `defer`-ed
|
||||
/// unlock, every subsequent host call on the same instance would
|
||||
/// deadlock on `_lock.lock()`. This test asserts the host is
|
||||
/// still usable after a `.duplicateRole` throw — a deadlock would
|
||||
/// hang the test indefinitely (Swift Testing default per-test
|
||||
/// timeout kicks in).
|
||||
@Test func hostStillUsableAfterDuplicateRoleThrow() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
|
||||
// First duplicate — throws.
|
||||
do {
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
Issue.record("Expected throw on duplicate role")
|
||||
} catch is EngineHostError {
|
||||
// Expected
|
||||
}
|
||||
|
||||
// Subsequent calls must not deadlock.
|
||||
#expect(host.engineCount == 1)
|
||||
#expect(host.engine(for: .nrtRender(slot: 0)) != nil)
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
|
||||
#expect(host.engineCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - 197.2 Role exclusivity (rtOutput device)
|
||||
|
||||
/// Same-`.rtOutput(deviceID:)` re-registration throws
|
||||
/// `.duplicateRole` because the `Hashable` enum case already
|
||||
/// discriminates by deviceID. Phase 198 (F8) dropped the dead
|
||||
/// `.duplicateDevice` enum case that would have covered cross-role
|
||||
/// same-device collisions — re-add when a future role shape
|
||||
/// requires it.
|
||||
@Test func makeEngineSameRtOutputRoleTwiceThrowsDuplicateRole() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .rtOutput(deviceID: 42), config: makeConfig())
|
||||
|
||||
var caught: EngineHostError? = nil
|
||||
do {
|
||||
_ = try host.makeEngine(role: .rtOutput(deviceID: 42), config: makeConfig())
|
||||
} catch let error as EngineHostError {
|
||||
caught = error
|
||||
}
|
||||
#expect(caught != nil)
|
||||
if case .duplicateRole(let role) = caught {
|
||||
#expect(role == .rtOutput(deviceID: 42))
|
||||
} else {
|
||||
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 197.3 Lookup + lifecycle
|
||||
|
||||
@Test func engineForUnregisteredRoleReturnsNil() {
|
||||
let host: EngineHost = EngineHost()
|
||||
#expect(host.engine(for: .nrtRender(slot: 99)) == nil)
|
||||
}
|
||||
|
||||
@Test func rolesSnapshotContainsAllRegistered() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
_ = try host.makeEngine(role: .auxiliary(name: "fx"), config: makeConfig())
|
||||
|
||||
let roles: [EngineHostRole] = host.roles
|
||||
#expect(roles.count == 2)
|
||||
#expect(roles.contains(.nrtRender(slot: 0)))
|
||||
#expect(roles.contains(.auxiliary(name: "fx")))
|
||||
}
|
||||
|
||||
@Test func startAllStartsEveryEngine() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
let a: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
let b: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
|
||||
|
||||
#expect(a.isRunning == false)
|
||||
#expect(b.isRunning == false)
|
||||
|
||||
try host.startAll()
|
||||
|
||||
#expect(a.isRunning == true)
|
||||
#expect(b.isRunning == true)
|
||||
|
||||
host.stopAll()
|
||||
|
||||
#expect(a.isRunning == false)
|
||||
#expect(b.isRunning == false)
|
||||
}
|
||||
|
||||
@Test func stopAllIdempotent() throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
|
||||
// Never started — stopAll should be a no-op (engine.stop()
|
||||
// is documented as safe when not running).
|
||||
host.stopAll()
|
||||
host.stopAll()
|
||||
}
|
||||
|
||||
// MARK: - 197.5 Adoption
|
||||
|
||||
@Test func adoptExistingEngine() throws {
|
||||
// Construct engine outside the host — exercises the migration
|
||||
// / direct-ctor scenario.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
try host.adopt(existing: engine, role: .custom("imported"))
|
||||
|
||||
#expect(host.engineCount == 1)
|
||||
#expect(host.engine(for: .custom("imported")) === engine)
|
||||
#expect(host.role(for: engine) == .custom("imported"))
|
||||
}
|
||||
|
||||
// MARK: - 197.4 NRT batch render
|
||||
|
||||
/// Build a temporary scratch directory for NRT output files,
|
||||
/// auto-cleaned at end of test via the returned cleanup closure.
|
||||
private func makeScratchDir() throws -> (URL, () -> Void) {
|
||||
let fm: FileManager = FileManager.default
|
||||
let dir: URL = fm.temporaryDirectory.appendingPathComponent(
|
||||
"EngineHostTests_\(UUID().uuidString)"
|
||||
)
|
||||
try fm.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
return (dir, { try? fm.removeItem(at: dir) })
|
||||
}
|
||||
|
||||
/// Lightweight test synthesizer: writes a constant value to bus 0.
|
||||
private final class ConstSynth: SynthesizerBase {
|
||||
let value: Double
|
||||
init(value: Double) {
|
||||
self.value = value
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: value))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func renderConcurrentEmptyJobsFinishesImmediately() async throws {
|
||||
let host: EngineHost = EngineHost()
|
||||
var count: Int = 0
|
||||
for try await _ in host.renderConcurrent(jobs: []) {
|
||||
count += 1
|
||||
}
|
||||
#expect(count == 0)
|
||||
}
|
||||
|
||||
@Test func renderConcurrentYieldsOnePerJob() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
let jobs: [NRTJob] = (0..<4).map { i in
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("out_\(i).caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try engine.add(ConstSynth(value: 0.1 * Double(i + 1)))
|
||||
}
|
||||
}
|
||||
|
||||
var results: [NRTResult] = []
|
||||
for try await result: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
|
||||
results.append(result)
|
||||
}
|
||||
|
||||
#expect(results.count == jobs.count)
|
||||
// Every job index reported exactly once (completion order varies).
|
||||
let indices: Set<Int> = Set(results.map(\.jobIndex))
|
||||
#expect(indices == Set(0..<jobs.count))
|
||||
|
||||
// Every output file should exist + non-empty.
|
||||
for result: NRTResult in results {
|
||||
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(
|
||||
atPath: result.outputURL.path
|
||||
)
|
||||
let size: Int = (attrs[.size] as? Int) ?? 0
|
||||
#expect(size > 0, "Output file \(result.outputURL.lastPathComponent) is empty")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func renderConcurrentPropagatesBuildFailure() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
struct DeliberateBuildFailure: Error {}
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
let jobs: [NRTJob] = [
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("ok.caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try engine.add(ConstSynth(value: 0.1))
|
||||
},
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("fail.caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { _ in
|
||||
throw DeliberateBuildFailure()
|
||||
}
|
||||
]
|
||||
|
||||
var caught: (any Error)? = nil
|
||||
do {
|
||||
for try await _ in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
|
||||
// drain
|
||||
}
|
||||
} catch {
|
||||
caught = error
|
||||
}
|
||||
#expect(caught is DeliberateBuildFailure)
|
||||
}
|
||||
|
||||
/// Phase 198 (F1 re-review): a `build` closure that deliberately
|
||||
/// throws `CancellationError` must propagate as a stream-level
|
||||
/// throw, not be misclassified as a caller-cancel and silently
|
||||
/// swallowed. The outer-catch `Task.isCancelled` guard distinguishes
|
||||
/// the two sources of `CancellationError`.
|
||||
@Test func renderConcurrentBuildCancellationErrorPropagates() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
let jobs: [NRTJob] = [
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("cancel_thrown.caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { _ in
|
||||
throw CancellationError()
|
||||
}
|
||||
]
|
||||
|
||||
var caught: (any Error)? = nil
|
||||
do {
|
||||
for try await _: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 1) {
|
||||
// drain
|
||||
}
|
||||
} catch {
|
||||
caught = error
|
||||
}
|
||||
let isCancellationError: Bool = caught is CancellationError
|
||||
#expect(isCancellationError,
|
||||
Comment(rawValue: "build closure throwing CancellationError must surface as a stream throw, " +
|
||||
"got \(String(describing: caught))"))
|
||||
}
|
||||
|
||||
/// Phase 198 (F1): caller breaking the for-await early must finish
|
||||
/// the stream cleanly, not throw `CancellationError`. The earlier
|
||||
/// implementation forwarded the cooperative-cancel from
|
||||
/// `withThrowingTaskGroup`'s for-await into `continuation.finish(throwing:)`,
|
||||
/// surfacing a thrown termination even on caller-initiated cancel.
|
||||
@Test func renderConcurrentCallerCancelFinishesCleanly() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
// Enough jobs that the for-await iterates more than once and we
|
||||
// can break midway.
|
||||
let jobs: [NRTJob] = (0..<6).map { i in
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("cancel_\(i).caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try engine.add(ConstSynth(value: 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
var caught: (any Error)? = nil
|
||||
var seenResults: Int = 0
|
||||
do {
|
||||
for try await _: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
|
||||
seenResults += 1
|
||||
if seenResults == 1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
caught = error
|
||||
}
|
||||
#expect(caught == nil,
|
||||
Comment(rawValue: "Caller-initiated cancel must not throw; got \(String(describing: caught))"))
|
||||
// Allow >= 1 to absorb scheduler-ordering windows where a
|
||||
// second result lands before the for-await's `break`
|
||||
// propagates through the AsyncSequence machinery.
|
||||
#expect(seenResults >= 1)
|
||||
}
|
||||
|
||||
@Test func renderConcurrentRespectsMaxConcurrentClamp() async throws {
|
||||
// Clamp `0` upward to `1`. Single-job stream finishes cleanly.
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
let jobs: [NRTJob] = [
|
||||
NRTJob(
|
||||
outputURL: dir.appendingPathComponent("clamp.caf"),
|
||||
duration: 0.05,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try engine.add(ConstSynth(value: 0.1))
|
||||
}
|
||||
]
|
||||
var count: Int = 0
|
||||
for try await _ in host.renderConcurrent(jobs: jobs, maxConcurrent: 0) {
|
||||
count += 1
|
||||
}
|
||||
#expect(count == 1)
|
||||
}
|
||||
|
||||
@Test func adoptDuplicateRoleThrows() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
|
||||
|
||||
var caught: EngineHostError? = nil
|
||||
do {
|
||||
try host.adopt(existing: engine, role: .nrtRender(slot: 0))
|
||||
} catch let error as EngineHostError {
|
||||
caught = error
|
||||
}
|
||||
#expect(caught != nil)
|
||||
if case .duplicateRole = caught {
|
||||
// Expected
|
||||
} else {
|
||||
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
// EngineMainGroupTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// Tests for the persistent mainGroup added to SynthesisEngine at init.
|
||||
|
||||
// MARK: - Helper: value-stamping synthesizer
|
||||
|
||||
// Test-only Synthesizer; RT-thread mutation of evaluateCallCount is acceptable in test scope only.
|
||||
/// Synthesizer that writes a constant Float value to a control bus every block.
|
||||
/// Used to verify render order by reading bus values in sequence.
|
||||
private final class ControlBusStamper: Synthesizer {
|
||||
let busIndex: Int
|
||||
let value: Float
|
||||
var evaluateCallCount: Int = 0
|
||||
|
||||
init(
|
||||
bus: Int,
|
||||
value: Float
|
||||
) {
|
||||
self.busIndex = bus
|
||||
self.value = value
|
||||
}
|
||||
|
||||
func build() {}
|
||||
|
||||
func evaluate(graph: SynthGraph, count: Int) {
|
||||
evaluateCallCount += 1
|
||||
graph.engine.controlBuses[busIndex] = value
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
@Suite("EngineMainGroup")
|
||||
struct EngineMainGroupTests {
|
||||
|
||||
// MARK: - Structural invariants at init time
|
||||
|
||||
@Test func mainGroupExistsAfterInit() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
// mainGroup is accessible immediately — no start() required.
|
||||
#expect(engine.mainGroup !== engine.rootGroup)
|
||||
}
|
||||
|
||||
@Test func mainGroupIsDirectChildOfRootGroupAtInit() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
// rootGroup holds exactly mainGroup as its sole direct child.
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
}
|
||||
|
||||
@Test func mainGroupIsEmptyAtInit() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
#expect(engine.mainGroup.isEmpty)
|
||||
}
|
||||
|
||||
@Test func rootGroupCountIsOneAfterInit() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
// rootGroup always has exactly 1 direct child (mainGroup) at init.
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
}
|
||||
|
||||
// MARK: - Default add target
|
||||
|
||||
@Test func defaultAddLandsInMainGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.contains(synth))
|
||||
}
|
||||
|
||||
@Test func defaultAddDoesNotLandDirectlyInRootGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// rootGroup only contains mainGroup as a direct child, not the synth.
|
||||
#expect(!engine.rootGroup.contains(synth))
|
||||
}
|
||||
|
||||
@Test func addTwoSynthsNewerAtHead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let first: TrackingNode = TrackingNode()
|
||||
let second: TrackingNode = TrackingNode()
|
||||
try engine.add(first)
|
||||
engine.processBlock(inputSamples: [])
|
||||
try engine.add(second)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// second was added last → lands at mainGroup.head (newest-first).
|
||||
#expect(engine.mainGroup.head?.synth === second)
|
||||
}
|
||||
|
||||
@Test func addedSynthsEvaluateViaMainGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(synth.evaluateCallCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - Pre-main and post-main positioning
|
||||
|
||||
@Test func addBeforeMainGroupInsertsIntoRootGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let preSynth: TrackingNode = TrackingNode()
|
||||
try engine.add(preSynth, position: .before(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
// preSynth sits in rootGroup immediately before mainGroup.
|
||||
#expect(engine.rootGroup.contains(preSynth))
|
||||
#expect(!engine.mainGroup.contains(preSynth))
|
||||
}
|
||||
|
||||
@Test func addAfterMainGroupInsertsIntoRootGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let postSynth: TrackingNode = TrackingNode()
|
||||
try engine.add(postSynth, position: .after(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.rootGroup.contains(postSynth))
|
||||
#expect(!engine.mainGroup.contains(postSynth))
|
||||
}
|
||||
|
||||
@Test func secondPreMainInsertionPushesFirstAwayFromMainGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let pre1: TrackingNode = TrackingNode()
|
||||
let pre2: TrackingNode = TrackingNode()
|
||||
try engine.add(pre1, position: .before(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
try engine.add(pre2, position: .before(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
// Structure: [pre1] [pre2] [mainGroup] ...
|
||||
// pre2 is immediately before mainGroup; pre1 is before pre2.
|
||||
// Walk rootGroup to find mainGroup position:
|
||||
var node: PreparedNode? = engine.rootGroup.head
|
||||
var order: [ObjectIdentifier] = []
|
||||
while let n: PreparedNode = node {
|
||||
order.append(ObjectIdentifier(n.synth))
|
||||
node = n.next
|
||||
}
|
||||
let mainGroupID: ObjectIdentifier = ObjectIdentifier(engine.mainGroup)
|
||||
let pre1ID: ObjectIdentifier = ObjectIdentifier(pre1)
|
||||
let pre2ID: ObjectIdentifier = ObjectIdentifier(pre2)
|
||||
if let idxMain: Int = order.firstIndex(of: mainGroupID),
|
||||
let idxPre1: Int = order.firstIndex(of: pre1ID),
|
||||
let idxPre2: Int = order.firstIndex(of: pre2ID) {
|
||||
// pre1 < pre2 < mainGroup in render order
|
||||
#expect(idxPre1 < idxPre2)
|
||||
#expect(idxPre2 < idxMain)
|
||||
} else {
|
||||
Issue.record("pre1, pre2, or mainGroup not found in rootGroup walk")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render order
|
||||
|
||||
@Test func renderOrderIsPreMainThenMainThenPostMain() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
blockSize: 8, numAudioBuses: 16, numControlBuses: 4096
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
// Each stamper overwrites control bus 0 with its tag value.
|
||||
// The last writer in evaluation order wins: reading bus 0 after processBlock
|
||||
// reveals which zone evaluated last.
|
||||
let probeControlBus: Int = 10
|
||||
|
||||
let preNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 1.0)
|
||||
let mainNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 2.0)
|
||||
let postNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 3.0)
|
||||
|
||||
try engine.add(preNode, position: .before(engine.mainGroup))
|
||||
try engine.add(mainNode)
|
||||
try engine.add(postNode, position: .after(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// postNode evaluated last → its value (3.0) wins.
|
||||
#expect(engine.controlBuses[probeControlBus] == 3.0)
|
||||
}
|
||||
|
||||
@Test func preMainEvaluatesBeforeMain() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
blockSize: 8, numAudioBuses: 16, numControlBuses: 4096
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
let probeControlBus: Int = 11
|
||||
let preNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 10.0)
|
||||
let mainNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 20.0)
|
||||
|
||||
try engine.add(preNode, position: .before(engine.mainGroup))
|
||||
try engine.add(mainNode)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// mainNode evaluated after preNode → mainNode's value (20.0) wins.
|
||||
#expect(engine.controlBuses[probeControlBus] == 20.0)
|
||||
}
|
||||
|
||||
// MARK: - groupFree on persistent groups is suppressed
|
||||
|
||||
@Test func groupFreeOnMainGroupIsNoOp() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// Directly calling free on mainGroup should be suppressed.
|
||||
engine.mainGroup.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// mainGroup is still a direct child of rootGroup.
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
// mainGroup still contains the synth (its children were NOT drained).
|
||||
#expect(engine.mainGroup.contains(synth))
|
||||
}
|
||||
|
||||
@Test func groupFreeOnRootGroupIsNoOp() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
|
||||
engine.rootGroup.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// rootGroup and mainGroup are both still in place.
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
}
|
||||
|
||||
@Test func groupFreeCountersUnchangedAfterPersistentFreeAttempt() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
let synthCountBefore: Int = engine.synthesizerCount
|
||||
|
||||
engine.mainGroup.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
#expect(engine.synthesizerCount == synthCountBefore)
|
||||
}
|
||||
|
||||
// MARK: - mainGroup.release cascade — persistent group survives
|
||||
|
||||
@Test func mainGroupReleaseWithNoGateChildrenDrainsMainGroupButGroupPersists() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
|
||||
let synth: TrackingNode = TrackingNode() // default release throws noGate → free immediately
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.contains(synth))
|
||||
|
||||
// release() cascades to the child; since it has no gate it gets freed via child.free().
|
||||
engine.mainGroup.release(engine: engine)
|
||||
// child.free posts a remove event; synth should be gone after next processBlock.
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// Child was removed, but mainGroup itself persists.
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup,
|
||||
"mainGroup must remain as rootGroup's direct child after release cascade")
|
||||
}
|
||||
|
||||
@Test func canAddToMainGroupAfterReleaseCascadeDrains() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
engine.mainGroup.release(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
|
||||
// Re-add after drain — mainGroup must accept new children.
|
||||
let newSynth: TrackingNode = TrackingNode()
|
||||
try engine.add(newSynth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.contains(newSynth))
|
||||
}
|
||||
|
||||
// MARK: - rootGroup remains as-is
|
||||
|
||||
@Test func rootGroupCountIsAlwaysAtLeastOneWhileEngineAlive() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
// Advance several blocks.
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
}
|
||||
|
||||
@Test func removeDoesNotRemoveMainGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
// engine.remove on a persistent group is silently ignored (language-side guard).
|
||||
engine.remove(engine.mainGroup)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// mainGroup must still be the sole direct child of rootGroup after the ignored remove.
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
}
|
||||
|
||||
// MARK: - B1 regression: second release cascades new children
|
||||
|
||||
/// Verify that a persistent group's _releaseStarted flag is reset after each release
|
||||
/// so a subsequent release() correctly cascades to any new children added in the interim.
|
||||
@Test func secondReleaseCascadesNewChildren() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
|
||||
// Round 1: add 2 children, release, settle until empty.
|
||||
let firstA: TrackingNode = TrackingNode()
|
||||
let firstB: TrackingNode = TrackingNode()
|
||||
try engine.add(firstA)
|
||||
try engine.add(firstB)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 2)
|
||||
|
||||
engine.mainGroup.release(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 0,
|
||||
"First release: mainGroup should be empty after settling")
|
||||
|
||||
// Round 2: add 2 new children, release again, settle until empty.
|
||||
let secondA: TrackingNode = TrackingNode()
|
||||
let secondB: TrackingNode = TrackingNode()
|
||||
try engine.add(secondA)
|
||||
try engine.add(secondB)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 2)
|
||||
|
||||
// This call would be silently dropped before B1 was fixed — _releaseStarted was
|
||||
// stuck at true from the first release, so only round 2's children would persist.
|
||||
engine.mainGroup.release(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 0,
|
||||
"Second release: mainGroup should be empty after settling")
|
||||
|
||||
// mainGroup itself must remain attached to rootGroup throughout.
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
}
|
||||
|
||||
// MARK: - stop() drains all non-persistent nodes
|
||||
|
||||
@Test func stopDrainsMainGroupChildren() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.mainGroup.count == 1)
|
||||
|
||||
engine.stop()
|
||||
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
#expect(engine.mainGroup.head == nil)
|
||||
#expect(engine.mainGroup.tail == nil)
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
}
|
||||
|
||||
@Test func stopDrainsPreAndPostMainNodes() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let pre: TrackingNode = TrackingNode()
|
||||
let post: TrackingNode = TrackingNode()
|
||||
try engine.add(pre, position: .before(engine.mainGroup))
|
||||
try engine.add(post, position: .after(engine.mainGroup))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.rootGroup.count == 3) // pre + mainGroup + post
|
||||
|
||||
engine.stop()
|
||||
|
||||
// rootGroup is back to its initial shape: mainGroup is the sole child.
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
#expect(engine.rootGroup.tail?.synth === engine.mainGroup)
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
}
|
||||
|
||||
@Test func stopPreservesPersistentRootAndMainGroup() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let originalRoot: Group = engine.rootGroup
|
||||
let originalMain: Group = engine.mainGroup
|
||||
try engine.start()
|
||||
try engine.add(TrackingNode())
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
engine.stop()
|
||||
|
||||
// Identity preserved — same `Group` instances.
|
||||
#expect(engine.rootGroup === originalRoot)
|
||||
#expect(engine.mainGroup === originalMain)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
}
|
||||
|
||||
@Test func stopDrainsNestedUserGroups() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let nested: Group = Group()
|
||||
try engine.add(nested)
|
||||
try engine.add(TrackingNode(), position: .head(of: nested))
|
||||
try engine.add(TrackingNode(), position: .tail(of: nested))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.groupCount == 1)
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
|
||||
engine.stop()
|
||||
|
||||
#expect(engine.groupCount == 0)
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
}
|
||||
|
||||
@Test func restartAfterStopBeginsFromEmptyBaseline() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
try engine.add(TrackingNode())
|
||||
try engine.add(TrackingNode())
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
engine.stop()
|
||||
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
#expect(engine.rootGroup.count == 1)
|
||||
#expect(engine.rootGroup.head?.synth === engine.mainGroup)
|
||||
}
|
||||
|
||||
@Test func stopDrainsCarryOverEvents() throws {
|
||||
// A future-dated `engine.remove(synth, at:)` parks in `carryOverEvents`
|
||||
// until its target time arrives. Without the carryOverEvents drain in
|
||||
// `_drainAllNonPersistentNodes`, the `Unmanaged.passRetained` ref inside
|
||||
// the `.remove` event would never balance after `stop()` — a synth ARC
|
||||
// leak. This test verifies the drain by asserting `carryOverEvents`
|
||||
// is empty (its capacity is preserved, so it returns to the same shape
|
||||
// as a freshly-started engine).
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// Future-dated remove — far enough out that the RT thread routes it
|
||||
// into `carryOverEvents` rather than firing this block.
|
||||
let farFuture: SampleTime = engine.currentTime + engine.seconds(60.0)
|
||||
_ = engine.remove(synth, at: farFuture)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// The remove is now parked in carryOverEvents holding a retained ref.
|
||||
#expect(engine.carryOverEvents.contains { event in
|
||||
if case .remove = event { return true }
|
||||
return false
|
||||
})
|
||||
|
||||
engine.stop()
|
||||
|
||||
// Drain emptied carryOverEvents; if its passRetained ref had not been
|
||||
// released, ARC would still hold the synth via the event existential.
|
||||
#expect(engine.carryOverEvents.isEmpty)
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.mainGroup.count == 0)
|
||||
}
|
||||
|
||||
@Test func postStopGroupFreeDoesNotPushSynthCountNegative() throws {
|
||||
// Regression: a `Group.free(engine:)` call landing in `pendingQueue`
|
||||
// AFTER `engine.stop()` returned would, on the next `start()`, run
|
||||
// `applyEvent(.groupFree)`. The handler walked the group's still-
|
||||
// populated internal linked list and decremented `_synthesizerCount`
|
||||
// per descendant — but `stop()` already zeroed the counter via
|
||||
// `_drainAllNonPersistentNodes`. Result: counter wrapped negative.
|
||||
//
|
||||
// Triggers in practice: any caller that holds a `Group` strongly
|
||||
// across stop/restart and frees it after stop returns —
|
||||
// `LyrebirdProcess._teardown` (group.free via its watcher timer),
|
||||
// `LyrebirdEventList` cleanup, ad-hoc app teardown paths.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let nested: Group = Group()
|
||||
try engine.add(nested)
|
||||
try engine.add(TrackingNode(), position: .head(of: nested))
|
||||
try engine.add(TrackingNode(), position: .tail(of: nested))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
#expect(engine.groupCount == 1)
|
||||
|
||||
engine.stop()
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
|
||||
// Free the group AFTER stop — enqueues `.groupFree` to pendingQueue.
|
||||
// The pendingQueue drain in `_drainAllNonPersistentNodes` ran during
|
||||
// stop(), so this event will be applied by the next start().
|
||||
nested.free(engine: engine)
|
||||
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
// Pump one block so the RT thread drains pendingQueue.
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
#expect(engine.synthesizerCount == 0,
|
||||
"synthesizerCount must not go negative after post-stop groupFree")
|
||||
#expect(engine.groupCount == 0,
|
||||
"groupCount must not go negative after post-stop groupFree")
|
||||
}
|
||||
|
||||
@Test func stopResetsNodeTreeMirror() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
try engine.add(TrackingNode())
|
||||
try engine.add(TrackingNode())
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// Before stop: rootGroup contains mainGroup, mainGroup contains 2 synths.
|
||||
let beforeRoot: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root
|
||||
let beforeMain: NodeTreeSnapshot.Node? = beforeRoot.children.first
|
||||
#expect(beforeMain?.children.count == 2)
|
||||
|
||||
engine.stop()
|
||||
|
||||
// After stop: rootGroup contains mainGroup, mainGroup is empty.
|
||||
let afterRoot: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root
|
||||
#expect(afterRoot.children.count == 1)
|
||||
let afterMain: NodeTreeSnapshot.Node? = afterRoot.children.first
|
||||
#expect(afterMain?.children.isEmpty == true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// EngineNodeCountTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Engine node counts")
|
||||
struct EngineNodeCountTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 16)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func freshEngineCountsAreZero() throws {
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
@Test func addingLeafSynthBumpsSynthesizerCount() throws {
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 1)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
@Test func removingLeafSynthDecrementsSynthesizerCount() throws {
|
||||
let s: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
|
||||
try engine.add(s)
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.remove(s)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
@Test func addingGroupBumpsGroupCount() throws {
|
||||
let g: Group = Group()
|
||||
try engine.add(g)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 1)
|
||||
}
|
||||
|
||||
@Test func addingParallelGroupBumpsGroupCount() throws {
|
||||
let pg: ParallelGroup = ParallelGroup(engine: engine)
|
||||
pg.add(ConstantSynth(value: 0.1, outputBus: 0))
|
||||
try engine.add(pg)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// ParallelGroup is the group; its child synth is *internal* to the parallel
|
||||
// group and is not counted at the engine level (it never traverses applyEvent).
|
||||
#expect(engine.groupCount == 1)
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
}
|
||||
|
||||
@Test func addingMixOfSynthsAndGroupsCountsBothIndependently() throws {
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0))
|
||||
try engine.add(ConstantSynth(value: 0.2, outputBus: 0))
|
||||
try engine.add(Group())
|
||||
try engine.add(Group())
|
||||
try engine.add(Group())
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
#expect(engine.groupCount == 3)
|
||||
}
|
||||
|
||||
@Test func freeingGroupDecrementsGroupCountAndItsDirectChildren() throws {
|
||||
let g: Group = Group()
|
||||
try engine.add(g)
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0), position: .tail(of: g))
|
||||
try engine.add(ConstantSynth(value: 0.2, outputBus: 0), position: .tail(of: g))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
#expect(engine.groupCount == 1)
|
||||
|
||||
g.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
/// Two-level nesting: freeing an outer group whose child is another group
|
||||
/// containing a synth must decrement counters for both the inner group and
|
||||
/// its grandchild synth. Mirrors the `LyrebirdEventList` tree shape
|
||||
/// (`el.group → proc.group → routeSynth`) that previously left a phantom
|
||||
/// `synthesizerCount` per process per kill cycle.
|
||||
@Test func freeingOuterGroupDecrementsNestedGroupAndGrandchildSynth() throws {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
try engine.add(outer)
|
||||
try engine.add(inner, position: .tail(of: outer))
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0), position: .tail(of: inner))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 1)
|
||||
#expect(engine.groupCount == 2)
|
||||
|
||||
outer.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
/// Three-level nesting with multiple grandchild synths confirms the subtree
|
||||
/// walk descends past the immediate grandchildren too.
|
||||
@Test func freeingOuterGroupDecrementsTripleNestedDescendants() throws {
|
||||
let outer: Group = Group()
|
||||
let middle: Group = Group()
|
||||
let inner: Group = Group()
|
||||
try engine.add(outer)
|
||||
try engine.add(middle, position: .tail(of: outer))
|
||||
try engine.add(inner, position: .tail(of: middle))
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0), position: .tail(of: inner))
|
||||
try engine.add(ConstantSynth(value: 0.2, outputBus: 0), position: .tail(of: inner))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
#expect(engine.groupCount == 3)
|
||||
|
||||
outer.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
|
||||
/// Outer group containing both a direct-child synth and a nested group with
|
||||
/// its own synth — verifies the direct-child decrement still works alongside
|
||||
/// the recursive descent.
|
||||
@Test func freeingOuterGroupWithMixedDirectAndNestedChildrenDecrementsAll() throws {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
try engine.add(outer)
|
||||
try engine.add(ConstantSynth(value: 0.1, outputBus: 0), position: .tail(of: outer))
|
||||
try engine.add(inner, position: .tail(of: outer))
|
||||
try engine.add(ConstantSynth(value: 0.2, outputBus: 0), position: .tail(of: inner))
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 2)
|
||||
#expect(engine.groupCount == 2)
|
||||
|
||||
outer.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
#expect(engine.groupCount == 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
// AutoFreeOnDoneTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import Synchronization
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("SynthesizerBase autoFreeOnDone")
|
||||
struct AutoFreeOnDoneTests {
|
||||
|
||||
// MARK: - Fixtures
|
||||
|
||||
/// Synth that wires a short auto-envelope into the auto-free watcher.
|
||||
private final class ControlAutoFreeSynth: SynthesizerBase {
|
||||
private let _envelope: Envelope
|
||||
init(envelope: Envelope) { _envelope = envelope }
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: _envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
autoFreeOnDone(env)
|
||||
output(bus: 0, source: 0.0 * env)
|
||||
}
|
||||
}
|
||||
|
||||
/// Same as `ControlAutoFreeSynth` but probes the Audio variant.
|
||||
private final class AudioAutoFreeSynth: SynthesizerBase {
|
||||
private let _envelope: Envelope
|
||||
init(envelope: Envelope) { _envelope = envelope }
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: _envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
autoFreeOnDone(env)
|
||||
output(bus: 0, source: 0.0 * env)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synth WITHOUT auto-free opt-in — used to verify the registry
|
||||
/// silently ignores synths that never called `autoFreeOnDone(_:)`.
|
||||
private final class PlainSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
output(bus: 0, source: 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-free envelope: 1 ms attack to 1.0, then 1 ms release back to 0.
|
||||
/// At 44.1 kHz / blockSize 64 that's ~3 audio blocks total — plenty of
|
||||
/// headroom for a `TestBlockDriver` burst to pick up `needsFree`.
|
||||
private static func shortAutoEnv() -> Envelope {
|
||||
Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [0.001, 0.001],
|
||||
curves: [.lin, .lin]
|
||||
)
|
||||
}
|
||||
|
||||
private func makeEngine() -> SynthesisEngine {
|
||||
SynthesisEngine(
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
/// Drive engine.processBlock in tight bursts so engine-time runs many
|
||||
/// multiples of wall-time. Same pattern as `LyrebirdEventListTests`.
|
||||
private final class TestBlockDriver: @unchecked Sendable {
|
||||
private var _thread: Thread?
|
||||
private let _running: Atomic<Bool> = Atomic<Bool>(false)
|
||||
private let _engine: SynthesisEngine
|
||||
private static let blocksPerBurst: Int = 32
|
||||
private static let wallSleepSeconds: TimeInterval = 0.001
|
||||
init(engine: SynthesisEngine) { _engine = engine }
|
||||
func start() {
|
||||
_running.store(true, ordering: .relaxed)
|
||||
let thread: Thread = Thread { [self] in
|
||||
while self._running.load(ordering: .relaxed) {
|
||||
for _ in 0..<Self.blocksPerBurst {
|
||||
self._engine.processBlock(inputSamples: [])
|
||||
}
|
||||
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
|
||||
}
|
||||
}
|
||||
thread.qualityOfService = .userInteractive
|
||||
thread.start()
|
||||
_thread = thread
|
||||
}
|
||||
func stop() { _running.store(false, ordering: .relaxed) }
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Test("EnvelopeGen.Control + .freeNode triggers auto-removal")
|
||||
func testControlAutoFree() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: ControlAutoFreeSynth = ControlAutoFreeSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
// Wait for envelope to complete + watcher to fire.
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
// mainGroup should now have no children (the auto-removal hit).
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"ControlAutoFreeSynth should have been auto-removed")
|
||||
}
|
||||
|
||||
@Test("EnvelopeGen.Audio + .freeNode triggers auto-removal")
|
||||
func testAudioAutoFree() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AudioAutoFreeSynth = AudioAutoFreeSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AudioAutoFreeSynth should have been auto-removed")
|
||||
}
|
||||
|
||||
@Test("Manual engine.remove before envelope done unregisters cleanly")
|
||||
func testManualRemoveUnregisters() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
// Note: no TestBlockDriver → engine-time stays at 0, envelope never fires.
|
||||
// We only need to verify that engine.remove drops the registry entry.
|
||||
|
||||
// Long envelope so it wouldn't auto-complete during the test even
|
||||
// if we were pumping blocks.
|
||||
let longEnv: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [10.0, 10.0],
|
||||
curves: [.lin, .lin]
|
||||
)
|
||||
let synth: ControlAutoFreeSynth = ControlAutoFreeSynth(envelope: longEnv)
|
||||
try engine.add(synth)
|
||||
_ = engine.remove(synth)
|
||||
|
||||
// Brief wait — if double-remove was triggered, this would surface
|
||||
// via a watcher panic or stray engine.remove call. Survival here
|
||||
// is the assertion.
|
||||
try await Task.sleep(nanoseconds: 50_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Multiple synths with independent envelopes each auto-free")
|
||||
func testMultipleSynthsIndependentAutoFree() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let a: ControlAutoFreeSynth = ControlAutoFreeSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
let b: AudioAutoFreeSynth = AudioAutoFreeSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(a)
|
||||
try engine.add(b)
|
||||
|
||||
try await Task.sleep(nanoseconds: 250_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"Both auto-free synths should have been removed")
|
||||
}
|
||||
|
||||
@Test("Synth without autoFreeOnDone is not registered (no spurious removal)")
|
||||
func testPlainSynthNotRegistered() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: PlainSynth = PlainSynth()
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 100_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.count == 1,
|
||||
"PlainSynth without autoFreeOnDone must stay in the tree")
|
||||
}
|
||||
|
||||
// MARK: - Auto-registration tests (no explicit autoFreeOnDone call)
|
||||
|
||||
/// EnvelopeGen.Control + .freeNode constructed inside build() — relies on
|
||||
/// auto-registration via SynthesizerBase._currentlyBuilding.
|
||||
private final class AutoRegEnvControlSynth: SynthesizerBase {
|
||||
private let _envelope: Envelope
|
||||
init(envelope: Envelope) { _envelope = envelope }
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: _envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
// Intentionally no autoFreeOnDone(env) — self-registration is the unit under test.
|
||||
output(bus: 0, source: 0.0 * env)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegEnvAudioSynth: SynthesizerBase {
|
||||
private let _envelope: Envelope
|
||||
init(envelope: Envelope) { _envelope = envelope }
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: _envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: 0.0 * env)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegLineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let line: Line.Control = Line.Control(
|
||||
start: 0.0, end: 1.0, dur: 0.002,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: 0.0 * line)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegExpLineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(
|
||||
start: 0.01, end: 1.0, dur: 0.002,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: 0.0 * line)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegPlayBufferSynth: SynthesizerBase {
|
||||
private let _buffer: LyrebirdBuffer
|
||||
init(buffer: LyrebirdBuffer) { _buffer = buffer }
|
||||
override func build() {
|
||||
let p: PlayBuffer.Audio = PlayBuffer.Audio(
|
||||
buffer: _buffer,
|
||||
loop: false,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: p)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegRecordBufferSynth: SynthesizerBase {
|
||||
private let _buffer: LyrebirdBuffer
|
||||
init(buffer: LyrebirdBuffer) { _buffer = buffer }
|
||||
override func build() {
|
||||
let r: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||
input: 0.0,
|
||||
buffer: _buffer,
|
||||
loop: false,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: r)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegDiskInSynth: SynthesizerBase {
|
||||
private let _url: URL
|
||||
init(url: URL) { _url = url }
|
||||
override func build() {
|
||||
guard let d: DiskIn.Audio = try? DiskIn.Audio(
|
||||
url: _url,
|
||||
channelCount: 1,
|
||||
sampleRate: 44100,
|
||||
rate: 1.0,
|
||||
loop: false,
|
||||
doneAction: .freeNode,
|
||||
bufferFrames: 1024
|
||||
) else {
|
||||
output(bus: 0, source: 0.0)
|
||||
return
|
||||
}
|
||||
output(bus: 0, source: d)
|
||||
}
|
||||
}
|
||||
|
||||
private final class AutoRegSpectralPlayBufferSynth: SynthesizerBase {
|
||||
private let _frameBuffer: SpectralFrameBuffer
|
||||
private let _fftSize: Int
|
||||
private let _hopSize: Int
|
||||
init(frameBuffer: SpectralFrameBuffer, fftSize: Int, hopSize: Int) {
|
||||
_frameBuffer = frameBuffer
|
||||
_fftSize = fftSize
|
||||
_hopSize = hopSize
|
||||
}
|
||||
override func build() {
|
||||
let p: SpectralPlayBuffer = SpectralPlayBuffer(
|
||||
frameBuffer: _frameBuffer,
|
||||
fftSize: _fftSize,
|
||||
hopSize: _hopSize,
|
||||
rate: 1.0,
|
||||
startPos: 0.0,
|
||||
loop: false,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a short test WAV file. Caller owns deletion via the returned URL.
|
||||
private static func writeShortWAV(frameCount: Int = 256, sampleRate: Double = 44100) throws -> URL {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||||
let float32BitsPerChannel: UInt32 = 32
|
||||
let nch: UInt32 = 1
|
||||
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: float32ByteSize * nch,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: float32ByteSize * nch,
|
||||
mChannelsPerFrame: nch,
|
||||
mBitsPerChannel: float32BitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
var ref: ExtAudioFileRef?
|
||||
guard ExtAudioFileCreateWithURL(
|
||||
url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
||||
AudioFileFlags.eraseFile.rawValue, &ref
|
||||
) == noErr, let ref: ExtAudioFileRef else {
|
||||
throw DiskInError.cannotOpenFile(-1)
|
||||
}
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
||||
var samples: [Float] = [Float](repeating: 0, count: frameCount)
|
||||
samples.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
var bl: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: nch,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: base
|
||||
)
|
||||
)
|
||||
_ = ExtAudioFileWrite(ref, UInt32(frameCount), &bl)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
/// EnvelopeGen.Control with .nothing — must NOT auto-free.
|
||||
private final class NoFreeEnvControlSynth: SynthesizerBase {
|
||||
private let _envelope: Envelope
|
||||
init(envelope: Envelope) { _envelope = envelope }
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: _envelope,
|
||||
doneAction: .nothing
|
||||
)
|
||||
output(bus: 0, source: 0.0 * env)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("EnvelopeGen.Control with .freeNode self-registers (no explicit autoFreeOnDone)")
|
||||
func testEnvControlAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AutoRegEnvControlSynth = AutoRegEnvControlSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegEnvControlSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("EnvelopeGen.Audio with .freeNode self-registers (no explicit autoFreeOnDone)")
|
||||
func testEnvAudioAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AutoRegEnvAudioSynth = AutoRegEnvAudioSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegEnvAudioSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("Line.Control with .freeNode self-registers")
|
||||
func testLineControlAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AutoRegLineSynth = AutoRegLineSynth()
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegLineSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("ExponentialLine.Control with .freeNode self-registers")
|
||||
func testExpLineControlAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AutoRegExpLineSynth = AutoRegExpLineSynth()
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegExpLineSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("PlayBuffer.Audio with .freeNode self-registers")
|
||||
func testPlayBufferAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
// Small buffer — finishes in a few audio blocks at rate 1.0.
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 256, channelCount: 1)
|
||||
let synth: AutoRegPlayBufferSynth = AutoRegPlayBufferSynth(buffer: buffer)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegPlayBufferSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("RecordBuffer.Audio with .freeNode self-registers")
|
||||
func testRecordBufferAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 256, channelCount: 1)
|
||||
let synth: AutoRegRecordBufferSynth = AutoRegRecordBufferSynth(buffer: buffer)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegRecordBufferSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("DiskIn.Audio with .freeNode self-registers")
|
||||
func testDiskInAutoRegister() async throws {
|
||||
let url: URL = try AutoFreeOnDoneTests.writeShortWAV(frameCount: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: AutoRegDiskInSynth = AutoRegDiskInSynth(url: url)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 300_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegDiskInSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("SpectralPlayBuffer with .freeNode self-registers")
|
||||
func testSpectralPlayBufferAutoRegister() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let fftSize: Int = 64
|
||||
let hopSize: Int = 16
|
||||
let frameCount: Int = 2
|
||||
let frameBuffer: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize,
|
||||
hopSize: hopSize,
|
||||
frameCount: frameCount,
|
||||
sampleRate: 44100
|
||||
)
|
||||
let synth: AutoRegSpectralPlayBufferSynth = AutoRegSpectralPlayBufferSynth(
|
||||
frameBuffer: frameBuffer,
|
||||
fftSize: fftSize,
|
||||
hopSize: hopSize
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 300_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.isEmpty,
|
||||
"AutoRegSpectralPlayBufferSynth should have been auto-removed via self-registration")
|
||||
}
|
||||
|
||||
@Test("EnvelopeGen.Control with .nothing does NOT auto-free")
|
||||
func testEnvControlNothingDoesNotAutoFree() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||||
driver.start()
|
||||
defer { driver.stop() }
|
||||
|
||||
let synth: NoFreeEnvControlSynth = NoFreeEnvControlSynth(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv()
|
||||
)
|
||||
try engine.add(synth)
|
||||
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
|
||||
let mainNode: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root.children[0]
|
||||
#expect(mainNode.children.count == 1,
|
||||
"doneAction: .nothing must NOT trigger auto-free")
|
||||
}
|
||||
|
||||
@Test("Constructing a .freeNode generator outside build() is a no-op")
|
||||
func testOutsideBuildIsNoOp() {
|
||||
// _currentlyBuilding is nil here. Constructing must not crash and must
|
||||
// not register anywhere. We have no synth to inspect — survival is the
|
||||
// assertion. Explicit autoFreeOnDone(_:) remains the escape hatch for
|
||||
// this path.
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: AutoFreeOnDoneTests.shortAutoEnv(),
|
||||
doneAction: .freeNode
|
||||
)
|
||||
_ = env // suppress unused-warning
|
||||
#expect(SynthesizerBase._currentlyBuilding == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// EnvelopeTimeScaleVerificationTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// One-off verification of `EnvelopeGen.{Audio,Control}` timeScale behavior
|
||||
/// — reproduces the MyPiece scenario: envelope durations [0.2, 0.6, 0.2]
|
||||
/// (sum 1.0), timeScale 8.0 → expected total 8 seconds.
|
||||
@Suite("EnvelopeGen timeScale verification")
|
||||
struct EnvelopeTimeScaleVerificationTests {
|
||||
|
||||
/// Drive an Audio envelope through `expectedSampleCount` samples at the
|
||||
/// engine's blockSize and check that the envelope's `isDone` flag flips
|
||||
/// at the right moment.
|
||||
@Test("EnvelopeGen.Audio timeScale=8 on a 1.0s envelope reaches isDone at ~8s")
|
||||
func testAudioEnvTimeScale8() {
|
||||
let blockSize: Int = 64
|
||||
let sampleRate: Double = 48000.0
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 1.0, 0.0],
|
||||
durations: [0.2, 0.6, 0.2],
|
||||
curves: [.sine, .lin, .sine]
|
||||
)
|
||||
let env: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: envelope,
|
||||
timeScale: 8.0,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
|
||||
// Drive the envelope directly via _computeSamples. Sum of durations *
|
||||
// timeScale = 1.0 * 8.0 = 8.0s. At sampleRate=48k, that's 384000 samples
|
||||
// = 6000 blocks @ blockSize=64.
|
||||
let expectedTotalSamples: Int = Int(8.0 * sampleRate)
|
||||
let blocksUntilDone: Int = (expectedTotalSamples + blockSize - 1) / blockSize
|
||||
|
||||
let graph: SynthGraph = SynthGraph(
|
||||
engine: engine,
|
||||
busOffset: 0,
|
||||
parameterTable: ParameterTable(),
|
||||
scratchBuses: nil
|
||||
)
|
||||
|
||||
var doneAtBlock: Int = -1
|
||||
for blockIdx: Int in 0..<(blocksUntilDone + 50) {
|
||||
engine.advanceSegmentSerial()
|
||||
_ = env.calculatedSamples(graph: graph, count: blockSize)
|
||||
if env.needsFree && doneAtBlock < 0 {
|
||||
doneAtBlock = blockIdx
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
#expect(doneAtBlock >= 0, "Envelope should have completed within budget")
|
||||
let elapsedSeconds: Double = Double(doneAtBlock * blockSize) / sampleRate
|
||||
#expect(abs(elapsedSeconds - 8.0) < 0.1,
|
||||
"Envelope should complete at ~8s, got \(elapsedSeconds)s (block \(doneAtBlock))")
|
||||
}
|
||||
|
||||
/// Independent SynthesizerBase instances each writing `OscSin.Audio *
|
||||
/// EnvelopeGen.Control` to the same audio bus — expect their outputs to
|
||||
/// sum additively. Verifies bug B premise.
|
||||
@Test("Multiple synths writing OscSin*env to one bus sum on the bus")
|
||||
func testMultipleSynthsAccumulate() throws {
|
||||
final class TestNote: SynthesizerBase {
|
||||
override func build() {
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [0.1, 0.1],
|
||||
curves: [.lin, .lin]
|
||||
),
|
||||
timeScale: 10.0 // → 2s total, plenty of sustain
|
||||
)
|
||||
output(bus: 4, source: OscSin.Audio(freq: 300.0) * env)
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let a: TestNote = TestNote()
|
||||
try engine.add(a)
|
||||
|
||||
// Drive blocks so the first envelope ramps to ~1 (after ~0.5s).
|
||||
for _ in 0..<400 { engine.processBlock(inputSamples: []) }
|
||||
let bus4: Int = 4
|
||||
var soloSample: Float = 0
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
soloSample = max(soloSample, abs(engine.audioBuses[bus4][i]))
|
||||
}
|
||||
#expect(soloSample > 0.1,
|
||||
"Solo note should write a non-trivial sample to bus 4 (got \(soloSample))")
|
||||
|
||||
// Add a second note — same frequency, same phase 0 at insertion → they
|
||||
// should sum constructively. Run a few more blocks then compare.
|
||||
let b: TestNote = TestNote()
|
||||
try engine.add(b)
|
||||
for _ in 0..<400 { engine.processBlock(inputSamples: []) }
|
||||
var duoSample: Float = 0
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
duoSample = max(duoSample, abs(engine.audioBuses[bus4][i]))
|
||||
}
|
||||
|
||||
#expect(duoSample > soloSample * 1.4,
|
||||
"Two notes should be louder than one (solo=\(soloSample) duo=\(duoSample))")
|
||||
}
|
||||
|
||||
@Test("EnvelopeGen.Control timeScale=8 on a 1.0s envelope reaches isDone at ~8s")
|
||||
func testControlEnvTimeScale8() {
|
||||
let blockSize: Int = 64
|
||||
let sampleRate: Double = 48000.0
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 1.0, 0.0],
|
||||
durations: [0.2, 0.6, 0.2],
|
||||
curves: [.sine, .lin, .sine]
|
||||
)
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: envelope,
|
||||
timeScale: 8.0,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
|
||||
let expectedTotalSamples: Int = Int(8.0 * sampleRate)
|
||||
let blocksUntilDone: Int = (expectedTotalSamples + blockSize - 1) / blockSize
|
||||
|
||||
let graph: SynthGraph = SynthGraph(
|
||||
engine: engine,
|
||||
busOffset: 0,
|
||||
parameterTable: ParameterTable(),
|
||||
scratchBuses: nil
|
||||
)
|
||||
|
||||
var doneAtBlock: Int = -1
|
||||
for blockIdx: Int in 0..<(blocksUntilDone + 50) {
|
||||
engine.advanceSegmentSerial()
|
||||
_ = env.calculatedSamples(graph: graph, count: blockSize)
|
||||
if env.needsFree && doneAtBlock < 0 {
|
||||
doneAtBlock = blockIdx
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
#expect(doneAtBlock >= 0, "Envelope should have completed within budget")
|
||||
let elapsedSeconds: Double = Double(doneAtBlock * blockSize) / sampleRate
|
||||
#expect(abs(elapsedSeconds - 8.0) < 0.1,
|
||||
"Envelope should complete at ~8s, got \(elapsedSeconds)s (block \(doneAtBlock))")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// EuclideanRhythmTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("EuclideanRhythm")
|
||||
struct EuclideanRhythmTests {
|
||||
|
||||
// MARK: - Pulse count
|
||||
|
||||
@Test("returns correct pulse count")
|
||||
func pulseCount() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8)
|
||||
var hits: Int = 0
|
||||
for _ in 0..<8 { if pat.next() == true { hits += 1 } }
|
||||
#expect(hits == 3)
|
||||
}
|
||||
|
||||
@Test("zero pulses all false")
|
||||
func zeroPulses() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 0, steps: 4)
|
||||
for _ in 0..<4 { #expect(pat.next() == false) }
|
||||
}
|
||||
|
||||
@Test("full pulses all true")
|
||||
func fullPulses() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 4, steps: 4)
|
||||
for _ in 0..<4 { #expect(pat.next() == true) }
|
||||
}
|
||||
|
||||
// MARK: - Classic patterns
|
||||
|
||||
@Test("E(3,8) Cuban tresillo")
|
||||
func tresillo() {
|
||||
// E(3,8) = [1,0,0,1,0,0,1,0]
|
||||
let expected: [Bool] = [true,false,false,true,false,false,true,false]
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8)
|
||||
let actual: [Bool] = (0..<8).compactMap { _ in pat.next() }
|
||||
#expect(actual == expected)
|
||||
}
|
||||
|
||||
@Test("E(2,3) standard two-against-three")
|
||||
func twoThree() {
|
||||
// E(2,3) = [1,0,1]
|
||||
let expected: [Bool] = [true, false, true]
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 2, steps: 3)
|
||||
let actual: [Bool] = (0..<3).compactMap { _ in pat.next() }
|
||||
#expect(actual == expected)
|
||||
}
|
||||
|
||||
@Test("E(5,8) base output")
|
||||
func fiveEight() {
|
||||
// Bresenham distribution of 5 hits in 8 steps
|
||||
let expected: [Bool] = [true,false,true,false,true,true,false,true]
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 5, steps: 8)
|
||||
let actual: [Bool] = (0..<8).compactMap { _ in pat.next() }
|
||||
#expect(actual == expected)
|
||||
}
|
||||
|
||||
@Test("E(5,8) rotation:2 yields Cinquillo")
|
||||
func fiveEightCinquillo() {
|
||||
// Cinquillo [1,0,1,1,0,1,1,0] is E(5,8) shifted by 2
|
||||
let expected: [Bool] = [true,false,true,true,false,true,true,false]
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 5, steps: 8, rotation: 2)
|
||||
let actual: [Bool] = (0..<8).compactMap { _ in pat.next() }
|
||||
#expect(actual == expected)
|
||||
}
|
||||
|
||||
@Test("E(4,4) all hits")
|
||||
func fourFour() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 4, steps: 4)
|
||||
let actual: [Bool] = (0..<4).compactMap { _ in pat.next() }
|
||||
#expect(actual == [true, true, true, true])
|
||||
}
|
||||
|
||||
// MARK: - Rotation
|
||||
|
||||
@Test("rotation shifts pattern cyclically")
|
||||
func rotation() {
|
||||
let base: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8, rotation: 0)
|
||||
let rotated: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8, rotation: 1)
|
||||
let baseSeq: [Bool] = (0..<8).compactMap { _ in base.next() }
|
||||
let rotSeq: [Bool] = (0..<8).compactMap { _ in rotated.next() }
|
||||
// rotated[i] == base[(i+1) % 8]
|
||||
let expected: [Bool] = (0..<8).map { i in baseSeq[(i + 1) % 8] }
|
||||
#expect(rotSeq == expected)
|
||||
}
|
||||
|
||||
@Test("negative rotation wraps correctly")
|
||||
func negativeRotation() {
|
||||
let forward: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8, rotation: 7)
|
||||
let backward: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8, rotation: -1)
|
||||
let fSeq: [Bool] = (0..<8).compactMap { _ in forward.next() }
|
||||
let bSeq: [Bool] = (0..<8).compactMap { _ in backward.next() }
|
||||
#expect(fSeq == bSeq)
|
||||
}
|
||||
|
||||
@Test("rotation by steps is identity")
|
||||
func rotationByStepsIdentity() {
|
||||
let base: Pattern<Bool> = euclideanRhythm(pulses: 5, steps: 12, rotation: 0)
|
||||
let shifted: Pattern<Bool> = euclideanRhythm(pulses: 5, steps: 12, rotation: 12)
|
||||
let bSeq: [Bool] = (0..<12).compactMap { _ in base.next() }
|
||||
let sSeq: [Bool] = (0..<12).compactMap { _ in shifted.next() }
|
||||
#expect(bSeq == sSeq)
|
||||
}
|
||||
|
||||
// MARK: - Pattern properties
|
||||
|
||||
@Test("pattern cycles infinitely by default")
|
||||
func infiniteCycling() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 3, steps: 8)
|
||||
for _ in 0..<100 { let v: Bool? = pat.next(); #expect(v != nil) }
|
||||
#expect(!pat.isExhausted)
|
||||
}
|
||||
|
||||
@Test("edge case steps=1 pulses=1")
|
||||
func oneStepOnePulse() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 1, steps: 1)
|
||||
#expect(pat.next() == true)
|
||||
}
|
||||
|
||||
@Test("edge case steps=1 pulses=0")
|
||||
func oneStepZeroPulse() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 0, steps: 1)
|
||||
#expect(pat.next() == false)
|
||||
}
|
||||
|
||||
@Test("pulses clamped above steps")
|
||||
func pulsesClampedAboveSteps() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: 10, steps: 4)
|
||||
let seq: [Bool] = (0..<4).compactMap { _ in pat.next() }
|
||||
let hits: Int = seq.filter { $0 }.count
|
||||
#expect(hits == 4)
|
||||
}
|
||||
|
||||
@Test("negative pulses treated as zero")
|
||||
func negativePulsesTreatedAsZero() {
|
||||
let pat: Pattern<Bool> = euclideanRhythm(pulses: -2, steps: 4)
|
||||
let seq: [Bool] = (0..<4).compactMap { _ in pat.next() }
|
||||
#expect(seq == [false, false, false, false])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// ExpanderParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Expander parameter ramping")
|
||||
struct ExpanderParameterRampingTests {
|
||||
|
||||
@Test func thresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-40.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Audio = Expander.Audio(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = expander.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Expander.Audio output must be finite with ParameterNode threshold")
|
||||
}
|
||||
|
||||
@Test func thresholdParameterRampChangesGain() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Start with threshold well above signal (-10 dB, signal ~0.1 ≈ -20 dB) → expansion active.
|
||||
let threshNode: ParameterNode = ParameterNode(-10.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Audio = Expander.Audio(in: signal, threshold: threshNode, ratio: 0.0) // gate
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [[Double]] = expander.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Now set threshold very low (gate opens) → signal passes through.
|
||||
threshNode.value = -80.0
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = expander.calculatedSamples(graph: g2, count: 64)
|
||||
|
||||
let rms1: Double = rmsValue(Array((out1.first ?? []).prefix(64)))
|
||||
let rms2: Double = rmsValue(Array((out2.first ?? []).prefix(64)))
|
||||
// With gate open (threshold=-80dB), signal should pass more freely.
|
||||
#expect(rms2 > rms1,
|
||||
"After gate threshold ramp to -80dB, signal should pass more freely: \(rms2) vs \(rms1)")
|
||||
}
|
||||
|
||||
@Test func controlThresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-40.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Control = Expander.Control(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = expander.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Expander.Control output must be finite with ParameterNode threshold")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
// ExponentialLineTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("ExponentialLine")
|
||||
struct ExponentialLineTests {
|
||||
|
||||
private func makeEngine() -> SynthesisEngine {
|
||||
makeTestEngine(blockSize: 64, sampleRate: 64)
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsControl() {
|
||||
let gen: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 100.0, dur: 1.0)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
// MARK: - Geometric progression: end-of-block ratio is constant
|
||||
|
||||
@Test func endOfBlockRatioIsConstant() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
// start=1, end=16, dur=4 → block ends are 2, 4, 8, 16. Ratio 2.0 each.
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 16.0, dur: 4.0)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
let endValues: [Double] = (0..<4).map { samples[$0 * 64 + 63] }
|
||||
let r1: Double = endValues[1] / endValues[0]
|
||||
let r2: Double = endValues[2] / endValues[1]
|
||||
let r3: Double = endValues[3] / endValues[2]
|
||||
#expect(abs(r1 - 2.0) < 1e-9)
|
||||
#expect(abs(r2 - 2.0) < 1e-9)
|
||||
#expect(abs(r3 - 2.0) < 1e-9)
|
||||
#expect(abs(endValues[3] - 16.0) < 1e-9)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Reaches end at duration
|
||||
|
||||
@Test func reachesEndAtDuration() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 0.001, end: 1.0, dur: 4.0)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
let lastSample: Double = samples.last ?? 0.0
|
||||
#expect(abs(lastSample - 1.0) < 1e-9)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Negative ramp: shares sign
|
||||
|
||||
@Test func negativeRampSharesSign() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: -1.0, end: -16.0, dur: 4.0)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
for s: Double in samples {
|
||||
#expect(s <= 0.0, "expected non-positive sample")
|
||||
}
|
||||
let lastSample: Double = samples.last ?? 0.0
|
||||
#expect(abs(lastSample - (-16.0)) < 1e-9)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Done action — .freeNode
|
||||
|
||||
@Test func doneActionFreeNodeSetsNeedsFree() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 100.0, dur: 2.0, doneAction: .freeNode)
|
||||
_ = collectBlocks(line, engine: engine, blocks: 3)
|
||||
#expect(line.needsFree == true)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func doneActionNothingDoesNotSetNeedsFree() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 100.0, dur: 2.0, doneAction: .nothing)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
#expect(line.needsFree == false)
|
||||
// Frozen at end after completion.
|
||||
for i: Int in (samples.count - 64)..<samples.count {
|
||||
#expect(abs(samples[i] - 100.0) < 1e-9)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - mul/add
|
||||
|
||||
@Test func mulAddScalesOutput() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let plain: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 16.0, dur: 4.0)
|
||||
let scaled: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 16.0, dur: 4.0, mul: 0.5, add: 1.0)
|
||||
let p: [Double] = collectBlocks(plain, engine: engine, blocks: 4)
|
||||
let s: [Double] = collectBlocks(scaled, engine: engine, blocks: 4)
|
||||
for i: Int in 0..<p.count {
|
||||
#expect(abs(s[i] - (p[i] * 0.5 + 1.0)) < 1e-9)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out cache
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 100.0, dur: 4.0)
|
||||
let out1: [Double] = Array(line.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(line.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Done action: .loop restarts
|
||||
|
||||
@Test func doneActionLoopRestarts() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
// start=1, end=4, dur=2 → block-end values 2.0 (block 1) and 4.0 (block 2 = end).
|
||||
// After completion .loop resets _pos and _rampTarget=start=1.
|
||||
// Block 3: ramps from 1.0 toward block-end-of-cycle-1 = 2.0.
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 4.0, dur: 2.0, doneAction: .loop)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
let block2End: Double = samples[127]
|
||||
let block3End: Double = samples[191]
|
||||
let block4End: Double = samples[255]
|
||||
#expect(abs(block2End - 4.0) < 1e-9)
|
||||
#expect(abs(block3End - 2.0) < 1e-9, "got \(block3End)")
|
||||
#expect(abs(block4End - 4.0) < 1e-9, "got \(block4End)")
|
||||
#expect(line.needsFree == false)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Sub-block bypass: state advances exactly once per audio block
|
||||
|
||||
@Test func stateAdvancesOncePerAudioBlock() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 64,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
try engine.start()
|
||||
let line: ExponentialLine.Control = ExponentialLine.Control(start: 1.0, end: 16.0, dur: 4.0)
|
||||
let samples: [Double] = collectBlocks(line, engine: engine, blocks: 4)
|
||||
let lastSample: Double = samples.last ?? 0.0
|
||||
#expect(abs(lastSample - 16.0) < 1e-9, "got \(lastSample)")
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
// FFTTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("FFT Infrastructure")
|
||||
struct FFTTests {
|
||||
|
||||
// MARK: - SpectralBuffer — bin access
|
||||
|
||||
@Test func spectralBufferBinCount() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
#expect(buf.binCount == 33) // fftSize/2 + 1
|
||||
}
|
||||
|
||||
@Test func spectralBufferMagnitudeDC() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.dcValue = 3.0
|
||||
#expect(buf.magnitude(at: 0) == 3.0)
|
||||
}
|
||||
|
||||
@Test func spectralBufferMagnitudeNegativeDC() {
|
||||
// DC may be negative; magnitude returns abs.
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.dcValue = -3.0
|
||||
#expect(buf.magnitude(at: 0) == 3.0)
|
||||
#expect(buf.dcValue == -3.0)
|
||||
}
|
||||
|
||||
@Test func spectralBufferMagnitudeNyquist() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.nyquistValue = 4.0
|
||||
#expect(buf.magnitude(at: 32) == 4.0) // bin == fftSize/2
|
||||
}
|
||||
|
||||
@Test func spectralBufferMagnitudeGeneralBin() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf[magnitude: 1] = 5.0
|
||||
buf[phase: 1] = 0.0
|
||||
#expect(abs(buf.magnitude(at: 1) - 5.0) < 1e-5)
|
||||
}
|
||||
|
||||
@Test func spectralBufferPhaseDCIsZero() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.dcValue = 5.0
|
||||
#expect(buf.phase(at: 0) == 0.0)
|
||||
}
|
||||
|
||||
@Test func spectralBufferPhaseNyquistIsZero() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.nyquistValue = 5.0
|
||||
#expect(buf.phase(at: 32) == 0.0)
|
||||
}
|
||||
|
||||
@Test func spectralBufferPhaseGeneralBin() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
let expected: Float = Float.pi / 4 // 45 degrees
|
||||
buf[phase: 1] = expected
|
||||
#expect(abs(buf.phase(at: 1) - expected) < 1e-5)
|
||||
}
|
||||
|
||||
@Test func spectralBufferSetMagnitudePreservesPhase() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
let originalPhase: Float = atan2f(4.0, 3.0) // corresponds to (3, 4i)
|
||||
buf[magnitude: 2] = 5.0
|
||||
buf[phase: 2] = originalPhase
|
||||
buf.setMagnitude(10.0, at: 2)
|
||||
#expect(abs(buf.magnitude(at: 2) - 10.0) < 1e-4)
|
||||
#expect(abs(buf.phase(at: 2) - originalPhase) < 1e-4)
|
||||
}
|
||||
|
||||
@Test func spectralBufferSetMagnitudeOnZeroBin() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64) // _mag[5] = 0, _phase[5] = 0
|
||||
buf.setMagnitude(7.0, at: 5)
|
||||
#expect(abs(buf.magnitude(at: 5) - 7.0) < 1e-4)
|
||||
// Phase defaults to 0 when original magnitude was zero
|
||||
#expect(abs(buf.phase(at: 5)) < 1e-5)
|
||||
}
|
||||
|
||||
@Test func spectralBufferSetMagnitudePreservesSignDC() {
|
||||
// setMagnitude on DC/Nyquist must preserve sign (sign encodes phase 0 or π).
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.dcValue = -3.0
|
||||
buf.setMagnitude(5.0, at: 0)
|
||||
#expect(buf.dcValue == -5.0, "Negative DC sign must be preserved after setMagnitude")
|
||||
#expect(buf.magnitude(at: 0) == 5.0)
|
||||
|
||||
buf.dcValue = 3.0
|
||||
buf.setMagnitude(5.0, at: 0)
|
||||
#expect(buf.dcValue == 5.0, "Positive DC sign must be preserved after setMagnitude")
|
||||
}
|
||||
|
||||
@Test func spectralBufferSetMagnitudePreservesSignNyquist() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.nyquistValue = -2.0
|
||||
buf.setMagnitude(4.0, at: 32) // bin == fftSize/2
|
||||
#expect(buf.nyquistValue == -4.0, "Negative Nyquist sign must be preserved after setMagnitude")
|
||||
#expect(buf.magnitude(at: 32) == 4.0)
|
||||
}
|
||||
|
||||
@Test func spectralBufferIsValid() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
#expect(buf.isValid)
|
||||
buf.invalidate()
|
||||
#expect(!buf.isValid)
|
||||
}
|
||||
|
||||
// MARK: - Rectangular ↔ polar round-trip
|
||||
|
||||
@Test func spectralBufferPolarRoundTrip() throws {
|
||||
// _writeFromRectangular → _readToRectangular must recover input within float tolerance.
|
||||
let fftSize: Int = 64
|
||||
let halfSize: Int = fftSize / 2
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||||
|
||||
var inRealp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
var inImagp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
inRealp[0] = 3.0; inImagp[0] = -2.0 // DC and Nyquist (signed)
|
||||
inRealp[1] = 3.0; inImagp[1] = 4.0 // bin 1: mag=5, phase=atan2(4,3)
|
||||
inRealp[5] = 1.0; inImagp[5] = 0.0 // bin 5: mag=1, phase=0
|
||||
inRealp[10] = 0.0; inImagp[10] = -1.0 // bin 10: mag=1, phase=-π/2
|
||||
|
||||
inRealp.withUnsafeBufferPointer { rp in
|
||||
guard let rpBase: UnsafePointer<Float> = rp.baseAddress else { return }
|
||||
inImagp.withUnsafeBufferPointer { ip in
|
||||
guard let ipBase: UnsafePointer<Float> = ip.baseAddress else { return }
|
||||
buf._writeFromRectangular(rpBase, imagp: ipBase)
|
||||
}
|
||||
}
|
||||
|
||||
var outRealp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
var outImagp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
outRealp.withUnsafeMutableBufferPointer { rp in
|
||||
guard let rpBase: UnsafeMutablePointer<Float> = rp.baseAddress else { return }
|
||||
outImagp.withUnsafeMutableBufferPointer { ip in
|
||||
guard let ipBase: UnsafeMutablePointer<Float> = ip.baseAddress else { return }
|
||||
buf._readToRectangular(realp: rpBase, imagp: ipBase)
|
||||
}
|
||||
}
|
||||
|
||||
let tolerance: Float = 1e-5
|
||||
#expect(abs(outRealp[0] - 3.0) < tolerance, "DC round-trip")
|
||||
#expect(abs(outImagp[0] - (-2.0)) < tolerance, "Nyquist round-trip")
|
||||
#expect(abs(outRealp[1] - 3.0) < tolerance, "Bin 1 real round-trip")
|
||||
#expect(abs(outImagp[1] - 4.0) < tolerance, "Bin 1 imag round-trip")
|
||||
#expect(abs(outRealp[5] - 1.0) < tolerance, "Bin 5 real round-trip")
|
||||
#expect(abs(outImagp[5] - 0.0) < tolerance, "Bin 5 imag round-trip")
|
||||
#expect(abs(outRealp[10] - 0.0) < tolerance, "Bin 10 real round-trip")
|
||||
#expect(abs(outImagp[10] - (-1.0)) < tolerance, "Bin 10 imag round-trip")
|
||||
}
|
||||
|
||||
@Test func spectralBufferDCNyquistPreservedThroughConversion() {
|
||||
// DC and Nyquist are signed scalars — must pass through unchanged (no abs).
|
||||
let fftSize: Int = 64
|
||||
let halfSize: Int = fftSize / 2
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||||
|
||||
var inRealp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
var inImagp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
inRealp[0] = -7.5 // negative DC
|
||||
inImagp[0] = 3.25 // positive Nyquist
|
||||
|
||||
inRealp.withUnsafeBufferPointer { rp in
|
||||
guard let rpBase: UnsafePointer<Float> = rp.baseAddress else { return }
|
||||
inImagp.withUnsafeBufferPointer { ip in
|
||||
guard let ipBase: UnsafePointer<Float> = ip.baseAddress else { return }
|
||||
buf._writeFromRectangular(rpBase, imagp: ipBase)
|
||||
}
|
||||
}
|
||||
|
||||
#expect(buf.dcValue == -7.5, "DC signed value must be preserved exactly")
|
||||
#expect(buf.nyquistValue == 3.25, "Nyquist signed value must be preserved exactly")
|
||||
|
||||
var outRealp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
var outImagp: [Float] = [Float](repeating: 0, count: halfSize)
|
||||
outRealp.withUnsafeMutableBufferPointer { rp in
|
||||
guard let rpBase: UnsafeMutablePointer<Float> = rp.baseAddress else { return }
|
||||
outImagp.withUnsafeMutableBufferPointer { ip in
|
||||
guard let ipBase: UnsafeMutablePointer<Float> = ip.baseAddress else { return }
|
||||
buf._readToRectangular(realp: rpBase, imagp: ipBase)
|
||||
}
|
||||
}
|
||||
|
||||
#expect(outRealp[0] == -7.5, "DC must survive polar round-trip unchanged")
|
||||
#expect(outImagp[0] == 3.25, "Nyquist must survive polar round-trip unchanged")
|
||||
}
|
||||
|
||||
// MARK: - SpectralMagnitudeScale
|
||||
|
||||
@Test func magnitudeScaleHalvesAllMagnitudes() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
buf.dcValue = 10.0 // DC (positive)
|
||||
buf.nyquistValue = 5.0 // Nyquist
|
||||
buf[magnitude: 1] = 10.0 // complex bin 1
|
||||
|
||||
let scaler: SpectralMagnitudeScale = SpectralMagnitudeScale(scale: 0.5)
|
||||
scaler.process(spectral: buf, engine: makeTestEngine())
|
||||
|
||||
#expect(abs(buf.magnitude(at: 0) - 5.0) < 1e-4, "DC magnitude should be halved")
|
||||
#expect(abs(buf.magnitude(at: 32) - 2.5) < 1e-4, "Nyquist magnitude should be halved")
|
||||
#expect(abs(buf.magnitude(at: 1) - 5.0) < 1e-4, "Bin 1 magnitude (was 10) should be halved")
|
||||
}
|
||||
|
||||
// MARK: - SpectralFreeze
|
||||
|
||||
@Test func freezeInactivePassesThrough() {
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
let freeze: SpectralFreeze = SpectralFreeze(fftSize: 64)
|
||||
buf.dcValue = 99.0
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // not frozen — should not modify buffer
|
||||
#expect(abs(buf.dcValue - 99.0) < 1e-5)
|
||||
}
|
||||
|
||||
@Test func freezeHoldsDCMagnitude() {
|
||||
// dcValue must be captured at freeze time and replayed verbatim.
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: 64)
|
||||
let freeze: SpectralFreeze = SpectralFreeze(fftSize: 64)
|
||||
|
||||
buf.dcValue = 42.0
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // phase-tracking hop (not frozen)
|
||||
|
||||
freeze.freeze() // request freeze
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // freeze activates, live frame unchanged
|
||||
#expect(freeze.isFrozen)
|
||||
|
||||
buf.dcValue = 0.0 // simulate new FFT hop overwriting DC
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // frozen hop: DC must be restored
|
||||
#expect(abs(buf.dcValue - 42.0) < 1e-5,
|
||||
"Frozen DC should be replayed unchanged")
|
||||
}
|
||||
|
||||
@Test func freezeHoldsBinMagnitude() {
|
||||
// Complex bin magnitude must stay constant each frozen hop regardless of phase.
|
||||
let fftSize: Int = 64
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||||
let freeze: SpectralFreeze = SpectralFreeze(fftSize: fftSize)
|
||||
|
||||
// Establish mag=5 at bin 1 (matches classic 3-4-5 right triangle).
|
||||
buf[magnitude: 1] = 5.0
|
||||
buf[phase: 1] = atan2f(4.0, 3.0)
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // phase-tracking: prevPhase[1] = atan2(4,3)
|
||||
|
||||
freeze.freeze()
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // freeze activates with frozenMag[1] = 5.0
|
||||
#expect(freeze.isFrozen)
|
||||
|
||||
// Several frozen hops — phase advances but magnitude stays 5.0.
|
||||
for hop: Int in 1...4 {
|
||||
buf[magnitude: 1] = 0.0 // overwrite to verify frozen hop restores it
|
||||
buf[phase: 1] = 0.0
|
||||
freeze.process(spectral: buf, engine: makeTestEngine())
|
||||
let mag: Float = buf.magnitude(at: 1)
|
||||
#expect(abs(mag - 5.0) < 1e-4,
|
||||
"Frozen bin 1 magnitude should be 5.0 on hop \(hop), got \(mag)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func freezePhaseAdvancesByDelta() {
|
||||
// After freeze, each hop the bin phase must advance by the frozen phaseDelta.
|
||||
let fftSize: Int = 64
|
||||
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||||
let freeze: SpectralFreeze = SpectralFreeze(fftSize: fftSize)
|
||||
|
||||
// Hop 1: phase 0
|
||||
buf[magnitude: 1] = 1.0; buf[phase: 1] = 0.0
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // prevPhase[1] = 0
|
||||
|
||||
// Hop 2: phase = π/2 → phaseDelta = π/2
|
||||
buf[magnitude: 1] = 1.0; buf[phase: 1] = Float.pi / 2
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // phaseDelta[1] = π/2
|
||||
|
||||
freeze.freeze()
|
||||
freeze.process(spectral: buf, engine: makeTestEngine()) // freeze activates; frozenPhase[1] = π/2
|
||||
#expect(freeze.isFrozen)
|
||||
|
||||
// Each frozen hop should advance phase by π/2 and keep magnitude 1.
|
||||
let expectedDeltas: [Float] = [Float.pi, 3 * Float.pi / 2, 2 * Float.pi, 5 * Float.pi / 2]
|
||||
for (hop, expectedPhase) in expectedDeltas.enumerated() {
|
||||
freeze.process(spectral: buf, engine: makeTestEngine())
|
||||
let rawPhase: Float = buf.phase(at: 1)
|
||||
// Wrap both to (-π, π] for comparison.
|
||||
var p: Float = expectedPhase
|
||||
while p > Float.pi { p -= 2 * Float.pi }
|
||||
while p < -Float.pi { p += 2 * Float.pi }
|
||||
// Circular angular distance: π and -π are the same angle.
|
||||
var angularDiff: Float = abs(rawPhase - p)
|
||||
if angularDiff > Float.pi { angularDiff = 2 * Float.pi - angularDiff }
|
||||
#expect(angularDiff < 1e-4,
|
||||
"Frozen phase after hop \(hop + 1) should be ≈ \(p), got \(rawPhase)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func freezePreservesAcrossSubsequentHops() throws {
|
||||
// Engine integration: DC bin stays frozen across multiple analysis hops.
|
||||
let fftSize: Int = 128
|
||||
let hopSize: Int = 64
|
||||
let blockSize: Int = hopSize
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let freeze: SpectralFreeze = SpectralFreeze(fftSize: fftSize)
|
||||
let analysis: SpectralChain.Audio = SpectralChain.Audio(
|
||||
input: Double(1.0),
|
||||
fftSize: fftSize,
|
||||
hopSize: hopSize,
|
||||
stages: [.mono(freeze)],
|
||||
analyzeOnly: true
|
||||
)
|
||||
|
||||
// Run 2 blocks so the ring is partially filled and first hop has fired.
|
||||
_ = analysis.calculatedSamples(graph: graph, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
_ = analysis.calculatedSamples(graph: graph, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
|
||||
let liveDC: Float = analysis.spectralBuffer.dcValue
|
||||
#expect(liveDC != 0.0, "DC should be non-zero for constant input")
|
||||
freeze.freeze() // request — RT thread captures on next hop
|
||||
|
||||
// Block 3: freeze activates (RT captures frozenDC ≈ liveDC from constant input).
|
||||
_ = analysis.calculatedSamples(graph: graph, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Block 4: full frozen hop; DC must equal the captured value.
|
||||
_ = analysis.calculatedSamples(graph: graph, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
|
||||
#expect(abs(analysis.spectralBuffer.dcValue - liveDC) < 0.1,
|
||||
"Frozen DC should be close to live DC for constant-input signal")
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - SpectralChain.Audio — analyze-only path
|
||||
|
||||
@Test func analyzeOnlyChainRateIsAudio() {
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(0.0), fftSize: 64, hopSize: 32,
|
||||
analyzeOnly: true)
|
||||
#expect(chain.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func analyzeOnlyChainOutputIsSilence() throws {
|
||||
let blockSize: Int = 32
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0), fftSize: 64, hopSize: 32,
|
||||
analyzeOnly: true)
|
||||
let out: [[Double]] = chain.calculatedSamples(graph: graph, count: blockSize)
|
||||
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(out[0][i] == 0.0, "analyzeOnly chain should output silence at sample \(i)")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func chainWritesSpectralBufferAfterHop() throws {
|
||||
// hopSize == blockSize: hop fires once per block.
|
||||
let fftSize: Int = 64
|
||||
let hopSize: Int = 32
|
||||
let blockSize: Int = hopSize
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
|
||||
fftSize: fftSize, hopSize: hopSize,
|
||||
analyzeOnly: true)
|
||||
|
||||
// After one block the first hop fires — DC must be non-zero.
|
||||
_ = chain.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(chain.spectralBuffer.dcValue != 0.0,
|
||||
"DC bin must be non-zero after the first hop for constant input")
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func chainDCBinDominatesForConstantInput() throws {
|
||||
// After several hops the DC bin should clearly dominate all other bins.
|
||||
let fftSize: Int = 128
|
||||
let hopSize: Int = 64
|
||||
let blockSize: Int = hopSize
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
|
||||
fftSize: fftSize, hopSize: hopSize,
|
||||
analyzeOnly: true)
|
||||
|
||||
// Run 4 blocks to reach steady state (ring fully filled with DC).
|
||||
for _ in 0..<4 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = chain.calculatedSamples(graph: g, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
let dcMag: Float = chain.spectralBuffer.magnitude(at: 0)
|
||||
#expect(dcMag > 0, "DC magnitude must be positive for constant input")
|
||||
|
||||
// DC should be larger than any other bin magnitude.
|
||||
let halfSize: Int = fftSize / 2
|
||||
for bin: Int in 1..<halfSize {
|
||||
let binMag: Float = chain.spectralBuffer.magnitude(at: bin)
|
||||
#expect(dcMag > binMag,
|
||||
"DC magnitude \(dcMag) should exceed bin \(bin) magnitude \(binMag)")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - SpectralChain.Audio — round-trip
|
||||
|
||||
@Test func chainRateIsAudio() {
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(0.0), fftSize: 128, hopSize: 64)
|
||||
#expect(chain.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func chainFirstBlockIsSilence() throws {
|
||||
// One-hop latency: block 0 emits silence before any IFFT result is
|
||||
// ready to read.
|
||||
let fftSize: Int = 128
|
||||
let hopSize: Int = 64
|
||||
let blockSize: Int = hopSize
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
|
||||
fftSize: fftSize, hopSize: hopSize)
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(out[0][i] == 0.0, "SpectralChain.Audio block 0 should be silent")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func chainRoundTripDCSignalReachesUnityGain() throws {
|
||||
// 50% overlap Hanning OLA — round-trip mean should equal input.
|
||||
let fftSize: Int = 128
|
||||
let hopSize: Int = 64 // 50% overlap
|
||||
let blockSize: Int = hopSize
|
||||
let dcInput: Double = 0.5
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: dcInput,
|
||||
fftSize: fftSize, hopSize: hopSize)
|
||||
|
||||
let warmUpBlocks: Int = 4
|
||||
let measureBlocks: Int = 4
|
||||
var steadyStateSum: Double = 0
|
||||
var steadyStateCount: Int = 0
|
||||
|
||||
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
|
||||
if block >= warmUpBlocks {
|
||||
for i: Int in 0..<blockSize {
|
||||
steadyStateSum += out[0][i]
|
||||
steadyStateCount += 1
|
||||
}
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
let mean: Double = steadyStateSum / Double(steadyStateCount)
|
||||
#expect(abs(mean - dcInput) < 0.05,
|
||||
"OLA round-trip mean \(mean) should be ≈ \(dcInput) (Hanning 50% OLA = unity gain)")
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func chainDeterministicSampleOutput() throws {
|
||||
// Deterministic per-sample check: DC input 1.0 → round-trip output ≈ 1.0 per sample.
|
||||
//
|
||||
// Uses 75% overlap (hopSize = fftSize/4). At 75% overlap, Σ Hanning²[n-kH] = 1.5
|
||||
// (constant per sample), satisfying the WOLA COLA condition.
|
||||
let fftSize: Int = 128
|
||||
let hopSize: Int = 32 // 75% overlap — Hanning² satisfies COLA (sum = 1.5, constant)
|
||||
let blockSize: Int = hopSize
|
||||
let dcInput: Double = 1.0
|
||||
let tolerance: Double = 0.005
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
|
||||
let chain: SpectralChain.Audio = SpectralChain.Audio(input: dcInput,
|
||||
fftSize: fftSize, hopSize: hopSize)
|
||||
|
||||
// Warm up: fftSize/hopSize hops to fill the ring + extra to reach OLA steady state.
|
||||
let warmUpBlocks: Int = 8
|
||||
for _ in 0..<warmUpBlocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = chain.calculatedSamples(graph: g, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Steady-state block: every sample must be ≈ 1.0.
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
|
||||
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(out[0][i] - dcInput) < tolerance,
|
||||
"SpectralChain.Audio steady-state sample \(i): expected ≈ \(dcInput), got \(out[0][i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// FanOutCachingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Tests that verify fan-out caching correctness.
|
||||
///
|
||||
/// The core invariant: when a single generator instance is consumed by multiple downstream
|
||||
/// generators within the same engine segment (same `segmentSerial`), its `_computeSamples`
|
||||
/// is invoked exactly once and the cached result is shared. This prevents the "double phase
|
||||
/// advance" artefact that one oscillator feeding two `Out` generators would otherwise produce.
|
||||
@Suite("Fan-out caching")
|
||||
struct FanOutCachingTests {
|
||||
|
||||
// MARK: - Serial cache invalidation
|
||||
|
||||
@Test func firstCallComputesSamples() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 0.0, phase: 0.25) // freq=0 → constant at sin(π/2)=1.0
|
||||
let result: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(result[0].prefix(4).allSatisfy { abs($0 - 1.0) < 1e-6 })
|
||||
}
|
||||
|
||||
@Test func secondCallInSameSegmentReturnsCachedResult() {
|
||||
// With the same segmentSerial, a second call must not re-compute (no phase advance).
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
|
||||
let result1: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
let result2: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
|
||||
// Identical arrays — cache hit, no recomputation.
|
||||
for i: Int in 0..<4 {
|
||||
#expect(result1[0][i] == result2[0][i])
|
||||
}
|
||||
}
|
||||
|
||||
@Test func newSegmentInvalidatesCache() {
|
||||
// After advanceBlock, the same generator must recompute (oscillator phase advances).
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
|
||||
let block1: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
let block2: [[Double]] = osc.calculatedSamples(graph: graph, count: 4)
|
||||
|
||||
// Blocks differ because the oscillator advanced phase.
|
||||
let identical: Bool = (0..<4).allSatisfy { block1[0][$0] == block2[0][$0] }
|
||||
#expect(!identical)
|
||||
}
|
||||
|
||||
// MARK: - Fan-out: shared generator feeds two consumers
|
||||
|
||||
@Test func sharedOscillatorsProduceIdenticalOutputForBothConsumers() throws {
|
||||
// Single OscSin → Out.Audio(bus:0) + Out.Audio(bus:1)
|
||||
// Both buses must contain bit-identical samples — proves _computeSamples ran once.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
|
||||
let freq: Double = 440.0
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let outL: Out.Audio = Out.Audio(bus: 0, source: osc)
|
||||
let outR: Out.Audio = Out.Audio(bus: 1, source: osc)
|
||||
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = outL.calculatedSamples(graph: graph, count: 16)
|
||||
_ = outR.calculatedSamples(graph: graph, count: 16)
|
||||
|
||||
// Bus 0 and Bus 1 must be identical.
|
||||
for i: Int in 0..<16 {
|
||||
#expect(engine.audioBuses[0][i] == engine.audioBuses[1][i],
|
||||
"sample \(i): bus0=\(engine.audioBuses[0][i]) bus1=\(engine.audioBuses[1][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func sharedOscillatorPhaseAdvancesOnlyOncePerSegment() throws {
|
||||
// Two consumers in the same segment must not double-advance the oscillator's phase.
|
||||
// Strategy: compare two-consumer output against a single-consumer reference.
|
||||
// If phase is doubled, output frequency is doubled — not bit-identical.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
|
||||
let freq: Double = 440.0
|
||||
let count: Int = 16
|
||||
|
||||
// Reference: single osc → single Out (correct phase)
|
||||
let refOsc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let refOut: Out.Audio = Out.Audio(bus: 2, source: refOsc)
|
||||
let refGraph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = refOut.calculatedSamples(graph: refGraph, count: count)
|
||||
let refSamples: [Float] = (0..<count).map { engine.audioBuses[2][$0] }
|
||||
|
||||
advanceBlock(engine)
|
||||
// Clear buses for the fan-out test
|
||||
for i: Int in 0..<count {
|
||||
engine.audioBuses[0][i] = 0.0
|
||||
engine.audioBuses[1][i] = 0.0
|
||||
}
|
||||
|
||||
// Fan-out: same osc → two Out generators
|
||||
let fanOsc: OscSin.Audio = OscSin.Audio(freq: freq) // fresh instance, same initial phase (0)
|
||||
let fanOutA: Out.Audio = Out.Audio(bus: 0, source: fanOsc)
|
||||
let fanOutB: Out.Audio = Out.Audio(bus: 1, source: fanOsc)
|
||||
let fanGraph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = fanOutA.calculatedSamples(graph: fanGraph, count: count)
|
||||
_ = fanOutB.calculatedSamples(graph: fanGraph, count: count)
|
||||
let fanSamples: [Float] = (0..<count).map { engine.audioBuses[0][$0] }
|
||||
|
||||
// Fan-out output must match the single-consumer reference — no phase doubling.
|
||||
for i: Int in 0..<count {
|
||||
#expect(abs(fanSamples[i] - refSamples[i]) < 1e-12,
|
||||
"sample \(i): fan=\(fanSamples[i]) ref=\(refSamples[i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out via SynthesizerBase (integration path)
|
||||
|
||||
@Test func engineEvaluateSegmentIncreasesSerial() throws {
|
||||
// processBlock → evaluateSegment → segmentSerial &+= 1
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let serialBefore: UInt64 = engine.segmentSerial
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(engine.segmentSerial == serialBefore + 1)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func fanOutViaProcessBlockProducesSameSamplesOnBothBuses() throws {
|
||||
// A Synthesizer that wires one OscSin to two buses through the real evaluateSegment
|
||||
// path — proves serial increment + fan-out caching work end-to-end.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
|
||||
try engine.start()
|
||||
|
||||
final class FanOutSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: osc))
|
||||
addOutputGenerator(Out.Audio(bus: 1, source: osc))
|
||||
}
|
||||
}
|
||||
|
||||
let synth: FanOutSynth = FanOutSynth()
|
||||
try engine.add(synth)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
let blockSize: Int = engine.blockSize
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(engine.audioBuses[0][i] == engine.audioBuses[1][i],
|
||||
"sample \(i): bus0=\(engine.audioBuses[0][i]) bus1=\(engine.audioBuses[1][i])")
|
||||
}
|
||||
|
||||
// Buses must not be all-zero (signal is actually running)
|
||||
let anyNonZero: Bool = (0..<blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
|
||||
#expect(anyNonZero)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - floatValue → calculatedSamples single-evaluation guarantee
|
||||
|
||||
@Test func floatValuePrimesFullBlockCache() {
|
||||
// floatValue routes through calculatedSamples(count: blockSize), priming the cache.
|
||||
// A subsequent calculatedSamples(count ≤ blockSize) in the same segment must be a
|
||||
// cache hit — no second state-advance.
|
||||
let blockSize: Int = 8
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// freq=0, phase=0.25 → constant 1.0 (phase never changes — any double-advance is invisible)
|
||||
let constOsc: OscSin.Audio = OscSin.Audio(freq: 0.0, phase: 0.25)
|
||||
let fv: Double = constOsc.floatValue(graph: graph)
|
||||
#expect(abs(fv - 1.0) < 1e-6)
|
||||
// Should hit cache — same result
|
||||
let result: [[Double]] = constOsc.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(result[0].prefix(4).allSatisfy { abs($0 - 1.0) < 1e-6 })
|
||||
}
|
||||
|
||||
@Test func floatValueThenCalculatedSamplesDoesNotDoubleAdvancePhase() throws {
|
||||
// Proves the floatValue-then-calculatedSamples case does NOT double the phase advance.
|
||||
// Strategy: compare a generator that had floatValue + calculatedSamples called against
|
||||
// a reference that had only calculatedSamples called. Both must produce the same output.
|
||||
let blockSize: Int = 16
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
|
||||
let freq: Double = 440.0
|
||||
|
||||
// Reference: only calculatedSamples, no floatValue call.
|
||||
let refOsc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let refGraph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let refResult: [[Double]] = refOsc.calculatedSamples(graph: refGraph, count: blockSize)
|
||||
|
||||
advanceBlock(engine)
|
||||
|
||||
// Subject: floatValue called first (primes cache), then calculatedSamples.
|
||||
let subjOsc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let subjGraph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = subjOsc.floatValue(graph: subjGraph) // primes cache via calculatedSamples(blockSize)
|
||||
let subjResult: [[Double]] = subjOsc.calculatedSamples(graph: subjGraph, count: blockSize)
|
||||
|
||||
// Results must be bit-identical — same starting phase, same frequency, single evaluation.
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(refResult[0][i] - subjResult[0][i]) < 1e-12,
|
||||
"double-advance at sample \(i): ref=\(refResult[0][i]) subj=\(subjResult[0][i])")
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// FlangerTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Flanger")
|
||||
struct FlangerTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic first sample
|
||||
|
||||
@Test func firstSampleDeterministic() {
|
||||
// input=0.5, depth=0, rate=0, feedback=0, mix=0.5 → first sample always 0.25.
|
||||
// Delay line starts all-zero; wet signal = 0; output = dry*(1-0.5) + 0*0.5 = 0.25.
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
delayTime: 0.005,
|
||||
depth: 0.0,
|
||||
rate: 0.0,
|
||||
feedback: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 1)
|
||||
let expected: Double = 0.25
|
||||
#expect(abs(out[0][0] - expected) < 1e-10, "First sample must be \(expected), got \(out[0][0])")
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: 0.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
#expect(flanger.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Silent input → output near zero (with mix 0.5, dry is 0 so output is 0)
|
||||
|
||||
@Test func silentInputProducesNearZeroOutput() {
|
||||
// With input = 0 and no feedback, delay line stays zero.
|
||||
// Output = 0 * (1 - mix) + 0 * mix = 0.
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-12 }
|
||||
#expect(allNearZero, "Zero input with no feedback must produce near-zero output")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent input → output differs from dry (modulation is happening)
|
||||
|
||||
@Test func nonSilentInputDiffersFromDry() {
|
||||
// After some blocks the modulated delay creates a different signal from dry.
|
||||
let amplitude: Double = 0.5
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(amplitude),
|
||||
delayTime: 0.005,
|
||||
depth: 0.5,
|
||||
rate: 2.0,
|
||||
feedback: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
|
||||
// Run several blocks to let delay line fill.
|
||||
for _ in 0..<5 {
|
||||
_ = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
// With constant input the delayed signal is also constant, so mix just attenuates.
|
||||
// At mix=0.5: output = 0.5 * amplitude + 0.5 * amplitude = amplitude.
|
||||
// Verify output is non-zero and finite.
|
||||
let rms: Double = rmsValue(samples)
|
||||
#expect(rms > 0, "Non-silent input must produce non-zero output")
|
||||
let allFinite: Bool = samples.allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out (same segment returns identical result)
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out1: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() {
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
_ = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
_ = flanger.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let block2: [[Double]] = flanger.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples after block advance must be finite")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
// With zero input: output = 0 * (1 - mix) + 0 * mix = 0.
|
||||
// After mulAdd(mul: 2.0, add: 1.0): output = 0 * 2 + 1 = 1.
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allNearOne: Bool = samples.allSatisfy { abs($0 - 1.0) < 1e-10 }
|
||||
#expect(allNearOne, "mulAdd(mul:2, add:1) on zero input must produce output of 1.0")
|
||||
}
|
||||
|
||||
// MARK: - Feedback affects output amplitude
|
||||
|
||||
@Test func feedbackOutputIsFinite() {
|
||||
// With feedback the delayed signal feeds back into the delay line.
|
||||
// Verify both variants (feedback=0 and feedback=0.8) produce finite output.
|
||||
let flangerNoFb: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.2),
|
||||
delayTime: 0.005,
|
||||
depth: 0.3,
|
||||
rate: 0.5,
|
||||
feedback: 0.0,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let flangerFb: Flanger.Audio = Flanger.Audio(
|
||||
input: ConstantGeneratorInput(0.2),
|
||||
delayTime: 0.005,
|
||||
depth: 0.3,
|
||||
rate: 0.5,
|
||||
feedback: 0.8,
|
||||
mix: 0.5,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
|
||||
for _ in 0..<10 {
|
||||
_ = flangerNoFb.calculatedSamples(graph: graph, count: 512)
|
||||
_ = flangerFb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let outNoFb: [Double] = Array(flangerNoFb.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)[0].prefix(512))
|
||||
let outFb: [Double] = Array(flangerFb.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)[0].prefix(512))
|
||||
let rmsNoFb: Double = rmsValue(outNoFb)
|
||||
let rmsFb: Double = rmsValue(outFb)
|
||||
// Feedback with constant input is stable (clamped to 0.9). Both must be finite.
|
||||
#expect(rmsNoFb.isFinite, "No-feedback output must be finite")
|
||||
#expect(rmsFb.isFinite, "Feedback output must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class FlangerSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let flanger: Flanger.Audio = Flanger.Audio(
|
||||
input: OscSin.Audio(freq: 220.0),
|
||||
delayTime: 0.005,
|
||||
depth: 0.5,
|
||||
rate: 0.5,
|
||||
feedback: 0.2,
|
||||
mix: 0.5,
|
||||
sampleRate: 44100
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: flanger))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: FlangerSynth = FlangerSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// FluteTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Flute")
|
||||
struct FluteTests {
|
||||
|
||||
// MARK: - Test fixture
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
let testMaxDelayTime: Double = 0.02
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
#expect(flute.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = flute.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Silent at zero excitation
|
||||
|
||||
@Test func silentAtZeroExcitation() {
|
||||
// With breathPressure = 0 and noiseGain = 0, no energy enters the waveguide.
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
breathPressure: 0.0,
|
||||
noiseGain: 0.0,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = flute.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-6 }
|
||||
#expect(allNearZero, "Output must be near zero with breathPressure = 0 and noiseGain = 0")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent with excitation
|
||||
|
||||
@Test func nonSilentWithExcitation() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
var lastSamples: [Double] = []
|
||||
for _ in 0..<10 {
|
||||
let out: [[Double]] = flute.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
lastSamples = Array(out[0].prefix(512))
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let rms: Double = rmsValue(lastSamples)
|
||||
#expect(rms > 0, "Flute must produce non-zero output with breathPressure > 0")
|
||||
#expect(lastSamples.allSatisfy { $0.isFinite }, "All samples must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Fan-out single evaluation
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out1: [[Double]] = flute.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = flute.calculatedSamples(graph: graph, count: 512)
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - State advances across blocks
|
||||
|
||||
@Test func stateAdvancesAcrossBlocks() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
breathPressure: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
_ = flute.calculatedSamples(graph: graph, count: 512)
|
||||
_ = flute.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block2: [[Double]] = flute.calculatedSamples(graph: graph2, count: 512)
|
||||
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples must be finite after block advance")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let flute1: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: ConstantGeneratorInput(0.5),
|
||||
noiseGain: ConstantGeneratorInput(0.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let flute2: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: ConstantGeneratorInput(0.5),
|
||||
noiseGain: ConstantGeneratorInput(0.0),
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out1: [Double] = Array(flute1.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(flute2.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
var relationshipHolds: Bool = true
|
||||
for i: Int in 0..<512 {
|
||||
let expected: Double = out1[i] * 2.0 + 1.0
|
||||
if abs(out2[i] - expected) > 1e-10 {
|
||||
relationshipHolds = false
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(relationshipHolds, "mul:2.0 add:1.0 must produce output × 2 + 1")
|
||||
}
|
||||
|
||||
// MARK: - Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class FluteSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: 0.5,
|
||||
sampleRate: 44100,
|
||||
maxDelayTime: 0.02
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: flute))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: FluteSynth = FluteSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Finite after many blocks
|
||||
|
||||
@Test func finiteAfterManyBlocks() {
|
||||
let flute: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: 0.5,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let blockCount: Int = 200
|
||||
var allFinite: Bool = true
|
||||
for _ in 0..<blockCount {
|
||||
let out: [[Double]] = flute.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
if !samples.allSatisfy({ $0.isFinite }) {
|
||||
allFinite = false
|
||||
break
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allFinite, "Flute must produce finite output for 200 blocks")
|
||||
}
|
||||
|
||||
// MARK: - Jet ratio affects tone
|
||||
|
||||
@Test func jetRatioAffectsTone() {
|
||||
let flute1: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: 0.5,
|
||||
jetRatio: 0.1,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let flute2: Flute.Audio = Flute.Audio(
|
||||
freq: 440.0,
|
||||
breathPressure: 0.5,
|
||||
jetRatio: 0.6,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
let warmupBlocks: Int = 20
|
||||
for b: Int in 0..<warmupBlocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = flute1.calculatedSamples(graph: g, count: 512)
|
||||
_ = flute2.calculatedSamples(graph: g, count: 512)
|
||||
advanceBlock(engine)
|
||||
_ = b
|
||||
}
|
||||
let gFinal: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [Double] = Array(flute1.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let out2: [Double] = Array(flute2.calculatedSamples(graph: gFinal, count: 512)[0].prefix(512))
|
||||
let identical: Bool = out1 == out2
|
||||
#expect(!identical, "Different jetRatio values must produce different output buffers")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// FormantGrainTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("FormantGrain")
|
||||
struct FormantGrainTests {
|
||||
|
||||
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
|
||||
try engine.start()
|
||||
return engine
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() throws {
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio()
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output shape
|
||||
|
||||
@Test func outputIsMonoOnechannel() throws {
|
||||
let engine: SynthesisEngine = try makeEngine()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count == 1, "FormantGrain must produce mono (1 channel), got \(out.count)")
|
||||
}
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 64)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out[0].count >= 64, "Output must cover at least count samples")
|
||||
// Verify the requested range was actually written to (not residual buffer state).
|
||||
let writtenEnergy: Double = out[0].prefix(64).reduce(0.0) { $0 + abs($1) }
|
||||
#expect(writtenEnergy > 0, "First 64 samples must be written by this block, not residual zeros")
|
||||
}
|
||||
|
||||
// MARK: - Non-silence
|
||||
|
||||
@Test func firstBlockIsNonSilent() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
// Default params: 100 Hz glottal, 700 Hz formant — first grain fires at sample 0.
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) }
|
||||
#expect(energy > 0, "First block must be non-silent — grain fires at sample 0")
|
||||
}
|
||||
|
||||
// MARK: - Grain envelope (rise then decay)
|
||||
|
||||
@Test func grainPeakOccursAfterRisePhase() throws {
|
||||
// At 700 Hz formant / 44100 SR: rise = SR/(2*700) ≈ 31.5 samples.
|
||||
// The peak should occur around sample 31.
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
// High glottalFreq relative to formant so only one grain fires in the block.
|
||||
// Actually use very low glottal so only one grain fires: 1 Hz → hopSize ≈ 44100 samples.
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 1.0,
|
||||
formantFreq: 700.0,
|
||||
bandwidth: 200.0,
|
||||
amp: 1.0
|
||||
)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = out[0]
|
||||
|
||||
// First sample should be near zero (envelope starts at sin²(0) = 0).
|
||||
#expect(abs(samples[0]) < 0.01, "First sample must be near zero (grain envelope starts at 0)")
|
||||
|
||||
// Find the sample with maximum absolute value.
|
||||
let maxAbsIdx: Range<ArraySlice<Double>.Index>.Element = samples.prefix(512).indices.max(by: { abs(samples[$0]) < abs(samples[$1]) }) ?? 0
|
||||
// Peak should be within a few samples of the theoretical rise end (~31.5 samples).
|
||||
let expectedRise: Int = Int(44100.0 / (2.0 * 700.0))
|
||||
#expect(maxAbsIdx >= expectedRise / 2, "Peak should occur after some rise; found at sample \(maxAbsIdx)")
|
||||
}
|
||||
|
||||
// MARK: - Decay to silence
|
||||
|
||||
@Test func grainDecaysToSilenceAfterSufficientTime() throws {
|
||||
// With bandwidth=2000 Hz, decay is very fast: exp(-π*2000/44100) ≈ 0.867 per sample.
|
||||
// After ~64 samples the grain should be near silent (well below fofGrainDeathThreshold=1e-4).
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 0.5, // one grain, far from next trigger
|
||||
formantFreq: 4000.0, // short rise
|
||||
bandwidth: 5000.0, // very fast decay
|
||||
amp: 1.0
|
||||
)
|
||||
// Run two full blocks.
|
||||
_ = gen.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
|
||||
let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) }
|
||||
#expect(energy2 < 1e-2, "Grain must decay to near silence within the second block with high bandwidth")
|
||||
}
|
||||
|
||||
// MARK: - Pool saturation
|
||||
|
||||
@Test func poolSaturationDoesNotProduceNaN() throws {
|
||||
// Very high glottal rate + low bandwidth (long grains) → many overlapping grains.
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 2000.0, // triggers every ~22 samples
|
||||
formantFreq: 500.0,
|
||||
bandwidth: 10.0, // very slow decay → long grains
|
||||
amp: 0.01
|
||||
)
|
||||
for _ in 0..<4 {
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
for s: Double in out[0].prefix(512) {
|
||||
#expect(s.isFinite, "Output must be finite; pool overflow must not produce NaN/Inf")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func poolFullStealsOldestGrain() throws {
|
||||
// Sustained over-saturation: glottal rate forces > poolSize grains alive simultaneously.
|
||||
// Steal-oldest policy must keep producing audible output (not silence).
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
// 4000 Hz triggers every ~11 samples → ~46 spawns per 512-block.
|
||||
// bandwidth=5 → decayFactor ≈ exp(-π*5/44100) ≈ 0.99964 — grains live thousands of samples.
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 4000.0,
|
||||
formantFreq: 600.0,
|
||||
bandwidth: 5.0,
|
||||
amp: 0.01
|
||||
)
|
||||
// Run several blocks to fully saturate the pool.
|
||||
for _ in 0..<8 {
|
||||
_ = gen.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
// After saturation, output must remain non-zero — steal-oldest keeps fresh grains active.
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) }
|
||||
#expect(energy > 0, "Output must remain audible after pool saturation; steal-oldest must keep new grains active")
|
||||
}
|
||||
|
||||
@Test func glottalFreqAboveSampleRateIsClamped() throws {
|
||||
// glottalFreq > sampleRate would cause hopSize < 1 and same-sample re-trigger;
|
||||
// input clamp must keep output finite and prevent infinite spawn loop.
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 256)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 1_000_000.0, // absurdly high — gets clamped to sampleRate
|
||||
formantFreq: 600.0,
|
||||
bandwidth: 200.0,
|
||||
amp: 0.01
|
||||
)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256)
|
||||
for s: Double in out[0].prefix(256) {
|
||||
#expect(s.isFinite, "Clamped glottalFreq must produce finite output")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func formantFreqAboveSampleRateIsFinite() throws {
|
||||
// formantFreq > sampleRate makes sinePhaseInc > 2π — wrap must use truncatingRemainder.
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 256)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 100.0,
|
||||
formantFreq: 100_000.0, // way above 44.1k
|
||||
bandwidth: 200.0,
|
||||
amp: 0.5
|
||||
)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256)
|
||||
for s: Double in out[0].prefix(256) {
|
||||
#expect(s.isFinite, "formantFreq > sampleRate phase wrap must remain finite")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Octaviation
|
||||
|
||||
@Test func octaviationZeroAndOneProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
defer { engine.stop() }
|
||||
|
||||
let graph1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen0: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
|
||||
octaviation: 0.0, amp: 0.5)
|
||||
let out0: [[Double]] = gen0.calculatedSamples(graph: graph1, count: 512)
|
||||
|
||||
let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
|
||||
octaviation: 1.0, amp: 0.5)
|
||||
let out1: [[Double]] = gen1.calculatedSamples(graph: graph1, count: 512)
|
||||
|
||||
// With octaviation, every other grain is negated — energy sum should differ.
|
||||
let sum0: Double = out0[0].prefix(512).reduce(0.0, +)
|
||||
let sum1: Double = out1[0].prefix(512).reduce(0.0, +)
|
||||
let octaviationDiffEpsilon: Double = 1e-6
|
||||
#expect(abs(sum0 - sum1) > octaviationDiffEpsilon,
|
||||
"Octaviation=0 and =1 must produce meaningfully different output (sum0=\(sum0), sum1=\(sum1))")
|
||||
}
|
||||
|
||||
// MARK: - MulAdd
|
||||
|
||||
@Test func mulScalesOutput() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen1x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
|
||||
amp: 0.5, mul: 1.0)
|
||||
let gen2x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
|
||||
amp: 0.5, mul: 2.0)
|
||||
|
||||
let out1: [[Double]] = gen1x.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = gen2x.calculatedSamples(graph: graph, count: 512)
|
||||
|
||||
let energy1: Double = out1[0].prefix(512).reduce(0.0) { $0 + abs($1) }
|
||||
let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) }
|
||||
#expect(abs(energy2 - 2.0 * energy1) < energy1 * 0.01,
|
||||
"mul:2 must double output energy; got \(energy2) vs \(2.0 * energy1)")
|
||||
}
|
||||
|
||||
// MARK: - Determinism
|
||||
|
||||
@Test func sameParamsSameOutput() throws {
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4)
|
||||
let gen2: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4)
|
||||
|
||||
let out1: [[Double]] = gen1.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: 512)
|
||||
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out1[0][i] == out2[0][i],
|
||||
"Same params must produce identical output at sample \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorInput driving
|
||||
|
||||
@Test func generatorDrivenFormantFreqIsFinite() throws {
|
||||
// When formantFreq is driven by a generator, output must remain finite.
|
||||
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqGen: OscSin.Audio = OscSin.Audio(freq: 1.0, mul: 200.0, add: 440.0)
|
||||
let gen: FormantGrain.Audio = FormantGrain.Audio(
|
||||
glottalFreq: 200.0,
|
||||
formantFreq: freqGen,
|
||||
bandwidth: 100.0,
|
||||
amp: 0.3
|
||||
)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
|
||||
for s: Double in out[0].prefix(512) {
|
||||
#expect(s.isFinite, "Generator-driven formantFreq must produce finite output")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// FractionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Fraction — exact rational arithmetic for Score")
|
||||
struct FractionTests {
|
||||
|
||||
@Test func reductionAtConstruction() {
|
||||
let f: Fraction = Fraction(num: 6, den: 8)
|
||||
#expect(f.num == 3)
|
||||
#expect(f.den == 4)
|
||||
}
|
||||
|
||||
@Test func signNormalisation() {
|
||||
let f: Fraction = Fraction(num: 3, den: -4)
|
||||
#expect(f.num == -3)
|
||||
#expect(f.den == 4)
|
||||
|
||||
let g: Fraction = Fraction(num: -6, den: -8)
|
||||
#expect(g.num == 3)
|
||||
#expect(g.den == 4)
|
||||
}
|
||||
|
||||
@Test func zeroAndOne() {
|
||||
#expect(Fraction.zero.num == 0)
|
||||
#expect(Fraction.zero.den == 1)
|
||||
#expect(Fraction.one.num == 1)
|
||||
#expect(Fraction.one.den == 1)
|
||||
}
|
||||
|
||||
@Test func addition() {
|
||||
// 1/2 + 1/3 = 5/6
|
||||
let s: Fraction = Fraction(num: 1, den: 2) + Fraction(num: 1, den: 3)
|
||||
#expect(s.num == 5)
|
||||
#expect(s.den == 6)
|
||||
}
|
||||
|
||||
@Test func additionReducesResult() {
|
||||
// 1/4 + 1/4 = 1/2 (not 2/4)
|
||||
let s: Fraction = Fraction(num: 1, den: 4) + Fraction(num: 1, den: 4)
|
||||
#expect(s.num == 1)
|
||||
#expect(s.den == 2)
|
||||
}
|
||||
|
||||
@Test func multiplication() {
|
||||
// (2/3) * (3/4) = 1/2 (after cross-cancellation)
|
||||
let p: Fraction = Fraction(num: 2, den: 3) * Fraction(num: 3, den: 4)
|
||||
#expect(p.num == 1)
|
||||
#expect(p.den == 2)
|
||||
}
|
||||
|
||||
@Test func tupletScaleMath() {
|
||||
// Triplet inside quintuplet inside the outer measure:
|
||||
// outer scale 1/1; quintuplet × 4/5; triplet × 2/3
|
||||
let s: Fraction = Fraction.one
|
||||
* Fraction(num: 4, den: 5)
|
||||
* Fraction(num: 2, den: 3)
|
||||
#expect(s.num == 8)
|
||||
#expect(s.den == 15)
|
||||
}
|
||||
|
||||
@Test func subtraction() {
|
||||
// 1/2 - 1/3 = 1/6
|
||||
let d: Fraction = Fraction(num: 1, den: 2) - Fraction(num: 1, den: 3)
|
||||
#expect(d.num == 1)
|
||||
#expect(d.den == 6)
|
||||
}
|
||||
|
||||
@Test func comparison() {
|
||||
let half: Fraction = Fraction(num: 1, den: 2)
|
||||
let third: Fraction = Fraction(num: 1, den: 3)
|
||||
#expect(third < half)
|
||||
#expect(!(half < third))
|
||||
#expect(half == Fraction(num: 2, den: 4))
|
||||
}
|
||||
|
||||
@Test func doubleConversion() {
|
||||
let f: Fraction = Fraction(num: 1, den: 4)
|
||||
#expect(abs(f.double - 0.25) < 1e-15)
|
||||
}
|
||||
|
||||
@Test func gcdEdges() {
|
||||
#expect(Fraction.gcd(0, 0) == 0)
|
||||
#expect(Fraction.gcd(12, 0) == 12)
|
||||
#expect(Fraction.gcd(0, 12) == 12)
|
||||
#expect(Fraction.gcd(12, 8) == 4)
|
||||
}
|
||||
|
||||
@Test func exactSumOfThirds() {
|
||||
// 1/3 + 1/3 + 1/3 == 1 — the canonical FP failure case must succeed exactly
|
||||
var acc: Fraction = Fraction.zero
|
||||
for _ in 0..<3 {
|
||||
acc += Fraction(num: 1, den: 3)
|
||||
}
|
||||
#expect(acc.num == 1)
|
||||
#expect(acc.den == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// FreeVerbTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("FreeVerb — stereo reverb")
|
||||
struct FreeVerbTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Output shape
|
||||
|
||||
@Test func outputIsStereo() {
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(0.5))
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2, "FreeVerb must produce exactly 2 channels")
|
||||
#expect(out[0].count >= 64)
|
||||
#expect(out[1].count >= 64)
|
||||
}
|
||||
|
||||
// MARK: - Dry pass-through
|
||||
|
||||
@Test func mixZeroPassesDryThrough() {
|
||||
let input: Double = 0.6
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(input), mix: 0.0)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(out[0][i] - input) < 1e-10,
|
||||
"L ch at mix=0 must equal dry input at sample \(i)")
|
||||
#expect(abs(out[1][i] - input) < 1e-10,
|
||||
"R ch at mix=0 must equal dry input at sample \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Wet output differs from dry
|
||||
|
||||
@Test func mixOneWetDiffersFromDry() {
|
||||
// Run constant-input blocks until delay lines fill; wet output must differ from input.
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), roomSize: 0.8,
|
||||
mix: 1.0, sampleRate: 44100)
|
||||
for _ in 0..<10 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
let anyDiffersL: Bool = out[0].prefix(512).contains { abs($0 - 1.0) > 1e-6 }
|
||||
#expect(anyDiffersL, "Wet output must differ from dry input once delay lines are filled")
|
||||
}
|
||||
|
||||
// MARK: - Impulse response decays
|
||||
|
||||
@Test func impulseResponseDecays() {
|
||||
let impulse: ImpulseSource = ImpulseSource()
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: impulse, roomSize: 0.8, mix: 1.0, sampleRate: 44100)
|
||||
|
||||
// Block 0: inject impulse — writes into comb delay lines, output is 0 (nothing to
|
||||
// read back yet; smallest comb size is 1116 > 512 samples/block).
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Blocks 1-2: advance until the first comb reflection wraps around.
|
||||
// Smallest comb (1116 samples) first echoes at sample 1116 → block 2, offset 92.
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Capture early tail energy (block 2 — first reflections audible).
|
||||
let earlyOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
let earlyEnergy: Double = earlyOut[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
|
||||
advanceBlock(engine)
|
||||
|
||||
// Advance 30 more blocks, then capture late tail.
|
||||
// At roomSize=0.8, feedback ≈ 0.924; after 30 blocks each comb decays to ~34%.
|
||||
var lateOut: [[Double]] = [[]]
|
||||
for _ in 0..<30 {
|
||||
lateOut = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let lateEnergy: Double = lateOut[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
|
||||
|
||||
#expect(earlyEnergy > 0, "Early tail must have non-zero energy after first reflections")
|
||||
#expect(lateEnergy < earlyEnergy, "Reverb tail must decay over time")
|
||||
}
|
||||
|
||||
// MARK: - Stereo channels are distinct
|
||||
|
||||
@Test func leftAndRightAreDistinct() {
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), roomSize: 0.5,
|
||||
mix: 1.0, spread: 23, sampleRate: 44100)
|
||||
for _ in 0..<5 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
|
||||
.contains { abs($0 - $1) > 1e-8 }
|
||||
#expect(anyDiff, "L and R channels must differ due to spread detuning")
|
||||
}
|
||||
|
||||
// MARK: - roomSize affects decay rate
|
||||
|
||||
@Test func largerRoomSizeSlowerDecay() {
|
||||
let impSml: ImpulseSource = ImpulseSource()
|
||||
let impLrg: ImpulseSource = ImpulseSource()
|
||||
let vSml: FreeVerb.Audio = FreeVerb.Audio(source: impSml, roomSize: 0.2, mix: 1.0, sampleRate: 44100)
|
||||
let vLrg: FreeVerb.Audio = FreeVerb.Audio(source: impLrg, roomSize: 0.9, mix: 1.0, sampleRate: 44100)
|
||||
|
||||
// Both receive impulse on block 0.
|
||||
_ = vSml.calculatedSamples(graph: graph, count: 512)
|
||||
_ = vLrg.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Advance 30 blocks; capture late tail.
|
||||
var tailSml: [[Double]] = [[]]
|
||||
var tailLrg: [[Double]] = [[]]
|
||||
for _ in 0..<30 {
|
||||
tailSml = vSml.calculatedSamples(graph: graph, count: 512)
|
||||
tailLrg = vLrg.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let energySml: Double = tailSml[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
|
||||
let energyLrg: Double = tailLrg[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
|
||||
#expect(energyLrg > energySml,
|
||||
"Larger roomSize must produce more energy in the late tail")
|
||||
}
|
||||
|
||||
// MARK: - Deterministic sample pin
|
||||
|
||||
@Test func firstCombEchoIsExact() {
|
||||
// With roomSize=0 (feedback=0.7), damping=0 (LP transparent: damp1=0 → state=out),
|
||||
// mix=1, spread=23 at 44100 Hz:
|
||||
//
|
||||
// Comb echo: smallest comb = 1116 samples. First echo at absolute sample 1116
|
||||
// = block 2, index 92. Only that one comb has wrapped; others are larger → sumL = out0.
|
||||
//
|
||||
// Allpass chain: all 4 allpass buffers are still zero at index 92 (confirmed by
|
||||
// tracing: each allpass size ≤ 556 samples; every position written before sample
|
||||
// 1116 received apL=0 input, so all positions hold 0). With zero-filled buffers,
|
||||
// each stage computes apOut = -input + 0 = -input. Four negations: (-1)^4 = +1.
|
||||
// Net allpass effect is identity, value preserved exactly.
|
||||
//
|
||||
// Expected: comb[0] reads buf[0] = freeVerbFixedGain (0.015), LP state = 0.015
|
||||
// (damp1=0 → no smoothing), sumL = 0.015, allpass identity → result = 0.015.
|
||||
let impulse: ImpulseSource = ImpulseSource()
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: impulse, roomSize: 0.0, damping: 0.0,
|
||||
mix: 1.0, spread: 23, sampleRate: 44100)
|
||||
|
||||
// Block 0: impulse at sample 0 written into comb delay positions.
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Block 1: no comb has wrapped yet (smallest comb = 1116 > 1023).
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Block 2: first comb wraps at sample 1116 = index 92 within this block.
|
||||
let block2: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(abs(block2[0][92] - 0.015) < 1e-12,
|
||||
"First echo from 1116-sample comb must equal freeVerbFixedGain at block-2 index 92")
|
||||
}
|
||||
|
||||
// MARK: - Channel aliases
|
||||
|
||||
@Test func channelAliasesMatchSubscripts() {
|
||||
// All three calls share the same segment; fan-out cache ensures FreeVerb
|
||||
// computes once and left/right extract from the cached 2-channel result.
|
||||
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), mix: 0.5, sampleRate: 44100)
|
||||
let leftOut: [[Double]] = verb.left.calculatedSamples(graph: graph, count: 64)
|
||||
let rightOut: [[Double]] = verb.right.calculatedSamples(graph: graph, count: 64)
|
||||
let fullOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10)
|
||||
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Test helpers
|
||||
|
||||
/// Emits 1.0 at sample 0 of the first block; 0.0 on every subsequent block.
|
||||
private final class ImpulseSource: GeneratorBase, AudioGenerator {
|
||||
private var _fired: Bool = false
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { 0.0 }
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count, "ImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
|
||||
// _fired is permanent — set on first _computeSamples call, never reset.
|
||||
// advanceBlock() increments segment serial so subsequent blocks get fresh calls here.
|
||||
_result[0][0] = _fired ? 0.0 : 1.0
|
||||
for i: Int in 1..<count { _result[0][i] = 0.0 }
|
||||
_fired = true
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
// FrequencyShifterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("FrequencyShifter")
|
||||
struct FrequencyShifterTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
let testSampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - 1. Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: 0.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
#expect(shifter.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - 2. Two-channel output count
|
||||
|
||||
@Test func outputCountTwoChannels() {
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(0.5),
|
||||
shiftHz: 100.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2, "FrequencyShifter.Audio must produce exactly 2 output channels")
|
||||
#expect(Array(out[0].prefix(64)).count == 64, "Upper sideband must have 64 samples")
|
||||
#expect(Array(out[1].prefix(64)).count == 64, "Lower sideband must have 64 samples")
|
||||
}
|
||||
|
||||
// MARK: - 3. Fan-out
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
shiftHz: 50.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out1: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let s1Upper: [Double] = Array(out1[0].prefix(512))
|
||||
let s2Upper: [Double] = Array(out2[0].prefix(512))
|
||||
let s1Lower: [Double] = Array(out1[1].prefix(512))
|
||||
let s2Lower: [Double] = Array(out2[1].prefix(512))
|
||||
#expect(s1Upper == s2Upper,
|
||||
"Fan-out: upper sideband must be identical on second call in same segment")
|
||||
#expect(s1Lower == s2Lower,
|
||||
"Fan-out: lower sideband must be identical on second call in same segment")
|
||||
}
|
||||
|
||||
// MARK: - 4. State advances once per block (cache hit does not double-advance)
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() {
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(0.3),
|
||||
shiftHz: 100.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
_ = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
_ = shifter.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let block2: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let allFiniteUpper: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
let allFiniteLower: Bool = Array(block2[1].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFiniteUpper, "Upper sideband must be finite after block advance")
|
||||
#expect(allFiniteLower, "Lower sideband must be finite after block advance")
|
||||
}
|
||||
|
||||
// MARK: - 5. Deterministic first sample
|
||||
|
||||
@Test func firstSampleUpperEqualsLowerAtZeroShift() {
|
||||
// Structural invariant: at θ = 0 (first sample with shiftHz = 0), cos(θ) = 1 and
|
||||
// sin(θ) = 0 so the SSB matrix collapses to upper = lower = xA. Both output channels
|
||||
// must match on sample 0 regardless of the underlying Hilbert cascade values.
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
shiftHz: 0.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == out[1][0],
|
||||
"At θ = 0 with zero shift, upper and lower outputs must match on sample 0")
|
||||
#expect(out[0][0].isFinite)
|
||||
}
|
||||
|
||||
@Test func nonZeroShiftProducesAsymmetricSidebands() {
|
||||
// After a long enough render with shiftHz ≠ 0, the SSB matrix should diverge upper
|
||||
// and lower outputs (the cos·sin asymmetry exercised). Verifies the SSB sign
|
||||
// convention — a sign flip on the xB·sin term would leave both rows equal at every
|
||||
// sample, not just at θ = 0.
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: OscSin.Audio(freq: 1_000.0),
|
||||
shiftHz: 200.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
// Settle Hilbert IIRs so the shifter is in steady state.
|
||||
for _: Int in 0..<32 {
|
||||
_ = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = shifter.calculatedSamples(
|
||||
graph: makeSynthGraph(engine: engine), count: 512
|
||||
)
|
||||
var anyDiff: Bool = false
|
||||
for i: Int in 0..<512 {
|
||||
if abs(out[0][i] - out[1][i]) > 1e-6 { anyDiff = true; break }
|
||||
}
|
||||
#expect(anyDiff,
|
||||
"Non-zero shift: upper and lower sidebands must diverge once steady state reached")
|
||||
}
|
||||
|
||||
// MARK: - 6. Zero shift — pass-through average
|
||||
|
||||
@Test func zeroShiftPassthrough() {
|
||||
// With shiftHz=0: cos(θ)=1, sin(θ)=0 for all samples (phase stays at 0).
|
||||
// upper = xA·1 + xB·0 = xA, lower = xA·1 − xB·0 = xA.
|
||||
// Both channels equal path A output. Average of upper+lower = xA = path A output.
|
||||
// After filter group delay, output should be non-zero and finite for a sine input.
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: input,
|
||||
shiftHz: 0.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
|
||||
// Both channels should be identical (xA·1 ± xB·0 = xA).
|
||||
let allMatch: Bool = zip(upper, lower).allSatisfy { abs($0 - $1) < 1e-10 }
|
||||
#expect(allMatch, "With shiftHz=0, upper and lower sidebands must be identical")
|
||||
|
||||
// Output should be non-trivial (filter introduces group delay but passes the sine).
|
||||
let rmsUpper: Double = rmsValue(upper)
|
||||
#expect(rmsUpper > 0.01, "Non-silent sine input with zero shift must produce non-trivial output")
|
||||
}
|
||||
|
||||
// MARK: - 7. DC input → quadrature oscillator visible
|
||||
|
||||
@Test func dcInputProducesOscillatorOutput() {
|
||||
// With DC input (constant 1.0): after the all-pass filters settle, xA ≈ xB ≈ 1.
|
||||
// upper ≈ cos(θ) − sin(θ), lower ≈ cos(θ) + sin(θ).
|
||||
// Both channels should be oscillating (non-DC) after many blocks.
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(1.0),
|
||||
shiftHz: 400.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
// Let the Hilbert filters settle.
|
||||
for _ in 0..<20 {
|
||||
_ = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
|
||||
// Compute RMS — a constant output would have very low AC content.
|
||||
// An oscillating signal at 400 Hz will have significant variation.
|
||||
let maxUpper: Double = upper.max() ?? 0
|
||||
let minUpper: Double = upper.min() ?? 0
|
||||
let rangeUpper: Double = maxUpper - minUpper
|
||||
#expect(rangeUpper > 0.5, "DC input with 400 Hz shift should produce oscillating upper sideband")
|
||||
|
||||
let maxLower: Double = lower.max() ?? 0
|
||||
let minLower: Double = lower.min() ?? 0
|
||||
let rangeLower: Double = maxLower - minLower
|
||||
#expect(rangeLower > 0.5, "DC input with 400 Hz shift should produce oscillating lower sideband")
|
||||
}
|
||||
|
||||
// MARK: - 8. Audio-rate shift input
|
||||
|
||||
@Test func audioRateShiftInput() {
|
||||
// Drive shiftHz with an OscSin generator — verify output is non-trivial and non-NaN.
|
||||
let shiftMod: OscSin.Audio = OscSin.Audio(freq: 2.0) // 2 Hz LFO
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: input,
|
||||
shiftHz: shiftMod,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
|
||||
let allFiniteUpper: Bool = upper.allSatisfy { $0.isFinite }
|
||||
let allFiniteLower: Bool = lower.allSatisfy { $0.isFinite }
|
||||
#expect(allFiniteUpper, "Audio-rate shift: upper sideband must not contain NaN/Inf")
|
||||
#expect(allFiniteLower, "Audio-rate shift: lower sideband must not contain NaN/Inf")
|
||||
|
||||
let rmsUpper: Double = rmsValue(upper)
|
||||
#expect(rmsUpper > 0.001, "Audio-rate shift: upper sideband must be non-trivial")
|
||||
}
|
||||
|
||||
// MARK: - 9. mulAdd applied
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
// Zero input → zero output for both sidebands.
|
||||
// With mul:2, add:1 → output must be 1.0 for all samples.
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: 0.0,
|
||||
shiftHz: 100.0,
|
||||
sampleRate: testSampleRate,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
let allNearOneUpper: Bool = upper.allSatisfy { abs($0 - 1.0) < 1e-10 }
|
||||
let allNearOneLower: Bool = lower.allSatisfy { abs($0 - 1.0) < 1e-10 }
|
||||
#expect(allNearOneUpper, "Upper sideband: mul:2 add:1 on zero input must produce 1.0")
|
||||
#expect(allNearOneLower, "Lower sideband: mul:2 add:1 on zero input must produce 1.0")
|
||||
}
|
||||
|
||||
// MARK: - 10. Denormal safety
|
||||
|
||||
@Test func denormalSafe() {
|
||||
// Feed a tiny sub-normal-adjacent input for many blocks — verify no NaN or Inf.
|
||||
let tinyInput: Double = 1e-300
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: ConstantGeneratorInput(tinyInput),
|
||||
shiftHz: 200.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
for _ in 0..<1000 {
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
let upperOk: Bool = upper.allSatisfy { $0.isFinite }
|
||||
let lowerOk: Bool = lower.allSatisfy { $0.isFinite }
|
||||
if !upperOk || !lowerOk {
|
||||
#expect(Bool(false), "Denormal input must not produce NaN/Inf in output")
|
||||
break
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 11. Channel aliases
|
||||
|
||||
@Test func channelAliasesMatchSubscripts() {
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 220.0)
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: input,
|
||||
shiftHz: 50.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let upperOut: [[Double]] = shifter.upper.calculatedSamples(graph: graph, count: 64)
|
||||
let lowerOut: [[Double]] = shifter.lower.calculatedSamples(graph: graph, count: 64)
|
||||
let fullOut: [[Double]] = shifter.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(upperOut[0][i] - fullOut[0][i]) < 1e-10,
|
||||
"upper alias must match channel 0 at index \(i)")
|
||||
#expect(abs(lowerOut[0][i] - fullOut[1][i]) < 1e-10,
|
||||
"lower alias must match channel 1 at index \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 12. Integration with engine
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class FreqShiftSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: OscSin.Audio(freq: 440.0),
|
||||
shiftHz: 100.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: shifter.upper))
|
||||
addOutputGenerator(Out.Audio(bus: 1, source: shifter.lower))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: FreqShiftSynth = FreqShiftSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
|
||||
// MARK: - 13. Upper and lower sidebands differ (non-trivial signal)
|
||||
|
||||
@Test func upperAndLowerSidebandsAreDifferent() {
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: input,
|
||||
shiftHz: 200.0,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
// Let the Hilbert filters settle so path A and B outputs diverge.
|
||||
for _ in 0..<10 {
|
||||
_ = shifter.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let upper: [Double] = Array(out[0].prefix(512))
|
||||
let lower: [Double] = Array(out[1].prefix(512))
|
||||
// upper = xA·cos + xB·sin, lower = xA·cos − xB·sin.
|
||||
// They differ when xB·sin ≠ 0, i.e. once the Hilbert filter is producing output.
|
||||
let anyDiff: Bool = zip(upper, lower).contains { abs($0 - $1) > 1e-6 }
|
||||
#expect(anyDiff, "Upper and lower sidebands must differ once the Hilbert filter is active")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// GVerbTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("GVerb — Griesinger algorithmic stereo reverb")
|
||||
struct GVerbTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Output shape
|
||||
|
||||
@Test func outputIsStereo() {
|
||||
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(0.5), sampleRate: 44100)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2, "GVerb must produce exactly 2 channels")
|
||||
#expect(out[0].count >= 64)
|
||||
#expect(out[1].count >= 64)
|
||||
}
|
||||
|
||||
// MARK: - Dry pass-through at earlyLevel=tailLevel=0
|
||||
|
||||
@Test func zeroLevelsProduceSilence() {
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(0.8),
|
||||
earlyLevel: 0.0,
|
||||
tailLevel: 0.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(out[0][i]) < 1e-10,
|
||||
"L ch must be silent when earlyLevel=tailLevel=0 (sample \(i))")
|
||||
#expect(abs(out[1][i]) < 1e-10,
|
||||
"R ch must be silent when earlyLevel=tailLevel=0 (sample \(i))")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Impulse RT60 within expected range at reverbTime=3.0
|
||||
|
||||
@Test func impulseRT60WithinRange() {
|
||||
// Inject a single impulse, capture energy evolution over many blocks.
|
||||
// With reverbTime=3.0 s, the tail energy should still be non-zero at 1 s
|
||||
// and significantly decayed by 6 s.
|
||||
let impulse: GVerbImpulseSource = GVerbImpulseSource()
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: impulse,
|
||||
roomSize: 10.0,
|
||||
reverbTime: 3.0,
|
||||
damping: 0.3,
|
||||
earlyLevel: 0.0, // isolate late tail
|
||||
tailLevel: 1.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
// Drain enough blocks for early reflections to settle.
|
||||
let blockSize: Int = 512
|
||||
let blocksPerSecond: Int = 44100 / blockSize // ~86 blocks/s
|
||||
|
||||
// Warm up — inject impulse on block 0, advance.
|
||||
_ = verb.calculatedSamples(graph: graph, count: blockSize)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Accumulate energy at ~1 s (expect significant tail).
|
||||
var energyAt1s: Double = 0.0
|
||||
let warmupBlocks: Int = blocksPerSecond
|
||||
for _ in 0..<warmupBlocks {
|
||||
let blk: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
|
||||
energyAt1s += blk[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Accumulate energy at ~5–6 s (expect substantially lower).
|
||||
var energyAt5s: Double = 0.0
|
||||
let laterBlocks: Int = blocksPerSecond * 4 // advance another 4 seconds
|
||||
for _ in 0..<laterBlocks {
|
||||
let blk: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
|
||||
energyAt5s += blk[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Reverb tail should have non-zero energy at 1 s.
|
||||
#expect(energyAt1s > 0.0, "Late tail must have energy ~1 s after impulse (reverbTime=3.0)")
|
||||
// And substantially less energy at 5 s (tail must decay).
|
||||
#expect(energyAt5s < energyAt1s,
|
||||
"Late tail must decay: energy at 5 s must be less than at 1 s")
|
||||
}
|
||||
|
||||
// MARK: - roomSize change affects tail without crash
|
||||
|
||||
@Test func roomSizeChangeNoCrash() {
|
||||
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(0.5), sampleRate: 44100)
|
||||
|
||||
// Warm up at default roomSize.
|
||||
for _ in 0..<10 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Change roomSize mid-stream via a new ConstantGeneratorInput — no crash expected.
|
||||
// (In practice roomSize is read each block via floatValue.)
|
||||
let verbLarge: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(0.5),
|
||||
roomSize: 80.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
for _ in 0..<10 {
|
||||
_ = verbLarge.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
// If we reach here without trap/crash the test passes.
|
||||
#expect(Bool(true), "roomSize change must not crash or exceed buffer bounds")
|
||||
}
|
||||
|
||||
// MARK: - Early and tail levels independently audible (NRT energy check)
|
||||
|
||||
@Test func earlyAndTailLevelsAreIndependent() {
|
||||
let blockSize: Int = 512
|
||||
let warmup: Int = 20
|
||||
|
||||
// Early only
|
||||
let impulseE: GVerbImpulseSource = GVerbImpulseSource()
|
||||
let verbEarly: GVerb.Audio = GVerb.Audio(
|
||||
source: impulseE,
|
||||
roomSize: 10.0, reverbTime: 3.0,
|
||||
earlyLevel: 1.0, tailLevel: 0.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
// Tail only
|
||||
let impulseT: GVerbImpulseSource = GVerbImpulseSource()
|
||||
let verbTail: GVerb.Audio = GVerb.Audio(
|
||||
source: impulseT,
|
||||
roomSize: 10.0, reverbTime: 3.0,
|
||||
earlyLevel: 0.0, tailLevel: 1.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
|
||||
var earlyEnergy: Double = 0.0
|
||||
var tailEnergy: Double = 0.0
|
||||
|
||||
for _ in 0..<warmup {
|
||||
let blkE: [[Double]] = verbEarly.calculatedSamples(graph: graph, count: blockSize)
|
||||
let blkT: [[Double]] = verbTail.calculatedSamples(graph: graph, count: blockSize)
|
||||
earlyEnergy += blkE[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
|
||||
tailEnergy += blkT[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
#expect(earlyEnergy > 0.0, "Early reflections must produce non-zero energy")
|
||||
#expect(tailEnergy > 0.0, "Tail reverb must produce non-zero energy")
|
||||
}
|
||||
|
||||
// MARK: - Stereo L/R are distinct
|
||||
|
||||
@Test func stereoLRDistinct() {
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(1.0),
|
||||
roomSize: 15.0, reverbTime: 3.0,
|
||||
earlyLevel: 0.5, tailLevel: 0.5,
|
||||
sampleRate: 44100
|
||||
)
|
||||
// Warm up.
|
||||
for _ in 0..<15 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
|
||||
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
|
||||
.contains { abs($0 - $1) > 1e-8 }
|
||||
#expect(anyDiff, "L and R channels must differ (asymmetric post-sum allpass diffuser chains)")
|
||||
}
|
||||
|
||||
// MARK: - Parameters update mid-stream (no RT alloc — no crash)
|
||||
|
||||
@Test func parametersUpdateMidStream() {
|
||||
// Use ConstantGeneratorInput values — replaced by different instances each block
|
||||
// to ensure parameter reads go through the protocol path every block.
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(0.3),
|
||||
roomSize: ConstantGeneratorInput(10.0),
|
||||
reverbTime: ConstantGeneratorInput(2.0),
|
||||
damping: ConstantGeneratorInput(0.5),
|
||||
sampleRate: 44100
|
||||
)
|
||||
for _ in 0..<5 {
|
||||
_ = verb.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// Create new verb with different params — simulates mid-stream param change.
|
||||
let verb2: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(0.3),
|
||||
roomSize: ConstantGeneratorInput(50.0),
|
||||
reverbTime: ConstantGeneratorInput(5.0),
|
||||
damping: ConstantGeneratorInput(0.8),
|
||||
sampleRate: 44100
|
||||
)
|
||||
for _ in 0..<5 {
|
||||
_ = verb2.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
#expect(Bool(true), "Parameter changes must not crash or allocate on the RT thread")
|
||||
}
|
||||
|
||||
// MARK: - dryLevel passes direct signal at unity
|
||||
|
||||
@Test func dryLevelPassesDirectSignal() {
|
||||
// With earlyLevel=0 and tailLevel=0, only the dry bypass path is active.
|
||||
// dryLevel=1.0 on cold buffers: first output sample must equal the first input sample
|
||||
// (after the one-pole input damper with inputBandwidth=1.0, which is pass-through).
|
||||
let blockSize: Int = 64
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: ConstantGeneratorInput(0.5),
|
||||
inputBandwidth: 1.0,
|
||||
earlyLevel: 0.0,
|
||||
tailLevel: 0.0,
|
||||
dryLevel: 1.0,
|
||||
sampleRate: 44100
|
||||
)
|
||||
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
|
||||
// All samples should equal 0.5 (dry bypass, no early/tail contribution).
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(out[0][i] - 0.5) < 1e-10,
|
||||
"L ch dry bypass must equal input 0.5 (sample \(i))")
|
||||
#expect(abs(out[1][i] - 0.5) < 1e-10,
|
||||
"R ch dry bypass must equal input 0.5 (sample \(i))")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Channel aliases match subscripts
|
||||
|
||||
@Test func channelAliasesMatchSubscripts() {
|
||||
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(1.0), earlyLevel: 0.4, tailLevel: 0.4,
|
||||
sampleRate: 44100)
|
||||
let leftOut: [[Double]] = verb.left.calculatedSamples(graph: graph, count: 64)
|
||||
let rightOut: [[Double]] = verb.right.calculatedSamples(graph: graph, count: 64)
|
||||
let fullOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10,
|
||||
"verb.left[i] must equal verb[0][i]")
|
||||
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10,
|
||||
"verb.right[i] must equal verb[1][i]")
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase 175 — branchless ring-buffer wrap exercised across many wraps of the
|
||||
/// tap delay (44000 samples ≈ 1 s) and 4 FDN delay lines. Drive a quiet
|
||||
/// non-zero input over ~3 s and assert output stays finite + bounded.
|
||||
/// Single shared engine; `advanceBlock` bumps `segmentSerial` so the
|
||||
/// generator's fan-out cache does not freeze on the first block's output.
|
||||
@Test func denormalLongTailStaysFinite() {
|
||||
let drive: ConstantGeneratorInput = ConstantGeneratorInput(1e-3)
|
||||
let verb: GVerb.Audio = GVerb.Audio(
|
||||
source: drive, roomSize: 20.0, reverbTime: 5.0,
|
||||
damping: 0.3, earlyLevel: 0.4, tailLevel: 0.5,
|
||||
sampleRate: 44100)
|
||||
let loopEngine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
let blocks: Int = (Int(44100.0 * 3.0) / 64) + 1
|
||||
var sawNonFinite: Bool = false
|
||||
var maxAbs: Double = 0.0
|
||||
for _: Int in 0..<blocks {
|
||||
let g: SynthGraph = makeSynthGraph(engine: loopEngine)
|
||||
let block: [[Double]] = verb.calculatedSamples(graph: g, count: 64)
|
||||
for ch: Int in 0..<2 {
|
||||
for v: Double in block[ch] {
|
||||
if !v.isFinite { sawNonFinite = true }
|
||||
let a: Double = abs(v)
|
||||
if a > maxAbs { maxAbs = a }
|
||||
}
|
||||
}
|
||||
advanceBlock(loopEngine)
|
||||
}
|
||||
#expect(!sawNonFinite, "GVerb output must remain finite across many ring wraps")
|
||||
#expect(maxAbs < 1.0, "quiet-input output must remain bounded")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Test helpers
|
||||
|
||||
/// Emits 1.0 at sample 0 of the first block; 0.0 on every subsequent block.
|
||||
private final class GVerbImpulseSource: GeneratorBase, AudioGenerator {
|
||||
private var _fired: Bool = false
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { 0.0 }
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count, "GVerbImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
|
||||
_result[0][0] = _fired ? 0.0 : 1.0
|
||||
for i: Int in 1..<count { _result[0][i] = 0.0 }
|
||||
_fired = true
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// GateTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Gate.Audio")
|
||||
struct GateAudioTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
let blockSize: Int = 64
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gen: Gate.Audio = Gate.Audio(input: 0.0, trig: 0.0)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
/// Constant trig=1 → pure passthrough.
|
||||
@Test func openGatePassesInput() {
|
||||
let input: Closure = Closure { _, i in Double(i) * 0.01 }
|
||||
let gen: Gate.Audio = Gate.Audio(input: input, trig: 1.0)
|
||||
let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(out[i] - Double(i) * 0.01) < 1e-12,
|
||||
"sample \(i): expected \(Double(i) * 0.01), got \(out[i])")
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant trig=0 → output stays at initial 0.0 regardless of input.
|
||||
@Test func closedGateHoldsZero() {
|
||||
let gen: Gate.Audio = Gate.Audio(input: 0.7, trig: 0.0)
|
||||
let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(out[i] == 0.0, "sample \(i) expected 0.0 got \(out[i])")
|
||||
}
|
||||
}
|
||||
|
||||
/// Gate falling-edge holds the last input seen during the high phase.
|
||||
@Test func fallingEdgeHoldsLastInput() {
|
||||
// Input ramps from 0 to 0.63 across samples 0..63 (step 0.01).
|
||||
let input: Closure = Closure { _, i in Double(i) * 0.01 }
|
||||
// Trigger high for samples 0..31, low for 32..63.
|
||||
let trig: Closure = Closure { _, i in i < 32 ? 1.0 : 0.0 }
|
||||
let gen: Gate.Audio = Gate.Audio(input: input, trig: trig)
|
||||
let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
|
||||
// Samples 0..31 — passthrough.
|
||||
for i: Int in 0..<32 {
|
||||
#expect(abs(out[i] - Double(i) * 0.01) < 1e-12)
|
||||
}
|
||||
// Samples 32..63 — held at last passed sample (i=31, value=0.31).
|
||||
for i: Int in 32..<blockSize {
|
||||
#expect(abs(out[i] - 0.31) < 1e-12,
|
||||
"sample \(i) expected held=0.31, got \(out[i])")
|
||||
}
|
||||
}
|
||||
|
||||
/// Held value persists across block boundaries.
|
||||
@Test func heldValuePersistsAcrossBlocks() {
|
||||
// Block 1: input ramps, gate high then low; held = 0.31 at end.
|
||||
// Block 2 (segmentSerial != block 1's): gate stays low.
|
||||
let firstSerial: UInt64 = engine.segmentSerial
|
||||
let input: Closure = Closure { _, i in Double(i) * 0.01 }
|
||||
let trig: Closure = Closure { graph, i in
|
||||
graph.engine.segmentSerial == firstSerial
|
||||
? (i < 32 ? 1.0 : 0.0)
|
||||
: 0.0
|
||||
}
|
||||
let gen: Gate.Audio = Gate.Audio(input: input, trig: trig)
|
||||
_ = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
|
||||
advanceBlock(engine)
|
||||
let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(out[i] - 0.31) < 1e-12,
|
||||
"block 2 sample \(i) expected held=0.31, got \(out[i])")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Gate.Control")
|
||||
struct GateControlTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
let blockSize: Int = 64
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func rateIsControl() {
|
||||
let gen: Gate.Control = Gate.Control(input: 0.0, trig: 0.0)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
/// Open gate, constant input → control output ramps from 0 to input value.
|
||||
@Test func openGateRampsToInput() {
|
||||
let gen: Gate.Control = Gate.Control(input: 0.5, trig: 1.0)
|
||||
let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
// First block — ramp from rampStart=0.0 to 0.5; last sample should be 0.5.
|
||||
#expect(abs(out[blockSize - 1] - 0.5) < 1e-12)
|
||||
// Step linear: each sample = step * (i+1), step = 0.5/64.
|
||||
let step: Double = 0.5 / Double(blockSize)
|
||||
for i: Int in 0..<blockSize {
|
||||
#expect(abs(out[i] - step * Double(i + 1)) < 1e-12)
|
||||
}
|
||||
#expect(abs(gen.previousOutputValue - 0.5) < 1e-12)
|
||||
}
|
||||
|
||||
@Test func closedGateHoldsZero() {
|
||||
let gen: Gate.Control = Gate.Control(input: 0.5, trig: 0.0)
|
||||
_ = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(gen.previousOutputValue == 0.0)
|
||||
}
|
||||
|
||||
@Test func floatValueReturnsPreviousOutputValue() {
|
||||
let gen: Gate.Control = Gate.Control(input: 0.5, trig: 1.0)
|
||||
#expect(gen.floatValue(graph: graph) == 0.0)
|
||||
_ = gen.calculatedSamples(graph: graph, count: blockSize)
|
||||
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// GatedKarplusStrongTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("GatedKarplusStrong")
|
||||
struct GatedKarplusStrongTests {
|
||||
|
||||
// MARK: - Test fixture
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
let testSampleRate: Double = 44100
|
||||
let testMaxDelayTime: Double = 0.05
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
#expect(gks.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = gks.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out1: [[Double]] = gks.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = gks.calculatedSamples(graph: graph, count: 512)
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - Gate off — delay line stays zero
|
||||
|
||||
@Test func gateOffOutputNearZero() {
|
||||
// With gate = 0 and delay line zero-initialised, the feedback loop recirculates zeros.
|
||||
// The one-pole filter produces (0 + 0) * 0.5 * feedback = 0 → output stays zero.
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: 0.0, // gate always off
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = gks.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allZero: Bool = samples.allSatisfy { abs($0) < 1e-12 }
|
||||
#expect(allZero, "With gate off and zero delay line, output must be zero")
|
||||
}
|
||||
|
||||
// MARK: - Gate on injects exciter into delay line
|
||||
|
||||
@Test func gateOnInjectsExciter() {
|
||||
// Gate = 1.0 → exciter constantly written into delay line.
|
||||
// After one block the delay line is full of exciter energy; output must be non-zero.
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.5),
|
||||
gate: 1.0, // gate always on
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = gks.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let rms: Double = rmsValue(samples)
|
||||
#expect(rms > 0, "With gate on and non-zero exciter, output RMS must be non-zero")
|
||||
}
|
||||
|
||||
// MARK: - Gate on then off — resonance continues
|
||||
|
||||
@Test func gateOnThenOffResonancesContinue() {
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: GatedBlockToggle(), // on for first block, off thereafter
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
// Block 0: gate on → delay line fills with noise.
|
||||
_ = gks.calculatedSamples(graph: graph, count: 512)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Block 1: gate off → should resonate (delay line now has energy).
|
||||
let resonanceOut: [[Double]] = gks.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let rms: Double = rmsValue(Array(resonanceOut[0].prefix(512)))
|
||||
#expect(rms > 0, "After gate-off, resonance should continue from filled delay line (rms=\(rms))")
|
||||
}
|
||||
|
||||
// MARK: - Continuous gate sustain
|
||||
|
||||
@Test func continuousGateSustain() {
|
||||
// With gate always on and constant exciter, output should stay non-zero across blocks.
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.3),
|
||||
gate: 1.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
var allBlocksNonZero: Bool = true
|
||||
for _ in 0..<10 {
|
||||
let out: [[Double]] = gks.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
let rms: Double = rmsValue(Array(out[0].prefix(512)))
|
||||
if rms <= 0 { allBlocksNonZero = false }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allBlocksNonZero, "Continuous gate must sustain non-zero output across all blocks")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
let gksBase: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.5),
|
||||
gate: 1.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let gksMul: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.5),
|
||||
gate: 1.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
|
||||
let outBase: [Double] = Array(gksBase.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
let outMul: [Double] = Array(gksMul.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
|
||||
var relationshipHolds: Bool = true
|
||||
for i: Int in 0..<512 {
|
||||
let expected: Double = outBase[i] * 2.0 + 1.0
|
||||
if abs(outMul[i] - expected) > 1e-10 {
|
||||
relationshipHolds = false
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(relationshipHolds, "mul:2.0 add:1.0 must produce output × 2 + 1")
|
||||
}
|
||||
|
||||
// MARK: - Integration
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class GKSSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gks: GatedKarplusStrong.Audio = GatedKarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
gate: LFSquare.Audio(freq: 4.0),
|
||||
freq: 220.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: 44100,
|
||||
maxDelayTime: 0.05
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gks))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: GKSSynth = GKSSynth()
|
||||
try intEngine.add(synth)
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Local test helpers
|
||||
|
||||
/// Gate source that outputs 1.0 on the first `calculatedSamples` call, then 0.0 forever.
|
||||
/// Simulates a gate that is open for exactly one audio block.
|
||||
private final class GatedBlockToggle: GeneratorBase, AudioGenerator {
|
||||
private var _firstBlock: Bool = true
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { _firstBlock ? 1.0 : 0.0 }
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count,
|
||||
"GatedBlockToggle: count \(count) exceeds buffer size \(_result[0].count)")
|
||||
let value: Double = _firstBlock ? 1.0 : 0.0
|
||||
for i: Int in 0..<count { _result[0][i] = value }
|
||||
_firstBlock = false
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
// Gendy1Tests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Gendy1")
|
||||
struct Gendy1Tests {
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gen: Gendy1.Audio = Gendy1.Audio()
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(seed: 1)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(seed: 2)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(seed: 3)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Second call in same segment: cache hit, no double advance.
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
// Advance to next segment.
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Block 2 must differ from block 1 (state advanced, different interpolation position).
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Output stays in [-1, 1] with mul=1
|
||||
|
||||
@Test func outputStaysInRange() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(seed: 4)
|
||||
for _ in 0..<20 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out[0][i] >= -1.0 && out[0][i] <= 1.0,
|
||||
"sample \(i) out of [-1,1]: \(out[0][i])")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Non-silent output
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(seed: 5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let nonZero: Bool = out[0].prefix(64).contains { $0 != 0.0 }
|
||||
#expect(nonZero)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic output with fixed seed
|
||||
|
||||
@Test func deterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy1.Audio = Gendy1.Audio(seed: 99)
|
||||
let gen2: Gendy1.Audio = Gendy1.Audio(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Different seeds produce different output
|
||||
|
||||
@Test func differentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy1.Audio = Gendy1.Audio(seed: 100)
|
||||
let gen2: Gendy1.Audio = Gendy1.Audio(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - ampscale=0 produces very stable waveform
|
||||
|
||||
@Test func ampScaleZeroProducesStableWaveform() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// With ampscale=0, amplitude breakpoints cannot drift.
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(ampscale: 0.0, durscale: 0.0, seed: 7)
|
||||
// Run two blocks; since neither amplitude nor duration changes, waveform repeats.
|
||||
let block1: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// With zero scale, the waveform pattern should be stable. Both blocks are in [-1,1].
|
||||
for sample: Double in block1 { #expect(sample >= -1.0 && sample <= 1.0) }
|
||||
for sample: Double in block2 { #expect(sample >= -1.0 && sample <= 1.0) }
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - mulAdd scales output
|
||||
|
||||
@Test func mulAddScalesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let genPlain: Gendy1.Audio = Gendy1.Audio(seed: 42)
|
||||
let genMulAdd: Gendy1.Audio = Gendy1.Audio(mul: 2.0, add: 1.0, seed: 42)
|
||||
let plain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let scaled: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = plain[i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[i] - expected) < 1e-9, "sample \(i): expected \(expected), got \(scaled[i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Integration
|
||||
|
||||
@Test func integrationRunsWithoutCrash() throws {
|
||||
final class Gendy1Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy1.Audio = Gendy1.Audio(minfreq: 100.0, maxfreq: 400.0, initCPs: 6)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy1Synth = Gendy1Synth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
@Test func controlRateIsControl() {
|
||||
let gen: Gendy1.Control = Gendy1.Control()
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
@Test func controlOutputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Control = Gendy1.Control(seed: 10)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlFanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Control = Gendy1.Control(seed: 11)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlStateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Control = Gendy1.Control(seed: 12)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Second call in same segment: cache hit — identical output.
|
||||
#expect(block1a == block1b)
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Different block: state has advanced.
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlProducesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Control = Gendy1.Control(seed: 13)
|
||||
var nonZeroFound: Bool = false
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
if out[0].prefix(64).contains(where: { $0 != 0.0 }) { nonZeroFound = true }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(nonZeroFound)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlAmpscaleZeroProducesStableAmplitudes() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy1.Control = Gendy1.Control(ampscale: 0.0, durscale: 0.0, seed: 14)
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
// With ampscale=0 amps can't drift; mul=1 so output stays in [-1,1].
|
||||
#expect(out[0][i] >= -1.0 && out[0][i] <= 1.0,
|
||||
"sample \(i) out of [-1,1]: \(out[0][i])")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlIntegrationRunsWithoutCrash() throws {
|
||||
final class Gendy1ControlSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy1.Control = Gendy1.Control(minfreq: 0.5, maxfreq: 4.0, initCPs: 6)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy1ControlSynth = Gendy1ControlSynth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic Control output with fixed seed
|
||||
|
||||
@Test func controlDeterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy1.Control = Gendy1.Control(seed: 99)
|
||||
let gen2: Gendy1.Control = Gendy1.Control(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlDifferentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy1.Control = Gendy1.Control(seed: 100)
|
||||
let gen2: Gendy1.Control = Gendy1.Control(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// Gendy2Tests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Gendy2")
|
||||
struct Gendy2Tests {
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gen: Gendy2.Audio = Gendy2.Audio()
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(seed: 1)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(seed: 2)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(seed: 3)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Non-silent output
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(seed: 5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let nonZero: Bool = out[0].prefix(64).contains { $0 != 0.0 }
|
||||
#expect(nonZero)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic output with fixed seed
|
||||
|
||||
@Test func deterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy2.Audio = Gendy2.Audio(seed: 99)
|
||||
let gen2: Gendy2.Audio = Gendy2.Audio(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Different seeds produce different output
|
||||
|
||||
@Test func differentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy2.Audio = Gendy2.Audio(seed: 100)
|
||||
let gen2: Gendy2.Audio = Gendy2.Audio(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Output stays in bounded range (Catmull-Rom may overshoot [-1,1] slightly)
|
||||
|
||||
@Test func outputStaysInBoundedRange() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// Catmull-Rom can overshoot breakpoint bounds slightly; verify output is finite
|
||||
// and within a reasonable margin. Gendy2 amps are clamped to [-1,1] but
|
||||
// cubic interpolation can produce values up to ~1.5× the breakpoint range.
|
||||
let catmullOvershootMargin: Double = 0.6
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(seed: 4)
|
||||
for _ in 0..<20 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let s: Double = out[0][i]
|
||||
#expect(s.isFinite, "sample \(i) is not finite: \(s)")
|
||||
#expect(s >= -(1.0 + catmullOvershootMargin) && s <= (1.0 + catmullOvershootMargin),
|
||||
"sample \(i) out of reasonable range: \(s)")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Differs from Gendy1 (cubic vs linear interpolation)
|
||||
|
||||
@Test func differsByInterpolationFromGendy1() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// Using same seed: both generators start with same breakpoint amplitudes,
|
||||
// but differ because Gendy2 uses cubic interpolation.
|
||||
let gen1: Gendy1.Audio = Gendy1.Audio(seed: 77)
|
||||
let gen2: Gendy2.Audio = Gendy2.Audio(seed: 77)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// The two generators differ in interpolation, so their output should differ.
|
||||
// (Both start from same RNG seed but Gendy2 also uses initCPs differently
|
||||
// due to different internal structures — outputs will differ regardless.)
|
||||
// Check that we get finite, non-identical output.
|
||||
let allFinite1: Bool = out1.allSatisfy { $0.isFinite }
|
||||
let allFinite2: Bool = out2.allSatisfy { $0.isFinite }
|
||||
#expect(allFinite1)
|
||||
#expect(allFinite2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - mulAdd scales output
|
||||
|
||||
@Test func mulAddScalesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let genPlain: Gendy2.Audio = Gendy2.Audio(seed: 42)
|
||||
let genMulAdd: Gendy2.Audio = Gendy2.Audio(mul: 2.0, add: 1.0, seed: 42)
|
||||
let plain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let scaled: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = plain[i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[i] - expected) < 1e-9, "sample \(i): expected \(expected), got \(scaled[i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Integration
|
||||
|
||||
@Test func integrationRunsWithoutCrash() throws {
|
||||
final class Gendy2Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy2.Audio = Gendy2.Audio(minfreq: 80.0, maxfreq: 300.0, initCPs: 8)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy2Synth = Gendy2Synth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
@Test func controlRateIsControl() {
|
||||
let gen: Gendy2.Control = Gendy2.Control()
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
@Test func controlOutputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Control = Gendy2.Control(seed: 10)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlFanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Control = Gendy2.Control(seed: 11)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlStateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Control = Gendy2.Control(seed: 12)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlProducesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy2.Control = Gendy2.Control(seed: 13)
|
||||
var nonZeroFound: Bool = false
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
if out[0].prefix(64).contains(where: { $0 != 0.0 }) { nonZeroFound = true }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(nonZeroFound)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlAmpscaleZeroProducesFiniteOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// ampscale=0: amplitude breakpoints cannot drift; Catmull-Rom may overshoot slightly.
|
||||
let catmullOvershootMargin: Double = 0.6
|
||||
let gen: Gendy2.Control = Gendy2.Control(ampscale: 0.0, durscale: 0.0, seed: 14)
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let s: Double = out[0][i]
|
||||
#expect(s.isFinite, "sample \(i) is not finite: \(s)")
|
||||
#expect(s >= -(1.0 + catmullOvershootMargin) && s <= (1.0 + catmullOvershootMargin),
|
||||
"sample \(i) out of expected range: \(s)")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlIntegrationRunsWithoutCrash() throws {
|
||||
final class Gendy2ControlSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy2.Control = Gendy2.Control(minfreq: 0.5, maxfreq: 4.0, initCPs: 6)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy2ControlSynth = Gendy2ControlSynth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic Control output with fixed seed
|
||||
|
||||
@Test func controlDeterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy2.Control = Gendy2.Control(seed: 99)
|
||||
let gen2: Gendy2.Control = Gendy2.Control(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlDifferentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy2.Control = Gendy2.Control(seed: 100)
|
||||
let gen2: Gendy2.Control = Gendy2.Control(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
// Gendy3Tests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Gendy3")
|
||||
struct Gendy3Tests {
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gen: Gendy3.Audio = Gendy3.Audio()
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(seed: 1)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(seed: 2)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(seed: 3)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Output stays in [-1, 1] with mul=1
|
||||
|
||||
@Test func outputStaysInRange() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(seed: 4)
|
||||
for _ in 0..<20 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out[0][i] >= -1.0 && out[0][i] <= 1.0,
|
||||
"sample \(i) out of [-1,1]: \(out[0][i])")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Non-silent output
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(seed: 5)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let nonZero: Bool = out[0].prefix(64).contains { $0 != 0.0 }
|
||||
#expect(nonZero)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic output with fixed seed
|
||||
|
||||
@Test func deterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy3.Audio = Gendy3.Audio(seed: 99)
|
||||
let gen2: Gendy3.Audio = Gendy3.Audio(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Different seeds produce different output
|
||||
|
||||
@Test func differentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy3.Audio = Gendy3.Audio(seed: 100)
|
||||
let gen2: Gendy3.Audio = Gendy3.Audio(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - ampscale=0 produces periodically repeating waveform shape
|
||||
|
||||
@Test func ampScaleZeroProducesStableAmplitudes() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// With ampscale=0, amplitudes never drift — waveform shape is fixed.
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(ampscale: 0.0, seed: 8)
|
||||
var allInRange: Bool = true
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
if out[0][i] < -1.0 || out[0][i] > 1.0 { allInRange = false }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allInRange)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Different freq produces different rhythm
|
||||
|
||||
@Test func differentFreqProducesDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 256)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy3.Audio = Gendy3.Audio(freq: 220.0, seed: 33)
|
||||
let gen2: Gendy3.Audio = Gendy3.Audio(freq: 880.0, seed: 33)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 256)[0].prefix(256))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 256)[0].prefix(256))
|
||||
// Different frequencies → different segment lengths → different output.
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - mulAdd scales output
|
||||
|
||||
@Test func mulAddScalesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let genPlain: Gendy3.Audio = Gendy3.Audio(seed: 42)
|
||||
let genMulAdd: Gendy3.Audio = Gendy3.Audio(mul: 2.0, add: 1.0, seed: 42)
|
||||
let plain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let scaled: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = plain[i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[i] - expected) < 1e-9, "sample \(i): expected \(expected), got \(scaled[i])")
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Integration
|
||||
|
||||
@Test func integrationRunsWithoutCrash() throws {
|
||||
final class Gendy3Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy3.Audio = Gendy3.Audio(freq: 330.0, ampscale: 0.3, initCPs: 8)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy3Synth = Gendy3Synth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
@Test func controlRateIsControl() {
|
||||
let gen: Gendy3.Control = Gendy3.Control()
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
@Test func controlOutputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Control = Gendy3.Control(seed: 10)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlFanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Control = Gendy3.Control(seed: 11)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlStateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Control = Gendy3.Control(seed: 12)
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block2 != block1a)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlProducesNonSilentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Control = Gendy3.Control(seed: 13)
|
||||
var nonZeroFound: Bool = false
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
if out[0].prefix(64).contains(where: { $0 != 0.0 }) { nonZeroFound = true }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(nonZeroFound)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlAmpscaleZeroProducesStableAmplitudes() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Gendy3.Control = Gendy3.Control(ampscale: 0.0, seed: 14)
|
||||
for _ in 0..<10 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out[0][i] >= -1.0 && out[0][i] <= 1.0,
|
||||
"sample \(i) out of [-1,1]: \(out[0][i])")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlIntegrationRunsWithoutCrash() throws {
|
||||
final class Gendy3ControlSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: Gendy3.Control = Gendy3.Control(freq: 2.0, ampscale: 0.3, initCPs: 6)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: gen * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: Gendy3ControlSynth = Gendy3ControlSynth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic Control output with fixed seed
|
||||
|
||||
@Test func controlDeterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy3.Control = Gendy3.Control(seed: 99)
|
||||
let gen2: Gendy3.Control = Gendy3.Control(seed: 99)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func controlDifferentSeedsProduceDifferentOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen1: Gendy3.Control = Gendy3.Control(seed: 100)
|
||||
let gen2: Gendy3.Control = Gendy3.Control(seed: 200)
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 != out2)
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// GeneratorArrayTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("GeneratorArray")
|
||||
struct GeneratorArrayTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph {
|
||||
makeSynthGraph(engine: engine)
|
||||
}
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test("expand factory builds N-row GeneratorArray")
|
||||
func expandFactory() {
|
||||
let arr: GeneratorArray = expand([1.0, 2.0, 3.0]) { ConstantAudioGen($0.floatValue(graph: makeSynthGraph(engine: engine))) }
|
||||
#expect(arr.outputChannelCount == 3)
|
||||
}
|
||||
|
||||
@Test("GeneratorArray * scalar scales every channel")
|
||||
func arrayTimesScalar() {
|
||||
let count: Int = 8
|
||||
let arr: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0),
|
||||
ConstantAudioGen(3.0)
|
||||
])
|
||||
let scaled: GeneratorArray = arr * (10.0 as Double)
|
||||
#expect(scaled.outputChannelCount == 3)
|
||||
let samples: [[Double]] = scaled.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 10.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 20.0 })
|
||||
#expect(samples[2].prefix(count).allSatisfy { $0 == 30.0 })
|
||||
}
|
||||
|
||||
@Test("scalar * GeneratorArray scales every channel")
|
||||
func scalarTimesArray() {
|
||||
let count: Int = 8
|
||||
let arr: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0)
|
||||
])
|
||||
let scaled: GeneratorArray = (5.0 as Double) * arr
|
||||
let samples: [[Double]] = scaled.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 5.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 10.0 })
|
||||
}
|
||||
|
||||
@Test("GeneratorArray + GeneratorArray is element-wise")
|
||||
func arrayPlusArrayElementWise() {
|
||||
let count: Int = 8
|
||||
let a: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0)
|
||||
])
|
||||
let b: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(10.0),
|
||||
ConstantAudioGen(20.0)
|
||||
])
|
||||
let sum: GeneratorArray = a + b
|
||||
let samples: [[Double]] = sum.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 11.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 22.0 })
|
||||
}
|
||||
|
||||
@Test("GeneratorArray subscript returns ChannelSelect for that channel")
|
||||
func subscriptChannel() {
|
||||
let count: Int = 8
|
||||
let arr: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0),
|
||||
ConstantAudioGen(3.0)
|
||||
])
|
||||
let mid: ChannelSelect.Audio = arr[1]
|
||||
let samples: [[Double]] = mid.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 2.0 })
|
||||
}
|
||||
|
||||
@Test("outputChannelCount matches contained generators")
|
||||
func outputChannelCountMatchesGenerators() {
|
||||
let arr: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0),
|
||||
ConstantAudioGen(3.0),
|
||||
ConstantAudioGen(4.0)
|
||||
])
|
||||
#expect(arr.outputChannelCount == 4)
|
||||
}
|
||||
|
||||
@Test("GeneratorArray * mono generator passes (other operand is 1-channel)")
|
||||
func arrayTimesMonoGenerator() {
|
||||
let count: Int = 8
|
||||
let arr: GeneratorArray = GeneratorArray([
|
||||
ConstantAudioGen(1.0),
|
||||
ConstantAudioGen(2.0)
|
||||
])
|
||||
let mono: ConstantAudioGen = ConstantAudioGen(10.0)
|
||||
let scaled: GeneratorArray = arr * mono
|
||||
#expect(scaled.outputChannelCount == 2)
|
||||
let samples: [[Double]] = scaled.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 10.0 })
|
||||
#expect(samples[1].prefix(count).allSatisfy { $0 == 20.0 })
|
||||
}
|
||||
|
||||
// GeneratorArray × multi-row-generator (e.g. `arr * Pan2(...)`) is intentionally rejected
|
||||
// at construction time via `precondition` in `_generatorArrayCheckOtherOperandMono` —
|
||||
// GeneratorArray reads only row 0 of each inner generator, so multi-row operands would
|
||||
// silently drop channels 1..N-1. The trap is documented but not testable via Swift Testing
|
||||
// (`precondition` terminates the process rather than throwing). The construction
|
||||
// `arr * Pan2(input: ...)` would trap with a message naming the rhs channel count and
|
||||
// pointing the caller at `ChannelSelect` / per-channel composition.
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// GeneratorInputProviderTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("GeneratorInputProvider")
|
||||
struct GeneratorInputProviderTests {
|
||||
|
||||
@Test("float literal yields scalar Double")
|
||||
func floatLiteral() {
|
||||
let provider: GeneratorInputProvider = 0.5
|
||||
let value: any ValidGeneratorInput = provider.make()
|
||||
#expect((value as? Double) == 0.5)
|
||||
}
|
||||
|
||||
@Test("integer literal yields Double-lifted scalar")
|
||||
func integerLiteral() {
|
||||
let provider: GeneratorInputProvider = 3
|
||||
let value: any ValidGeneratorInput = provider.make()
|
||||
#expect((value as? Double) == 3.0)
|
||||
}
|
||||
|
||||
@Test("scalar provider returns same value on repeat calls")
|
||||
func scalarStable() {
|
||||
let provider: GeneratorInputProvider = 1.25
|
||||
let a: any ValidGeneratorInput = provider.make()
|
||||
let b: any ValidGeneratorInput = provider.make()
|
||||
#expect((a as? Double) == 1.25)
|
||||
#expect((b as? Double) == 1.25)
|
||||
}
|
||||
|
||||
@Test("closure init returns whatever the body builds")
|
||||
func closureBody() {
|
||||
let provider: GeneratorInputProvider = GeneratorInputProvider { 42.0 }
|
||||
let value: any ValidGeneratorInput = provider.make()
|
||||
#expect((value as? Double) == 42.0)
|
||||
}
|
||||
|
||||
@Test("closure init yields distinct Generator instances per call")
|
||||
func closureFreshGenerator() {
|
||||
let provider: GeneratorInputProvider = GeneratorInputProvider {
|
||||
ConstantAudioGen(0.0)
|
||||
}
|
||||
let a: any ValidGeneratorInput = provider.make()
|
||||
let b: any ValidGeneratorInput = provider.make()
|
||||
guard let aGen: any Generator = a as? any Generator,
|
||||
let bGen: any Generator = b as? any Generator else {
|
||||
Issue.record("expected Generator from provider")
|
||||
return
|
||||
}
|
||||
#expect(ObjectIdentifier(aGen) != ObjectIdentifier(bGen))
|
||||
}
|
||||
|
||||
@Test("provider survives capture in a detached @Sendable Task")
|
||||
func sendableAcrossTask() async {
|
||||
let provider: GeneratorInputProvider = 7.5
|
||||
let value: Double = await Task.detached { () -> Double in
|
||||
let v: any ValidGeneratorInput = provider.make()
|
||||
return (v as? Double) ?? .nan
|
||||
}.value
|
||||
#expect(value == 7.5)
|
||||
}
|
||||
|
||||
// MARK: - Phase 170 — provider as first-class ValidGeneratorInput
|
||||
|
||||
@Test("ValidGeneratorInput._resolvedInput default returns self")
|
||||
func defaultResolveIsIdentity() {
|
||||
let scalar: any ValidGeneratorInput = 3.14
|
||||
let resolved: any ValidGeneratorInput = scalar._resolvedInput()
|
||||
#expect((resolved as? Double) == 3.14)
|
||||
}
|
||||
|
||||
@Test("GeneratorInputProvider._resolvedInput invokes make")
|
||||
func providerResolveInvokesMake() {
|
||||
let provider: GeneratorInputProvider = 11.5
|
||||
let resolved: any ValidGeneratorInput = provider._resolvedInput()
|
||||
#expect((resolved as? Double) == 11.5)
|
||||
// Resolved value is not itself a provider — would re-trap if it were.
|
||||
#expect((resolved as? GeneratorInputProvider) == nil)
|
||||
}
|
||||
|
||||
@Test("scalar provider passed to AmbiEncoder1 azimuth slot resolves transparently")
|
||||
func providerInAmbiEncoderAzimuthSlot() {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
let providerEncoder: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantAudioGen(1.0),
|
||||
azimuth: GeneratorInputProvider { 0.0 }
|
||||
)
|
||||
let scalarEncoder: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantAudioGen(1.0),
|
||||
azimuth: 0.0
|
||||
)
|
||||
let graphA: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let graphB: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let outA: [[Double]] = providerEncoder._computeSamples(graph: graphA, count: 8)
|
||||
let outB: [[Double]] = scalarEncoder._computeSamples(graph: graphB, count: 8)
|
||||
#expect(outA.count == outB.count)
|
||||
#expect(outA.count == 4)
|
||||
for ch: Int in 0..<outA.count {
|
||||
#expect(outA[ch] == outB[ch])
|
||||
}
|
||||
}
|
||||
|
||||
@Test("provider passed as mul resolves via MulAddSpec at helper boundary")
|
||||
func providerInMulAddSpecMul() {
|
||||
let providerSpec: MulAddSpec = MulAddSpec(
|
||||
mul: GeneratorInputProvider { 2.0 },
|
||||
add: 0.0
|
||||
)
|
||||
let scalarSpec: MulAddSpec = MulAddSpec(mul: 2.0, add: 0.0)
|
||||
// Both specs should be non-identity (mul != 1.0) and the mul scalar
|
||||
// should match. mulIsGenerator stays false because the provider
|
||||
// resolved to a Double.
|
||||
#expect(providerSpec.isIdentity == false)
|
||||
#expect(scalarSpec.isIdentity == false)
|
||||
#expect(providerSpec.mulIsGenerator == false)
|
||||
#expect((providerSpec.mulInput as? Double) == 2.0)
|
||||
#expect((scalarSpec.mulInput as? Double) == 2.0)
|
||||
}
|
||||
|
||||
@Test("provider yielding a Generator passes through to Generator-typed storage")
|
||||
func providerYieldingGeneratorResolvesAsGenerator() {
|
||||
let encoder: AmbiEncoder1 = AmbiEncoder1(
|
||||
input: ConstantAudioGen(1.0),
|
||||
azimuth: GeneratorInputProvider { ConstantAudioGen(0.5) }
|
||||
)
|
||||
// After resolution, azimuth slot holds a Generator (not a Double, not
|
||||
// a provider). The is-generator classification at init time must
|
||||
// reflect that.
|
||||
let mirror: Mirror = Mirror(reflecting: encoder)
|
||||
let isGen: Bool? = mirror.descendant("_azimuthIsGenerator") as? Bool
|
||||
#expect(isGen == true)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// GeneratorProtocolTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// File-scope helpers used across generator tests
|
||||
|
||||
final class ConstantAudioGen: GeneratorBase, AudioGenerator {
|
||||
let value: Double
|
||||
init(_ v: Double) { value = v }
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
[[Double](repeating: value, count: count)]
|
||||
}
|
||||
func floatValue(graph: SynthGraph) -> Double { value }
|
||||
}
|
||||
|
||||
/// A ControlGenerator with a fixed target value, used to test the default
|
||||
/// interpolated-ramp behaviour.
|
||||
final class ConstantControlGen: GeneratorBase, ControlGenerator {
|
||||
let value: Double
|
||||
/// Required by ControlGenerator — ramp start for the next block. Starts at 0.
|
||||
var previousOutputValue: Double = 0.0
|
||||
|
||||
init(_ v: Double) {
|
||||
value = v
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
func floatValue(graph: SynthGraph) -> Double { value }
|
||||
// _computeSamples uses the default ControlGenerator extension (interpolated ramp).
|
||||
}
|
||||
|
||||
/// A ControlGenerator whose target can be changed between blocks, used to test that
|
||||
/// previousOutputValue carries the ramp state correctly across block boundaries.
|
||||
final class MutableControlGen: GeneratorBase, ControlGenerator {
|
||||
var target: Double
|
||||
var previousOutputValue: Double = 0.0
|
||||
init(_ v: Double) {
|
||||
target = v
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
func floatValue(graph: SynthGraph) -> Double { target }
|
||||
}
|
||||
|
||||
@Suite("ProcessingRate")
|
||||
struct ProcessingRateTests {
|
||||
@Test func audioRateExists() {
|
||||
let r: ProcessingRate = .audio
|
||||
#expect(r == .audio)
|
||||
}
|
||||
|
||||
@Test func controlRateExists() {
|
||||
let r: ProcessingRate = .control
|
||||
#expect(r == .control)
|
||||
}
|
||||
|
||||
@Test func spectralRateExists() {
|
||||
let r: ProcessingRate = .spectral
|
||||
#expect(r == .spectral)
|
||||
}
|
||||
|
||||
@Test func demandRateExists() {
|
||||
let r: ProcessingRate = .demand
|
||||
#expect(r == .demand)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Generator protocol")
|
||||
struct GeneratorProtocolTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
@Test func audioGeneratorDefaultRateIsAudio() {
|
||||
let gen: ConstantAudioGen = ConstantAudioGen(1.0)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func controlGeneratorDefaultRateIsControl() {
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
@Test func generatorConformsToValidGeneratorInput() throws {
|
||||
let gen: ConstantAudioGen = ConstantAudioGen(2.5)
|
||||
let input: any ValidGeneratorInput = gen
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
#expect(input.floatValue(graph: graph) == 2.5)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - ControlGenerator interpolation
|
||||
|
||||
@Test func controlGeneratorPreviousValueInitiallyZero() {
|
||||
// All ControlGenerator conformers must initialise previousOutputValue to 0.
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
#expect(gen.previousOutputValue == 0.0)
|
||||
}
|
||||
|
||||
@Test func controlGeneratorCalculatedSamplesRampsToTarget() {
|
||||
// previousOutputValue=0, target=1, count=4 → step = 0.25
|
||||
// samples: [0.25, 0.50, 0.75, 1.00] — reaches target at last sample
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(samples[0] == [0.25, 0.5, 0.75, 1.0])
|
||||
}
|
||||
|
||||
@Test func controlGeneratorReachesTargetAtLastSample() {
|
||||
let target: Double = 2.5
|
||||
let gen: ConstantControlGen = ConstantControlGen(target)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 8)
|
||||
#expect(samples[0].last == target)
|
||||
}
|
||||
|
||||
@Test func controlGeneratorFirstSampleIsOneStepAbovePrevious() {
|
||||
// first sample = prev + step = prev + (target - prev) / count
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
let count: Int = 4
|
||||
let step: Double = (1.0 - 0.0) / Double(count)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0][0] == step)
|
||||
}
|
||||
|
||||
@Test func controlGeneratorUpdatesPreviousOutputValueAfterBlock() {
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(gen.previousOutputValue == 1.0)
|
||||
}
|
||||
|
||||
@Test func controlGeneratorSecondBlockStartsFromPreviousTarget() {
|
||||
// Block 1: 0→1 → [0.25, 0.50, 0.75, 1.00], previousOutputValue = 1.0
|
||||
// Block 2: 1→1 → [1.00, 1.00, 1.00, 1.00] (step = 0, constant at target)
|
||||
let gen: ConstantControlGen = ConstantControlGen(1.0)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
let block2: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(block2[0] == [1.0, 1.0, 1.0, 1.0])
|
||||
}
|
||||
|
||||
@Test func controlGeneratorRampsDownWhenTargetDecreases() {
|
||||
// Block 1: 0→2 → previousOutputValue = 2
|
||||
// Block 2: 2→0 → [1.5, 1.0, 0.5, 0.0]
|
||||
let gen: MutableControlGen = MutableControlGen(2.0)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
gen.target = 0.0
|
||||
let block2: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(block2[0] == [1.5, 1.0, 0.5, 0.0])
|
||||
}
|
||||
|
||||
@Test func controlGeneratorRampCarriesAcrossConsecutiveBlocks() {
|
||||
// Two-block ramp: 0→1 then 1→3
|
||||
// Block 1: step=(1-0)/4=0.25 → [0.25, 0.50, 0.75, 1.00]
|
||||
// Block 2: step=(3-1)/4=0.50 → [1.50, 2.00, 2.50, 3.00]
|
||||
let gen: MutableControlGen = MutableControlGen(1.0)
|
||||
let block1: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
advanceBlock(engine)
|
||||
gen.target = 3.0
|
||||
let block2: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(block1[0] == [0.25, 0.5, 0.75, 1.0])
|
||||
#expect(block2[0] == [1.5, 2.0, 2.5, 3.0])
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
||||
// GroupSemanticsTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test fixture: gate-capable synthesizer
|
||||
|
||||
/// Synthesizer that tracks gate-zero calls (simulates EnvelopeGen release).
|
||||
final class GatedSynth: Synthesizer {
|
||||
var releaseCallCount: Int = 0
|
||||
var freeCallCount: Int = 0
|
||||
|
||||
func build() {}
|
||||
func evaluate(graph: SynthGraph, count: Int) {}
|
||||
|
||||
func release(engine: SynthesisEngine) throws {
|
||||
releaseCallCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
/// Synthesizer with no gate — release() throws noGate (uses Synthesizer default).
|
||||
final class NoGateSynth: Synthesizer {
|
||||
var freeWasCalled: Bool = false
|
||||
func build() {}
|
||||
func evaluate(graph: SynthGraph, count: Int) {}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
@Suite("Group Semantics")
|
||||
struct GroupSemanticsTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
|
||||
// MARK: - count Atomic
|
||||
|
||||
@Test func countStartsAtZero() throws {
|
||||
let group: Group = Group()
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func countIncreasesOnAddToTail() throws {
|
||||
let group: Group = Group()
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
#expect(group.count == 2)
|
||||
}
|
||||
|
||||
@Test func countDecreasesOnRemove() throws {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.remove(node)
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
// MARK: - addBefore / addAfter
|
||||
|
||||
@Test func addBeforeInsertsBeforeTarget() throws {
|
||||
let group: Group = Group()
|
||||
let a: TrackingNode = TrackingNode()
|
||||
let b: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(a))
|
||||
// insert b before a
|
||||
let nodeB: PreparedNode = PreparedNode(b)
|
||||
let inserted: Bool = group.addBefore(nodeB, target: a)
|
||||
#expect(inserted == true)
|
||||
#expect(group.count == 2)
|
||||
// b should be at head (evaluates first)
|
||||
var callOrder: [ObjectIdentifier] = []
|
||||
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
|
||||
// Swap evaluate to capture order: re-implement via evaluate call
|
||||
// Verify by checking head pointer directly
|
||||
#expect(group.head?.synth === b)
|
||||
}
|
||||
|
||||
@Test func addAfterInsertsAfterTarget() throws {
|
||||
let group: Group = Group()
|
||||
let a: TrackingNode = TrackingNode()
|
||||
let b: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(a))
|
||||
let nodeB: PreparedNode = PreparedNode(b)
|
||||
let inserted: Bool = group.addAfter(nodeB, target: a)
|
||||
#expect(inserted == true)
|
||||
#expect(group.count == 2)
|
||||
// b should be at tail
|
||||
#expect(group.tail?.synth === b)
|
||||
}
|
||||
|
||||
@Test func addBeforeReturnsFalseIfTargetNotFound() throws {
|
||||
let group: Group = Group()
|
||||
let outsider: TrackingNode = TrackingNode()
|
||||
let newNode: PreparedNode = PreparedNode(TrackingNode())
|
||||
let result: Bool = group.addBefore(newNode, target: outsider)
|
||||
#expect(result == false)
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func addAfterReturnsFalseIfTargetNotFound() throws {
|
||||
let group: Group = Group()
|
||||
let outsider: TrackingNode = TrackingNode()
|
||||
let newNode: PreparedNode = PreparedNode(TrackingNode())
|
||||
let result: Bool = group.addAfter(newNode, target: outsider)
|
||||
#expect(result == false)
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func addBeforeSearchesNestedGroup() throws {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
let target: TrackingNode = TrackingNode()
|
||||
outer.addToTail(PreparedNode(inner))
|
||||
inner.addToTail(PreparedNode(target))
|
||||
|
||||
let newNode: PreparedNode = PreparedNode(TrackingNode())
|
||||
let result: Bool = outer.addBefore(newNode, target: target)
|
||||
#expect(result == true)
|
||||
// inner now has 2 children
|
||||
#expect(inner.count == 2)
|
||||
#expect(inner.head?.synth === newNode.synth)
|
||||
}
|
||||
|
||||
@Test func addAfterSearchesNestedGroup() throws {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
let target: TrackingNode = TrackingNode()
|
||||
outer.addToTail(PreparedNode(inner))
|
||||
inner.addToTail(PreparedNode(target))
|
||||
|
||||
let newNode: PreparedNode = PreparedNode(TrackingNode())
|
||||
let result: Bool = outer.addAfter(newNode, target: target)
|
||||
#expect(result == true)
|
||||
#expect(inner.count == 2)
|
||||
#expect(inner.tail?.synth === newNode.synth)
|
||||
}
|
||||
|
||||
// MARK: - NodePosition via engine
|
||||
|
||||
@Test func engineAddPositionHeadInsertsAtHead() throws {
|
||||
let group: Group = Group()
|
||||
try engine.add(group)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
let a: TrackingNode = TrackingNode()
|
||||
let b: TrackingNode = TrackingNode()
|
||||
try engine.add(a, position: .tail(of: group))
|
||||
try engine.add(b, position: .head(of: group))
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// b at head, a at tail
|
||||
#expect(group.head?.synth === b)
|
||||
#expect(group.tail?.synth === a)
|
||||
}
|
||||
|
||||
@Test func engineAddPositionAfterInsertsAfterTarget() throws {
|
||||
let group: Group = Group()
|
||||
try engine.add(group)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
let a: TrackingNode = TrackingNode()
|
||||
let b: TrackingNode = TrackingNode()
|
||||
try engine.add(a, position: .tail(of: group))
|
||||
engine.processBlock(inputSamples: []) // ensure `a` is in tree before `.after(a)`
|
||||
|
||||
try engine.add(b, position: .after(a))
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
#expect(group.tail?.synth === b)
|
||||
}
|
||||
|
||||
@Test func engineAddPositionBeforeFallsBackToMainGroupHeadWhenMissing() throws {
|
||||
let outsider: TrackingNode = TrackingNode()
|
||||
let newSynth: TrackingNode = TrackingNode()
|
||||
try engine.add(newSynth, position: .before(outsider))
|
||||
engine.processBlock(inputSamples: [])
|
||||
// Target not found → falls back to mainGroup head (not rootGroup tail).
|
||||
#expect(engine.mainGroup.contains(newSynth))
|
||||
}
|
||||
|
||||
// MARK: - Synthesizer.release default
|
||||
|
||||
@Test func defaultReleaseThrowsNoGate() throws {
|
||||
let synth: TrackingNode = TrackingNode()
|
||||
var threw: Bool = false
|
||||
do {
|
||||
try synth.release(engine: engine)
|
||||
} catch SynthesizerError.noGate {
|
||||
threw = true
|
||||
} catch {}
|
||||
#expect(threw == true)
|
||||
}
|
||||
|
||||
// MARK: - Group.release cascade
|
||||
|
||||
@Test func groupReleaseCascadesGateToGatedChildren() throws {
|
||||
let group: Group = Group()
|
||||
let gated: GatedSynth = GatedSynth()
|
||||
group.addToTail(PreparedNode(gated))
|
||||
|
||||
group.release(engine: engine)
|
||||
|
||||
#expect(gated.releaseCallCount == 1)
|
||||
}
|
||||
|
||||
@Test func groupReleaseNonGatedChildRemovedFromTreeAfterProcessBlock() throws {
|
||||
let group: Group = Group()
|
||||
let noGate: TrackingNode = TrackingNode() // default release throws noGate → group calls free
|
||||
try engine.add(group)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// Manually add noGate to group's linked list so it appears in the tree
|
||||
group.addToTail(PreparedNode(noGate))
|
||||
#expect(group.count == 1)
|
||||
|
||||
// release: noGate throws noGate → engine.remove(noGate) event posted
|
||||
group.release(engine: engine)
|
||||
|
||||
// Process: applies remove event for noGate
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func groupReleaseIsIdempotent() throws {
|
||||
let group: Group = Group()
|
||||
let gated: GatedSynth = GatedSynth()
|
||||
group.addToTail(PreparedNode(gated))
|
||||
|
||||
group.release(engine: engine)
|
||||
group.release(engine: engine) // second call should be no-op
|
||||
|
||||
#expect(gated.releaseCallCount == 1)
|
||||
}
|
||||
|
||||
// MARK: - Group.free
|
||||
|
||||
@Test func groupFreePostsEventAndRemovesFromTree() throws {
|
||||
let group: Group = Group()
|
||||
try engine.add(group)
|
||||
engine.processBlock(inputSamples: [])
|
||||
// engine.add now places into mainGroup, not rootGroup directly.
|
||||
#expect(engine.mainGroup.contains(group))
|
||||
|
||||
group.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
#expect(!engine.mainGroup.contains(group))
|
||||
}
|
||||
|
||||
@Test func groupFreeRemovesAllChildren() throws {
|
||||
let group: Group = Group()
|
||||
let child: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(child))
|
||||
|
||||
try engine.add(group)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
group.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
// Group is gone from mainGroup (where engine.add now places it)
|
||||
#expect(!engine.mainGroup.contains(group))
|
||||
// Group is now empty (children drained by applyEvent)
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
// MARK: - removeRecursive
|
||||
|
||||
@Test func removeRecursiveFindsNestedSynth() throws {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
let target: TrackingNode = TrackingNode()
|
||||
outer.addToTail(PreparedNode(inner))
|
||||
inner.addToTail(PreparedNode(target))
|
||||
|
||||
let removed: PreparedNode? = outer.removeRecursive(target)
|
||||
#expect(removed != nil)
|
||||
#expect(inner.count == 0)
|
||||
#expect(outer.count == 1) // inner still in outer
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// GroupTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// Group tests operate on the Group directly (internal API via @testable import).
|
||||
// A minimal engine is used to construct SynthGraph — it does not need to be started.
|
||||
//
|
||||
// addToTail / addToHead accept PreparedNode (pre-allocated off-RT), so tests wrap
|
||||
// Synthesizer values in PreparedNode(_:) at the call site — mirroring what
|
||||
// SynthesisEngine.schedule does on the main thread.
|
||||
|
||||
@Suite("Group")
|
||||
struct GroupTests {
|
||||
|
||||
// Shared engine for SynthGraph construction (no audio I/O needed)
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
|
||||
var graph: SynthGraph { SynthGraph(engine: engine, busOffset: 0) }
|
||||
|
||||
// MARK: - Empty group
|
||||
|
||||
@Test func emptyGroupHasCountZero() {
|
||||
let group: Group = Group()
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func emptyGroupIsEmpty() {
|
||||
let group: Group = Group()
|
||||
#expect(group.isEmpty == true)
|
||||
}
|
||||
|
||||
@Test func emptyGroupEvaluatesSilently() {
|
||||
// Evaluating an empty group must not crash and must leave buses untouched.
|
||||
let group: Group = Group()
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
// No assertion needed beyond "did not crash"
|
||||
}
|
||||
|
||||
// MARK: - addToTail
|
||||
|
||||
@Test func addToTailIncrementsCount() {
|
||||
let group: Group = Group()
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
#expect(group.count == 1)
|
||||
}
|
||||
|
||||
@Test func addToTailMultipleIncrementsCount() {
|
||||
let group: Group = Group()
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
#expect(group.count == 3)
|
||||
}
|
||||
|
||||
@Test func addToTailMakesGroupNonEmpty() {
|
||||
let group: Group = Group()
|
||||
group.addToTail(PreparedNode(TrackingNode()))
|
||||
#expect(group.isEmpty == false)
|
||||
}
|
||||
|
||||
@Test func addToTailOrderIsPreserved() {
|
||||
// Children must be evaluated in tail-insertion order (FIFO).
|
||||
let group: Group = Group()
|
||||
var callOrder: [Int] = []
|
||||
|
||||
let nodeA: TrackingNode = TrackingNode()
|
||||
let nodeB: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeA))
|
||||
group.addToTail(PreparedNode(nodeB))
|
||||
|
||||
// We verify ordering by evaluating and checking call counts
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
#expect(nodeA.evaluateCallCount == 1)
|
||||
#expect(nodeB.evaluateCallCount == 1)
|
||||
_ = callOrder // suppress unused warning
|
||||
}
|
||||
|
||||
// MARK: - addToHead
|
||||
|
||||
@Test func addToHeadIncrementsCount() {
|
||||
let group: Group = Group()
|
||||
group.addToHead(PreparedNode(TrackingNode()))
|
||||
#expect(group.count == 1)
|
||||
}
|
||||
|
||||
@Test func addToHeadPlacesBeforeExistingTail() {
|
||||
// If nodeA is at tail and nodeB is added to head, nodeB evaluates first.
|
||||
let group: Group = Group()
|
||||
var order: [String] = []
|
||||
|
||||
let nodeFirst: TrackingNode = TrackingNode()
|
||||
let nodeLast: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeLast)) // added first, but will be pushed to tail
|
||||
group.addToHead(PreparedNode(nodeFirst)) // added second, but placed at head
|
||||
|
||||
// After first evaluate, both have count 1 — ordering tested via node identity
|
||||
// The head should be nodeFirst. We verify by checking contains and count.
|
||||
#expect(group.contains(nodeFirst))
|
||||
#expect(group.contains(nodeLast))
|
||||
#expect(group.count == 2)
|
||||
_ = order
|
||||
}
|
||||
|
||||
// MARK: - remove
|
||||
|
||||
@Test func removeDecreasesCount() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.remove(node)
|
||||
#expect(group.count == 0)
|
||||
}
|
||||
|
||||
@Test func removeReturnsTrueForMember() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
#expect(group.remove(node) != nil)
|
||||
}
|
||||
|
||||
@Test func removeReturnsFalseForNonMember() {
|
||||
let group: Group = Group()
|
||||
let outsider: TrackingNode = TrackingNode()
|
||||
#expect(group.remove(outsider) == nil)
|
||||
}
|
||||
|
||||
@Test func removeOnlyMemberLeavesGroupEmpty() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.remove(node)
|
||||
#expect(group.isEmpty == true)
|
||||
}
|
||||
|
||||
@Test func removeHeadPreservesOthers() {
|
||||
let group: Group = Group()
|
||||
let nodeA: TrackingNode = TrackingNode()
|
||||
let nodeB: TrackingNode = TrackingNode()
|
||||
let nodeC: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeA))
|
||||
group.addToTail(PreparedNode(nodeB))
|
||||
group.addToTail(PreparedNode(nodeC))
|
||||
group.remove(nodeA)
|
||||
#expect(group.count == 2)
|
||||
#expect(group.contains(nodeB))
|
||||
#expect(group.contains(nodeC))
|
||||
}
|
||||
|
||||
@Test func removeTailPreservesOthers() {
|
||||
let group: Group = Group()
|
||||
let nodeA: TrackingNode = TrackingNode()
|
||||
let nodeB: TrackingNode = TrackingNode()
|
||||
let nodeC: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeA))
|
||||
group.addToTail(PreparedNode(nodeB))
|
||||
group.addToTail(PreparedNode(nodeC))
|
||||
group.remove(nodeC)
|
||||
#expect(group.count == 2)
|
||||
#expect(group.contains(nodeA))
|
||||
#expect(group.contains(nodeB))
|
||||
}
|
||||
|
||||
@Test func removeMiddlePreservesHeadAndTail() {
|
||||
let group: Group = Group()
|
||||
let nodeA: TrackingNode = TrackingNode()
|
||||
let nodeB: TrackingNode = TrackingNode()
|
||||
let nodeC: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeA))
|
||||
group.addToTail(PreparedNode(nodeB))
|
||||
group.addToTail(PreparedNode(nodeC))
|
||||
group.remove(nodeB)
|
||||
#expect(group.count == 2)
|
||||
#expect(group.contains(nodeA))
|
||||
#expect(group.contains(nodeC))
|
||||
}
|
||||
|
||||
@Test func removedNodeNoLongerEvaluates() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.remove(node)
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
#expect(node.evaluateCallCount == 0)
|
||||
}
|
||||
|
||||
// MARK: - evaluate
|
||||
|
||||
@Test func evaluateCallsAllChildren() {
|
||||
let group: Group = Group()
|
||||
let nodeA: TrackingNode = TrackingNode()
|
||||
let nodeB: TrackingNode = TrackingNode()
|
||||
let nodeC: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(nodeA))
|
||||
group.addToTail(PreparedNode(nodeB))
|
||||
group.addToTail(PreparedNode(nodeC))
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
#expect(nodeA.evaluateCallCount == 1)
|
||||
#expect(nodeB.evaluateCallCount == 1)
|
||||
#expect(nodeC.evaluateCallCount == 1)
|
||||
}
|
||||
|
||||
@Test func evaluatePassesCountToChildren() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
let expectedCount: Int = 4
|
||||
group.evaluate(graph: graph, count: expectedCount)
|
||||
#expect(node.lastCount == expectedCount)
|
||||
}
|
||||
|
||||
@Test func evaluateCalledTwiceCallsChildrenTwice() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
group.evaluate(graph: graph, count: 8)
|
||||
#expect(node.evaluateCallCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - Nested groups
|
||||
|
||||
@Test func nestedGroupEvaluatesItsChildren() {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
inner.addToTail(PreparedNode(node))
|
||||
outer.addToTail(PreparedNode(inner))
|
||||
outer.evaluate(graph: graph, count: 8)
|
||||
#expect(node.evaluateCallCount == 1)
|
||||
}
|
||||
|
||||
@Test func nestedGroupCountReflectsOnlyDirectChildren() {
|
||||
let outer: Group = Group()
|
||||
let inner: Group = Group()
|
||||
inner.addToTail(PreparedNode(TrackingNode()))
|
||||
inner.addToTail(PreparedNode(TrackingNode()))
|
||||
outer.addToTail(PreparedNode(inner))
|
||||
// outer.count == 1 (inner is the only direct child)
|
||||
#expect(outer.count == 1)
|
||||
// inner.count == 2
|
||||
#expect(inner.count == 2)
|
||||
}
|
||||
|
||||
// MARK: - contains
|
||||
|
||||
@Test func containsReturnsTrueForDirectChild() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
#expect(group.contains(node) == true)
|
||||
}
|
||||
|
||||
@Test func containsReturnsFalseForNonChild() {
|
||||
let group: Group = Group()
|
||||
let outsider: TrackingNode = TrackingNode()
|
||||
#expect(group.contains(outsider) == false)
|
||||
}
|
||||
|
||||
@Test func containsReturnsFalseAfterRemove() {
|
||||
let group: Group = Group()
|
||||
let node: TrackingNode = TrackingNode()
|
||||
group.addToTail(PreparedNode(node))
|
||||
group.remove(node)
|
||||
#expect(group.contains(node) == false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// HalfbandDownsampler2xTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("HalfbandDownsampler2x")
|
||||
struct HalfbandDownsampler2xTests {
|
||||
|
||||
@Test("DC input becomes DC output (gain = 1.0)")
|
||||
func dcGainIsUnity() {
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
let warmupPairs: Int = HalfbandFIR.length
|
||||
var y: Double = 0.0
|
||||
for _ in 0..<warmupPairs {
|
||||
y = dn.process(1.0, 1.0)
|
||||
}
|
||||
for _ in 0..<64 {
|
||||
y = dn.process(1.0, 1.0)
|
||||
}
|
||||
#expect(abs(y - 1.0) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("Reset clears state to zero")
|
||||
func resetClearsState() {
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
for _ in 0..<HalfbandFIR.length {
|
||||
_ = dn.process(1.0, 1.0)
|
||||
}
|
||||
dn.reset()
|
||||
let y: Double = dn.process(0.0, 0.0)
|
||||
#expect(y == 0.0)
|
||||
}
|
||||
|
||||
@Test("Impulse on even upsampled phase hits only the center tap (0.5 at frame 5)")
|
||||
func impulseAtEvenPhaseHitsCenterTap() {
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
// x0 = 1 → impulse at upsampled index 0 (even phase). Even-phase
|
||||
// impulses are filtered only by odd-absolute-index taps, all of
|
||||
// which are zero in a halfband FIR except the center tap h[11] = 0.5.
|
||||
// Group delay 11 upsampled samples = 5 input pairs → output is 0.5
|
||||
// at decimated frame 5, zero elsewhere.
|
||||
var outs: [Double] = []
|
||||
outs.append(dn.process(1.0, 0.0))
|
||||
for _ in 0..<10 {
|
||||
outs.append(dn.process(0.0, 0.0))
|
||||
}
|
||||
#expect(abs(outs[5] - HalfbandFIR.centerCoef) < 1e-12)
|
||||
for i: Int in 0..<outs.count where i != 5 {
|
||||
#expect(outs[i] == 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Impulse on odd upsampled phase hits only even-absolute-index taps (folded ringing)")
|
||||
func impulseAtOddPhaseHitsFoldedTaps() {
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
// x1 = 1 → impulse at upsampled index 1 (odd phase). Odd-phase
|
||||
// impulses are filtered only by even-absolute-index taps. The
|
||||
// resulting decimated impulse response visits h[0], h[2], …, h[22]
|
||||
// in order. By symmetry these equal `foldedCoefs[i]` and
|
||||
// `foldedCoefs[foldedCount-1-i]` paired around frames 5 and 6.
|
||||
var outs: [Double] = []
|
||||
outs.append(dn.process(0.0, 1.0))
|
||||
for _ in 0..<14 {
|
||||
outs.append(dn.process(0.0, 0.0))
|
||||
}
|
||||
// Frames 0..5 walk through folded[0] → folded[5]; 6..11 mirror back.
|
||||
for i: Int in 0...5 {
|
||||
#expect(abs(outs[i] - HalfbandFIR.foldedCoefs[i]) < 1e-12)
|
||||
#expect(abs(outs[11 - i] - HalfbandFIR.foldedCoefs[i]) < 1e-12)
|
||||
}
|
||||
// Sum of the visible response = 2 · sumFolded = 2 · 0.25 = 0.5
|
||||
// (the even-absolute-index taps contribute exactly half of the
|
||||
// FIR's total DC gain of 1.0; the other half lives in the center tap,
|
||||
// which is invisible to odd-phase impulses).
|
||||
let sum: Double = outs.prefix(12).reduce(0.0, +)
|
||||
#expect(abs(sum - 0.5) < 1e-9)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// HalfbandFIRTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("HalfbandFIR coefficients")
|
||||
struct HalfbandFIRTests {
|
||||
|
||||
@Test("Length and counts are halfband Type-1 (4k+3) with k=5")
|
||||
func lengthAndCounts() {
|
||||
#expect(HalfbandFIR.length == 23)
|
||||
#expect(HalfbandFIR.foldedCount == 6)
|
||||
#expect(HalfbandFIR.groupDelayUpsampled == 11)
|
||||
#expect(HalfbandFIR.groupDelayInputRate == 5)
|
||||
}
|
||||
|
||||
@Test("Center tap held at exactly 0.5")
|
||||
func centerTapHeldAtOneHalf() {
|
||||
#expect(HalfbandFIR.centerCoef == 0.5)
|
||||
}
|
||||
|
||||
@Test("Folded coefficient table size matches foldedCount")
|
||||
func foldedTableSize() {
|
||||
#expect(HalfbandFIR.foldedCoefs.count == HalfbandFIR.foldedCount)
|
||||
}
|
||||
|
||||
@Test("Folded coefficients are normalised so total FIR DC gain = 1.0 exactly")
|
||||
func dcGainIsExactlyOne() {
|
||||
let sumOdd: Double = HalfbandFIR.foldedCoefs.reduce(0.0, +)
|
||||
let totalDCGain: Double = HalfbandFIR.centerCoef + 2.0 * sumOdd
|
||||
#expect(abs(totalDCGain - 1.0) < 1e-12)
|
||||
}
|
||||
|
||||
@Test("Folded coefficients alternate sign as expected for halfband sinc lowpass")
|
||||
func signsAlternate() {
|
||||
// Hamming-windowed sinc with cutoff π/2 has alternating-sign odd taps.
|
||||
// Folded ordering (i = 0 → ±11, i = 5 → ±1) → signs −, +, −, +, −, +.
|
||||
let signs: [Double] = HalfbandFIR.foldedCoefs.map {
|
||||
$0 > 0 ? 1.0 : ($0 < 0 ? -1.0 : 0.0)
|
||||
}
|
||||
#expect(signs == [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// HalfbandRoundTripTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Halfband oversampling round-trip")
|
||||
struct HalfbandRoundTripTests {
|
||||
|
||||
@Test("2× up → 2× down preserves DC at unity gain")
|
||||
func roundTripDC2x() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
var last: Double = 0.0
|
||||
for _ in 0..<128 {
|
||||
let (a, b) = up.process(1.0)
|
||||
last = dn.process(a, b)
|
||||
}
|
||||
#expect(abs(last - 1.0) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("2× up → 2× down preserves a low-frequency sine RMS within tight tolerance")
|
||||
func roundTripSineRMS2x() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
|
||||
let length: Int = 4096
|
||||
let warmup: Int = 128
|
||||
let normalisedFreq: Double = 1.0 / 32.0 // cycles per input sample, well below Fs/4
|
||||
let twoPi: Double = 2.0 * .pi
|
||||
|
||||
var inputs: [Double] = [Double](repeating: 0.0, count: length)
|
||||
var outputs: [Double] = [Double](repeating: 0.0, count: length)
|
||||
for n: Int in 0..<length {
|
||||
let x: Double = sin(twoPi * normalisedFreq * Double(n))
|
||||
inputs[n] = x
|
||||
let (a, b) = up.process(x)
|
||||
outputs[n] = dn.process(a, b)
|
||||
}
|
||||
let inputRMS: Double = rmsValue(Array(inputs[warmup..<length]))
|
||||
let outputRMS: Double = rmsValue(Array(outputs[warmup..<length]))
|
||||
// Tolerance allows for normal Hamming-window passband ripple of the
|
||||
// 23-tap halfband (≈ ±0.1 dB ≈ ±1.2 % at the working rate).
|
||||
#expect(abs(outputRMS / inputRMS - 1.0) < 1.5e-2)
|
||||
}
|
||||
|
||||
@Test("4× up → 4× down preserves DC at unity gain")
|
||||
func roundTripDC4x() {
|
||||
var up: HalfbandUpsampler4x = HalfbandUpsampler4x()
|
||||
var dn: HalfbandDownsampler4x = HalfbandDownsampler4x()
|
||||
var last: Double = 0.0
|
||||
for _ in 0..<256 {
|
||||
let (a, b, c, d) = up.process(1.0)
|
||||
last = dn.process(a, b, c, d)
|
||||
}
|
||||
#expect(abs(last - 1.0) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("4× up → 4× down preserves a low-frequency sine RMS within tight tolerance")
|
||||
func roundTripSineRMS4x() {
|
||||
var up: HalfbandUpsampler4x = HalfbandUpsampler4x()
|
||||
var dn: HalfbandDownsampler4x = HalfbandDownsampler4x()
|
||||
|
||||
let length: Int = 8192
|
||||
let warmup: Int = 256
|
||||
let normalisedFreq: Double = 1.0 / 64.0
|
||||
let twoPi: Double = 2.0 * .pi
|
||||
|
||||
var inputs: [Double] = [Double](repeating: 0.0, count: length)
|
||||
var outputs: [Double] = [Double](repeating: 0.0, count: length)
|
||||
for n: Int in 0..<length {
|
||||
let x: Double = sin(twoPi * normalisedFreq * Double(n))
|
||||
inputs[n] = x
|
||||
let (a, b, c, d) = up.process(x)
|
||||
outputs[n] = dn.process(a, b, c, d)
|
||||
}
|
||||
let inputRMS: Double = rmsValue(Array(inputs[warmup..<length]))
|
||||
let outputRMS: Double = rmsValue(Array(outputs[warmup..<length]))
|
||||
// Tolerance allows for normal Hamming-window passband ripple of the
|
||||
// 23-tap halfband (≈ ±0.1 dB ≈ ±1.2 % at the working rate).
|
||||
#expect(abs(outputRMS / inputRMS - 1.0) < 1.5e-2)
|
||||
}
|
||||
|
||||
@Test("Image rejection — synthetic 2× upsampled aliasing tone is suppressed by the downsampler")
|
||||
func imageRejectionDownsample2x() {
|
||||
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
|
||||
// Feed the downsampler a sine at 0.45 cycles per upsampled sample
|
||||
// (i.e. 0.9 · Fs at the input rate of 2 · Fs). This is well into the
|
||||
// halfband stopband (>0.25 of working rate), simulating a typical
|
||||
// image generated by a non-bandlimited 2× zero-stuff or by a
|
||||
// nonlinearity inserted between up and down stages. The downsampler
|
||||
// alone must attenuate it heavily.
|
||||
let length: Int = 4096
|
||||
let warmup: Int = 256
|
||||
let normalisedFreq: Double = 0.45 // cycles per upsampled-rate sample
|
||||
let twoPi: Double = 2.0 * .pi
|
||||
|
||||
var inputs: [Double] = [Double](repeating: 0.0, count: length)
|
||||
var outputs: [Double] = [Double](repeating: 0.0, count: length / 2)
|
||||
for n: Int in 0..<length {
|
||||
inputs[n] = sin(twoPi * normalisedFreq * Double(n))
|
||||
}
|
||||
for n: Int in 0..<(length / 2) {
|
||||
outputs[n] = dn.process(inputs[2 * n], inputs[2 * n + 1])
|
||||
}
|
||||
let inputRMS: Double = rmsValue(Array(inputs[warmup..<length]))
|
||||
let outputRMS: Double = rmsValue(Array(outputs[(warmup / 2)..<(length / 2)]))
|
||||
// 23-tap Hamming-windowed halfband: ~−40 dB stopband. Single
|
||||
// application → output RMS at most a few percent of input RMS.
|
||||
#expect(outputRMS / inputRMS < 0.1)
|
||||
}
|
||||
|
||||
@Test("Reset on 4× cascade clears all stages")
|
||||
func reset4xClearsAllStages() {
|
||||
var up: HalfbandUpsampler4x = HalfbandUpsampler4x()
|
||||
var dn: HalfbandDownsampler4x = HalfbandDownsampler4x()
|
||||
for _ in 0..<64 {
|
||||
let (a, b, c, d) = up.process(1.0)
|
||||
_ = dn.process(a, b, c, d)
|
||||
}
|
||||
up.reset()
|
||||
dn.reset()
|
||||
let (a, b, c, d) = up.process(0.0)
|
||||
#expect(a == 0.0)
|
||||
#expect(b == 0.0)
|
||||
#expect(c == 0.0)
|
||||
#expect(d == 0.0)
|
||||
let y: Double = dn.process(0.0, 0.0, 0.0, 0.0)
|
||||
#expect(y == 0.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// HalfbandUpsampler2xTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("HalfbandUpsampler2x")
|
||||
struct HalfbandUpsampler2xTests {
|
||||
|
||||
@Test("DC input becomes DC output after group delay (gain ≈ 1.0)")
|
||||
func dcGainIsUnity() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
let warmupInputs: Int = HalfbandFIR.length
|
||||
let measureInputs: Int = 64
|
||||
var lastEven: Double = 0.0
|
||||
var lastOdd: Double = 0.0
|
||||
for _ in 0..<warmupInputs {
|
||||
(lastEven, lastOdd) = up.process(1.0)
|
||||
}
|
||||
// After warmup the FIR is fully primed.
|
||||
for _ in 0..<measureInputs {
|
||||
(lastEven, lastOdd) = up.process(1.0)
|
||||
}
|
||||
// Even output = full FIR sum at DC = 2 × (sum_odd_folded × 2) = 1.0
|
||||
// (DC gain of the FIR is exactly 1.0 by construction; ×2 zero-stuff
|
||||
// gain compensates for the 0.5 average of the zero-stuffed signal).
|
||||
#expect(abs(lastEven - 1.0) < 1e-9)
|
||||
// Odd output = exact passthrough of x[n - 5] = 1.0.
|
||||
#expect(abs(lastOdd - 1.0) < 1e-12)
|
||||
}
|
||||
|
||||
@Test("Odd output is exact x[n - 5] passthrough")
|
||||
func oddOutputIsExactPassthrough() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
// Push a known sequence and check the odd output exactly tracks x[n - 5].
|
||||
let inputs: [Double] = (0..<32).map { Double($0) * 0.123 - 0.5 }
|
||||
var oddOuts: [Double] = []
|
||||
for x: Double in inputs {
|
||||
let (_, yOdd) = up.process(x)
|
||||
oddOuts.append(yOdd)
|
||||
}
|
||||
// For n >= 5: oddOuts[n] should equal inputs[n - 5] exactly.
|
||||
for n: Int in 5..<inputs.count {
|
||||
#expect(oddOuts[n] == inputs[n - HalfbandFIR.groupDelayInputRate])
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Reset clears state to zero")
|
||||
func resetClearsState() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
for _ in 0..<HalfbandFIR.length {
|
||||
_ = up.process(1.0)
|
||||
}
|
||||
up.reset()
|
||||
let (yEven, yOdd) = up.process(0.0)
|
||||
#expect(yEven == 0.0)
|
||||
#expect(yOdd == 0.0)
|
||||
}
|
||||
|
||||
@Test("Impulse response has expected total energy and odd-output spike at delay")
|
||||
func impulseResponse() {
|
||||
var up: HalfbandUpsampler2x = HalfbandUpsampler2x()
|
||||
// Feed a single unit impulse at n = 0, then zeros.
|
||||
var samples: [Double] = []
|
||||
let (e0, o0) = up.process(1.0)
|
||||
samples.append(e0); samples.append(o0)
|
||||
for _ in 0..<(HalfbandFIR.length + 4) {
|
||||
let (e, o) = up.process(0.0)
|
||||
samples.append(e); samples.append(o)
|
||||
}
|
||||
// Odd outputs are x[n - 5] passthrough → exactly one nonzero sample
|
||||
// at output index 2*5 + 1 = 11 (group delay 11 at upsampled rate).
|
||||
#expect(samples[2 * HalfbandFIR.groupDelayInputRate + 1] == 1.0)
|
||||
// Other odd outputs must be zero.
|
||||
var i: Int = 1
|
||||
while i < samples.count {
|
||||
if i != 2 * HalfbandFIR.groupDelayInputRate + 1 {
|
||||
#expect(samples[i] == 0.0)
|
||||
}
|
||||
i += 2
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// HilbertTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Hilbert")
|
||||
struct HilbertTests {
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
let testSampleRate: Double = 44100
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Render `totalSamples` of a Hilbert pair driven by a sine at `freqHz`.
|
||||
/// Returns (pathA, pathB) arrays of length `totalSamples`.
|
||||
private func renderSine(
|
||||
freqHz: Double,
|
||||
totalSamples: Int
|
||||
) -> (a: [Double], b: [Double]) {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freqHz)
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: osc)
|
||||
let blockSize: Int = engine.blockSize
|
||||
var a: [Double] = []
|
||||
var b: [Double] = []
|
||||
a.reserveCapacity(totalSamples)
|
||||
b.reserveCapacity(totalSamples)
|
||||
var rendered: Int = 0
|
||||
while rendered < totalSamples {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let n: Int = min(blockSize, totalSamples - rendered)
|
||||
let out: [[Double]] = h.calculatedSamples(graph: g, count: n)
|
||||
a.append(contentsOf: out[0].prefix(n))
|
||||
b.append(contentsOf: out[1].prefix(n))
|
||||
advanceBlock(engine)
|
||||
rendered += n
|
||||
}
|
||||
return (a, b)
|
||||
}
|
||||
|
||||
// MARK: - 1. Rate / channel count
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: 0.0)
|
||||
#expect(h.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func outputCountTwoChannels() {
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: ConstantGeneratorInput(0.5))
|
||||
let out: [[Double]] = h.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 2)
|
||||
#expect(h.outputChannelCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - 2. Analytic-signal magnitude — sqrt(xA² + xB²) ≈ input amplitude
|
||||
|
||||
@Test func analyticMagnitudeWithinHalfDbAt1kHz() {
|
||||
verifyAnalyticMagnitude(freqHz: 1_000, toleranceDb: 0.5)
|
||||
}
|
||||
|
||||
@Test func analyticMagnitudeWithinHalfDbAt5kHz() {
|
||||
verifyAnalyticMagnitude(freqHz: 5_000, toleranceDb: 0.5)
|
||||
}
|
||||
|
||||
@Test func analyticMagnitudeWithinHalfDbAt10kHz() {
|
||||
verifyAnalyticMagnitude(freqHz: 10_000, toleranceDb: 0.5)
|
||||
}
|
||||
|
||||
private func verifyAnalyticMagnitude(freqHz: Double, toleranceDb: Double) {
|
||||
let warmup: Int = 4096
|
||||
let measure: Int = 4096
|
||||
let (a, b): ([Double], [Double]) = renderSine(freqHz: freqHz, totalSamples: warmup + measure)
|
||||
var envSqSum: Double = 0
|
||||
for i: Int in warmup..<(warmup + measure) {
|
||||
envSqSum += a[i] * a[i] + b[i] * b[i]
|
||||
}
|
||||
let meanEnvSq: Double = envSqSum / Double(measure)
|
||||
// Input sine has amplitude 1 → mean(xA² + xB²) should be 1.0 for a perfect Hilbert.
|
||||
let errorDb: Double = 10.0 * log10(meanEnvSq)
|
||||
#expect(abs(errorDb) < toleranceDb,
|
||||
"\(freqHz) Hz: analytic magnitude error \(errorDb) dB exceeds ±\(toleranceDb) dB")
|
||||
}
|
||||
|
||||
// MARK: - 3. Envelope flatness — (xA² + xB²) should be near constant for a Hilbert pair
|
||||
//
|
||||
// For sin input through an ideal Hilbert pair (pathA in-phase, pathB 90° leading),
|
||||
// pathA² + pathB² ≈ sin²(θ) + cos²(θ) = const. If the two paths were identical
|
||||
// (no Hilbert action), the same sum would be 2·sin²(θ) — oscillating between 0
|
||||
// and 2 with mean 1. Variance of the envelope distinguishes the two cases — a true
|
||||
// Hilbert pair has near-zero envelope variance.
|
||||
|
||||
@Test func envelopeFlatnessAt1kHz() {
|
||||
verifyEnvelopeFlatness(freqHz: 1_000, maxVarianceRatio: 0.05)
|
||||
}
|
||||
|
||||
@Test func envelopeFlatnessAt5kHz() {
|
||||
verifyEnvelopeFlatness(freqHz: 5_000, maxVarianceRatio: 0.05)
|
||||
}
|
||||
|
||||
@Test func envelopeFlatnessAt10kHz() {
|
||||
verifyEnvelopeFlatness(freqHz: 10_000, maxVarianceRatio: 0.05)
|
||||
}
|
||||
|
||||
private func verifyEnvelopeFlatness(freqHz: Double, maxVarianceRatio: Double) {
|
||||
let warmup: Int = 4096
|
||||
let measure: Int = 4096
|
||||
let (a, b): ([Double], [Double]) = renderSine(freqHz: freqHz, totalSamples: warmup + measure)
|
||||
var sum: Double = 0
|
||||
for i: Int in warmup..<(warmup + measure) {
|
||||
sum += a[i] * a[i] + b[i] * b[i]
|
||||
}
|
||||
let mean: Double = sum / Double(measure)
|
||||
var ssDev: Double = 0
|
||||
for i: Int in warmup..<(warmup + measure) {
|
||||
let env: Double = a[i] * a[i] + b[i] * b[i]
|
||||
let d: Double = env - mean
|
||||
ssDev += d * d
|
||||
}
|
||||
let variance: Double = ssDev / Double(measure)
|
||||
let ratio: Double = variance / (mean * mean)
|
||||
#expect(ratio < maxVarianceRatio,
|
||||
"\(freqHz) Hz: envelope variance / mean² = \(ratio), expected < \(maxVarianceRatio) for a quadrature pair")
|
||||
}
|
||||
|
||||
// MARK: - 4. SSB integration — Hilbert pair drives proper single-sideband recovery
|
||||
//
|
||||
// End-to-end smoke: feed a 1 kHz sine through FrequencyShifter (which consumes
|
||||
// Hilbert.Audio post-refactor) shifted up by 200 Hz. Upper sideband should contain
|
||||
// 1200 Hz; lower sideband should contain 800 Hz. Confirms the extracted Hilbert
|
||||
// produces a Hilbert pair sufficient for SSB modulation — the canonical downstream
|
||||
// use case.
|
||||
|
||||
@Test func ssbIntegrationViaFrequencyShifter() {
|
||||
let sourceFreqHz: Double = 1_000
|
||||
let shiftHz: Double = 200
|
||||
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
|
||||
input: OscSin.Audio(freq: sourceFreqHz),
|
||||
shiftHz: shiftHz,
|
||||
sampleRate: testSampleRate
|
||||
)
|
||||
let warmup: Int = 4096
|
||||
let measure: Int = 4096
|
||||
let blockSize: Int = engine.blockSize
|
||||
var upper: [Double] = []
|
||||
var lower: [Double] = []
|
||||
upper.reserveCapacity(warmup + measure)
|
||||
lower.reserveCapacity(warmup + measure)
|
||||
var rendered: Int = 0
|
||||
while rendered < warmup + measure {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let n: Int = min(blockSize, warmup + measure - rendered)
|
||||
let out: [[Double]] = shifter.calculatedSamples(graph: g, count: n)
|
||||
upper.append(contentsOf: out[0].prefix(n))
|
||||
lower.append(contentsOf: out[1].prefix(n))
|
||||
advanceBlock(engine)
|
||||
rendered += n
|
||||
}
|
||||
// Goertzel single-bin power at expected and unexpected target frequencies.
|
||||
func goertzelPower(_ samples: ArraySlice<Double>, freqHz: Double) -> Double {
|
||||
let omega: Double = 2.0 * .pi * freqHz / testSampleRate
|
||||
let coeff: Double = 2.0 * cos(omega)
|
||||
var s0: Double = 0
|
||||
var s1: Double = 0
|
||||
var s2: Double = 0
|
||||
for x: Double in samples {
|
||||
s0 = x + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
return s1 * s1 + s2 * s2 - coeff * s1 * s2
|
||||
}
|
||||
let upperSlice: ArraySlice<Double> = upper[warmup..<(warmup + measure)]
|
||||
let lowerSlice: ArraySlice<Double> = lower[warmup..<(warmup + measure)]
|
||||
|
||||
let upperAtTarget: Double = goertzelPower(upperSlice, freqHz: sourceFreqHz + shiftHz) // 1200
|
||||
let upperAtOpposite: Double = goertzelPower(upperSlice, freqHz: sourceFreqHz - shiftHz) // 800
|
||||
let lowerAtTarget: Double = goertzelPower(lowerSlice, freqHz: sourceFreqHz - shiftHz) // 800
|
||||
let lowerAtOpposite: Double = goertzelPower(lowerSlice, freqHz: sourceFreqHz + shiftHz) // 1200
|
||||
|
||||
// Suppression ratio target / opposite > 20 dB (factor 100 in power). The Niemitalo
|
||||
// IIR Hilbert is approximate — measured suppression at 1 kHz with 200 Hz shift sits
|
||||
// around 30 dB, well above the 20 dB practical-use threshold.
|
||||
let minRatio: Double = 100
|
||||
#expect(upperAtTarget > minRatio * upperAtOpposite,
|
||||
"Upper sideband: target / opposite = \(upperAtTarget / upperAtOpposite), expected > \(minRatio)")
|
||||
#expect(lowerAtTarget > minRatio * lowerAtOpposite,
|
||||
"Lower sideband: target / opposite = \(lowerAtTarget / lowerAtOpposite), expected > \(minRatio)")
|
||||
}
|
||||
|
||||
// MARK: - 5. Scalar input (DC) — both rows settle to a finite value
|
||||
|
||||
@Test func dcInputSettlesToFiniteValue() {
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: 0.5)
|
||||
// Highest-Q pole at radius ~0.9994 → τ ≈ 1500 samples. 24576 ≈ 16τ
|
||||
// gives ~1e-7 settling on the slow pole — comfortably under 1e-4.
|
||||
let settleSamples: Int = 24576
|
||||
var rendered: Int = 0
|
||||
let blockSize: Int = engine.blockSize
|
||||
var lastA: Double = 0
|
||||
var lastB: Double = 0
|
||||
while rendered < settleSamples {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = h.calculatedSamples(graph: g, count: blockSize)
|
||||
lastA = out[0][blockSize - 1]
|
||||
lastB = out[1][blockSize - 1]
|
||||
advanceBlock(engine)
|
||||
rendered += blockSize
|
||||
}
|
||||
#expect(lastA.isFinite)
|
||||
#expect(lastB.isFinite)
|
||||
// For DC input, both all-pass paths converge to the same steady-state value (the input).
|
||||
#expect(abs(lastA - 0.5) < 1e-4, "Path A DC steady-state \(lastA), expected 0.5")
|
||||
#expect(abs(lastB - 0.5) < 1e-4, "Path B DC steady-state \(lastB), expected 0.5")
|
||||
}
|
||||
|
||||
// MARK: - 6. Denormal safety — silence after signal doesn't blow up
|
||||
|
||||
@Test func silenceAfterSignalIsDenormalSafe() {
|
||||
// Burst of noise, then silence — confirm no denormals accumulate.
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: osc)
|
||||
// 4 blocks of signal.
|
||||
for _: Int in 0..<4 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = h.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
// Replace source with silence by constructing a fresh chain. (Cannot null the
|
||||
// input mid-stream; this just confirms the existing chain keeps running cleanly
|
||||
// when sustained at a constant value.)
|
||||
let silentH: Hilbert.Audio = Hilbert.Audio(input: 0.0)
|
||||
for _: Int in 0..<8 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = silentH.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
for s: Double in out[0].prefix(engine.blockSize) { #expect(s.isFinite) }
|
||||
for s: Double in out[1].prefix(engine.blockSize) { #expect(s.isFinite) }
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 7. Named aliases match subscripts
|
||||
|
||||
@Test func realAndImagAliasesMatchSubscripts() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: osc)
|
||||
let real: ChannelSelect.Audio = h.real
|
||||
let imag: ChannelSelect.Audio = h.imag
|
||||
let out: [[Double]] = h.calculatedSamples(graph: graph, count: 64)
|
||||
let realOut: [[Double]] = real.calculatedSamples(graph: graph, count: 64)
|
||||
let imagOut: [[Double]] = imag.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(realOut[0][i] == out[0][i])
|
||||
#expect(imagOut[0][i] == out[1][i])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 8. mul/add applies to both rows
|
||||
|
||||
@Test func mulAddAppliesToBothRows() {
|
||||
let h: Hilbert.Audio = Hilbert.Audio(input: 0.5, mul: 2.0, add: 0.1)
|
||||
// Long settle for the slow IIR pole — see dcInputSettlesToFiniteValue.
|
||||
let settleSamples: Int = 24576
|
||||
var rendered: Int = 0
|
||||
var lastA: Double = 0
|
||||
var lastB: Double = 0
|
||||
while rendered < settleSamples {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = h.calculatedSamples(graph: g, count: engine.blockSize)
|
||||
lastA = out[0][engine.blockSize - 1]
|
||||
lastB = out[1][engine.blockSize - 1]
|
||||
advanceBlock(engine)
|
||||
rendered += engine.blockSize
|
||||
}
|
||||
// DC 0.5 × 2.0 + 0.1 = 1.1 on both rows once settled.
|
||||
#expect(abs(lastA - 1.1) < 1e-4, "Path A mul/add steady-state \(lastA), expected 1.1")
|
||||
#expect(abs(lastB - 1.1) < 1e-4, "Path B mul/add steady-state \(lastB), expected 1.1")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
// InGeneratorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("In (audio bus)")
|
||||
struct InGeneratorTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let gen: In.Audio = In.Audio(bus: 0)
|
||||
#expect(gen.rate == .audio)
|
||||
}
|
||||
|
||||
@Test func readsFromCorrectBus() {
|
||||
// Write a known pattern to bus 5
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
engine.audioBuses[5][i] = Float(i) * 0.1
|
||||
}
|
||||
let gen: In.Audio = In.Audio(bus: 5)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
#expect(abs(samples[0][i] - Double(i) * 0.1) < 1e-6)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func returnsLyrebirdFloatNotFloat() {
|
||||
let gen: In.Audio = In.Audio(bus: 0)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 8)
|
||||
// Double is Double — just check the type compiles correctly
|
||||
let _: [Double] = samples[0]
|
||||
// In now pre-allocates lyrebirdDefaultResultBufferSize elements like all generators;
|
||||
// callers take prefix(count) for the valid portion.
|
||||
#expect(samples[0].count >= 8)
|
||||
}
|
||||
|
||||
@Test func returnsCountSamples() {
|
||||
let gen: In.Audio = In.Audio(bus: 0)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
// Pre-allocated buffer is at least lyrebirdDefaultResultBufferSize; first 64 are valid.
|
||||
#expect(samples[0].count >= 64)
|
||||
}
|
||||
|
||||
@Test func readsAtBusOffset() {
|
||||
// Set bus 2 to distinct values
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
engine.audioBuses[2][i] = Float(i + 100)
|
||||
}
|
||||
let gen: In.Audio = In.Audio(bus: 2)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine, busOffset: 10)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 4)
|
||||
#expect(samples[0][0] == Double(110))
|
||||
#expect(samples[0][1] == Double(111))
|
||||
#expect(samples[0][2] == Double(112))
|
||||
#expect(samples[0][3] == Double(113))
|
||||
}
|
||||
|
||||
@Test func doesNotModifyBus() {
|
||||
for i: Int in 0..<engine.blockSize {
|
||||
engine.audioBuses[1][i] = Float(i) * 0.5
|
||||
}
|
||||
let snapshot: [Float] = engine.audioBuses[1]
|
||||
let gen: In.Audio = In.Audio(bus: 1)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = gen.calculatedSamples(graph: graph, count: engine.blockSize)
|
||||
#expect(engine.audioBuses[1] == snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("ControlIn")
|
||||
struct ControlInTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func rateIsControl() {
|
||||
let gen: In.Control = In.Control(bus: 0)
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
@Test func readsFromControlBus() {
|
||||
engine.controlBuses[3] = 0.75
|
||||
let gen: In.Control = In.Control(bus: 3)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
#expect(abs(gen.floatValue(graph: graph) - 0.75) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func calculatedSamplesInterpolatesToBusValue() throws {
|
||||
// ControlIn ramps from previousOutputValue (0.0 initially) to the current bus value.
|
||||
// With count=8 and target=1.5: step = 1.5/8 = 0.1875
|
||||
// Last valid sample (index 7) must equal the bus value exactly.
|
||||
// The pre-allocated buffer is lyrebirdDefaultResultBufferSize (512); only first 8 are valid.
|
||||
engine.controlBuses[7] = 1.5
|
||||
let gen: In.Control = In.Control(bus: 7)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: 8)
|
||||
#expect(samples[0].count >= 8)
|
||||
let validSlice: Array<Double>.SubSequence = samples[0].prefix(8)
|
||||
let last: Double = try #require(validSlice.last, "samples[0] must not be empty")
|
||||
#expect(abs(last - 1.5) < 1e-6)
|
||||
// Verify it is strictly increasing (ramp from 0 toward 1.5)
|
||||
let arr: [Double] = Array(validSlice)
|
||||
for i: Int in 0..<7 {
|
||||
#expect(arr[i] < arr[i + 1])
|
||||
}
|
||||
}
|
||||
|
||||
@Test func calculatedSamplesUpdatesPreviousOutputValue() {
|
||||
engine.controlBuses[7] = 1.5
|
||||
let gen: In.Control = In.Control(bus: 7)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 8)
|
||||
#expect(abs(gen.previousOutputValue - 1.5) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func doesNotModifyControlBus() {
|
||||
engine.controlBuses[4] = 2.0
|
||||
let gen: In.Control = In.Control(bus: 4)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 8)
|
||||
#expect(engine.controlBuses[4] == 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-channel In.Audio
|
||||
|
||||
@Suite("In.Audio multi-channel")
|
||||
struct InAudioMultiChannelTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func multiChannelReturnsCorrectChannelCount() {
|
||||
let gen: In.Audio = In.Audio(bus: 4, channels: 3)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 3)
|
||||
}
|
||||
|
||||
@Test func multiChannelReadsConsecutiveBuses() {
|
||||
engine.audioBuses[4][0] = 0.1
|
||||
engine.audioBuses[5][0] = 0.5
|
||||
engine.audioBuses[6][0] = 0.9
|
||||
let gen: In.Audio = In.Audio(bus: 4, channels: 3)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0] - 0.1) < 1e-6)
|
||||
#expect(abs(out[1][0] - 0.5) < 1e-6)
|
||||
#expect(abs(out[2][0] - 0.9) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func singleChannelDefaultBehaviourUnchanged() {
|
||||
engine.audioBuses[7][0] = 0.42
|
||||
let gen: In.Audio = In.Audio(bus: 7)
|
||||
#expect(gen.channels == 1)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out.count == 1)
|
||||
#expect(abs(out[0][0] - 0.42) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func floatValueAlwaysReturnsChannel0() {
|
||||
engine.audioBuses[4][0] = 0.25
|
||||
engine.audioBuses[5][0] = 0.75
|
||||
let gen: In.Audio = In.Audio(bus: 4, channels: 2)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
#expect(abs(gen.floatValue(graph: graph) - 0.25) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func audioBusConvenienceInitUsesChannelCount() throws {
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||
engine.audioBuses[bus.index][0] = 0.3
|
||||
engine.audioBuses[bus.index + 1][0] = 0.7
|
||||
let gen: In.Audio = In.Audio(bus: bus)
|
||||
#expect(gen.channels == 2)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out.count == 2)
|
||||
#expect(abs(out[0][0] - 0.3) < 1e-6)
|
||||
#expect(abs(out[1][0] - 0.7) < 1e-6)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-channel In.Control
|
||||
|
||||
@Suite("In.Control multi-channel")
|
||||
struct InControlMultiChannelTests {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func multiChannelReturnsCorrectChannelCount() {
|
||||
let gen: In.Control = In.Control(bus: 10, channels: 3)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 3)
|
||||
}
|
||||
|
||||
@Test func multiChannelReadsConsecutiveControlBuses() {
|
||||
engine.controlBuses[10] = 1.0
|
||||
engine.controlBuses[11] = 2.0
|
||||
engine.controlBuses[12] = 3.0
|
||||
let gen: In.Control = In.Control(bus: 10, channels: 3)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
// Each channel ramps from 0 to its bus value; last sample equals bus value
|
||||
#expect(abs(out[0].prefix(64).last! - 1.0) < 1e-6)
|
||||
#expect(abs(out[1].prefix(64).last! - 2.0) < 1e-6)
|
||||
#expect(abs(out[2].prefix(64).last! - 3.0) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func perChannelRampStateIsIndependent() {
|
||||
engine.controlBuses[20] = 1.0
|
||||
engine.controlBuses[21] = 0.0
|
||||
let gen: In.Control = In.Control(bus: 20, channels: 2)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
// ch0 ramps up, ch1 stays flat at 0
|
||||
#expect(out[0].prefix(64).last! > 0.5)
|
||||
#expect(out[1].prefix(64).allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
|
||||
@Test func previousOutputValueProxiesChannel0() {
|
||||
engine.controlBuses[30] = 0.8
|
||||
let gen: In.Control = In.Control(bus: 30, channels: 2)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(gen.previousOutputValue - 0.8) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func singleChannelDefaultBehaviourUnchanged() {
|
||||
engine.controlBuses[5] = 0.5
|
||||
let gen: In.Control = In.Control(bus: 5)
|
||||
#expect(gen.channels == 1)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(out.count == 1)
|
||||
#expect(abs(out[0].prefix(64).last! - 0.5) < 1e-6)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// JitterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("Jitter")
|
||||
struct JitterTests {
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsControl() {
|
||||
let gen: Jitter.Control = Jitter.Control()
|
||||
#expect(gen.rate == .control)
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Jitter.Control = Jitter.Control(center: 0.0, speed: 1.0, amount: 0.1, seed: 1)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutReturnsCachedResult() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let gen: Jitter.Control = Jitter.Control(center: 0.0, speed: 1.0, amount: 0.1, seed: 2)
|
||||
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block (bypass)
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let gen: Jitter.Control = Jitter.Control(center: 0.0, speed: 2.0, amount: 1.0, seed: 3)
|
||||
|
||||
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
// Second call in same segment is a cache hit — must be identical.
|
||||
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(block1a == block1b)
|
||||
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
|
||||
// Block 2 should differ from block 1 (jitter advances state per block).
|
||||
// This tests that a new block was computed, not a stale cache.
|
||||
#expect(block2.last != nil)
|
||||
_ = block2 // ensure block2 is used
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Output stays within [center - amount, center + amount]
|
||||
|
||||
@Test func outputStaysWithinBounds() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let center: Double = 5.0
|
||||
let amount: Double = 2.0
|
||||
let gen: Jitter.Control = Jitter.Control(center: center, speed: 10.0, amount: amount, seed: 42)
|
||||
|
||||
for _ in 0..<50 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
// Check last sample of each block (post-ramp settled value).
|
||||
let last: Double = out[0][63]
|
||||
#expect(last >= center - amount - 1e-9 && last <= center + amount + 1e-9)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Output drifts from center
|
||||
|
||||
@Test func outputDriftsFromCenter() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// High speed + high amount should cause the output to move noticeably from 0.0.
|
||||
let gen: Jitter.Control = Jitter.Control(center: 0.0, speed: 20.0, amount: 1.0, seed: 55)
|
||||
|
||||
var values: [Double] = []
|
||||
for _ in 0..<20 {
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
values.append(out[0][63])
|
||||
advanceBlock(engine)
|
||||
}
|
||||
|
||||
// With amount=1.0 and high speed, variance should be non-zero.
|
||||
let mean: Double = values.reduce(0, +) / Double(values.count)
|
||||
let variance: Double = values.map { ($0 - mean) * ($0 - mean) }.reduce(0, +) / Double(values.count)
|
||||
#expect(variance > 0.0)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Speed=0 freezes output
|
||||
|
||||
@Test func speedZeroFreezesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
var graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// With speed=0, coeff=1.0, so _smoothed doesn't change. But the random step is
|
||||
// still added (scaled by 1-coeff = 0). Output should remain at 0 (no perturbation).
|
||||
let gen: Jitter.Control = Jitter.Control(center: 0.0, speed: 0.0, amount: 1.0, seed: 11)
|
||||
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block1: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
advanceBlock(engine)
|
||||
graph = makeSynthGraph(engine: engine)
|
||||
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
|
||||
// With speed=0, last sample of both blocks should be the same.
|
||||
#expect(block1.last == block2.last)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Ramp: last sample equals target
|
||||
|
||||
@Test func rampLastSampleEqualsTarget() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// amount=0 clamps [center-0, center+0], forcing output to center=3.0 regardless of PRNG.
|
||||
let gen: Jitter.Control = Jitter.Control(center: 3.0, speed: 1.0, amount: 0.0, seed: 9)
|
||||
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(abs(out[0][63] - 3.0) < 1e-9)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Deterministic output with fixed seed
|
||||
|
||||
@Test func deterministicOutputWithSeed() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
let gen1: Jitter.Control = Jitter.Control(center: 0.0, speed: 2.0, amount: 0.5, seed: 9999)
|
||||
let gen2: Jitter.Control = Jitter.Control(center: 0.0, speed: 2.0, amount: 0.5, seed: 9999)
|
||||
|
||||
let out1: [Double] = Array(gen1.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let out2: [Double] = Array(gen2.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
#expect(out1 == out2)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - mulAdd
|
||||
|
||||
@Test func mulAddScalesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
|
||||
// amount=0 → output = center = 2.0 always.
|
||||
let genPlain: Jitter.Control = Jitter.Control(center: 2.0, speed: 1.0, amount: 0.0, seed: 66)
|
||||
let genMulAdd: Jitter.Control = Jitter.Control(center: 2.0, speed: 1.0, amount: 0.0, seed: 66, mul: 3.0, add: -1.0)
|
||||
|
||||
let plain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let scaled: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
|
||||
// Expected: 2.0 × 3 + (-1) = 5.0
|
||||
let expected: Double = (plain.last ?? 0.0) * 3.0 + (-1.0)
|
||||
#expect(abs((scaled.last ?? 0.0) - expected) < 1e-9)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
// MARK: - Integration: builds and evaluates without crash
|
||||
|
||||
@Test func integrationRunsWithoutCrash() throws {
|
||||
final class JitterSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let jitter: Jitter.Control = Jitter.Control(center: 440.0, speed: 0.5, amount: 50.0)
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: jitter)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: osc * 0.1))
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
let synth: JitterSynth = JitterSynth()
|
||||
synth.build()
|
||||
|
||||
for _ in 0..<10 {
|
||||
engine.advanceSegmentSerial()
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
synth.evaluate(graph: graph, count: 64)
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// KarplusStrongTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("KarplusStrong")
|
||||
struct KarplusStrongTests {
|
||||
|
||||
// MARK: - Test fixture
|
||||
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||||
|
||||
// Shared structural params for tests.
|
||||
let testSampleRate: Double = 44100
|
||||
let testMaxDelayTime: Double = 0.05
|
||||
|
||||
init() throws {
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Rate
|
||||
|
||||
@Test func rateIsAudio() {
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
#expect(ks.rate == .audio)
|
||||
}
|
||||
|
||||
// MARK: - Silent before trigger
|
||||
|
||||
@Test func silentBeforeTrigger() {
|
||||
// With trigger held at 0 and delay line zero-initialised, output must be zero.
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let allZero: Bool = samples.allSatisfy { abs($0) < 1e-12 }
|
||||
#expect(allZero, "Output must be zero before any trigger fires")
|
||||
}
|
||||
|
||||
// MARK: - Output count
|
||||
|
||||
@Test func outputCountMatchesRequest() {
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(out.count >= 1)
|
||||
#expect(out[0].count >= 512)
|
||||
}
|
||||
|
||||
// MARK: - Fan-out
|
||||
|
||||
@Test func fanOutSingleEvaluation() {
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let out1: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
let out2: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
// Same segment serial — second call must return cached result.
|
||||
let s1: [Double] = Array(out1[0].prefix(512))
|
||||
let s2: [Double] = Array(out2[0].prefix(512))
|
||||
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
|
||||
}
|
||||
|
||||
// MARK: - State advances once per block
|
||||
|
||||
@Test func stateAdvancesOncePerBlock() {
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: 0.0,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
_ = ks.calculatedSamples(graph: graph, count: 512)
|
||||
_ = ks.calculatedSamples(graph: graph, count: 512) // cache hit
|
||||
advanceBlock(engine)
|
||||
let graph2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let block2: [[Double]] = ks.calculatedSamples(graph: graph2, count: 512)
|
||||
// Both blocks are zero (no trigger); just confirm no crash and output is finite.
|
||||
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
|
||||
#expect(allFinite, "All output samples must be finite")
|
||||
}
|
||||
|
||||
// MARK: - Non-silent after trigger
|
||||
|
||||
@Test func nonSilentAfterTrigger() throws {
|
||||
// Use an ImpulseSource-style trigger that fires at sample 0.
|
||||
let trigger: OneShotTrigger = OneShotTrigger()
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: trigger,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
// Block 0: trigger fires → delay line starts filling with exciter.
|
||||
let out: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
let samples: [Double] = Array(out[0].prefix(512))
|
||||
let rms: Double = rmsValue(samples)
|
||||
// After trigger, the delay line is being filled with noise; output should be non-zero.
|
||||
#expect(rms > 0, "RMS must be non-zero after trigger fires")
|
||||
}
|
||||
|
||||
// MARK: - Decay over time
|
||||
|
||||
@Test func decayOverTime() throws {
|
||||
let trigger: OneShotTrigger = OneShotTrigger()
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: trigger,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
|
||||
// Block 0: fire trigger, capture early RMS.
|
||||
let earlyOut: [[Double]] = ks.calculatedSamples(graph: graph, count: 512)
|
||||
let earlyRms: Double = rmsValue(Array(earlyOut[0].prefix(512)))
|
||||
advanceBlock(engine)
|
||||
|
||||
// Advance many blocks to allow decay.
|
||||
let decayBlocks: Int = 100
|
||||
var lateOut: [[Double]] = [[]]
|
||||
for _ in 0..<decayBlocks {
|
||||
lateOut = ks.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
|
||||
advanceBlock(engine)
|
||||
}
|
||||
let lateRms: Double = rmsValue(Array(lateOut[0].prefix(512)))
|
||||
|
||||
#expect(earlyRms > 0, "Early RMS must be non-zero")
|
||||
#expect(lateRms < earlyRms, "KarplusStrong output must decay over time (lateRms \(lateRms) < earlyRms \(earlyRms))")
|
||||
}
|
||||
|
||||
// MARK: - mulAdd
|
||||
|
||||
@Test func mulAddApplied() {
|
||||
// Trigger at block 0 so output is non-zero, then compare with/without mulAdd.
|
||||
let trigger1: OneShotTrigger = OneShotTrigger()
|
||||
let trigger2: OneShotTrigger = OneShotTrigger()
|
||||
|
||||
let ksBase: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.5),
|
||||
trigger: trigger1,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime
|
||||
)
|
||||
let ksMul: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: ConstantGeneratorInput(0.5),
|
||||
trigger: trigger2,
|
||||
freq: 440.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: testSampleRate,
|
||||
maxDelayTime: testMaxDelayTime,
|
||||
mul: 2.0,
|
||||
add: 1.0
|
||||
)
|
||||
|
||||
let outBase: [Double] = Array(ksBase.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
let outMul: [Double] = Array(ksMul.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
|
||||
|
||||
// The mul/add relationship only holds for samples where both computed the same exciter.
|
||||
// Since exciter is constant (0.5), the delay line fill is identical and the relationship
|
||||
// must hold. Verify a few early samples.
|
||||
var relationshipHolds: Bool = true
|
||||
for i: Int in 0..<512 {
|
||||
let expected: Double = outBase[i] * 2.0 + 1.0
|
||||
if abs(outMul[i] - expected) > 1e-10 {
|
||||
relationshipHolds = false
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(relationshipHolds, "mul:2.0 add:1.0 must produce output × 2 + 1")
|
||||
}
|
||||
|
||||
// MARK: - Integration
|
||||
|
||||
@Test func integrationWithEngine() throws {
|
||||
final class KSSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let ks: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||
exciter: WhiteNoise.Audio(),
|
||||
trigger: Impulse.Audio(freq: 4.0),
|
||||
freq: 220.0,
|
||||
feedback: 0.99,
|
||||
sampleRate: 44100,
|
||||
maxDelayTime: 0.05
|
||||
)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: ks))
|
||||
}
|
||||
}
|
||||
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
|
||||
try intEngine.start()
|
||||
let synth: KSSynth = KSSynth()
|
||||
try intEngine.add(synth)
|
||||
// Render a few blocks without crashing.
|
||||
for _ in 0..<4 {
|
||||
intEngine.processBlock(inputSamples: [])
|
||||
}
|
||||
intEngine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Local test helpers
|
||||
|
||||
/// Emits 1.0 at sample 0 of the first `calculatedSamples` call, then 0.0 forever after.
|
||||
/// This simulates a one-shot rising edge at the very first sample.
|
||||
private final class OneShotTrigger: GeneratorBase, AudioGenerator {
|
||||
private var _fired: Bool = false
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { 0.0 }
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count,
|
||||
"OneShotTrigger: count \(count) exceeds buffer size \(_result[0].count)")
|
||||
_result[0][0] = _fired ? 0.0 : 1.0
|
||||
for i: Int in 1..<count { _result[0][i] = 0.0 }
|
||||
_fired = true
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// LFCurveNoiseAudioGenFreqTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("LFCurveNoise.Audio generator freq")
|
||||
struct LFCurveNoiseAudioGenFreqTests {
|
||||
|
||||
@Test func generatorFreqDoesNotCrash() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqNode: ParameterNode = ParameterNode(2.0)
|
||||
let noise: LFCurveNoise.Audio = LFCurveNoise.Audio(freq: freqNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = noise.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "LFCurveNoise.Audio output must be finite")
|
||||
}
|
||||
|
||||
@Test func generatorFreqRampChangesOutput() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqNode: ParameterNode = ParameterNode(0.0)
|
||||
let noise: LFCurveNoise.Audio = LFCurveNoise.Audio(freq: freqNode, seed: 7)
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = noise.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
freqNode.value = 3000.0
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = noise.calculatedSamples(graph: g2, count: 64)
|
||||
|
||||
let samples2: [Double] = Array((out2.first ?? []).prefix(64))
|
||||
#expect(samples2.allSatisfy { $0.isFinite }, "LFCurveNoise.Audio output finite after freq ramp")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// LFDutyCycleTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - LFDutyCycle Tests
|
||||
|
||||
@Suite("LFDutyCycle")
|
||||
struct LFDutyCycleTests {
|
||||
|
||||
@Test("LFDutyCycle.Audio rate is .audio")
|
||||
func testAudioRate() {
|
||||
#expect(LFDutyCycle.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle.Control rate is .control")
|
||||
func testControlRate() {
|
||||
#expect(LFDutyCycle.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle.Audio produces 64 samples")
|
||||
func testAudioOutputCount() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = LFDutyCycle.Audio(freq: 1.0).calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle.Audio fan-out returns identical first channel")
|
||||
func testAudioFanOut() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 1.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
// MARK: dutyCycle extreme values
|
||||
|
||||
@Test("LFDutyCycle.Audio dutyCycle=0.0 produces all -1")
|
||||
func testDutyCycleZeroAllLow() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// dutyCycle=0 → phase never < 0 → always -1
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] == -1.0,
|
||||
"dutyCycle=0 sample \(i) = \(out[0][i]), expected -1")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle.Audio dutyCycle=1.0 produces all +1")
|
||||
func testDutyCycleOneAllHigh() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// dutyCycle=1 → phase always < 1.0 → always +1
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 1.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] == 1.0,
|
||||
"dutyCycle=1 sample \(i) = \(out[0][i]), expected +1")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: dutyCycle=0.5 matches LFSquare
|
||||
|
||||
@Test("LFDutyCycle.Audio dutyCycle=0.5 matches LFSquare output")
|
||||
func testDutyCycleHalfMatchesLFSquare() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let freq: Double = 5.0
|
||||
let square: LFSquare.Audio = LFSquare.Audio(freq: freq)
|
||||
let dutyCycle: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: freq, dutyCycle: 0.5)
|
||||
let sqOut: [[Double]] = square.calculatedSamples(graph: graph, count: 512)
|
||||
let dcOut: [[Double]] = dutyCycle.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(sqOut[0][i] == dcOut[0][i],
|
||||
"sample \(i): square=\(sqOut[0][i]) dutyCycle=\(dcOut[0][i])")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Output only ±1 (no analog ramps)
|
||||
|
||||
@Test("LFDutyCycle.Audio output is only +1 or -1")
|
||||
func testAudioOutputRange() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 10.0, dutyCycle: 0.3)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] == 1.0 || out[0][i] == -1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Audio-rate dutyCycle generator input
|
||||
|
||||
@Test("LFDutyCycle.Audio audio-rate dutyCycle generator input does not crash")
|
||||
func testAudioRateDutyCycleGeneratorInput() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// Use a sine wave as the duty cycle input — values move through [-1,1] but get clamped to [0,1]
|
||||
let dutyGen: OscSin.Audio = OscSin.Audio(freq: 2.0, mul: 0.5, add: 0.5)
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 5.0, dutyCycle: dutyGen)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
// Verify output is bounded in [-1, 1]
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] >= -1.0)
|
||||
#expect(out[0][i] <= 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: GeneratorEnum
|
||||
|
||||
@Test("LFDutyCycle GeneratorEnum AudioType rate is .audio")
|
||||
func testGeneratorEnumAudio() {
|
||||
#expect(LFDutyCycle.AudioType.self == LFDutyCycle.Audio.self)
|
||||
#expect(LFDutyCycle.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle GeneratorEnum ControlType rate is .control")
|
||||
func testGeneratorEnumControl() {
|
||||
#expect(LFDutyCycle.ControlType.self == LFDutyCycle.Control.self)
|
||||
#expect(LFDutyCycle.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
// MARK: mul/add
|
||||
|
||||
@Test("LFDutyCycle.Audio mul:2 add:1 scales output")
|
||||
func testAudioMulAdd() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let oscBase: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 5.0, dutyCycle: 0.3)
|
||||
let oscMulAdd: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 5.0, dutyCycle: 0.3, mul: 2.0, add: 1.0)
|
||||
let base: [[Double]] = oscBase.calculatedSamples(graph: graph, count: 64)
|
||||
let scaled: [[Double]] = oscMulAdd.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = base[0][i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[0][i] - expected) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Control cache-hit bypass
|
||||
|
||||
@Test("LFDutyCycle.Control second call in same segment is cache hit")
|
||||
func testControlCacheHit() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFDutyCycle.Control = LFDutyCycle.Control(freq: 100.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
let phaseAfterFirst: Double = osc._phase
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(osc._phase == phaseAfterFirst)
|
||||
for i: Int in 0..<512 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
// MARK: Phase offset
|
||||
|
||||
@Test("LFDutyCycle.Audio phase=0.7 dutyCycle=0.5 first sample is -1")
|
||||
func testAudioPhaseOffsetBeyondDuty() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.7, duty=0.5 → 0.7 >= 0.5 → -1
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.5, phase: 0.7)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == -1.0)
|
||||
}
|
||||
|
||||
@Test("LFDutyCycle.Audio phase=0.2 dutyCycle=0.5 first sample is +1")
|
||||
func testAudioPhaseOffsetWithinDuty() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.2, duty=0.5 → 0.2 < 0.5 → +1
|
||||
let osc: LFDutyCycle.Audio = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.5, phase: 0.2)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == 1.0)
|
||||
}
|
||||
|
||||
// MARK: State advances across blocks
|
||||
|
||||
@Test("LFDutyCycle.Control state advances across blocks")
|
||||
func testControlStateAdvances() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
// Use a frequency whose phase crosses the duty boundary between blocks.
|
||||
// At 44100 Hz, 512 samples/block: dt_per_block = 100/44100*512 ≈ 1.16.
|
||||
// Phase wraps multiple times per block; collect two blocks and compare phase.
|
||||
let osc: LFDutyCycle.Control = LFDutyCycle.Control(freq: 100.0)
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = osc.calculatedSamples(graph: g1, count: 512)
|
||||
let phaseAfterBlock1: Double = osc._phase
|
||||
advanceBlock(engine)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = osc.calculatedSamples(graph: g2, count: 512)
|
||||
let phaseAfterBlock2: Double = osc._phase
|
||||
// Phase must have changed (it wraps, so we compare the raw accumulated phase)
|
||||
#expect(phaseAfterBlock1 != phaseAfterBlock2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// LFLineNoiseAudioGenFreqTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("LFLineNoise.Audio generator freq")
|
||||
struct LFLineNoiseAudioGenFreqTests {
|
||||
|
||||
@Test func generatorFreqDoesNotCrash() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqNode: ParameterNode = ParameterNode(2.0)
|
||||
let noise: LFLineNoise.Audio = LFLineNoise.Audio(freq: freqNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = noise.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "LFLineNoise.Audio output must be finite")
|
||||
#expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-6 }, "LFLineNoise.Audio output must be in [-1, 1]")
|
||||
}
|
||||
|
||||
@Test func generatorFreqRampChangesOutput() throws {
|
||||
// Block 1: freq=0 (frozen interpolation). Block 2: freq ramps to high value.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqNode: ParameterNode = ParameterNode(0.0)
|
||||
let noise: LFLineNoise.Audio = LFLineNoise.Audio(freq: freqNode, seed: 99)
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = noise.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
freqNode.value = 3000.0
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = noise.calculatedSamples(graph: g2, count: 64)
|
||||
|
||||
let samples2: [Double] = Array((out2.first ?? []).prefix(64))
|
||||
#expect(samples2.allSatisfy { $0.isFinite }, "LFLineNoise.Audio output finite after freq ramp")
|
||||
// With high freq, the output should be moving (not constant).
|
||||
let range: Double = (samples2.max() ?? 0) - (samples2.min() ?? 0)
|
||||
#expect(range > 1e-6, "LFLineNoise.Audio with high freq should have non-constant output")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// LFSawtoothTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - LFSawtooth Tests
|
||||
|
||||
@Suite("LFSawtooth")
|
||||
struct LFSawtoothTests {
|
||||
|
||||
// MARK: Rate
|
||||
|
||||
@Test("LFSawtooth.Audio rate is .audio")
|
||||
func testAudioRate() {
|
||||
#expect(LFSawtooth.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Control rate is .control")
|
||||
func testControlRate() {
|
||||
#expect(LFSawtooth.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
// MARK: Output count
|
||||
|
||||
@Test("LFSawtooth.Audio produces 64 samples")
|
||||
func testAudioOutputCount() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 1.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Control produces 64 samples")
|
||||
func testControlOutputCount() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
// MARK: Fan-out
|
||||
|
||||
@Test("LFSawtooth.Audio fan-out returns identical first channel")
|
||||
func testAudioFanOut() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 1.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out1[0][i] == out2[0][i])
|
||||
}
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Control fan-out returns identical first channel")
|
||||
func testControlFanOut() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
#expect(out1[0][i] == out2[0][i])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Output range
|
||||
|
||||
@Test("LFSawtooth.Audio output stays in [-1, 1]")
|
||||
func testAudioOutputRange() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 10.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] >= -1.0)
|
||||
#expect(out[0][i] <= 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Waveform shape — specific phase values
|
||||
|
||||
@Test("LFSawtooth.Audio phase=0 starts near -1")
|
||||
func testAudioPhaseZeroStartsNearMinusOne() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0 → raw = 2*0 - 1 = -1.0
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 1.0, phase: 0.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0] - (-1.0)) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Audio phase=0.5 produces near 0")
|
||||
func testAudioPhaseHalfNearZero() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.5 → raw = 2*0.5 - 1 = 0.0
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 1.0, phase: 0.5)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0]) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Audio phase=0.25 produces near -0.5")
|
||||
func testAudioPhaseQuarterNearMinusHalf() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.25 → raw = 2*0.25 - 1 = -0.5
|
||||
let osc: LFSawtooth.Audio = LFSawtooth.Audio(freq: 1.0, phase: 0.25)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0] - (-0.5)) < 1e-9)
|
||||
}
|
||||
|
||||
// MARK: GeneratorEnum
|
||||
|
||||
@Test("LFSawtooth GeneratorEnum AudioType rate is .audio")
|
||||
func testGeneratorEnumAudio() {
|
||||
#expect(LFSawtooth.AudioType.self == LFSawtooth.Audio.self)
|
||||
#expect(LFSawtooth.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFSawtooth GeneratorEnum ControlType rate is .control")
|
||||
func testGeneratorEnumControl() {
|
||||
#expect(LFSawtooth.ControlType.self == LFSawtooth.Control.self)
|
||||
#expect(LFSawtooth.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
// MARK: mul/add
|
||||
|
||||
@Test("LFSawtooth.Audio mul:2 add:1 scales output")
|
||||
func testAudioMulAdd() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let oscBase: LFSawtooth.Audio = LFSawtooth.Audio(freq: 5.0)
|
||||
let oscMulAdd: LFSawtooth.Audio = LFSawtooth.Audio(freq: 5.0, mul: 2.0, add: 1.0)
|
||||
let base: [[Double]] = oscBase.calculatedSamples(graph: graph, count: 64)
|
||||
let scaled: [[Double]] = oscMulAdd.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = base[0][i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[0][i] - expected) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("LFSawtooth.Control mul:2 add:1 scales output")
|
||||
func testControlMulAdd() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let oscBase: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0)
|
||||
let oscMulAdd: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0, mul: 2.0, add: 1.0)
|
||||
let base: [Double] = Array(oscBase.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let scaled: [Double] = Array(oscMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
|
||||
let baseLast: Double = base[63]
|
||||
let scaledLast: Double = scaled[63]
|
||||
#expect(abs(scaledLast - (baseLast * 2.0 + 1.0)) < 1e-6)
|
||||
}
|
||||
|
||||
// MARK: Control cache-hit bypass
|
||||
|
||||
@Test("LFSawtooth.Control second call in same segment is cache hit")
|
||||
func testControlCacheHit() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSawtooth.Control = LFSawtooth.Control(freq: 100.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
let phaseAfterFirst: Double = osc._phase
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(osc._phase == phaseAfterFirst)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out1[0][i] == out2[0][i])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: State advances across blocks
|
||||
|
||||
@Test("LFSawtooth.Control state advances across blocks")
|
||||
func testControlStateAdvances() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let osc: LFSawtooth.Control = LFSawtooth.Control(freq: 5.0)
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let v1: [Double] = Array(osc.calculatedSamples(graph: g1, count: 512)[0].prefix(512))
|
||||
advanceBlock(engine)
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let v2: [Double] = Array(osc.calculatedSamples(graph: g2, count: 512)[0].prefix(512))
|
||||
#expect(v1[511] != v2[511])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// LFSquareTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - LFSquare Tests
|
||||
|
||||
@Suite("LFSquare")
|
||||
struct LFSquareTests {
|
||||
|
||||
@Test("LFSquare.Audio rate is .audio")
|
||||
func testAudioRate() {
|
||||
#expect(LFSquare.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFSquare.Control rate is .control")
|
||||
func testControlRate() {
|
||||
#expect(LFSquare.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
@Test("LFSquare.Audio produces 64 samples")
|
||||
func testAudioOutputCount() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = LFSquare.Audio(freq: 1.0).calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
@Test("LFSquare.Audio fan-out returns identical first channel")
|
||||
func testAudioFanOut() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSquare.Audio = LFSquare.Audio(freq: 1.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
@Test("LFSquare.Audio output stays in [-1, 1]")
|
||||
func testAudioOutputRange() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSquare.Audio = LFSquare.Audio(freq: 10.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] == 1.0 || out[0][i] == -1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Waveform shape
|
||||
|
||||
@Test("LFSquare.Audio phase=0 first sample is +1")
|
||||
func testAudioPhaseZeroIsHigh() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0 → 0 < 0.5 → +1
|
||||
let osc: LFSquare.Audio = LFSquare.Audio(freq: 1.0, phase: 0.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == 1.0)
|
||||
}
|
||||
|
||||
@Test("LFSquare.Audio phase=0.75 first sample is -1")
|
||||
func testAudioPhaseThreeQuartersIsLow() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.75 → 0.75 >= 0.5 → -1
|
||||
let osc: LFSquare.Audio = LFSquare.Audio(freq: 1.0, phase: 0.75)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == -1.0)
|
||||
}
|
||||
|
||||
// MARK: GeneratorEnum
|
||||
|
||||
@Test("LFSquare GeneratorEnum AudioType rate is .audio")
|
||||
func testGeneratorEnumAudio() {
|
||||
#expect(LFSquare.AudioType.self == LFSquare.Audio.self)
|
||||
#expect(LFSquare.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFSquare GeneratorEnum ControlType rate is .control")
|
||||
func testGeneratorEnumControl() {
|
||||
#expect(LFSquare.ControlType.self == LFSquare.Control.self)
|
||||
#expect(LFSquare.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
// MARK: mul/add
|
||||
|
||||
@Test("LFSquare.Audio mul:2 add:1 scales output")
|
||||
func testAudioMulAdd() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let oscBase: LFSquare.Audio = LFSquare.Audio(freq: 5.0)
|
||||
let oscMulAdd: LFSquare.Audio = LFSquare.Audio(freq: 5.0, mul: 2.0, add: 1.0)
|
||||
let base: [[Double]] = oscBase.calculatedSamples(graph: graph, count: 64)
|
||||
let scaled: [[Double]] = oscMulAdd.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = base[0][i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[0][i] - expected) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Control cache-hit bypass
|
||||
|
||||
@Test("LFSquare.Control second call in same segment is cache hit")
|
||||
func testControlCacheHit() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFSquare.Control = LFSquare.Control(freq: 100.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
let phaseAfterFirst: Double = osc._phase
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(osc._phase == phaseAfterFirst)
|
||||
for i: Int in 0..<512 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
// MARK: Phase offset shifts waveform
|
||||
|
||||
@Test("LFSquare.Audio phase=0.5 first sample is -1 (second half of cycle)")
|
||||
func testAudioPhaseOffsetHalf() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.5 → 0.5 >= 0.5 → -1
|
||||
let osc: LFSquare.Audio = LFSquare.Audio(freq: 1.0, phase: 0.5)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(out[0][0] == -1.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// LFStepNoiseAudioGenFreqTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("LFStepNoise.Audio generator freq")
|
||||
struct LFStepNoiseAudioGenFreqTests {
|
||||
|
||||
@Test func generatorFreqDoesNotCrash() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let freqNode: ParameterNode = ParameterNode(4.0)
|
||||
let noise: LFStepNoise.Audio = LFStepNoise.Audio(freq: freqNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = noise.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "LFStepNoise.Audio output must be finite")
|
||||
#expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-6 }, "LFStepNoise.Audio output must be in [-1, 1]")
|
||||
}
|
||||
|
||||
@Test func generatorFreqProducesMultipleStepsWhenHigh() throws {
|
||||
// Use a constant high freq (not ramp) wired as a Generator to verify the generator path.
|
||||
// At 5000 Hz with blockSize=64 and sampleRate=44100, there should be ~7 steps per block.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// ParameterNode pre-primed to 5000 Hz (no ramp: both atomic and previousOutputValue = 5000).
|
||||
let freqNode: ParameterNode = ParameterNode(5000.0)
|
||||
let noise: LFStepNoise.Audio = LFStepNoise.Audio(freq: freqNode, seed: 42)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = noise.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
let uniqueCount: Int = Set(samples).count
|
||||
#expect(uniqueCount > 1, "LFStepNoise.Audio with generator freq=5000Hz should produce multiple values per block (got \(uniqueCount) unique values)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// LFTriangleTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - LFTriangle Tests
|
||||
|
||||
@Suite("LFTriangle")
|
||||
struct LFTriangleTests {
|
||||
|
||||
@Test("LFTriangle.Audio rate is .audio")
|
||||
func testAudioRate() {
|
||||
#expect(LFTriangle.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Control rate is .control")
|
||||
func testControlRate() {
|
||||
#expect(LFTriangle.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio produces 64 samples")
|
||||
func testAudioOutputCount() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = LFTriangle.Audio(freq: 1.0).calculatedSamples(graph: graph, count: 64)
|
||||
#expect(Array(out[0].prefix(64)).count == 64)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio fan-out returns identical first channel")
|
||||
func testAudioFanOut() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 1.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio output stays in [-1, 1]")
|
||||
func testAudioOutputRange() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 10.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
for i: Int in 0..<512 {
|
||||
#expect(out[0][i] >= -1.0)
|
||||
#expect(out[0][i] <= 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Waveform shape
|
||||
|
||||
@Test("LFTriangle.Audio phase=0 starts at -1")
|
||||
func testAudioPhaseZeroStartsAtBottom() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0 → 4*0 - 1 = -1.0
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 1.0, phase: 0.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0] - (-1.0)) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio phase=0.25 produces 0 (ascending zero crossing)")
|
||||
func testAudioPhaseQuarterIsZero() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.25 → 4*0.25 - 1 = 0.0
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 1.0, phase: 0.25)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0]) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio phase=0.5 produces +1 (peak)")
|
||||
func testAudioPhaseHalfIsPeak() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.5 → 3 - 4*0.5 = 1.0
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 1.0, phase: 0.5)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0] - 1.0) < 1e-9)
|
||||
}
|
||||
|
||||
@Test("LFTriangle.Audio phase=0.75 produces 0 (descending zero crossing)")
|
||||
func testAudioPhaseThreeQuartersIsZero() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
// phase=0.75 → 3 - 4*0.75 = 0.0
|
||||
let osc: LFTriangle.Audio = LFTriangle.Audio(freq: 1.0, phase: 0.75)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 1)
|
||||
#expect(abs(out[0][0]) < 1e-9)
|
||||
}
|
||||
|
||||
// MARK: GeneratorEnum
|
||||
|
||||
@Test("LFTriangle GeneratorEnum AudioType rate is .audio")
|
||||
func testGeneratorEnumAudio() {
|
||||
#expect(LFTriangle.AudioType.self == LFTriangle.Audio.self)
|
||||
#expect(LFTriangle.Audio(freq: 1.0).rate == .audio)
|
||||
}
|
||||
|
||||
@Test("LFTriangle GeneratorEnum ControlType rate is .control")
|
||||
func testGeneratorEnumControl() {
|
||||
#expect(LFTriangle.ControlType.self == LFTriangle.Control.self)
|
||||
#expect(LFTriangle.Control(freq: 1.0).rate == .control)
|
||||
}
|
||||
|
||||
// MARK: mul/add
|
||||
|
||||
@Test("LFTriangle.Audio mul:2 add:1 scales output")
|
||||
func testAudioMulAdd() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let oscBase: LFTriangle.Audio = LFTriangle.Audio(freq: 5.0)
|
||||
let oscMulAdd: LFTriangle.Audio = LFTriangle.Audio(freq: 5.0, mul: 2.0, add: 1.0)
|
||||
let base: [[Double]] = oscBase.calculatedSamples(graph: graph, count: 64)
|
||||
let scaled: [[Double]] = oscMulAdd.calculatedSamples(graph: graph, count: 64)
|
||||
for i: Int in 0..<64 {
|
||||
let expected: Double = base[0][i] * 2.0 + 1.0
|
||||
#expect(abs(scaled[0][i] - expected) < 1e-10)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Control cache-hit bypass
|
||||
|
||||
@Test("LFTriangle.Control second call in same segment is cache hit")
|
||||
func testControlCacheHit() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFTriangle.Control = LFTriangle.Control(freq: 100.0)
|
||||
let out1: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
let phaseAfterFirst: Double = osc._phase
|
||||
let out2: [[Double]] = osc.calculatedSamples(graph: graph, count: 512)
|
||||
#expect(osc._phase == phaseAfterFirst)
|
||||
for i: Int in 0..<512 { #expect(out1[0][i] == out2[0][i]) }
|
||||
}
|
||||
|
||||
// MARK: Ramp reaches target
|
||||
|
||||
@Test("LFTriangle.Control last sample equals ramp target")
|
||||
func testControlRampTarget() {
|
||||
let engine: SynthesisEngine = makeTestEngine(sampleRate: 44100)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let osc: LFTriangle.Control = LFTriangle.Control(freq: 5.0)
|
||||
let out: [[Double]] = osc.calculatedSamples(graph: graph, count: 64)
|
||||
// Last sample should equal previousOutputValue (the ramp end)
|
||||
let last: Double = out[0][63]
|
||||
#expect(abs(last - osc.previousOutputValue) < 1e-9)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user