v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user