// LyrebirdProcessReleaseNodeHoldTest.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable import LyrebirdSynth /// Regression — verify that `Envelope.releaseNode` uses the /// SuperCollider-style LEVEL INDEX convention. The user-facing case: /// /// ```swift /// Envelope( /// levels: [0.0, 1.0, 0.0], /// durations: [2.0, 2.0], /// releaseNode: 1 // hold at levels[1] = 1.0 /// ) /// ``` /// /// must hold at the peak value (1.0) indefinitely while gate > 0, not at /// `levels[releaseNode + 1] = levels[2] = 0` (the earlier behavior). @MainActor @Suite("LyrebirdProcess envelope holds at releaseNode level index") struct LyrebirdProcessReleaseNodeHoldTest { @Test("Envelope.releaseNode is a LEVEL INDEX — hold value equals levels[releaseNode]") func testReleaseNodeIsLevelIndex() throws { let env: Envelope = Envelope( levels: [0.0, 1.0, 0.0], durations: [2.0, 2.0], curves: [.lin, .lin], releaseNode: 1 ) let rn: Int = try #require(env.releaseNode, "releaseNode should not be nil") #expect(rn == 1, "Public releaseNode value should be preserved as the level index") // levels[releaseNode] = levels[1] = 1.0 — the SUSTAIN level, not 0. #expect(env.levels[rn] == 1.0) } @Test("Process envelope holds at releaseNode level — process keeps running past total-duration") func testReleaseNodeHold() async throws { let blockSize: Int = 64 let sampleRate: Double = 48000.0 let engine: SynthesisEngine = SynthesisEngine( blockSize: blockSize, sampleRate: sampleRate, numOutputChannels: 2, numInputChannels: 0, driver: OfflineDriver() ) try engine.start() defer { engine.stop() } // `releaseNode: 1` on `[0.0, 1.0, 0.0]` holds at level[1] = 1.0. // Segment 0 (attack, 0.05 s) plays, then the route envelope sustains at // level 1.0 indefinitely while gate > 0. With `gate` still 1.0 there is // no auto-completion — the process keeps running past the envelope's // nominal total duration (0.1 s). let processEnv: Envelope = Envelope( levels: [0.0, 1.0, 0.0], durations: [0.05, 0.05], curves: [.sine, .sine], releaseNode: 1 ) let proc: LyrebirdProcess = LyrebirdProcess( id: "release-hold", envelope: processEnv, numChannels: 1, body: { ctx in while ctx.isRunning { await ctx.wait(0.01) } } ) proc.play(engine: engine) // Drive engine-time way past the envelope's 0.1 s total. Without the // SC-style hold, the envelope would reach level[2] = 0, the watcher // would observe `needsFree`, and the process would tear down within // a tick. let blocksFor1Second: Int = Int(sampleRate / Double(blockSize)) for _ in 0..<(blocksFor1Second * 2) { engine.processBlock(inputSamples: []) } #expect(proc.isRunning, "Process should still be running after 2s with no release()") // Now release. The envelope progresses through segment 1 (1.0 → 0.0) // as the release tail, then auto-frees. proc.release() for _ in 0..