Files
Lyrebird/Sources/Lyrebird/Generators/Triggers/Trig.swift
T
2026-06-21 11:45:58 -07:00

227 lines
8.4 KiB
Swift

// Trig.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// File-scope zero-fill block — used as the `??` fallback when an upstream
/// generator returns an empty channel array.
private let trigZeroBlock: [Double] = [Double](
repeating: 0,
count: lyrebirdDefaultResultBufferSize
)
/// Trigger-length pulse that outputs the captured input level.
///
/// On each ≤0 → >0 rising edge of `input`, captures the input value at that
/// exact frame and outputs it for `dur` seconds, then returns to `0.0`.
/// A new rising edge during the hold restarts the timer and re-captures the
/// level at the new edge frame.
///
/// SC equivalent: `Trig`.
///
/// ```swift
/// // Capture amplitude and hold it for 0.1 s every time a trigger fires.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0))
/// let clock = Impulse.Audio(freq: 4.0)
/// let pulse = Trig.Audio(input: amp, dur: 0.1)
/// ```
///
/// - Parameters:
/// - input: Signal to monitor for rising edges; the captured level is this value at the edge frame.
/// - dur: Hold duration in seconds. Converted to samples via engine sample rate.
/// Clamped to a minimum of 1 sample. Init-time scalar only.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum Trig {
// MARK: - Shared base
public class _Base: GeneratorBase {
let _input: any ValidGeneratorInput
let _mulAdd: MulAddSpec
let _dur: Double
var _prevTrig: Double = 0.0
var _remaining: Int = 0
var _level: Double = 0.0
init(
input: any ValidGeneratorInput,
dur: Double,
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_dur = dur
_mulAdd = MulAddSpec(mul: mul, add: add)
}
}
// MARK: - Audio rate
/// Sample-accurate trig pulse that outputs the input level for `dur` seconds.
///
/// - Parameters:
/// - input: Signal to monitor for rising edges; captured level is this value at the edge frame.
/// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - input: Signal to monitor for rising edges; captured level is this value at the edge frame.
/// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
input: any ValidGeneratorInput,
dur: Double = 0.1,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, dur: dur, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first
?? trigZeroBlock
let sampleRate: Double = graph.engine.sampleRate
let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded()))
var prevTrig: Double = _prevTrig
var remaining: Int = _remaining
var level: Double = _level
for i: Int in 0..<count {
let x: Double = inputSamples[i]
if x > 0 && prevTrig <= 0 {
// Rising edge: capture level and restart countdown.
level = x
remaining = delaySamples
}
prevTrig = x
if remaining > 0 {
_result[0][i] = level
remaining -= 1
} else {
_result[0][i] = 0.0
}
}
_prevTrig = prevTrig
_remaining = remaining
_level = level
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control rate
/// Block-rate trig pulse. Scans the full audio-rate input block for rising edges.
/// The block-final level (captured value or 0) is output as a flat block — no ramp.
///
/// > Note: Trigger/counter outputs must not be interpolated/smoothed because they
/// > are discrete-valued. This variant writes a flat constant block equal to the
/// > block-final state rather than using `fillRampedResult`.
///
/// - Parameters:
/// - input: Signal to monitor for rising edges; captured level is this value at the edge frame.
/// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
/// - input: Signal to monitor for rising edges; captured level is this value at the edge frame.
/// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
input: any ValidGeneratorInput,
dur: Double = 0.1,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, dur: dur, mul: mul, add: add)
_setupSubBlockBuffer()
}
/// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning
/// the full audio-rate input once per audio block, not per sub-block chunk.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first
?? trigZeroBlock
let sampleRate: Double = graph.engine.sampleRate
let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded()))
var prevTrig: Double = _prevTrig
var remaining: Int = _remaining
var level: Double = _level
// Run the exact per-sample state machine and capture the output at
// the final sample — the block-representative (block-final) value.
// Capturing the per-sample output (rather than inferring from the
// post-loop `remaining`) keeps the boundary correct when a hold
// spans exactly one block: the hold is active across every sample,
// so the block-final value is `level`, not `0`.
var lastOutput: Double = 0.0
for i: Int in 0..<count {
let x: Double = inputSamples[i]
if x > 0 && prevTrig <= 0 {
level = x
remaining = delaySamples
}
prevTrig = x
if remaining > 0 {
lastOutput = level
remaining -= 1
} else {
lastOutput = 0.0
}
}
_prevTrig = prevTrig
_remaining = remaining
_level = level
let outputValue: Double = lastOutput
for i: Int in 0..<count {
_result[0][i] = outputValue
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
if count > 0 { previousOutputValue = _result[0][count - 1] }
return _result
}
}
}
extension Trig: GeneratorEnum {
public typealias AudioType = Trig.Audio
public typealias ControlType = Trig.Control
}