// Trig1ControlTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @MainActor @Suite("Trig1.Control") struct Trig1ControlTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } let blockSize: Int = 64 init() throws { engine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() } @Test func rateIsControl() { let gen: Trig1.Control = Trig1.Control(input: 0.0, dur: 0.1) #expect(gen.rate == .control) } /// Constant-zero input produces no rising edge; output holds 0. @Test func noTriggerOutputsZero() { let gen: Trig1.Control = Trig1.Control(input: 0.0, dur: 0.1) _ = gen.calculatedSamples(graph: graph, count: blockSize) #expect(gen.previousOutputValue == 0.0) } /// Rising edge in the block causes previousOutputValue = 1.0 (unity, not input level). @Test func risingEdgeOutputsUnity() { let durSamples: Int = blockSize * 2 let dur: Double = Double(durSamples) / 44100.0 // Input = 0 for samples 0..15, then 0.99 (non-unity to confirm Trig1 outputs 1.0). let input: Closure = Closure { _, i in i < 16 ? 0.0 : 0.99 } let gen: Trig1.Control = Trig1.Control(input: input, dur: dur) _ = gen.calculatedSamples(graph: graph, count: blockSize) #expect(abs(gen.previousOutputValue - 1.0) < 1e-12, "previousOutputValue expected 1.0 got \(gen.previousOutputValue)") } /// Boundary: a pulse whose duration equals exactly one block stays high /// across every sample, so the block-final value is 1.0 — not 0 /// (regression for inferring output from post-loop `remaining`). @Test func pulseSpanningExactlyOneBlockOutputsUnity() { let durSamples: Int = blockSize // pulse == one block exactly let dur: Double = Double(durSamples) / 44100.0 let gen: Trig1.Control = Trig1.Control(input: 0.3, dur: dur) _ = gen.calculatedSamples(graph: graph, count: blockSize) #expect(abs(gen.previousOutputValue - 1.0) < 1e-12, "full-block pulse expected 1.0 got \(gen.previousOutputValue)") } /// Output block is flat (discrete, not ramped). @Test func outputBlockIsFlat() { let durSamples: Int = blockSize * 2 let dur: Double = Double(durSamples) / 44100.0 // Constant 0.3 input — fires at sample 0 (prevTrig=0, x=0.3 > 0). let gen: Trig1.Control = Trig1.Control(input: 0.3, dur: dur) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) let block: [Double] = Array(out[0].prefix(blockSize)) // After trigger at sample 0, output is unity = 1.0 flat. for i: Int in 0..