v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
This commit is contained in:
@@ -62,7 +62,7 @@ struct ProjectScaffolderBuildTests {
|
||||
/// Raw strings (not `ProjectTemplate` cases) are the parametrized arguments
|
||||
/// because `@Test(arguments:)` requires `Sendable` and the public
|
||||
/// `ProjectTemplate` enum does not declare the conformance.
|
||||
static let spmTemplateRawValues: [String] = ["basic", "demo", "nrt", "score", "ui-demo"]
|
||||
static let spmTemplateRawValues: [String] = ["quickstart", "basic", "demo", "nrt", "score", "ui-demo"]
|
||||
|
||||
@Test(arguments: spmTemplateRawValues)
|
||||
func templateBuildsAgainstLiveLyrebird(_ rawValue: String) throws {
|
||||
|
||||
@@ -221,6 +221,10 @@ struct ProjectScaffolderTests {
|
||||
// MARK: - ProjectTemplate
|
||||
|
||||
@Test func templateInitFromString() {
|
||||
#expect(ProjectTemplate(string: "quickstart") == .quickstart)
|
||||
#expect(ProjectTemplate(string: "quick-start") == .quickstart)
|
||||
#expect(ProjectTemplate(string: "quick") == .quickstart)
|
||||
#expect(ProjectTemplate(string: "QuickStart") == .quickstart)
|
||||
#expect(ProjectTemplate(string: "basic") == .basic)
|
||||
#expect(ProjectTemplate(string: "demo") == .demo)
|
||||
#expect(ProjectTemplate(string: "ui-demo") == .uiDemo)
|
||||
@@ -240,6 +244,7 @@ struct ProjectScaffolderTests {
|
||||
}
|
||||
|
||||
@Test func shipsXcodeProjectClassification() {
|
||||
#expect(ProjectTemplate.quickstart.shipsXcodeProject == false)
|
||||
#expect(ProjectTemplate.basic.shipsXcodeProject == false)
|
||||
#expect(ProjectTemplate.demo.shipsXcodeProject == false)
|
||||
#expect(ProjectTemplate.uiDemo.shipsXcodeProject == false)
|
||||
@@ -648,6 +653,26 @@ struct ProjectScaffolderTests {
|
||||
#expect(fm.fileExists(atPath: (sources as NSString).appendingPathComponent("MyAppSynth.swift")))
|
||||
}
|
||||
|
||||
// MARK: - quickstart template
|
||||
|
||||
@Test func quickstartMainSwiftPlaysThenExits() {
|
||||
let source: String = ProjectScaffolder.mainSwift(name: "MyFirstSound", template: .quickstart)
|
||||
// The pedagogical shape: define a synth, start, add, sleep, stop.
|
||||
#expect(source.contains("SineTone"))
|
||||
#expect(source.contains("OscSin.Audio(freq: 440.0)"))
|
||||
#expect(source.contains("engine.start()"))
|
||||
#expect(source.contains("engine.add(SineTone())"))
|
||||
#expect(source.contains("Thread.sleep(forTimeInterval:"))
|
||||
#expect(source.contains("engine.stop()"))
|
||||
// Plays for a fixed duration and exits — no RunLoop.
|
||||
#expect(!source.contains("RunLoop.main.run()"))
|
||||
}
|
||||
|
||||
@Test func quickstartPackageManifestDoesNotIncludeLyrebirdUI() {
|
||||
let manifest: String = ProjectScaffolder.packageManifest(name: "MyFirstSound", template: .quickstart)
|
||||
#expect(!manifest.contains("LyrebirdUI"))
|
||||
}
|
||||
|
||||
// MARK: - nrt template
|
||||
|
||||
@Test func nrtMainSwiftUsesNRTDriver() {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// DistributionKindGoldenValueTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Pins the golden values documented in `DistributionKind`'s per-distribution examples.
|
||||
///
|
||||
/// `scripts/check-doc-snippets.sh` typechecks those fences, but a typecheck cannot see a
|
||||
/// *value* drift: the example still compiles while its `// → …` comment silently becomes a
|
||||
/// lie. That happened — three of the four documented sequences (`.lpRand`, `.hpRand`,
|
||||
/// `.meanRand`) had drifted away from what the code actually produces, and the fences
|
||||
/// additionally passed `seed:` to `TemporalTendency`, which has no such parameter (the seed
|
||||
/// belongs to `TemporalStream`).
|
||||
///
|
||||
/// If a distribution's maths or the PRNG changes, this suite fails — update the doc comment
|
||||
/// in `Sources/Lyrebird/Distributions/DistributionKind.swift` and these expectations
|
||||
/// together.
|
||||
@Suite("DistributionKind golden values (docs)") struct DistributionKindGoldenValueTests {
|
||||
|
||||
/// The seed the doc comment names. Any change here invalidates every value below.
|
||||
private static let seed: UInt64 = 0xDEADCAFE12345678
|
||||
private static let sampleCount: Int = 5
|
||||
/// Values are documented to 3 decimal places, so compare at that resolution.
|
||||
private static let tolerance: Double = 0.0005
|
||||
/// The algebraic identities below are exact, not rounded — hold them to full precision.
|
||||
private static let exactTolerance: Double = 1e-12
|
||||
|
||||
private func collect(_ kind: DistributionKind) -> [Double] {
|
||||
TemporalStream(
|
||||
TemporalTendency(distribution: kind, parX: .value(0), parY: .value(1)),
|
||||
seed: Self.seed
|
||||
).collect(Self.sampleCount)
|
||||
}
|
||||
|
||||
/// Collect from an explicitly-built tendency, for the distributions whose documented
|
||||
/// example uses parameters other than `parX: 0, parY: 1`.
|
||||
private func collect(_ t: TemporalTendency) -> [Double] {
|
||||
TemporalStream(t, seed: Self.seed).collect(Self.sampleCount)
|
||||
}
|
||||
|
||||
private func expect(_ label: String, _ actual: [Double], _ expected: [Double]) {
|
||||
#expect(actual.count == expected.count)
|
||||
for (a, e) in zip(actual, expected) {
|
||||
#expect(abs(a - e) < Self.tolerance,
|
||||
"\(label) drifted from the documented sequence: got \(actual), doc says \(expected)")
|
||||
}
|
||||
}
|
||||
|
||||
private func expect(_ kind: DistributionKind, _ expected: [Double]) {
|
||||
expect("\(kind)", collect(kind), expected)
|
||||
}
|
||||
|
||||
@Test func uniformMatchesDocs() {
|
||||
expect(.uniform, [0.744, 0.046, 0.799, 0.681, 0.517])
|
||||
}
|
||||
|
||||
@Test func lpRandMatchesDocs() {
|
||||
expect(.lpRand, [0.553, 0.002, 0.638, 0.464, 0.267])
|
||||
}
|
||||
|
||||
@Test func hpRandMatchesDocs() {
|
||||
expect(.hpRand, [0.447, 0.998, 0.362, 0.536, 0.733])
|
||||
}
|
||||
|
||||
@Test func meanRandMatchesDocs() {
|
||||
expect(.meanRand, [0.395, 0.740, 0.400, 0.410, 0.899])
|
||||
}
|
||||
|
||||
/// The documented characterisations, checked as relationships rather than values:
|
||||
/// `.lpRand` is the squared uniform and `.hpRand` its mirror. This is what makes the
|
||||
/// prose ("squared uniform, biases toward lo") verifiable rather than merely asserted.
|
||||
@Test func lpAndHpRandAreSquaredUniformAndItsMirror() {
|
||||
let u: [Double] = collect(.uniform)
|
||||
let lp: [Double] = collect(.lpRand)
|
||||
let hp: [Double] = collect(.hpRand)
|
||||
for i: Int in 0..<Self.sampleCount {
|
||||
#expect(abs(lp[i] - u[i] * u[i]) < Self.exactTolerance,
|
||||
"lpRand should be the squared uniform")
|
||||
#expect(abs(hp[i] - (1.0 - u[i] * u[i])) < Self.exactTolerance,
|
||||
"hpRand should mirror the squared uniform")
|
||||
}
|
||||
}
|
||||
|
||||
// The remaining documented distributions. Every one of these sequences was wrong before
|
||||
// being regenerated from the real API — the doc had drifted while its prose stayed right.
|
||||
|
||||
@Test func expRandMatchesDocs() {
|
||||
expect("expRand", collect(TemporalTendency(distribution: .expRand,
|
||||
parX: .value(1), parY: .value(100))),
|
||||
[30.743, 1.234, 39.596, 23.035, 10.818])
|
||||
}
|
||||
|
||||
@Test func exponentialMatchesDocs() {
|
||||
expect("exponential", collect(TemporalTendency(distribution: .exponential, parX: .value(1))),
|
||||
[0.296, 3.085, 0.225, 0.384, 0.660])
|
||||
}
|
||||
|
||||
@Test func gammaMatchesDocs() {
|
||||
expect("gamma", collect(TemporalTendency(distribution: .gamma, parX: .value(2))),
|
||||
[2.812, 0.776, 1.756, 1.326, 3.649])
|
||||
}
|
||||
|
||||
@Test func laplaceMatchesDocs() {
|
||||
expect("laplace", collect(TemporalTendency(distribution: .laplace, parX: .value(1))),
|
||||
[0.669, -2.392, 0.910, 0.450, 0.035])
|
||||
}
|
||||
|
||||
@Test func alaplaceMatchesDocs() {
|
||||
expect("alaplace", collect(TemporalTendency(distribution: .alaplace, parX: .value(1))),
|
||||
[0.527, -3.898, 1.332, -0.039, -0.433])
|
||||
}
|
||||
|
||||
@Test func hcosMatchesDocs() {
|
||||
expect("hcos", collect(TemporalTendency(distribution: .hcos, parX: .value(1))),
|
||||
[0.162, -0.363, 0.204, 0.118, 0.011])
|
||||
}
|
||||
|
||||
@Test func logisticMatchesDocs() {
|
||||
expect("logistic", collect(TemporalTendency(distribution: .logistic, parX: .value(1))),
|
||||
[1.066, -3.039, 1.379, 0.759, 0.068])
|
||||
}
|
||||
|
||||
@Test func poissonMatchesDocs() {
|
||||
expect("poisson", collect(TemporalTendency(distribution: .poisson, parX: .value(3))),
|
||||
[1.000, 4.000, 4.000, 1.000, 4.000])
|
||||
}
|
||||
|
||||
@Test func arcsinMatchesDocs() {
|
||||
expect("arcsin", collect(TemporalTendency(distribution: .arcsin, parX: .value(1))),
|
||||
[0.693, -0.990, 0.807, 0.539, 0.054])
|
||||
}
|
||||
|
||||
@Test func betaRandMatchesDocs() {
|
||||
expect("betaRand", collect(TemporalTendency(distribution: .betaRand,
|
||||
parX: .value(0), parY: .value(1),
|
||||
parA: .value(2), parB: .value(5))),
|
||||
[0.482, 0.301, 0.471, 0.415, 0.066])
|
||||
}
|
||||
|
||||
@Test func cauchyMatchesDocs() {
|
||||
expect("cauchy", collect(TemporalTendency(distribution: .cauchy,
|
||||
parX: .value(0), parY: .value(1))),
|
||||
[0.962, -6.916, 1.366, 0.640, 0.054])
|
||||
}
|
||||
|
||||
@Test func gaussMatchesDocs() {
|
||||
expect("gauss", collect(TemporalTendency(distribution: .gauss,
|
||||
parX: .value(1), parY: .value(0))),
|
||||
[0.738, -0.281, -0.238, 0.068, 0.328])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// MaxEventsPerBlockTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Verifies the configurable per-block scheduling cap governs the future-event
|
||||
/// look-ahead depth carried across block boundaries.
|
||||
@MainActor
|
||||
@Suite("maxEventsPerBlock look-ahead cap") struct MaxEventsPerBlockTests {
|
||||
|
||||
private static let blockSize: Int = 64
|
||||
// Fire target well past block 0 so every scheduled event lands in carry-over first.
|
||||
private static let targetBlock: Int = 8
|
||||
private static let scheduledCount: Int = 300
|
||||
|
||||
/// Schedule `scheduledCount` synths at a single future time, then run blocks until it
|
||||
/// passes. Returns how many actually activated.
|
||||
private func activatedCount(maxEventsPerBlock: Int) throws -> Int {
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
blockSize: Self.blockSize,
|
||||
eventQueueCapacity: 1024,
|
||||
maxEventsPerBlock: maxEventsPerBlock
|
||||
)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let targetTime: SampleTime = SampleTime(Self.targetBlock * Self.blockSize)
|
||||
for _ in 0..<Self.scheduledCount {
|
||||
try engine.schedule(ConstantSynth(value: 0.0), at: targetTime)
|
||||
}
|
||||
|
||||
// Run past the target block: block 0 drains the pending queue into carry-over
|
||||
// (capped), later blocks carry it forward, the target block fires it.
|
||||
for _ in 0...(Self.targetBlock + 1) {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
return engine.synthesizerCount
|
||||
}
|
||||
|
||||
@Test func defaultCapDropsSurplusLookAhead() throws {
|
||||
// 300 future events > default cap 256 → only the cap survives carry-over.
|
||||
let activated: Int = try activatedCount(maxEventsPerBlock: lyrebirdDefaultMaxEventsPerBlock)
|
||||
#expect(activated == lyrebirdDefaultMaxEventsPerBlock)
|
||||
}
|
||||
|
||||
@Test func raisedCapKeepsAllLookAhead() throws {
|
||||
// Cap 512 > 300 scheduled → every event survives carry-over and fires.
|
||||
let activated: Int = try activatedCount(maxEventsPerBlock: 512)
|
||||
#expect(activated == Self.scheduledCount)
|
||||
}
|
||||
|
||||
@Test func exceedingCapIncrementsDropCounter() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
blockSize: Self.blockSize,
|
||||
eventQueueCapacity: 1024,
|
||||
maxEventsPerBlock: lyrebirdDefaultMaxEventsPerBlock
|
||||
)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
#expect(engine.perBlockEventDropCount == 0)
|
||||
|
||||
let targetTime: SampleTime = SampleTime(Self.targetBlock * Self.blockSize)
|
||||
for _ in 0..<Self.scheduledCount {
|
||||
try engine.schedule(ConstantSynth(value: 0.0), at: targetTime)
|
||||
}
|
||||
for _ in 0...(Self.targetBlock + 1) {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
// 300 scheduled, 256 cap → 44 dropped from the look-ahead carry-over.
|
||||
#expect(engine.perBlockEventDropCount == UInt64(Self.scheduledCount - lyrebirdDefaultMaxEventsPerBlock))
|
||||
}
|
||||
|
||||
@Test func withinCapLeavesDropCounterZero() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(
|
||||
blockSize: Self.blockSize,
|
||||
eventQueueCapacity: 1024,
|
||||
maxEventsPerBlock: 512
|
||||
)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let targetTime: SampleTime = SampleTime(Self.targetBlock * Self.blockSize)
|
||||
for _ in 0..<Self.scheduledCount {
|
||||
try engine.schedule(ConstantSynth(value: 0.0), at: targetTime)
|
||||
}
|
||||
for _ in 0...(Self.targetBlock + 1) {
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
#expect(engine.perBlockEventDropCount == 0)
|
||||
}
|
||||
|
||||
@Test func configuredValueIsExposed() {
|
||||
let engine: SynthesisEngine = makeTestEngine(eventQueueCapacity: 2048, maxEventsPerBlock: 1024)
|
||||
#expect(engine.maxEventsPerBlock == 1024)
|
||||
}
|
||||
|
||||
@Test func defaultValueMatchesConstant() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
#expect(engine.maxEventsPerBlock == lyrebirdDefaultMaxEventsPerBlock)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// RoutineContextOnMainTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// `LyrebirdRoutineContext.onMain` — construct `@MainActor` synthesizers from inside a
|
||||
/// `@Sendable` routine/task body, instead of pre-allocating them outside and capturing.
|
||||
///
|
||||
/// The suite is intentionally **not** `@MainActor`: `LyrebirdTask.run` blocks the calling
|
||||
/// thread, and the body's `ctx.add` / `ctx.onMain` hops need a free main thread to service
|
||||
/// them. Running the test off-main takes `waitUntilComplete()`'s plain-poll branch and leaves
|
||||
/// the main queue available — matching the existing `LyrebirdTask` suites.
|
||||
@Suite("RoutineContext.onMain") struct RoutineContextOnMainTests {
|
||||
|
||||
/// Bounded wait for main-dispatched `build()` calls: 100 × 10 ms = 1 s ceiling.
|
||||
private let pollAttempts: Int = 100
|
||||
private let pollIntervalSeconds: Double = 0.01
|
||||
|
||||
/// Counts `build()` calls so a test can prove a dynamically-constructed synth
|
||||
/// actually reached the engine.
|
||||
///
|
||||
/// The counter is an `Atomic` because `build()` runs on the main thread (inside the
|
||||
/// `engine.add` that `ctx.add` dispatches) while the test reads it from the test thread —
|
||||
/// a plain `var` would be a data race even though the values would usually agree.
|
||||
final class CountingSynth: SynthesizerBase {
|
||||
// `nonisolated` is legal here (immutable `let` of a Sendable type) — it would be
|
||||
// rejected on a mutable stored property. Needed so the off-main test body can read it.
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
let value: Double
|
||||
|
||||
init(value: Double) {
|
||||
self.value = value
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
CountingSynth.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
addOutputGenerator(Out.Audio(bus: 0, source: value))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func onMainReturnsValueBuiltOnMainThread() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let bodyWasOffMain: Ref<Bool> = Ref(false)
|
||||
let workRanOnMain: Ref<Bool> = Ref(false)
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
// Establish the body is off-main first, so the assertion below proves a real
|
||||
// hop occurred rather than passing vacuously via the bridge's inline branch.
|
||||
bodyWasOffMain.value = !Thread.isMainThread
|
||||
workRanOnMain.value = ctx.onMain { Thread.isMainThread }
|
||||
}
|
||||
#expect(bodyWasOffMain.value)
|
||||
#expect(workRanOnMain.value)
|
||||
}
|
||||
|
||||
@Test func onMainConstructsSynthesizerInsideBody() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let expected: Int = 3
|
||||
CountingSynth.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// The body decides how many synths to make — impossible with pre-allocation.
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
for i: Int in 0..<expected {
|
||||
let s: CountingSynth = ctx.onMain { CountingSynth(value: Double(i)) }
|
||||
ctx.add(s)
|
||||
try ctx.wait(seconds: 0.01)
|
||||
}
|
||||
}
|
||||
|
||||
// `ctx.add` dispatches `engine.add` (and therefore `build()`) to main asynchronously,
|
||||
// so the final one may still be in flight when `run` returns. Poll with a bounded
|
||||
// timeout rather than assuming a wall-clock margin.
|
||||
var count: Int = 0
|
||||
for _ in 0..<pollAttempts {
|
||||
count = CountingSynth.buildCount.load(ordering: .acquiring)
|
||||
if count == expected { break }
|
||||
Thread.sleep(forTimeInterval: pollIntervalSeconds)
|
||||
}
|
||||
#expect(count == expected)
|
||||
}
|
||||
|
||||
@Test func onMainPropagatesThrownError() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let caught: Ref<Bool> = Ref(false)
|
||||
|
||||
struct ProbeError: Error {}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
do {
|
||||
let _: Int = try ctx.onMain { throw ProbeError() }
|
||||
} catch is ProbeError {
|
||||
caught.value = true
|
||||
}
|
||||
}
|
||||
#expect(caught.value)
|
||||
}
|
||||
|
||||
@Test func onMainReturnsNonSendableReferenceType() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let value: Ref<Double> = Ref(0)
|
||||
|
||||
// `SynthesizerBase` subclasses are not Sendable — the box must carry one back anyway.
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
let s: CountingSynth = ctx.onMain { CountingSynth(value: 7.0) }
|
||||
value.value = s.value
|
||||
}
|
||||
#expect(value.value == 7.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal reference box so a `@Sendable` task body can report a result back to the test.
|
||||
/// `@unchecked Sendable`: the body writes `value`, the test reads it only after
|
||||
/// `LyrebirdTask.run` has joined the body thread — no concurrent access.
|
||||
private final class Ref<T>: @unchecked Sendable {
|
||||
var value: T
|
||||
init(_ value: T) { self.value = value }
|
||||
}
|
||||
@@ -745,4 +745,54 @@ struct LyrebirdTaskDemoIdiomTests {
|
||||
#expect(elapsed < 0.1,
|
||||
"waitUntilComplete must return immediately on terminal state; took \(elapsed)s")
|
||||
}
|
||||
|
||||
/// `ctx.set(_:to:)` writes a live-parameter node from the routine body (its own thread) with no
|
||||
/// main-thread dispatch — the value is readable immediately after via the node's atomic.
|
||||
@Test func ctxSetWritesLiveParameter() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let param: ParameterNode = ParameterNode(1.0) // Sendable — captured in the @Sendable body
|
||||
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
|
||||
ctx.set(param, to: 7.5)
|
||||
done.signal()
|
||||
}
|
||||
routine.start(engine: engine)
|
||||
_ = done.wait(timeout: .now() + 2)
|
||||
|
||||
#expect(abs(param.value - 7.5) < 1e-9,
|
||||
"ctx.set must store the value in the parameter node's atomic")
|
||||
}
|
||||
|
||||
/// `ctx.ramp(_:to:seconds:)` blocks for the duration and lands exactly on the target.
|
||||
@Test func ctxRampLandsOnTarget() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let param: ParameterNode = ParameterNode(1.0)
|
||||
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
|
||||
try? ctx.ramp(param, to: 5.0, seconds: 0.05)
|
||||
done.signal()
|
||||
}
|
||||
routine.start(engine: engine)
|
||||
_ = done.wait(timeout: .now() + 2)
|
||||
|
||||
#expect(abs(param.value - 5.0) < 1e-9, "ramp must finish exactly on the target value")
|
||||
}
|
||||
|
||||
/// A non-positive duration jumps straight to the target (no stepping).
|
||||
@Test func ctxRampZeroDurationJumps() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let param: ParameterNode = ParameterNode(2.0)
|
||||
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
|
||||
try? ctx.ramp(param, to: 9.0, seconds: 0.0)
|
||||
done.signal()
|
||||
}
|
||||
routine.start(engine: engine)
|
||||
_ = done.wait(timeout: .now() + 2)
|
||||
|
||||
#expect(abs(param.value - 9.0) < 1e-9)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// SynthesizerReleaseDispatchTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
// These tests guard the dispatch of `release(engine:)` / `free(engine:)` on SynthesizerBase
|
||||
// subclasses. Two distinct guards are at work, and both matter:
|
||||
//
|
||||
// 1. The `override` keyword below is a COMPILE-time guard. If the `open` members were ever
|
||||
// removed from SynthesizerBase — putting the witness back on the Synthesizer extension
|
||||
// default — these fixtures stop compiling outright. Do not "simplify" these by dropping
|
||||
// `override`: that silently restores the original bug, in which a subclass method was
|
||||
// statically shadowed and unreachable through `any Synthesizer`.
|
||||
// 2. The `#expect`s are a RUNTIME guard on the existential and Group-cascade paths, which
|
||||
// are how real callers reach these methods.
|
||||
|
||||
/// A gated synthesizer of the shape the docs tell users to write: override `release(engine:)`
|
||||
/// to drop the gate instead of being hard-freed.
|
||||
private final class GatedNote: SynthesizerBase {
|
||||
var releaseCalled: Bool = false
|
||||
var freeCalled: Bool = false
|
||||
|
||||
override func build() {}
|
||||
|
||||
override func release(engine: SynthesisEngine) throws {
|
||||
releaseCalled = true
|
||||
}
|
||||
|
||||
override func free(engine: SynthesisEngine) {
|
||||
freeCalled = true
|
||||
super.free(engine: engine)
|
||||
}
|
||||
}
|
||||
|
||||
/// A synthesizer with no gate — must still hit the `.noGate` default.
|
||||
private final class UngatedNote: SynthesizerBase {
|
||||
override func build() {}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func makeEngine() -> SynthesisEngine {
|
||||
let blockSize: Int = 512
|
||||
let sampleRate: Double = 44100.0
|
||||
let outputChannelCount: Int = 2
|
||||
let inputChannelCount: Int = 0
|
||||
|
||||
return SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: outputChannelCount,
|
||||
numInputChannels: inputChannelCount,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("Synthesizer release dispatch")
|
||||
struct SynthesizerReleaseDispatchTests {
|
||||
|
||||
/// The regression. `release` is a protocol requirement with an extension default; when
|
||||
/// `SynthesizerBase` declared no member, the witness bound statically to that default and
|
||||
/// a subclass override was unreachable through `any Synthesizer` — so every gated synth
|
||||
/// got `.noGate` and was hard-freed instead of released.
|
||||
@MainActor
|
||||
@Test("subclass release is reached through an `any Synthesizer` existential")
|
||||
func releaseDispatchesThroughExistential() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let note: GatedNote = GatedNote()
|
||||
|
||||
let erased: any Synthesizer = note
|
||||
try erased.release(engine: engine)
|
||||
|
||||
#expect(note.releaseCalled, "release must dispatch to the subclass, not the extension default")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test("subclass free is reached through an `any Synthesizer` existential")
|
||||
func freeDispatchesThroughExistential() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let note: GatedNote = GatedNote()
|
||||
|
||||
let erased: any Synthesizer = note
|
||||
erased.free(engine: engine)
|
||||
|
||||
#expect(note.freeCalled, "free must dispatch to the subclass, not the extension default")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test("a synthesizer without a gate still throws .noGate")
|
||||
func ungatedStillThrowsNoGate() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let note: UngatedNote = UngatedNote()
|
||||
|
||||
let erased: any Synthesizer = note
|
||||
#expect(throws: SynthesizerError.noGate) {
|
||||
try erased.release(engine: engine)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Group.release` cascades to children through `any Synthesizer` and frees any child that
|
||||
/// throws `.noGate`. A gated child must be released, never freed.
|
||||
@MainActor
|
||||
@Test("Group.release cascade releases a gated child instead of freeing it")
|
||||
func groupCascadeReleasesGatedChild() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let group: Group = Group()
|
||||
try engine.add(group)
|
||||
|
||||
let note: GatedNote = GatedNote()
|
||||
try engine.add(note, position: .tail(of: group))
|
||||
engine.processBlock(inputSamples: [])
|
||||
|
||||
group.release(engine: engine)
|
||||
|
||||
#expect(note.releaseCalled, "gated child must have its release() called")
|
||||
#expect(!note.freeCalled, "gated child must not be hard-freed by the cascade")
|
||||
|
||||
// The cascade left the child alive (correctly), so the group's self-free poll timer
|
||||
// would keep running until the group deallocs. Empty the group so it cancels.
|
||||
note.free(engine: engine)
|
||||
engine.processBlock(inputSamples: [])
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ func makeTestEngine(
|
||||
numInputChannels: Int = 2,
|
||||
numAudioBuses: Int = 128,
|
||||
numControlBuses: Int = 4096,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock
|
||||
) -> SynthesisEngine {
|
||||
SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
@@ -24,6 +25,7 @@ func makeTestEngine(
|
||||
numAudioBuses: numAudioBuses,
|
||||
numControlBuses: numControlBuses,
|
||||
eventQueueCapacity: eventQueueCapacity,
|
||||
maxEventsPerBlock: maxEventsPerBlock,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,15 @@ import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Golden-value check for `docs/stdlib/theory.md`'s examples.
|
||||
///
|
||||
/// `scripts/check-doc-snippets.sh` now typechecks 17 of that doc's 21 fences, so this suite
|
||||
/// is no longer the thing keeping them *compiling*. It earns its place on the other half:
|
||||
/// the doc writes results as trailing comments (`Interval.majorThird.semitones // 4`) and a
|
||||
/// typecheck cannot see a `// 4` silently become a lie. Same division of labour as
|
||||
/// `DistributionKindGoldenValueTests`.
|
||||
///
|
||||
/// When an assertion here fails, fix `docs/stdlib/theory.md` and this suite together.
|
||||
@Suite("doc snippet check — docs/stdlib/theory.md examples compile + match")
|
||||
struct _DocTheorySnippetCheckTests {
|
||||
|
||||
|
||||
Reference in New Issue
Block a user