1.0.0 release
This commit is contained in:
@@ -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))")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user