v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop

This commit is contained in:
2026-07-20 10:02:49 -07:00
parent 560724d116
commit 38d2107f64
104 changed files with 14471 additions and 105 deletions
@@ -0,0 +1,46 @@
// DSLArgumentTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@Suite("DSLArgument")
struct DSLArgumentTests {
@Test func doubleFromDoubleAndInt() throws {
#expect(try DSLArgument.double(sig(2.5), "G", "x") == 2.5)
#expect(try DSLArgument.double(sig(3), "G", "x") == 3.0)
}
@Test func doubleRejectsSignal() throws {
let signal: any ValidGeneratorInput = OscSin.Audio(freq: 440)
#expect(throws: DSLBuildError.expectedNumber(builtin: "G", label: "x")) {
_ = try DSLArgument.double(sig(signal), "G", "x")
}
}
@Test func missingRequiredThrows() {
#expect(throws: DSLBuildError.missingArgument(builtin: "G", label: "x")) {
_ = try DSLArgument.double(nil, "G", "x")
}
}
@Test func intTruncatesFraction() throws {
#expect(try DSLArgument.int(sig(3.9), "G", "x") == 3)
#expect(try DSLArgument.int(sig(-2.9), "G", "x") == -2)
}
@Test func intOutOfRangeThrowsInsteadOfTrapping() {
#expect(throws: DSLBuildError.numberOutOfRange(builtin: "G", label: "x")) {
_ = try DSLArgument.int(sig(1e30), "G", "x")
}
}
@Test func floatCoerces() throws {
#expect(try DSLArgument.float(sig(0.5), "G", "x") == Float(0.5))
}
}
@@ -0,0 +1,48 @@
// DSLBuiltinTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSLBuiltin")
struct DSLBuiltinTests {
/// A `DSLBuiltin` wrapping `OscSin` — the exact shape the code-gen tool will
/// emit — constructs a real generator that renders audio through the engine.
/// Locks the registry contract that the parser/builder will consume.
@Test func builtinConstructsAndRendersGenerator() throws {
let builtin: DSLBuiltin = DSLBuiltin(
name: "OscSin",
rate: .audio,
parameters: [
DSLParameter(label: "freq", hasDefault: false),
DSLParameter(label: "mul", hasDefault: true),
DSLParameter(label: "add", hasDefault: true),
],
make: { args in
OscSin.Audio(
freq: try DSLArgument.input(args["freq"], "OscSin", "freq"),
mul: try DSLArgument.input(args["mul"] ?? .signal(1.0), "OscSin", "mul"),
add: try DSLArgument.input(args["add"] ?? .signal(0.0), "OscSin", "add")
)
}
)
#expect(builtin.name == "OscSin")
#expect(builtin.parameters.first == DSLParameter(label: "freq", hasDefault: false))
let graph: any ValidGeneratorInput = try builtin.make(["freq": sig(440.0), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
}
@@ -0,0 +1,140 @@
// DSLInterpreterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSLInterpreter")
struct DSLInterpreterTests {
/// Add each built output to the engine and render one block.
private func render(_ outputs: [DSLOutput]) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
for output: DSLOutput in outputs {
try engine.add(ClosureSynthesizer { output.graph })
}
engine.processBlock(inputSamples: [])
return engine
}
@Test func evaluatesAndRendersASineTimesGain() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("OscSin(freq: 440) * 0.1")
#expect(outputs.count == 1)
#expect(outputs[0].slot == nil)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func slotAssignmentCarriesTheSlotName() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("bass = OscSin(freq: 55) * 0.2")
#expect(outputs[0].slot == "bass")
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func nestedGraphRendersStereo() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"Pan2(input: OscSin(freq: 440) * 0.1, pan: 0)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
#expect(busHasSignal(engine, bus: 1))
}
@Test func positionalArgumentsBind() throws {
// OscSin(freq) positionally.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("OscSin(440) * 0.1")
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func multipleStatementsProduceMultipleOutputs() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"bass = OscSin(freq: 55) * 0.2\nlead = OscSin(freq: 440) * 0.1"
)
#expect(outputs.count == 2)
#expect(outputs.map { $0.slot } == ["bass", "lead"])
}
@Test func unknownGeneratorThrows() {
#expect(throws: DSLBuildError.unknownBuiltin("NotAGenerator")) {
_ = try DSLInterpreter.evaluate("NotAGenerator(freq: 1)")
}
}
@Test func unknownArgumentThrows() {
#expect(throws: DSLBuildError.unknownArgument(builtin: "OscSin", label: "nope")) {
_ = try DSLInterpreter.evaluate("OscSin(nope: 1)")
}
}
@Test func missingRequiredArgumentThrows() {
// OscSin.freq is required.
#expect(throws: DSLBuildError.missingArgument(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(mul: 0.1)")
}
}
@Test func controlOnlyGeneratorResolvesViaFallback() throws {
// MouseX is control-only; the builder falls back to its sole rate.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("MouseX()")
#expect(outputs.count == 1)
}
@Test func explicitControlRateSelectsControlVariant() throws {
// `.Control` requests the control-rate OscSin driving an audio OscSin's freq.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"OscSin(freq: OscSin.Control(freq: 4, mul: 50, add: 440), mul: 0.1)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func explicitRateOnUnavailableVariantThrows() {
// Pan2 is audio-only; `.Control` must fail rather than silently pick audio.
#expect(throws: DSLBuildError.rateUnavailable(builtin: "Pan2", rate: "control")) {
_ = try DSLInterpreter.evaluate("Pan2.Control(input: OscSin(freq: 1), pan: 0)")
}
}
@Test func invalidRateSuffixThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLInterpreter.evaluate("OscSin.xyz(freq: 440)")
}
}
/// Paste-compatibility: the exact Swift form `OscSin.Audio(freq: 440) * 0.1`
/// — capitalized nested-class name and all — evaluates and renders in the
/// DSL, so a graph expression copied to/from a Lyrebird `build()` is spelled
/// the same in both places.
@Test func swiftFormGraphExpressionEvaluates() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"Pan2(input: OscSin.Audio(freq: 440) * 0.1, pan: 0)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
#expect(busHasSignal(engine, bus: 1))
}
@Test func duplicateArgumentThrows() {
// A parameter bound twice (positional then label) is an error.
#expect(throws: DSLBuildError.duplicateArgument(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(440, freq: 550)")
}
}
@Test func foldedConstantSatisfiesNumericParameter() throws {
// DelayLine.delay is a Double (numeric-literal-only). A folded computed
// constant must reach it as a number, not a signal — build must succeed
// (an un-folded `0.1 * 2` would be a generator and throw expectedNumber).
_ = try DSLInterpreter.evaluate(
"DelayLine(input: OscSin(freq: 440) * 0.1, maxDelay: 0.5, delay: 0.1 * 2)"
)
}
}
@@ -0,0 +1,51 @@
// DSLLexerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdGraphDSL
@Suite("DSLLexer")
struct DSLLexerTests {
private func kinds(_ source: String) throws -> [DSLToken.Kind] {
try DSLLexer.tokenize(source).map { $0.kind }
}
@Test func tokenizesACall() throws {
#expect(try kinds("OscSin(freq: 440)") == [
.identifier, .leftParen, .identifier, .colon, .number, .rightParen, .eof,
])
}
@Test func tokenizesOperatorsAndParens() throws {
#expect(try kinds("(a + b) * 0.5") == [
.leftParen, .identifier, .plus, .identifier, .rightParen, .star, .number, .eof,
])
}
@Test func skipsCommentsAndCollapsesNewlines() throws {
#expect(try kinds("a # comment\n\n\nb") == [
.identifier, .newline, .identifier, .eof,
])
}
@Test func numberFormsAndUnderscores() throws {
let toks: [DSLToken] = try DSLLexer.tokenize("440 0.15 2e3 44_100")
let numbers: [String] = toks.filter { $0.kind == .number }.map { $0.text }
#expect(numbers == ["440", "0.15", "2e3", "44_100"])
}
@Test func unexpectedCharacterThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLLexer.tokenize("a @ b")
}
}
@Test func spansCoverSourceText() throws {
let toks: [DSLToken] = try DSLLexer.tokenize("OscSin")
#expect(toks.first?.span == DSLSpan(start: 0, end: 6))
}
}
@@ -0,0 +1,112 @@
// DSLParserTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdGraphDSL
@Suite("DSLParser")
struct DSLParserTests {
@Test func parsesAnonymousCall() throws {
let program: DSLProgram = try DSLParser.parse("OscSin(freq: 440, mul: 0.1)")
#expect(program.statements.count == 1)
guard case .expression(let expr) = program.statements[0],
case .call(let name, _, let args, _) = expr else {
Issue.record("expected a call expression"); return
}
#expect(name == "OscSin")
#expect(args.map { $0.label } == ["freq", "mul"])
}
@Test func parsesSlotAssignment() throws {
let program: DSLProgram = try DSLParser.parse("bass = OscSin(freq: 55)")
guard case .assignment(let name, _, _) = program.statements[0] else {
Issue.record("expected an assignment"); return
}
#expect(name == "bass")
}
@Test func operatorPrecedenceMultiplyBeforeAdd() throws {
// a + b * c ==> a + (b * c)
let program: DSLProgram = try DSLParser.parse("A(freq: 1) + B(freq: 2) * C(freq: 3)")
guard case .expression(let expr) = program.statements[0],
case .binary(let op, _, let rhs, _) = expr else {
Issue.record("expected a binary add"); return
}
#expect(op == .add)
guard case .binary(let innerOp, _, _, _) = rhs else {
Issue.record("rhs should be the multiply"); return
}
#expect(innerOp == .multiply)
}
@Test func parensOverridePrecedence() throws {
// (a + b) * c ==> multiply at the top
let program: DSLProgram = try DSLParser.parse("(A(freq: 1) + B(freq: 2)) * C(freq: 3)")
guard case .expression(let expr) = program.statements[0],
case .binary(let op, _, _, _) = expr else {
Issue.record("expected a binary"); return
}
#expect(op == .multiply)
}
@Test func nestedCallAsArgument() throws {
let program: DSLProgram = try DSLParser.parse("Pan2(input: OscSin(freq: 440), pan: 0)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .call(let innerName, _, _, _) = args[0].value else {
Issue.record("expected a nested call argument"); return
}
#expect(innerName == "OscSin")
}
@Test func multipleStatementsAcrossLines() throws {
let program: DSLProgram = try DSLParser.parse("bass = A(freq: 1)\nlead = B(freq: 2)")
#expect(program.statements.count == 2)
}
@Test func trailingGarbageThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLParser.parse("OscSin(freq: 440) 123")
}
}
@Test func deeplyNestedInputThrowsInsteadOfCrashing() {
// Pathological / generated input must not overflow the stack.
let deep: String = String(repeating: "(", count: 1000) + "1"
+ String(repeating: ")", count: 1000)
#expect(throws: DSLParseError.self) {
_ = try DSLParser.parse(deep)
}
}
@Test func unclosedParenThrowsSpecificError() throws {
do {
_ = try DSLParser.parse("OscSin(freq: 440")
Issue.record("expected unclosedParen")
} catch let error as DSLParseError {
#expect(error.kind == .unclosedParen)
}
}
@Test func constantFoldingProducesNumberNodes() throws {
// 220 * 2 folds to a single number literal.
let program: DSLProgram = try DSLParser.parse("Osc(freq: 220 * 2)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .number(let n, _) = args[0].value else {
Issue.record("expected a folded number"); return
}
#expect(n == 440)
}
@Test func unaryMinusFoldsToNegativeNumber() throws {
let program: DSLProgram = try DSLParser.parse("Osc(add: -0.5)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .number(let n, _) = args[0].value else {
Issue.record("expected a negative number literal"); return
}
#expect(n == -0.5)
}
}
@@ -0,0 +1,93 @@
// DSLResourceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSL resources (buffers)")
struct DSLResourceTests {
/// A short buffer filled with a constant so a PlayBuffer read is audible.
private func makeBuffer() -> LyrebirdBuffer {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
buffer.fill(with: 0.5)
return buffer
}
/// A bare identifier resolves to the registered buffer as a `.buffer`
/// `DSLValue` — the resolution the DSL adds. (Constructing a buffer generator
/// like PlayBuffer and rendering it is the core buffer tests' job; doing it
/// here only re-tests that RT path, and a mapped buffer held in a torn-down
/// test engine races ARC at teardown — a known core buffer-lifecycle issue.)
@Test func bufferReferenceResolvesToBufferValue() throws {
let buffer: LyrebirdBuffer = makeBuffer()
let resources: DSLBufferTable = DSLBufferTable(["kick": buffer])
let value: DSLValue = try DSLGraphBuilder.build(
.reference(name: "kick", DSLSpan.point(0)),
resources: resources
)
guard case .buffer(let resolved) = value else {
Issue.record("expected the reference to resolve to a buffer"); return
}
#expect(resolved === buffer)
}
@Test func bufferParameterIsExposedOnBufferBuiltins() throws {
// The code-gen emits buffer generators with a `buffer` parameter.
let playBuffer: DSLBuiltin = try DSLBuiltinRegistry.lookup("PlayBuffer")
#expect(playBuffer.parameters.contains { $0.label == "buffer" && !$0.hasDefault })
}
@Test func unknownReferenceThrows() {
#expect(throws: DSLBuildError.unknownReference("missing")) {
_ = try DSLInterpreter.evaluate(
"PlayBuffer(buffer: missing, rate: 1)",
resources: DSLBufferTable([:])
)
}
}
@Test func signalWhereBufferExpectedThrows() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// Handing a signal (a number) to the buffer parameter must fail.
#expect(throws: DSLBuildError.expectedBuffer(builtin: "PlayBuffer", label: "buffer")) {
_ = try DSLInterpreter.evaluate("PlayBuffer(buffer: 440, rate: 1)", resources: resources)
}
}
@Test func bufferUsedAsSignalThrows() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// A buffer can't be multiplied or played on its own.
#expect(throws: DSLBuildError.operatorRequiresSignal) {
_ = try DSLInterpreter.evaluate("kick * 0.5", resources: resources)
}
}
@Test func topLevelBareBufferCannotBePlayed() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
#expect(throws: DSLBuildError.cannotPlayResource) {
_ = try DSLInterpreter.evaluate("kick", resources: resources)
}
}
@Test func bufferInSignalSlotThrowsExpectedSignal() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// OscSin.freq is a signal parameter; a buffer there is the wrong kind.
#expect(throws: DSLBuildError.expectedSignal(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(freq: kick)", resources: resources)
}
}
@Test func forgottenCallParensHintsItIsAGenerator() {
// A bare generator name (no parens) is a reference the resolver can't
// find — but it is a known generator, so hint that.
#expect(throws: DSLBuildError.referenceIsGenerator("OscSin")) {
_ = try DSLInterpreter.evaluate("OscSin")
}
}
}
@@ -0,0 +1,33 @@
// DSLTestSupport.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdGraphDSL
/// Shared offline engine for DSL round-trip tests.
@MainActor
func makeDSLTestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 16,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
/// `true` when any sample in bus `bus` of `engine` is non-zero.
@MainActor
func busHasSignal(_ engine: SynthesisEngine, bus: Int) -> Bool {
(0..<engine.blockSize).contains { engine.audioBuses[bus][$0] != 0.0 }
}
/// Wrap a signal value as a `DSLValue` for direct `DSLBuiltin.make` calls.
func sig(_ value: any ValidGeneratorInput) -> DSLValue { .signal(value) }
@@ -0,0 +1,176 @@
// GeneratedRegistryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("GeneratedDSLRegistry")
struct GeneratedRegistryTests {
/// Floor on the generated table size — a regression that halved the registry
/// (e.g. a scanner change) would trip this rather than pass silently.
private static let minimumBuiltinCount: Int = 150
@Test func registryIsPopulatedAndUnique() {
#expect(DSLBuiltinRegistry.all.count >= GeneratedRegistryTests.minimumBuiltinCount)
// Each (name, rate) is unique — no entry collapsed in the lookup table.
let totalEntries: Int = DSLBuiltinRegistry.byName.values.reduce(0) { $0 + $1.count }
#expect(totalEntries == DSLBuiltinRegistry.all.count)
}
@Test func generatorsAvailableAtBothRates() throws {
// OscSin exists at audio and control; lookup defaults to audio.
#expect(DSLBuiltinRegistry.rates(of: "OscSin") == Set([.audio, .control]))
let audio: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
#expect(audio.rate == .audio)
let control: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin", rate: .control)
#expect(control.rate == .control)
}
/// A doubly-nested control-only type (`Mouse.X.Control`) is registered under
/// its joined path name (`MouseX`), not the bare inner enum (`X`), and
/// constructs via the full `Mouse.X.Control` path.
@Test func doublyNestedTypeUsesJoinedNameAndFullConstructor() throws {
#expect(DSLBuiltinRegistry.rates(of: "MouseX") == Set([.control]))
// The bare inner name must NOT leak into the flat DSL namespace.
#expect(DSLBuiltinRegistry.rates(of: "X").isEmpty)
let mouseX: DSLBuiltin = try DSLBuiltinRegistry.lookup("MouseX", rate: .control)
#expect(mouseX.rate == .control)
// Constructs without throwing (no args; reads the mouse input registry).
_ = try mouseX.make([:])
}
@Test func unavailableRateThrows() throws {
// Pan2 is audio-only (no ControlGenerator variant).
#expect(DSLBuiltinRegistry.rates(of: "Pan2") == Set([.audio]))
#expect(throws: DSLBuildError.rateUnavailable(builtin: "Pan2", rate: "control")) {
_ = try DSLBuiltinRegistry.lookup("Pan2", rate: .control)
}
}
@Test func controlRateBuiltinRenders() throws {
// A control-rate OscSin drives an audio OscSin's frequency — the kind of
// modulation nesting the DSL will produce.
let lfoControl: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin", rate: .control)
let audio: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let lfo: any ValidGeneratorInput = try lfoControl.make(["freq": sig(4.0), "mul": sig(50.0), "add": sig(440.0)])
let graph: any ValidGeneratorInput = try audio.make(["freq": sig(lfo), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
@Test func wellKnownGeneratorsArePresent() throws {
for name: String in ["OscSin", "OscSawtooth", "OscSquare", "WhiteNoise", "Pan2"] {
let builtin: DSLBuiltin = try DSLBuiltinRegistry.lookup(name)
#expect(builtin.name == name)
}
}
@Test func lookupOfUnknownNameThrows() {
#expect(throws: DSLBuildError.unknownBuiltin("NotAGenerator")) {
_ = try DSLBuiltinRegistry.lookup("NotAGenerator")
}
}
@Test func requiredParameterIsReportedAndEnforced() throws {
// OscSin's `freq` has no default, so it is required.
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let freq: DSLParameter? = osc.parameters.first { $0.label == "freq" }
#expect(freq?.hasDefault == false)
#expect(throws: DSLBuildError.missingArgument(builtin: "OscSin", label: "freq")) {
_ = try osc.make([:])
}
}
/// The generated closure builds a real generator that renders audio.
@Test func generatedBuiltinRendersAudio() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let graph: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
/// A generator taking a signal input builds when handed another generator —
/// the nesting the DSL parser will produce.
@Test func nestedGeneratorArgumentBuilds() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let pan: DSLBuiltin = try DSLBuiltinRegistry.lookup("Pan2")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.1)])
let graph: any ValidGeneratorInput = try pan.make(["input": sig(source), "pan": sig(0.0)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
// Pan2 is stereo — both buses should carry signal.
let leftNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
let rightNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[1][$0] != 0.0 }
#expect(leftNonZero)
#expect(rightNonZero)
}
/// A parameter typed `Double` on the Swift init rejects a signal, since a
/// literal number is required there.
@Test func numericParameterRejectsSignal() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let signal: any ValidGeneratorInput = try osc.make(["freq": sig(440.0)])
let delay: DSLBuiltin = try DSLBuiltinRegistry.lookup("DelayLine")
// `maxDelay` is a Double on the init — handing it a generator must throw.
#expect(throws: DSLBuildError.expectedNumber(builtin: "DelayLine", label: "maxDelay")) {
_ = try delay.make(["input": sig(signal), "maxDelay": sig(signal), "delay": sig(0.1)])
}
}
/// A generated builtin with a positional Swift argument (`Abs(_ signal:)`)
/// binds its unlabeled argument correctly through the emitted call.
@Test func positionalBuiltinBindsAndRenders() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let abs: DSLBuiltin = try DSLBuiltinRegistry.lookup("Abs")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.5)])
let graph: any ValidGeneratorInput = try abs.make(["signal": sig(source)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
/// A parameter whose Swift default is a named internal constant
/// (`LeakDC.coef = leakDCDefaultAudioCoef`) is exposed with a default and
/// builds when omitted — proves the code-gen's constant inlining works.
@Test func namedConstantDefaultIsUsable() throws {
let leak: DSLBuiltin = try DSLBuiltinRegistry.lookup("LeakDC")
let coef: DSLParameter? = leak.parameters.first { $0.label == "coef" }
#expect(coef?.hasDefault == true)
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.5)])
// `coef` omitted — must not throw a missing-argument error.
let graph: any ValidGeneratorInput = try leak.make(["input": sig(source)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
/// Lock in which overload of a multi-init class the generator exposes.
/// `RBJBandPass` declares its `bandwidth:` init first, so that is the one
/// shipped; a future reorder that silently flipped it to `q:` trips here.
@Test func multiInitClassExposesFirstOverload() throws {
let bp: DSLBuiltin = try DSLBuiltinRegistry.lookup("RBJBandPass")
let labels: [String] = bp.parameters.map { $0.label }
#expect(labels.contains("bandwidth"))
#expect(!labels.contains("q"))
}
}
@@ -0,0 +1,75 @@
// ClosureSynthesizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
/// Reference box so a closure can record how many times it ran.
private final class CallCounter {
var count: Int = 0
}
@MainActor
@Suite("ClosureSynthesizer")
struct ClosureSynthesizerTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
init() throws {
try engine.start()
}
@Test func closureGraphWritesToBusZero() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer { 0.5 }
try engine.add(synth)
engine.processBlock(inputSamples: [])
for i: Int in 0..<engine.blockSize {
#expect(abs(engine.audioBuses[0][i] - 0.5) < 1e-6)
}
}
@Test func busParameterSelectsOutputBus() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer(bus: 2) { 0.7 }
try engine.add(synth)
engine.processBlock(inputSamples: [])
#expect(abs(engine.audioBuses[2][0] - 0.7) < 1e-6)
#expect(engine.audioBuses[0][0] == 0.0)
}
@Test func closureRunsExactlyOncePerInstanceAtAdd() throws {
let counter: CallCounter = CallCounter()
let synth: ClosureSynthesizer = ClosureSynthesizer {
counter.count += 1
return 0.25
}
// build() — and thus the closure — runs synchronously inside add.
try engine.add(synth)
#expect(counter.count == 1)
engine.processBlock(inputSamples: [])
// Rendering does not re-run the closure.
#expect(counter.count == 1)
}
@Test func bareOscillatorGraphProducesAudio() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer {
OscSin.Audio(freq: 440, mul: 0.1)
}
try engine.add(synth)
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
@Test func multiChannelSourceFansAcrossBuses() throws {
// A stereo Pan2 source writes bus 0 and bus 1.
let synth: ClosureSynthesizer = ClosureSynthesizer {
Pan2(input: 0.5, pan: 0)
}
try engine.add(synth)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0][0] != 0.0)
#expect(engine.audioBuses[1][0] != 0.0)
}
}
+104
View File
@@ -0,0 +1,104 @@
// DebugTapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Synchronization
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// The debug tap's invocation is compiled out of release builds (`#if DEBUG` around the
// call site in `SynthesizerBase.evaluate`). These tests assert the tap fires, so they are
// meaningful only in a debug configuration — which is how `swift test` runs by default.
#if DEBUG
/// Records every `debugTap` invocation and the arguments it received.
///
/// Counters use `Atomic` because `debugTap` runs on the render thread; the offline driver
/// processes synchronously in-test, but atomics keep the fixture race-free regardless.
private final class DebugTapProbe: SynthesizerBase {
let bus: Int
let tapCount: Atomic<Int> = Atomic<Int>(0)
let lastOutputCount: Atomic<Int> = Atomic<Int>(-1)
let lastCount: Atomic<Int> = Atomic<Int>(-1)
init(bus: Int = 0) {
self.bus = bus
super.init()
}
override func build() {
// `output(bus:source:)` registers exactly once (Out.Audio self-registers via
// RootRegistering); an explicit `addOutputGenerator(Out.Audio(...))` would double-count.
output(bus: bus, source: 0.25)
}
override func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {
_ = tapCount.wrappingAdd(1, ordering: .relaxed)
lastOutputCount.store(outputs.count, ordering: .relaxed)
lastCount.store(count, ordering: .relaxed)
}
}
@MainActor
@Suite("SynthesizerBase debug tap")
struct DebugTapTests {
let engine: SynthesisEngine = makeTestEngine()
init() throws {
try engine.start()
}
@Test func tapDoesNotFireWhenDisabled() throws {
let probe: DebugTapProbe = DebugTapProbe()
try engine.add(probe)
engine.processBlock(inputSamples: [])
#expect(probe.tapCount.load(ordering: .relaxed) == 0)
}
@Test func tapFiresWhenEnabled() throws {
let probe: DebugTapProbe = DebugTapProbe()
probe.debugTapEnabled = true
try engine.add(probe)
engine.processBlock(inputSamples: [])
#expect(probe.tapCount.load(ordering: .relaxed) >= 1)
}
@Test func tapReceivesOutputsAndFullBlockCount() throws {
let probe: DebugTapProbe = DebugTapProbe()
probe.debugTapEnabled = true
try engine.add(probe)
engine.processBlock(inputSamples: [])
// One `Out.Audio` was registered in build().
#expect(probe.lastOutputCount.load(ordering: .relaxed) == 1)
// No scheduled events this block, so the segment spans the whole block.
#expect(probe.lastCount.load(ordering: .relaxed) == engine.blockSize)
}
@Test func gatingIsPerInstance() throws {
let on: DebugTapProbe = DebugTapProbe(bus: 0)
let off: DebugTapProbe = DebugTapProbe(bus: 1)
on.debugTapEnabled = true
try engine.add(on)
try engine.add(off)
engine.processBlock(inputSamples: [])
#expect(on.tapCount.load(ordering: .relaxed) >= 1)
#expect(off.tapCount.load(ordering: .relaxed) == 0)
}
@Test func flagRoundTripsThroughAtomicProperty() throws {
let probe: DebugTapProbe = DebugTapProbe()
#expect(probe.debugTapEnabled == false)
probe.debugTapEnabled = true
#expect(probe.debugTapEnabled == true)
probe.debugTapEnabled = false
#expect(probe.debugTapEnabled == false)
}
}
#endif
+18
View File
@@ -664,4 +664,22 @@ struct DiskInOutTests {
diskOut.close() // second call must not crash or deadlock
#expect(FileManager.default.fileExists(atPath: outURL.path))
}
/// A `DiskOut.Audio` whose output path is unwritable must throw from `init`
/// rather than construct a half-built recorder. This throw happens before
/// `super.init()`, so the ring storage is freed by an explicit
/// `deallocate()` on the throw path (Swift does not run `deinit` for an
/// initializer that throws before `super.init()`).
@Test func diskOutInvalidURLThrows() {
// A path under a directory that does not exist — ExtAudioFileCreateWithURL fails.
let badURL: URL = URL(fileURLWithPath: "/nonexistent-dir-\(UUID().uuidString)/out.wav")
#expect(throws: DiskOutError.self) {
_ = try DiskOut.Audio(source: 0.0 as Double,
channelCount: 2,
url: badURL,
sampleRate: 44100,
format: .wav,
bufferFrames: 8192)
}
}
}
@@ -76,8 +76,8 @@ struct AutoFreeOnDoneTests {
/// 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 _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
private static let blocksPerBurst: Int = 32
private static let wallSleepSeconds: TimeInterval = 0.001
@@ -91,12 +91,17 @@ struct AutoFreeOnDoneTests {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread so no `processBlock` runs after
/// `stop()` returns to race the engine's own `stop()`. Idempotent.
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
// MARK: - Tests
@@ -46,8 +46,8 @@ private func sustainedEnvelope() -> Envelope {
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -66,13 +66,20 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
/// Thread-safe one-shot fulfillment token.
@@ -76,8 +76,8 @@ private func makeSimpleEventList(
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -96,13 +96,20 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
// MARK: - Helpers
@@ -7,6 +7,7 @@
import Testing
import Foundation
import AudioToolbox
import Synchronization
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Private test fixtures
@@ -35,25 +36,34 @@ private func shortAutoEnvelope() -> Envelope {
/// Drives `engine.processBlock` at ~1 ms intervals while `_running` is true.
private final class TimelineTestBlockDriver: @unchecked Sendable {
private var _running: Bool = false
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
private static let blockIntervalSeconds: Double = 0.001
init(engine: SynthesisEngine) { _engine = engine }
func start() {
_running = true
_running.store(true, ordering: .relaxed)
let t: Thread = Thread { [self] in
while self._running {
while self._running.load(ordering: .relaxed) {
self._engine.processBlock(inputSamples: [])
Thread.sleep(forTimeInterval: TimelineTestBlockDriver.blockIntervalSeconds)
}
self._done.signal()
}
t.qualityOfService = .userInteractive
t.start()
}
func stop() { _running = false }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
/// Returns a temporary directory. Caller is responsible for cleanup.
@@ -64,8 +64,8 @@ private func makeProcessTestEngine() -> SynthesisEngine {
/// The `OfflineDriver` does not generate its own render callbacks, so tests that
/// rely on envelope completion must drive the engine themselves.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -86,14 +86,19 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
_running.store(false, ordering: .relaxed)
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
+207
View File
@@ -0,0 +1,207 @@
// SampleLoopTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SampleLoop")
struct SampleLoopTests {
/// y[n] = x[n] + a·y[n-1] with a constant input converges to x/(1-a).
@Test func singlePoleFeedbackConverges() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let a: Double = 0.5
let node: SampleLoop<[Double]> = SampleLoop(
makeState: { n in [Double](repeating: 0.0, count: n) },
inputs: [1.0]
) { z, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
let y: Double = ins[0][ch][i] + a * z[ch]
z[ch] = y
out[ch][i] = y
}
}
}
let block: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)[0]
#expect(abs(block[0] - 1.0) < 1e-12) // 1 + 0.5·0
#expect(abs(block[1] - 1.5) < 1e-12) // 1 + 0.5·1
#expect(abs(block[2] - 1.75) < 1e-12) // 1 + 0.5·1.5
#expect(block[7] > 1.98 && block[7] < 2.0) // → 2.0
}
/// Feedback state carries across block boundaries.
@Test func statePersistsAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<[Double]> = SampleLoop(
makeState: { n in [Double](repeating: 0.0, count: n) },
inputs: [1.0]
) { z, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
let y: Double = ins[0][ch][i] + 0.5 * z[ch]
z[ch] = y
out[ch][i] = y
}
}
}
let block1: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
advanceBlock(engine)
let block2: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(abs(block2[0] - (1.0 + 0.5 * block1[3])) < 1e-12)
#expect(abs(node.state[0] - block2[3]) < 1e-12)
}
/// Output channel count is inferred from the widest input, and a mono input broadcasts
/// to every output channel.
@Test func infersChannelsAndBroadcastsMonoInput() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let stereoIn: Pan2 = Pan2(input: 1.0, pan: 0.0) // 2-row generator
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [stereoIn, 3.0] // stereo + mono scalar
) { _, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
out[ch][i] = ins[0][ch][i] + ins[1][ch][i] // mono input 1 broadcast to both
}
}
}
#expect(node.outputChannelCount == 2)
let result: [[Double]] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
#expect(result.count == 2)
// Pan2 at pan 0 → equal-power ≈ 0.707 per channel; + 3.0 broadcast mono.
#expect(abs(result[0][0] - (result[1][0])) < 1e-9) // symmetric channels
#expect(result[0][0] > 3.0 && result[0][0] < 4.0)
}
/// An explicit `channels:` up-mixes a pure source with no inputs to infer from.
@Test func explicitChannelsForPureSource() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [],
channels: 3
) { _, _, numChannels, out, n, _ in
for ch: Int in 0..<numChannels {
for i: Int in 0..<n { out[ch][i] = Double(ch) }
}
}
#expect(node.outputChannelCount == 3)
let result: [[Double]] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
#expect(result.count == 3)
#expect(result[0][0] == 0.0 && result[1][0] == 1.0 && result[2][0] == 2.0)
}
/// Two instances keep independent state (graph-copy-per-instance model).
@Test func instancesAreIndependent() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
func makeCounter() -> SampleLoop<[Double]> {
SampleLoop(makeState: { n in [Double](repeating: 0.0, count: n) }, inputs: []) { s, _, _, out, n, _ in
for i: Int in 0..<n {
s[0] += 1.0
out[0][i] = s[0]
}
}
}
let a: SampleLoop<[Double]> = makeCounter()
let b: SampleLoop<[Double]> = makeCounter()
_ = a.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
advanceBlock(engine)
_ = a.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4) // a advanced twice
_ = b.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4) // b advanced once
#expect(abs(a.state[0] - 8.0) < 1e-12)
#expect(abs(b.state[0] - 4.0) < 1e-12)
}
/// `mul` / `add` scale the body's output after the fact.
@Test func mulAddScalesOutput() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [3.0],
mul: 2.0,
add: 1.0
) { _, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels { out[ch][i] = ins[0][ch][i] } // 3.0
}
}
let block: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(Array(block.prefix(4)) == [7.0, 7.0, 7.0, 7.0]) // 3·2 + 1
}
/// Regression: a `Generator` input's own `_result` buffer must not be copied-on-write
/// across blocks. Aliasing the input row in a stored property (instead of copying into
/// private scratch) would leave the row referenced twice at the input's next in-place
/// write, reallocating its buffer — a per-block RT-thread allocation. A stable base
/// address across blocks proves no reallocation occurred.
@Test func generatorInputIsNotCopiedOnWriteAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let osc: OscSin.Audio = OscSin.Audio(freq: 100.0)
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: [osc]) { _, ins, nc, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<nc { out[ch][i] = ins[0][ch][i] }
}
}
func oscRowBase() -> UnsafeRawPointer? {
osc._result[0].withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) }
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base1: UnsafeRawPointer? = oscRowBase()
advanceBlock(engine)
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base2: UnsafeRawPointer? = oscRowBase()
#expect(base1 != nil)
#expect(base1 == base2) // no CoW reallocation of the input's buffer
}
/// Regression: the private input scratch and the output buffer are never reallocated
/// across blocks (both pre-allocated at init).
@Test func scratchAndOutputBuffersStableAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: [0.5]) { _, ins, nc, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<nc { out[ch][i] = ins[0][ch][i] }
}
}
func outBase() -> UnsafeRawPointer? {
node._result[0].withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) }
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base1: UnsafeRawPointer? = outBase()
advanceBlock(engine)
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base2: UnsafeRawPointer? = outBase()
#expect(base1 != nil)
#expect(base1 == base2)
}
/// The output buffer is pre-zeroed: a body that writes only part of the block leaves
/// silence in the gaps, never stale data from the previous block.
@Test func outputPreZeroedBetweenBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: []) { call, _, _, out, n, _ in
let writeCount: Int = (call == 0) ? n : 1
for i: Int in 0..<writeCount { out[0][i] = 9.0 }
call += 1
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
advanceBlock(engine)
let block2: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(Array(block2.prefix(4)) == [9.0, 0.0, 0.0, 0.0])
}
}