1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,702 @@
// LyrebirdEventListBuildFromFileTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Private test fixtures
/// Returns a minimal engine backed by OfflineDriver (no real-time audio needed).
private func makeBFFTestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: OfflineDriver()
)
}
/// A short, self-releasing envelope (~40 ms total).
private func shortEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.02],
curves: [.lin, .lin]
)
}
/// Factory dictionary entry for a given base ID — builds a minimal process with that minted ID.
private func makeFactory(_ baseID: String) -> (String) -> LyrebirdProcess {
return { mintedID in
LyrebirdProcess(
id: mintedID,
envelope: Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.02],
curves: [.lin, .lin]
),
numChannels: 1,
body: { _ in }
)
}
}
/// Write a `[LyrebirdTimelineEntry]` as a JSON file to `url`.
private func writeEntries(_ entries: [LyrebirdTimelineEntry], to url: URL) throws {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(entries)
try data.write(to: url, options: .atomic)
}
/// Returns a fresh temporary directory URL (directory is NOT yet created — caller
/// must call `FileManager.default.createDirectory` if needed).
private func makeTempDir() -> URL {
FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
}
/// Best-effort removal of a temp directory.
private func removeTempDir(_ url: URL) {
try? FileManager.default.removeItem(at: url)
}
// MARK: - Suite
@Suite("LyrebirdEventListBuildFromFile")
struct LyrebirdEventListBuildFromFileTests {
// MARK: - Test 1: Single file, no tolerance grouping needed
@Test("Single file, 3 entries at distinct offsets → 3 events with IDs bell_0, drone_0, wash_0")
func testSingleFileNoGrouping() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 2.0, eventIndex: 2, startedProcessIDs: ["wash"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test1",
engine: engine,
processFactories: factories,
tolerance: 0.5,
paths: [fileURL]
)
// 3 entries with gaps > 0.5 → 3 separate events.
#expect(list.nextEvent == 0)
// Play all events to inspect the minted IDs via timeline capture.
// We can't directly query event internals, so we rely on the timeline.
// But timeline only captures started/released IDs after play().
// Instead verify event count by driving index to the end.
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 3)
// Inspect the captured timeline for minted IDs.
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 3)
#expect(timeline[0].startedProcessIDs == ["bell_0"])
#expect(timeline[1].startedProcessIDs == ["drone_0"])
#expect(timeline[2].startedProcessIDs == ["wash_0"])
}
// MARK: - Test 2: Tolerance merges close entries
@Test("Tolerance 0.2 merges entries at 0.0, 0.05, 0.1 into a single event")
func testToleranceMergesCloseEntries() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.05, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.1, eventIndex: 2, startedProcessIDs: ["wash"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test2",
engine: engine,
processFactories: factories,
tolerance: 0.2,
paths: [fileURL]
)
// All three within 0.2 s of the first → 1 event.
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 1)
// That single event should have started all three processes.
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 1)
#expect(timeline[0].startedProcessIDs.contains("bell_0"))
#expect(timeline[0].startedProcessIDs.contains("drone_0"))
#expect(timeline[0].startedProcessIDs.contains("wash_0"))
#expect(timeline[0].startedProcessIDs.count == 3)
}
// MARK: - Test 3: Tolerance does not merge across gap
@Test("Tolerance 0.2 splits entries at 0.0, 0.1, 1.0 into 2 events")
func testToleranceDoesNotMergeAcrossGap() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.1, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 2, startedProcessIDs: ["wash"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test3",
engine: engine,
processFactories: factories,
tolerance: 0.2,
paths: [fileURL]
)
// bell+drone at 0.0/0.1 merge; wash at 1.0 is a new group.
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 2)
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 2)
// First group: bell and drone.
#expect(timeline[0].startedProcessIDs.contains("bell_0"))
#expect(timeline[0].startedProcessIDs.contains("drone_0"))
#expect(timeline[0].startedProcessIDs.count == 2)
// Second group: wash.
#expect(timeline[1].startedProcessIDs == ["wash_0"])
}
// MARK: - Test 4: Multiple files concatenated and sorted
@Test("Two files with interleaved offsets are concatenated and sorted → 4 events")
func testMultipleFilesConcatAndSort() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileA: URL = tempDir.appendingPathComponent("logA.json")
let fileB: URL = tempDir.appendingPathComponent("logB.json")
// File A: offsets 0.0 and 2.0.
try writeEntries([
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 2.0, eventIndex: 1, startedProcessIDs: ["wash"], releasedProcessIDs: [])
], to: fileA)
// File B: offsets 1.0 and 3.0.
try writeEntries([
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 0, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 3.0, eventIndex: 1, startedProcessIDs: ["rain"], releasedProcessIDs: [])
], to: fileB)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash"),
"rain": makeFactory("rain")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test4",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileA, fileB]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 4)
// Verify sorted order by checking startedProcessIDs.
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 4)
#expect(timeline[0].startedProcessIDs == ["bell_0"])
#expect(timeline[1].startedProcessIDs == ["drone_0"])
#expect(timeline[2].startedProcessIDs == ["wash_0"])
#expect(timeline[3].startedProcessIDs == ["rain_0"])
}
// MARK: - Test 5: Same baseID across multiple events gets deduplicated IDs
@Test("Same baseID starting at two separate events mints bell_0 and bell_1")
func testSameBaseIDDeduplication() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 5.0, eventIndex: 1, startedProcessIDs: ["bell"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test5",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileURL]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 2)
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 2)
#expect(timeline[0].startedProcessIDs == ["bell_0"])
#expect(timeline[1].startedProcessIDs == ["bell_1"])
}
// MARK: - Test 6: Releases resolve to latest minted instance
@Test("Release at t=1.0 resolves to bell_0; second start+release pair uses bell_1")
func testReleasesResolveToLatestMinted() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
// bell starts at 0.0, released at 1.0; then bell starts again at 2.0, released at 3.0.
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 1, startedProcessIDs: [], releasedProcessIDs: ["bell"]),
LyrebirdTimelineEntry(offset: 2.0, eventIndex: 2, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 3.0, eventIndex: 3, startedProcessIDs: [], releasedProcessIDs: ["bell"])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test6",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileURL]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 4)
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 4)
// Event 0: starts bell_0, no releases.
#expect(timeline[0].startedProcessIDs == ["bell_0"])
#expect(timeline[0].releasedProcessIDs == [])
// Event 1: releases bell_0, no starts.
#expect(timeline[1].startedProcessIDs == [])
#expect(timeline[1].releasedProcessIDs == ["bell_0"])
// Event 2: starts bell_1, no releases.
#expect(timeline[2].startedProcessIDs == ["bell_1"])
#expect(timeline[2].releasedProcessIDs == [])
// Event 3: releases bell_1, no starts.
#expect(timeline[3].startedProcessIDs == [])
#expect(timeline[3].releasedProcessIDs == ["bell_1"])
}
// MARK: - Test 7: Duplicate baseID in same merged group
@Test("startedProcessIDs with two 'bell' entries in one group mints bell_0 and bell_1")
func testDuplicateBaseIDInSameGroup() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
// Single entry with two 'bell' IDs in startedProcessIDs.
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(
offset: 0.0,
eventIndex: 0,
startedProcessIDs: ["bell", "bell"],
releasedProcessIDs: []
)
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test7",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileURL]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 1)
let timeline: [LyrebirdTimelineEntry] = list.timeline
#expect(timeline.count == 1)
// Both bells minted in the same event.
#expect(timeline[0].startedProcessIDs.count == 2)
#expect(timeline[0].startedProcessIDs.contains("bell_0"))
#expect(timeline[0].startedProcessIDs.contains("bell_1"))
}
// MARK: - Test 8: Unknown factory throws
@Test("Entry referencing an unknown baseID throws unknownProcessFactory")
func testUnknownFactoryThrows() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["unknown_id"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [:] // empty — no factories
do {
_ = try LyrebirdEventList.buildFromFile(
id: "test8",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileURL]
)
Issue.record("Expected LyrebirdProcessError.unknownProcessFactory to be thrown")
} catch let error as LyrebirdProcessError {
if case .unknownProcessFactory(let baseID) = error {
#expect(baseID == "unknown_id")
} else {
Issue.record("Unexpected LyrebirdProcessError variant: \(error)")
}
}
}
// MARK: - Test 9: Release before start throws
@Test("Release of a baseID before any start throws releaseBeforeStart")
func testReleaseBeforeStartThrows() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
// Release 'bell' at offset 0.0 before any start.
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: [], releasedProcessIDs: ["bell"])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell")
]
do {
_ = try LyrebirdEventList.buildFromFile(
id: "test9",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [fileURL]
)
Issue.record("Expected LyrebirdProcessError.releaseBeforeStart to be thrown")
} catch let error as LyrebirdProcessError {
if case .releaseBeforeStart(let baseID) = error {
#expect(baseID == "bell")
} else {
Issue.record("Unexpected LyrebirdProcessError variant: \(error)")
}
}
}
// MARK: - Test 10: Empty paths array throws
@Test("Empty paths array throws buildFromFileNoInput")
func testEmptyPathsThrows() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
do {
_ = try LyrebirdEventList.buildFromFile(
id: "test10",
engine: engine,
processFactories: [:],
tolerance: 0.1,
paths: []
)
Issue.record("Expected LyrebirdProcessError.buildFromFileNoInput to be thrown")
} catch let error as LyrebirdProcessError {
if case .buildFromFileNoInput = error {
// Expected.
} else {
Issue.record("Unexpected LyrebirdProcessError variant: \(error)")
}
}
}
// MARK: - Test 11: Negative tolerance throws
@Test("Negative tolerance throws invalidTolerance")
func testNegativeToleranceThrows() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
try writeEntries([], to: fileURL)
let negativeTolerance: Double = -0.1
do {
_ = try LyrebirdEventList.buildFromFile(
id: "test11",
engine: engine,
processFactories: [:],
tolerance: negativeTolerance,
paths: [fileURL]
)
Issue.record("Expected LyrebirdProcessError.invalidTolerance to be thrown")
} catch let error as LyrebirdProcessError {
if case .invalidTolerance(let value) = error {
#expect(value == negativeTolerance)
} else {
Issue.record("Unexpected LyrebirdProcessError variant: \(error)")
}
}
}
// MARK: - Test 12: Tolerance 0 — every entry is its own event
@Test("Tolerance 0 gives each entry its own event even for adjacent offsets")
func testZeroToleranceSeparatesAllEntries() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("log.json")
// Three entries at the same offset — with tolerance 0 every entry is its own group.
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.001, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.002, eventIndex: 2, startedProcessIDs: ["wash"], releasedProcessIDs: [])
]
try writeEntries(entries, to: fileURL)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test12",
engine: engine,
processFactories: factories,
tolerance: 0.0,
paths: [fileURL]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 3)
}
// MARK: - Test 13: Empty file with other non-empty files is tolerated
@Test("Empty file alongside non-empty files is tolerated; non-empty files contribute entries")
func testEmptyFileTolerated() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let emptyFile: URL = tempDir.appendingPathComponent("empty.json")
let activeFile: URL = tempDir.appendingPathComponent("active.json")
// Write an empty JSON array.
try writeEntries([], to: emptyFile)
try writeEntries([
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: [])
], to: activeFile)
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone")
]
let list: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "test13",
engine: engine,
processFactories: factories,
tolerance: 0.1,
paths: [emptyFile, activeFile]
)
var eventCount: Int = 0
while list.nextEvent != nil {
list.next()
eventCount += 1
}
#expect(eventCount == 2)
}
// MARK: - Test 14: Round-trip — save timeline then buildFromFile
@Test("Round-trip: save a known timeline and rebuild with buildFromFile gives same event count and minted IDs")
func testRoundTrip() throws {
let engine: SynthesisEngine = makeBFFTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
// Build a 3-event EventList and inject a known timeline with distinct offsets.
// Using setTimeline avoids relying on wall-clock timing (which could round
// multiple near-simultaneous events to offset 0.0000 after 4 dp rounding).
let procA: LyrebirdProcess = LyrebirdProcess(id: "bell", envelope: shortEnvelope(), numChannels: 1, body: { _ in })
let procB: LyrebirdProcess = LyrebirdProcess(id: "drone", envelope: shortEnvelope(), numChannels: 1, body: { _ in })
let procC: LyrebirdProcess = LyrebirdProcess(id: "wash", envelope: shortEnvelope(), numChannels: 1, body: { _ in })
let sourceList: LyrebirdEventList = try LyrebirdEventList(
id: "source",
events: [
LyrebirdEvent(starts: [procA]),
LyrebirdEvent(starts: [procB]),
LyrebirdEvent(starts: [procC])
],
engine: engine
)
// Inject a known timeline with clearly-distinct offsets.
let knownEntries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["bell"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 1, startedProcessIDs: ["drone"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 2.0, eventIndex: 2, startedProcessIDs: ["wash"], releasedProcessIDs: [])
]
try sourceList.setTimeline(knownEntries)
let savedTimelineURL: URL = tempDir.appendingPathComponent("timeline.json")
try sourceList.saveTimeline(to: savedTimelineURL)
// The saved timeline uses the original IDs (e.g. "bell", "drone", "wash").
// buildFromFile will mint "bell_0", "drone_0", "wash_0".
let factories: [String: (String) -> LyrebirdProcess] = [
"bell": makeFactory("bell"),
"drone": makeFactory("drone"),
"wash": makeFactory("wash")
]
let rebuiltList: LyrebirdEventList = try LyrebirdEventList.buildFromFile(
id: "rebuilt",
engine: engine,
processFactories: factories,
tolerance: 0.5,
paths: [savedTimelineURL]
)
// The rebuilt list should have the same number of events as the source timeline.
var eventCount: Int = 0
while rebuiltList.nextEvent != nil {
rebuiltList.next()
eventCount += 1
}
#expect(eventCount == knownEntries.count)
// Minted IDs follow the <baseID>_<counter> scheme.
let rebuiltTimeline: [LyrebirdTimelineEntry] = rebuiltList.timeline
#expect(rebuiltTimeline.count == 3)
#expect(rebuiltTimeline[0].startedProcessIDs == ["bell_0"])
#expect(rebuiltTimeline[1].startedProcessIDs == ["drone_0"])
#expect(rebuiltTimeline[2].startedProcessIDs == ["wash_0"])
}
}
@@ -0,0 +1,271 @@
// LyrebirdEventListPrePostGroupTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Test fixtures
private final class SilentSynth: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.0))
}
}
private func sustainedEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.05],
curves: [.lin, .lin],
releaseNode: 2
)
}
private func makePrePostTestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: OfflineDriver()
)
}
@Suite("LyrebirdEventList preMasterGroup / postMasterGroup")
struct LyrebirdEventListPrePostGroupTests {
@Test("preMasterGroup and postMasterGroup are non-nil before play")
func testGroupsExistBeforePlay() throws {
let engine: SynthesisEngine = makePrePostTestEngine()
let proc: LyrebirdProcess = LyrebirdProcess(
id: "p",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-groups-exist",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Groups are constructed in init — accessible immediately.
#expect(list.preMasterGroup.count == 0)
#expect(list.postMasterGroup.count == 0)
}
@Test("addPreMaster routes synth into preMasterGroup")
func testAddPreMasterRoutes() async throws {
let engine: SynthesisEngine = makePrePostTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "p",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-add-pre",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Fire first event so groups are added to the engine.
list.next()
// Drive a block so pendingQueue events apply.
engine.processBlock(inputSamples: [])
let pre: SilentSynth = SilentSynth()
try list.addPreMaster(pre)
engine.processBlock(inputSamples: [])
#expect(list.preMasterGroup.count == 1)
#expect(list.postMasterGroup.count == 0)
list.killAll()
}
@Test("addPostMaster routes synth into postMasterGroup")
func testAddPostMasterRoutes() async throws {
let engine: SynthesisEngine = makePrePostTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "p",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-add-post",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
list.next()
engine.processBlock(inputSamples: [])
let post: SilentSynth = SilentSynth()
try list.addPostMaster(post)
engine.processBlock(inputSamples: [])
#expect(list.postMasterGroup.count == 1)
#expect(list.preMasterGroup.count == 0)
list.killAll()
}
@Test("pre-master synth evaluates before master, post-master evaluates after master (bus content order)")
func testEvaluationOrder() async throws {
let engine: SynthesisEngine = makePrePostTestEngine()
try engine.start()
defer { engine.stop() }
// Drive a process that does nothing (sustained, no writes).
let proc: LyrebirdProcess = LyrebirdProcess(
id: "silent",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
// EventList configured with amp=1.0, ampLag~0 so master is effective passthrough.
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-order",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
amp: 1.0,
ampLag: 0.0001,
bus: AudioBus(index: 0, channelCount: 1)
)
list.next()
// Drive several blocks to let the master synth's Lag.Audio settle to
// its target. At sr=44100 and ampLag=0.0001 s ≈ 4.4 samples, smoothing
// settles in <1 block (64 samples). The 8-block warm-up is generous —
// it covers the pending-queue dispatch (first event setup → master
// synth build → Lag.Audio init) plus several full blocks of headroom
// so the master synth's amp is at its target by the time the test
// measures bus content.
for _: Int in 0..<8 { engine.processBlock(inputSamples: []) }
// Pre-master synth additively writes 0.3 to bus 0.
final class PreWriter: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.3 as Double))
}
}
// Post-master synth additively writes 0.1 to bus 0.
final class PostWriter: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.1 as Double))
}
}
try list.addPreMaster(PreWriter())
try list.addPostMaster(PostWriter())
// Drive one block to apply the adds, then a second block where both synths run.
engine.processBlock(inputSamples: [])
engine.processBlock(inputSamples: [])
// Expected sequence in this block:
// process group (no write)
// pre-master: bus[0] += 0.3 → 0.3
// master: bus[0] = 0.3 * 1.0 → 0.3 (ReplaceOut)
// post-master: bus[0] += 0.1 → 0.4
// Tolerance allows for Lag.Audio ramp residuals.
let sample: Float = engine.audioBuses[0][0]
#expect(abs(sample - 0.4) < 0.05)
list.killAll()
}
@Test("pre-master synth contribution is scaled by master amp, post-master is not")
func testMasterScalesPreNotPost() async throws {
let engine: SynthesisEngine = makePrePostTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "silent",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-master-scaling",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
amp: 0.5,
ampLag: 0.0001,
bus: AudioBus(index: 0, channelCount: 1)
)
list.next()
for _: Int in 0..<8 { engine.processBlock(inputSamples: []) }
final class PreWriter: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.4 as Double))
}
}
final class PostWriter: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.1 as Double))
}
}
try list.addPreMaster(PreWriter())
try list.addPostMaster(PostWriter())
engine.processBlock(inputSamples: [])
engine.processBlock(inputSamples: [])
// Expected: (0.4 * 0.5) + 0.1 = 0.3
let sample: Float = engine.audioBuses[0][0]
#expect(abs(sample - 0.3) < 0.05)
list.killAll()
}
@Test("teardown frees pre/post group children")
func testTeardownFreesChildren() async throws {
let engine: SynthesisEngine = makePrePostTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "p",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-teardown",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
list.next()
engine.processBlock(inputSamples: [])
try list.addPreMaster(SilentSynth())
try list.addPostMaster(SilentSynth())
engine.processBlock(inputSamples: [])
#expect(list.preMasterGroup.count == 1)
#expect(list.postMasterGroup.count == 1)
list.killAll()
// After teardown the EventList re-allocates fresh empty groups.
engine.processBlock(inputSamples: [])
#expect(list.preMasterGroup.count == 0)
#expect(list.postMasterGroup.count == 0)
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,607 @@
// LyrebirdEventListTimelineTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import AudioToolbox
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Private test fixtures
/// Returns a minimal engine backed by OfflineDriver (no real-time audio).
private func makeTimelineTestEngine(sampleRate: Double = 44100) -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: OfflineDriver()
)
}
/// Short auto-releasing envelope (~40 ms).
private func shortAutoEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.02],
curves: [.lin, .lin]
)
}
/// Drives `engine.processBlock` at ~1 ms intervals while `_running` is true.
private final class TimelineTestBlockDriver: @unchecked Sendable {
private var _running: Bool = false
private let _engine: SynthesisEngine
private static let blockIntervalSeconds: Double = 0.001
init(engine: SynthesisEngine) { _engine = engine }
func start() {
_running = true
let t: Thread = Thread { [self] in
while self._running {
self._engine.processBlock(inputSamples: [])
Thread.sleep(forTimeInterval: TimelineTestBlockDriver.blockIntervalSeconds)
}
}
t.qualityOfService = .userInteractive
t.start()
}
func stop() { _running = false }
}
/// Returns a temporary directory. Caller is responsible for cleanup.
private func makeTempDir() -> URL {
FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
}
/// Best-effort temp directory removal.
private func removeTempDir(_ url: URL) {
try? FileManager.default.removeItem(at: url)
}
/// Build a `LyrebirdEventList` with `count` events, each starting one new process.
/// Returns both the list and all processes in event-order.
private func makeSimpleEventList(
id: String,
count: Int,
engine: SynthesisEngine
) throws -> (list: LyrebirdEventList, processes: [LyrebirdProcess]) {
var processes: [LyrebirdProcess] = []
var events: [LyrebirdEvent] = []
for i: Int in 0..<count {
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-\(i)",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in }
)
processes.append(proc)
events.append(LyrebirdEvent(starts: [proc]))
}
let list: LyrebirdEventList = try LyrebirdEventList(id: id, events: events, engine: engine, bus: AudioBus(index: 0, channelCount: 2))
return (list, processes)
}
// MARK: - Suite
@Suite("LyrebirdEventListTimeline")
struct LyrebirdEventListTimelineTests {
// MARK: - Test 1: Live capture count
@Test("Live capture: firing 3 events produces timeline.count == 3")
func testLiveCaptureCount() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "live-count", count: 3, engine: engine)
list.next()
try? await Task.sleep(nanoseconds: 10_000_000) // 10 ms
list.next()
try? await Task.sleep(nanoseconds: 10_000_000)
list.next()
#expect(list.timeline.count == 3)
}
// MARK: - Test 2: First entry has offset == 0.0
@Test("First captured entry has offset == 0.0")
func testFirstEntryOffsetIsZero() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "first-zero", count: 2, engine: engine)
list.next()
#expect(list.timeline.first?.offset == 0.0)
}
// MARK: - Test 3: startedProcessIDs / releasedProcessIDs
@Test("Timeline entries capture correct startedProcessIDs and releasedProcessIDs")
func testProcessIDCapture() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let procA: LyrebirdProcess = LyrebirdProcess(
id: "alpha",
envelope: Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.05, 0.2],
curves: [.lin, .lin],
releaseNode: 2
),
numChannels: 1,
body: { _ in }
)
let procB: LyrebirdProcess = LyrebirdProcess(
id: "beta",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in }
)
// Event 0 starts A; event 1 starts B and releases A.
let list: LyrebirdEventList = try LyrebirdEventList(
id: "id-capture",
events: [
LyrebirdEvent(starts: [procA]),
LyrebirdEvent(starts: [procB], releases: [procA])
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
list.next() // fires event 0
try? await Task.sleep(nanoseconds: 50_000_000) // 50 ms
list.next() // fires event 1
let entries: [LyrebirdTimelineEntry] = list.timeline
#expect(entries.count == 2)
#expect(entries[0].startedProcessIDs == ["alpha"])
#expect(entries[0].releasedProcessIDs == [])
#expect(entries[1].startedProcessIDs == ["beta"])
#expect(entries[1].releasedProcessIDs == ["alpha"])
}
// MARK: - Test 4: saveTimeline / loadTimeline round-trip
@Test("saveTimeline then loadTimeline produces equal entry arrays")
func testSaveLoadRoundTrip() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("timeline.json")
let (listA, _) = try makeSimpleEventList(id: "roundtrip-A", count: 3, engine: engine)
listA.next()
try? await Task.sleep(nanoseconds: 30_000_000)
listA.next()
try? await Task.sleep(nanoseconds: 30_000_000)
listA.next()
try listA.saveTimeline(to: fileURL)
// Load into a fresh EventList with the same event count.
let (listB, _) = try makeSimpleEventList(id: "roundtrip-B", count: 3, engine: engine)
try listB.loadTimeline(from: fileURL)
#expect(listA.timeline == listB.timeline)
}
// MARK: - Test 5: JSON format — human-readable, pretty-printed, sorted keys
@Test("JSON output is pretty-printed and contains all required property keys")
func testJSONFormatContainsExpectedKeys() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("fmt-check.json")
let proc: LyrebirdProcess = LyrebirdProcess(
id: "json-proc",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "json-list",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
list.next()
try list.saveTimeline(to: fileURL)
let content: String = try String(contentsOf: fileURL, encoding: .utf8)
// Pretty-printed JSON has newlines.
#expect(content.contains("\n"), "Expected pretty-printed JSON with newlines")
// All required keys are present.
#expect(content.contains("\"eventIndex\""))
#expect(content.contains("\"offset\""))
#expect(content.contains("\"releasedProcessIDs\""))
#expect(content.contains("\"startedProcessIDs\""))
}
// MARK: - Test 6: loadTimeline rejects out-of-range eventIndex
@Test("loadTimeline throws LyrebirdTimelineError for out-of-range eventIndex")
func testLoadTimelineOutOfRange() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
let tempDir: URL = makeTempDir()
defer { removeTempDir(tempDir) }
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let fileURL: URL = tempDir.appendingPathComponent("bad-index.json")
// Write a JSON entry with eventIndex == 99, but list only has 2 events.
let badJSON: String = """
[
{
"eventIndex": 99,
"offset": 0.0,
"releasedProcessIDs": [],
"startedProcessIDs": []
}
]
"""
try badJSON.write(to: fileURL, atomically: true, encoding: .utf8)
let (list, _) = try makeSimpleEventList(id: "bad-index-list", count: 2, engine: engine)
do {
try list.loadTimeline(from: fileURL)
Issue.record("Expected LyrebirdTimelineError.eventIndexOutOfRange to be thrown")
} catch let error as LyrebirdTimelineError {
switch error {
case .eventIndexOutOfRange(_, let idx):
#expect(idx == 99)
}
}
}
// MARK: - Test 7: playTimeline fires events in order
@Test("playTimeline fires events in index order with expected timing")
func testPlayTimelineSchedulesCorrectly() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "play-timing", count: 2, engine: engine)
let secondEventOffset: Double = 0.1 // 100 ms
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["proc-0"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: secondEventOffset, eventIndex: 1, startedProcessIDs: ["proc-1"], releasedProcessIDs: [])
]
try list.setTimeline(entries)
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120.0)
var firedIndices: [Int] = []
let firedLock: NSLock = NSLock()
list.onEvent = { idx in
firedLock.withLock { firedIndices.append(idx) }
}
list.playTimeline(clock: clock)
#expect(list.isPlayingTimeline)
// Wait up to 3 s for both events to fire.
let deadline: Date = Date().addingTimeInterval(3.0)
while Date() < deadline {
let count: Int = firedLock.withLock { firedIndices.count }
if count >= 2 { break }
try? await Task.sleep(nanoseconds: 5_000_000)
}
let allFired: [Int] = firedLock.withLock { firedIndices }
#expect(allFired.count >= 1)
if allFired.count >= 2 {
#expect(allFired[0] == 0)
#expect(allFired[1] == 1)
}
}
// MARK: - Test 8: _isReplaying suppresses capture
@Test("playTimeline replay does not double-append entries into the timeline")
func testReplayDoesNotDoubleCapture() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "no-double", count: 2, engine: engine)
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["proc-0"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.05, eventIndex: 1, startedProcessIDs: ["proc-1"], releasedProcessIDs: [])
]
try list.setTimeline(entries)
let expectedCount: Int = entries.count
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120.0)
list.playTimeline(clock: clock)
// Wait for playback to complete (up to 3 s).
let deadline: Date = Date().addingTimeInterval(3.0)
while list.isPlayingTimeline && Date() < deadline {
try? await Task.sleep(nanoseconds: 10_000_000)
}
// Timeline must remain exactly as loaded — no extra entries from replay.
#expect(list.timeline.count == expectedCount)
}
// MARK: - Test 9: stopTimelinePlayback cancels remaining events
@Test("stopTimelinePlayback sets isPlayingTimeline to false and cancels pending events")
func testStopTimelinePlayback() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "stop-test", count: 3, engine: engine)
// Three events: immediate, 0.5 s, 1.0 s — we stop after ~100 ms.
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: [], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.5, eventIndex: 1, startedProcessIDs: [], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 1.0, eventIndex: 2, startedProcessIDs: [], releasedProcessIDs: [])
]
try list.setTimeline(entries)
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120.0)
list.playTimeline(clock: clock)
#expect(list.isPlayingTimeline)
// Let the first event fire, then stop.
try? await Task.sleep(nanoseconds: 100_000_000) // 100 ms
list.stopTimelinePlayback()
#expect(!list.isPlayingTimeline)
}
// MARK: - Test 10: reset() clears timeline
@Test("reset() empties the timeline array")
func testResetClearsTimeline() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "reset-clear", count: 2, engine: engine)
list.next()
list.next()
#expect(list.timeline.count == 2)
list.reset()
#expect(list.timeline.isEmpty)
}
// MARK: - Test 11: clearTimeline() empties without killing processes
@Test("clearTimeline() empties array without affecting running state or processes")
func testClearTimeline() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "clear-test", count: 2, engine: engine)
list.next()
#expect(list.timeline.count == 1)
#expect(list.isRunning)
list.clearTimeline()
#expect(list.timeline.isEmpty)
// Running state is unaffected by clearTimeline.
#expect(list.isRunning)
}
// MARK: - Test 12: setTimeline validates range and accepts valid input
@Test("setTimeline accepts valid entries and rejects out-of-range eventIndex")
func testSetTimelineValidation() throws {
let engine: SynthesisEngine = makeTimelineTestEngine()
let (list, _) = try makeSimpleEventList(id: "set-validate", count: 3, engine: engine)
// Valid entries referencing indices 0 and 2 (both in 0..<3).
let validEntries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: [], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: 0.1, eventIndex: 2, startedProcessIDs: [], releasedProcessIDs: [])
]
try list.setTimeline(validEntries)
#expect(list.timeline == validEntries)
// Invalid entry: index == 3 (out of range for 3-event list).
let badEntries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 3, startedProcessIDs: [], releasedProcessIDs: [])
]
do {
try list.setTimeline(badEntries)
Issue.record("Expected LyrebirdTimelineError to be thrown for out-of-range index")
} catch let error as LyrebirdTimelineError {
switch error {
case .eventIndexOutOfRange(_, let idx):
#expect(idx == 3)
}
}
// Existing timeline must be unchanged after a failed setTimeline call.
#expect(list.timeline == validEntries)
}
// MARK: - Test 13: NRT replay smoke test
@Test("NRT replay: playTimeline fires events at approximately correct wall-clock intervals")
func testNRTReplaySmoke() async throws {
let engine: SynthesisEngine = makeTimelineTestEngine(sampleRate: 44100)
try engine.start()
defer { engine.stop() }
// The block driver advances engine.currentTime so waitUntil(sampleTime:) can resolve.
let driver: TimelineTestBlockDriver = TimelineTestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "nrt-smoke", count: 2, engine: engine)
let secondEventOffset: Double = 0.2 // 200 ms
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(offset: 0.0, eventIndex: 0, startedProcessIDs: ["proc-0"], releasedProcessIDs: []),
LyrebirdTimelineEntry(offset: secondEventOffset, eventIndex: 1, startedProcessIDs: ["proc-1"], releasedProcessIDs: [])
]
try list.setTimeline(entries)
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120.0)
var eventFiredAt: [Int: Date] = [:]
let firedLock: NSLock = NSLock()
list.onEvent = { idx in
firedLock.withLock { eventFiredAt[idx] = Date() }
}
list.playTimeline(clock: clock)
// Wait up to 3 s for both events to fire.
let deadline: Date = Date().addingTimeInterval(3.0)
while Date() < deadline {
let count: Int = firedLock.withLock { eventFiredAt.count }
if count >= 2 { break }
try? await Task.sleep(nanoseconds: 10_000_000)
}
let firedMap: [Int : Date] = firedLock.withLock { eventFiredAt }
#expect(firedMap.count == 2)
if let t0: Date = firedMap[0], let t1: Date = firedMap[1] {
let measuredInterval: TimeInterval = t1.timeIntervalSince(t0)
// Wall-clock measurement against a 200 ms target. The
// `TimelineTestBlockDriver` ticks engine.processBlock on a
// background thread with `Thread.sleep(forTimeInterval:
// 0.001)`. Cumulative OS scheduling jitter over 200 ms can
// exceed 50 ms on a loaded CI runner — the previous 100 ms
// tolerance flaked intermittently. 200 ms (= the target
// interval itself) is the practical ceiling for this kind
// of smoke test; tightening below that requires moving off
// the wall-clock measurement entirely (e.g. sample-time
// delta from the engine itself).
let intervalTolerance: Double = 0.2
#expect(abs(measuredInterval - secondEventOffset) < intervalTolerance,
"Expected ~\(secondEventOffset)s between events, got \(measuredInterval)s")
}
}
// MARK: - Test 14: JSON format stability snapshot
@Test("JSON snapshot has correct key order and round-trips values correctly")
func testJSONSnapshot() throws {
let testOffset: Double = 1.2345
let entries: [LyrebirdTimelineEntry] = [
LyrebirdTimelineEntry(
offset: testOffset,
eventIndex: 2,
startedProcessIDs: ["alpha", "beta"],
releasedProcessIDs: ["gamma"]
)
]
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(entries)
guard let json: String = String(data: data, encoding: .utf8) else {
Issue.record("JSON encoding produced non-UTF8 data")
return
}
// Sorted key order: eventIndex < offset < releasedProcessIDs < startedProcessIDs.
let eventIndexPos: Range<String.Index>? = json.range(of: "\"eventIndex\"")
let offsetPos: Range<String.Index>? = json.range(of: "\"offset\"")
let releasedPos: Range<String.Index>? = json.range(of: "\"releasedProcessIDs\"")
let startedPos: Range<String.Index>? = json.range(of: "\"startedProcessIDs\"")
#expect(eventIndexPos != nil, "eventIndex key missing from JSON")
#expect(offsetPos != nil, "offset key missing from JSON")
#expect(releasedPos != nil, "releasedProcessIDs key missing from JSON")
#expect(startedPos != nil, "startedProcessIDs key missing from JSON")
if let ep: Range<String.Index> = eventIndexPos, let op: Range<String.Index> = offsetPos, let rp: Range<String.Index> = releasedPos, let sp: Range<String.Index> = startedPos {
#expect(ep.lowerBound < op.lowerBound, "eventIndex must precede offset in sorted JSON")
#expect(op.lowerBound < rp.lowerBound, "offset must precede releasedProcessIDs in sorted JSON")
#expect(rp.lowerBound < sp.lowerBound, "releasedProcessIDs must precede startedProcessIDs in sorted JSON")
}
// Round-trip correctness.
let decoder: JSONDecoder = JSONDecoder()
let roundTripped: [LyrebirdTimelineEntry] = try decoder.decode([LyrebirdTimelineEntry].self, from: data)
#expect(roundTripped.count == 1)
let entry: LyrebirdTimelineEntry = roundTripped[0]
#expect(entry.offset == testOffset)
#expect(entry.eventIndex == 2)
#expect(entry.startedProcessIDs == ["alpha", "beta"])
#expect(entry.releasedProcessIDs == ["gamma"])
}
}
@@ -0,0 +1,135 @@
// LyrebirdProcessReleaseNodeHoldTest.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdSynth
/// Regression — verify that `Envelope.releaseNode` uses the
/// SuperCollider-style LEVEL INDEX convention. The user-facing case:
///
/// ```swift
/// Envelope(
/// levels: [0.0, 1.0, 0.0],
/// durations: [2.0, 2.0],
/// releaseNode: 1 // hold at levels[1] = 1.0
/// )
/// ```
///
/// must hold at the peak value (1.0) indefinitely while gate > 0, not at
/// `levels[releaseNode + 1] = levels[2] = 0` (the pre-Phase-162 behavior).
@Suite("LyrebirdProcess envelope holds at releaseNode level index")
struct LyrebirdProcessReleaseNodeHoldTest {
@Test("Envelope.releaseNode is a LEVEL INDEX — hold value equals levels[releaseNode]")
func testReleaseNodeIsLevelIndex() throws {
let env: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [2.0, 2.0],
curves: [.lin, .lin],
releaseNode: 1
)
let rn: Int = try #require(env.releaseNode, "releaseNode should not be nil")
#expect(rn == 1, "Public releaseNode value should be preserved as the level index")
// levels[releaseNode] = levels[1] = 1.0 — the SUSTAIN level, not 0.
#expect(env.levels[rn] == 1.0)
}
@Test("Process envelope holds at releaseNode level — process keeps running past total-duration")
func testReleaseNodeHold() async throws {
let blockSize: Int = 64
let sampleRate: Double = 48000.0
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: OfflineDriver()
)
try engine.start()
defer { engine.stop() }
// `releaseNode: 1` on `[0.0, 1.0, 0.0]` holds at level[1] = 1.0.
// Segment 0 (attack, 0.05 s) plays, then the route envelope sustains at
// level 1.0 indefinitely while gate > 0. With `gate` still 1.0 there is
// no auto-completion — the process keeps running past the envelope's
// nominal total duration (0.1 s).
let processEnv: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.05, 0.05],
curves: [.sine, .sine],
releaseNode: 1
)
let proc: LyrebirdProcess = LyrebirdProcess(
id: "release-hold",
envelope: processEnv,
numChannels: 1,
body: { ctx in
while ctx.isRunning {
await ctx.wait(0.01)
}
}
)
proc.play(engine: engine)
// Drive engine-time way past the envelope's 0.1 s total. Without the
// SC-style hold, the envelope would reach level[2] = 0, the watcher
// would observe `needsFree`, and the process would tear down within
// a tick.
let blocksFor1Second: Int = Int(sampleRate / Double(blockSize))
for _ in 0..<(blocksFor1Second * 2) {
engine.processBlock(inputSamples: [])
}
#expect(proc.isRunning, "Process should still be running after 2s with no release()")
// Now release. The envelope progresses through segment 1 (1.0 → 0.0)
// as the release tail, then auto-frees.
proc.release()
for _ in 0..<blocksFor1Second {
engine.processBlock(inputSamples: [])
}
try await Task.sleep(nanoseconds: 200_000_000)
#expect(!proc.isRunning, "Process should have torn down after release() + envelope tail")
}
@Test("Out-of-range releaseNode is clamped to nil")
func testOutOfRangeClampsToNil() {
// Level index 0 is the start point — not a valid hold. Clamps to nil.
let envZero: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.1, 0.1],
curves: [.lin, .lin],
releaseNode: 0
)
#expect(envZero.releaseNode == nil)
// Level index 99 is out of range. Clamps to nil.
let envBig: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.1, 0.1],
curves: [.lin, .lin],
releaseNode: 99
)
#expect(envBig.releaseNode == nil)
}
@Test("releaseNode at the final level index is valid")
func testReleaseNodeAtFinalLevel() {
// levels.count == 3, levels.count - 1 == 2 — top of the valid range.
// Holds at levels[2] = 0.0 (silent hold — legal but uncommon).
let env: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.1, 0.1],
curves: [.lin, .lin],
releaseNode: 2
)
#expect(env.releaseNode == 2)
}
}
File diff suppressed because it is too large Load Diff