// RecordBufferTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @MainActor @Suite("RecordBuffer") struct RecordBufferTests { // MARK: - Helpers func makeEngine(blockSize: Int = 16) throws -> SynthesisEngine { let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize) try engine.start() return engine } // MARK: - Basic recording @Test func recordsMonoInputIntoBuffer() throws { let engine: SynthesisEngine = try makeEngine() let graph: SynthGraph = makeSynthGraph(engine: engine) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 0.5, buffer: buf, loop: false) _ = rec.calculatedSamples(graph: graph, count: 16) for i: Int in 0..<16 { #expect(buf[i, 0] == 0.5, "frame \(i): expected 0.5, got \(buf[i, 0])") } engine.stop() } @Test func rateIsAudio() { let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf) #expect(rec.rate == .audio) } // MARK: - preLevel mix @Test func preLevelMixesWithExistingContent() throws { // ParameterNode ramps over one block. Advance one block to let preLevel settle at 0.5, // then verify the second block's writes use the flat value. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) buf.fill(with: 1.0) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: true) rec.preLevel = 0.5 // mix: new*1 + existing*0.5 = 1.0 + 0.5 = 1.5 // Block 1 (frames 0–7): preLevel ramps 0→0.5; mixed values vary. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } advanceBlock(engine) // Block 2 (frames 8–15): preLevel flat at 0.5; every frame = 1.0 + 0.5*1.0 = 1.5. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } for i: Int in 8..<16 { #expect(abs(buf[i, 0] - 1.5) < 1e-9, "frame \(i): expected 1.5, got \(buf[i, 0])") } engine.stop() } @Test func recLevelScalesNewSignal() throws { // ParameterNode ramps over one block. Use a two-block test: block 1 lets recLevel // settle at 0.25; block 2 records with a flat 0.25 scale. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: true) rec.recLevel = 0.25 // Block 1 (frames 0–7): recLevel ramps 1.0→0.25; values vary. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } advanceBlock(engine) // Block 2 (frames 8–15): recLevel flat at 0.25. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } for i: Int in 8..<16 { #expect(abs(buf[i, 0] - 0.25) < 1e-9, "frame \(i): expected 0.25, got \(buf[i, 0])") } engine.stop() } // MARK: - run gate @Test func runZeroPausesRecording() throws { // ParameterNode ramps over one block. Advance one block to let run settle at 0.0, // then verify the second block writes nothing. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 32) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf) rec.run = 0.0 // Block 1 (frames 0–7): run ramps 1.0→0.0; some frames may be written. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } advanceBlock(engine) // Block 2 (frames 8–15): run is flat 0.0; no frames written. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } for i: Int in 8..<16 { #expect(buf[i, 0] == 0.0, "frame \(i) should be unwritten (run=0)") } engine.stop() } @Test func runZeroHoldsWritePosition() throws { // Advance one block to let run ramp to 0.0, then record and verify write head stays put. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 32) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf) rec.run = 0.0 // Block 1: run ramps down (some writes may occur). do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } advanceBlock(engine) // Snapshot write position after block 1 completes. // Block 2: run = 0.0 flat — write head should not advance. let bufSnapshot: [Double] = (0..<32).map { buf[$0, 0] } do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } // Frames that should be zero in block 1 must remain zero in block 2. for i: Int in 8..<16 { #expect(buf[i, 0] == 0.0, "frame \(i) should still be unwritten; snapshot was \(bufSnapshot[i])") } engine.stop() } // MARK: - Loop behaviour @Test func loopWrapsWritePosition() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 16) let graph: SynthGraph = makeSynthGraph(engine: engine) let bufferFrames: Int = 8 let buf: LyrebirdBuffer = LyrebirdBuffer(count: bufferFrames) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: true) // One block of 16 samples → writes 16 frames into an 8-frame buffer (wraps once) _ = rec.calculatedSamples(graph: graph, count: 16) for i: Int in 0.. 8, "some frames should be written while run ramps down") #expect(rec.recordedFrameCount < buf.count, "recording stopped short of the full buffer") engine.stop() } @Test func recordedFrameCountControlVariantTracksWritePos() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) let rec: RecordBuffer.Control = RecordBuffer.Control(input: 1.0, buffer: buf, loop: false) for blockIdx: Int in 0..<3 { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) #expect(rec.recordedFrameCount == blockIdx + 1, "block \(blockIdx): expected recordedFrameCount \(blockIdx + 1)") advanceBlock(engine) } engine.stop() } // MARK: - requestReset @Test func requestResetRestartsWritePosAtNextBlock() throws { // Simulate a looper "reset" action: record a few frames of one value, call // requestReset(), then record a new value — the second take must overwrite // starting at frame 0, not continue from the mid-buffer writePos. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 32) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: false) // First take: 8 frames of 1.0. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } #expect(rec.recordedFrameCount == 8, "first take should write 8 frames") advanceBlock(engine) rec.requestReset() // recLevel is a ParameterNode-backed @LiveParam: it ramps toward its new target // over one block. Block A (frames 0–7, writePos restarted at 0 by the reset) // ramps recLevel 1.0→2.0 with varying values; Block B (frames 8–15) records // with recLevel flat at 2.0 — mirrors the recLevelScalesNewSignal pattern above. rec.recLevel = 2.0 do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } #expect(rec.recordedFrameCount == 8, "reset should restart writePos at 0, so this block again reaches frame count 8") advanceBlock(engine) do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } #expect(rec.recordedFrameCount == 16, "writePos should continue advancing normally after the reset settles") for i: Int in 8..<16 { #expect(abs(buf[i, 0] - 2.0) < 1e-9, "frame \(i): expected fresh take value 2.0 after reset, got \(buf[i, 0])") } for i: Int in 16..<32 { #expect(buf[i, 0] == 0.0, "frame \(i): region never reached by either take should remain unwritten") } engine.stop() } @Test func requestResetClearsDoneAndNeedsFree() throws { // A prior .freeNode completion (isDone == true, needsFree == true) must be // fully cleared by requestReset() so the same instance can record again. let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 8) let rec: RecordBuffer.Audio = RecordBuffer.Audio( input: 1.0, buffer: buf, loop: false, doneAction: .freeNode ) do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } #expect(rec.needsFree, "doneAction .freeNode should set needsFree once buffer fills") advanceBlock(engine) rec.requestReset() do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } // handleEndOfBuffer pins writePos at buffer.count - 1 (matches // doneActionFreeNodeSetsNeedsFree convention above) rather than buffer.count. #expect(rec.recordedFrameCount == buf.count - 1, "recording should resume and refill the buffer after reset") #expect(rec.needsFree, "recording to the end again should re-trigger needsFree") engine.stop() } // MARK: - Fast-path coverage /// Default-mode hot path: `recLevel == 1`, `preLevel == 0`, `run == 1`, `loop == true`. /// Pre-existing buffer content must be overwritten (pre == 0 → no read-back). @Test func defaultFastPathOverwritesExistingContent() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) buf.fill(with: 9.0) // poison existing content let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 0.5, buffer: buf, loop: true) // Defaults: recLevel = 1, preLevel = 0, run = 1. for _: Int in 0..<2 { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) advanceBlock(engine) } // Whole buffer overwritten with 0.5 — pre == 0 fast path must not mix the 9.0s. for i: Int in 0..<16 { #expect(abs(buf[i, 0] - 0.5) < 1e-12, "frame \(i): expected 0.5, got \(buf[i, 0])") } engine.stop() } /// Mid-block transition of `run` (positive → zero) must still gate writes correctly. /// Fast-path detection examines first + last sample; if they disagree, the general /// per-sample-gate path runs. @Test func midBlockRunTransitionHonoursGate() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) // Build a synthesizer that records a constant 1.0 with a run that ramps from 1 → 0 // mid-block via a Line.Audio fed to a private RecordBuffer-style harness. We don't // have direct mid-block gate control via @LiveParam (block-rate ramps end-to-end), // so this test forces the run-stability detection edge case by setting run=1, then // run=0 across two blocks: the first block has run rising from default → 1, the // second block transitions 1 → 0. Each block's first/last disagreement forces the // general path. We then verify writes match the per-sample gate. let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: false) // Block 1: run begins at default (1.0); leave at 1.0 — flat block, fast path. do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } advanceBlock(engine) // Frames 0..7 should all be 1.0 (recorded). for i: Int in 0..<8 { #expect(abs(buf[i, 0] - 1.0) < 1e-12, "block 1 frame \(i): expected 1.0, got \(buf[i, 0])") } // Block 2: drive run to 0. The ramp 1 → 0 produces a per-sample transition; // first/last sample disagree → general gate path. Writes stop somewhere within // the block; frames remain at their initial 0.0 once gate closes. rec.run = 0.0 do { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) } // Some prefix of frames 8..15 written, suffix untouched (0.0). Exact split // depends on ramp curvature; we verify (a) at least one frame written, (b) all // untouched frames remain 0.0, (c) all written frames are 1.0. var sawWritten: Bool = false var sawZero: Bool = false for i: Int in 8..<16 { let v: Double = buf[i, 0] if abs(v - 1.0) < 1e-12 { sawWritten = true } else if abs(v) < 1e-12 { sawZero = true } } #expect(sawWritten, "general path must still write while gate is open") #expect(sawZero, "general path must stop writing once gate closes") engine.stop() } /// Mono **generator** input with default fast-path flags hits the dedicated /// mono-generator `runStable && preBlockZero && recBlockOne` overwrite branch /// (distinct from the scalar `!inputIsGenerator` branch tested above). This /// is the hottest case in MyPiece's `MixAndRecordInputs` (mono mix of input /// buses → RecordBuffer). @Test func monoGeneratorDefaultFastPathOverwrites() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) buf.fill(with: 9.0) // poison existing content let src: RecordBufferFixtureGen = RecordBufferFixtureGen(0.5) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: src, buffer: buf, loop: true) // Defaults: recLevel = 1, preLevel = 0, run = 1 — all block-constant after // one settling block. for _: Int in 0..<2 { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) advanceBlock(engine) } for i: Int in 0..<16 { #expect(abs(buf[i, 0] - 0.5) < 1e-12, "frame \(i): expected 0.5, got \(buf[i, 0])") } engine.stop() } /// Mono generator + `recLevel = 0.25` exercises the `runStable && preBlockZero` /// (rec varies, pre still 0) sub-branch. @Test func monoGeneratorRecLevelFastPath() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16) let src: RecordBufferFixtureGen = RecordBufferFixtureGen(1.0) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: src, buffer: buf, loop: true) rec.recLevel = 0.25 // Block 1 (frames 0..7) settles the recLevel ramp 0 → 0.25 — frames 0..7 // hold the ramped values, not constant 0.25. Block 2 (frames 8..15) runs // with `recLevel` flat at 0.25 — frames 8..15 record `1.0 * 0.25 = 0.25`. for _: Int in 0..<2 { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) advanceBlock(engine) } for i: Int in 8..<16 { #expect(abs(buf[i, 0] - 0.25) < 1e-12, "frame \(i): expected 0.25, got \(buf[i, 0])") } engine.stop() } /// Stereo recording with default fast-path flags exercises the multi-channel pre==0 /// && rec==1 branch (overwrite both channels, no read-back). @Test func stereoDefaultFastPathOverwrites() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 8) let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16, channelCount: 2) // Poison both channels — fill(with:) is mono-only, so seed via setValue. for i: Int in 0..<16 { buf.setValue(7.0, frame: i, channel: 0) buf.setValue(7.0, frame: i, channel: 1) } let stereo: GeneratorArray = GeneratorArray([ RecordBufferFixtureGen(0.25), RecordBufferFixtureGen(-0.75) ]) let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: stereo, buffer: buf, loop: true) for _: Int in 0..<2 { let graph: SynthGraph = makeSynthGraph(engine: engine) _ = rec.calculatedSamples(graph: graph, count: 8) advanceBlock(engine) } for i: Int in 0..<16 { #expect(abs(buf[i, 0] - 0.25) < 1e-12, "ch0 frame \(i): expected 0.25, got \(buf[i, 0])") #expect(abs(buf[i, 1] - (-0.75)) < 1e-12, "ch1 frame \(i): expected -0.75, got \(buf[i, 1])") } engine.stop() } } // MARK: - Test fixture // test-only: allocates [[Double]] per call — RT allocation acceptable in tests. private final class RecordBufferFixtureGen: GeneratorBase, AudioGenerator { let value: Double init(_ v: Double) { value = v } func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) return [[Double](repeating: value, count: count)] } func floatValue(graph: SynthGraph) -> Double { value } }