560724d116
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
653 lines
30 KiB
Swift
653 lines
30 KiB
Swift
// EnvelopeGen.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Foundation
|
||
import Synchronization
|
||
|
||
/// Multi-segment envelope generator with audio-rate (`EnvelopeGen.Audio`) and
|
||
/// control-rate (`EnvelopeGen.Control`) variants.
|
||
///
|
||
/// **Curve shapes** — pass `EnvelopeCurve` named cases (`.sine`, `.exponential`,
|
||
/// `.welch`, …) or numeric literals for parametric curves. See ``EnvelopeCurve``
|
||
/// for the full shape table and parametric formula.
|
||
///
|
||
/// **Done actions:**
|
||
/// - `.nothing`: freeze at the final level
|
||
/// - `.loop`: restart from the beginning
|
||
/// - `.freeNode`: freeze and set `needsFree = true`
|
||
///
|
||
/// **`levelScale` and `levelBias`** are applied to every output sample:
|
||
/// `output = level × levelScale + levelBias`
|
||
///
|
||
/// **`timeScale`** multiplies each segment's duration before it is converted to
|
||
/// samples. `timeScale: 2.0` stretches a 1-second envelope to 2 seconds; `0.5`
|
||
/// halves it. Read once per block; applied at the next segment entry (the
|
||
/// segment currently in progress is not re-timed mid-flight). Negative values
|
||
/// clamp to `0`, which snaps the affected segment to its end level. Default `1.0`.
|
||
///
|
||
/// **`gate`** — pass any `ValidGeneratorInput` (default `1.0`). Read once per block
|
||
/// (block-constant). Interacts with two optional `Envelope` fields:
|
||
/// - `envelope.releaseNode`: holds at `levels[releaseNode]` while `gate > 0`; resumes on `≤ 0`.
|
||
/// (`releaseNode` is a level index — SuperCollider convention.)
|
||
/// - `envelope.loopNode`: loops back to the segment start while `gate > 0`; exits loop on `≤ 0`.
|
||
/// Once `gate` drops to `≤ 0`, both hold and loop are permanently disabled for this instance.
|
||
/// Pass a `ParameterNode` (`$liveparam`) to update the gate at runtime from a `Synthesizer`.
|
||
public enum EnvelopeGen {
|
||
|
||
// MARK: - Shared base
|
||
|
||
/// Shared state and helpers for both rate variants.
|
||
/// Not for direct use — instantiate `EnvelopeGen.Audio` or `EnvelopeGen.Control`.
|
||
public class _Base: GeneratorBase {
|
||
var _packet: EnvelopePacket
|
||
let levelScaleInput: any ValidGeneratorInput
|
||
let levelBiasInput: any ValidGeneratorInput
|
||
let timeScaleInput: any ValidGeneratorInput
|
||
let gateInput: any ValidGeneratorInput
|
||
|
||
private let _doneAction: DoneAction
|
||
var doneAction: DoneAction { _doneAction }
|
||
|
||
/// Set to `true` by the RT render pass when `doneAction == .freeNode` and the
|
||
/// envelope has finished. Read from a non-RT context after `processBlock` returns
|
||
/// to schedule node removal. Never post to `pendingQueue` from inside the RT
|
||
/// callback in response to this flag.
|
||
private let _needsFree: Atomic<Bool> = Atomic(false)
|
||
var needsFree: Bool { _needsFree.load(ordering: .acquiring) }
|
||
|
||
// Lock-free RT-safe envelope swap queue.
|
||
// Main thread encodes Envelope → EnvelopePacket (no heap, no ARC) and enqueues.
|
||
// RT thread dequeues and value-copies the packet. No kill queue needed — overwriting
|
||
// a packet slot releases no heap and triggers no ARC.
|
||
private let _envInQueue: SPSCQueue<EnvelopePacket> = SPSCQueue(capacity: EnvelopePacket.queueCapacity)
|
||
|
||
// Tracks the segment serial of the last _checkEnvelopeSwap drain.
|
||
// Prevents draining more than one packet per audio block in sub-block mode.
|
||
fileprivate var _swapSerial: UInt64 = UInt64.max
|
||
|
||
// MARK: - Playback state
|
||
|
||
var currentSegment: Int = 0
|
||
var samplePos: Int = 0
|
||
var isDone: Bool = false
|
||
var _heldAtRelease: Bool = false
|
||
var _heldRawLevel: Double = 0.0
|
||
/// Set to `true` the first time `gate ≤ 0` is seen. Once released, loop and
|
||
/// release-hold are permanently bypassed — the envelope runs to completion even
|
||
/// if `gate` later returns to `> 0`.
|
||
var _released: Bool = false
|
||
|
||
// MARK: - Segment cache
|
||
//
|
||
// Pre-computed once per segment entry (initSegmentCache), never on the hot path.
|
||
//
|
||
// .parametric / .trueExponential: one multiply per sample (_segCurrentExp *= _segStep).
|
||
// .sine / .welch: digital oscillator — two multiplies and two adds per sample
|
||
// (_segOscCos, _segOscSin updated via rotation matrix), no trig per sample.
|
||
// .squared / .cubed / .step / .hold / .linear: delegate to
|
||
// EnvelopeSegmentCurve.value(startLevel:range:pos:) — pure arithmetic, no trig.
|
||
|
||
var _segCachedIndex: Int = -1
|
||
var _segCachedSampleRate: Double = -1.0
|
||
var _segCurve: EnvelopeSegmentCurve = EnvelopeSegmentCurve(curve: .lin)
|
||
var _segSamples: Double = 0.0
|
||
// .parametric / .trueExponential multiplicative step state
|
||
var _segStep: Double = 1.0
|
||
var _segCurrentExp: Double = 1.0
|
||
var _segEndExp: Double = 1.0
|
||
var _segDenom: Double = 1.0
|
||
// .sine / .welch digital oscillator state (rotation matrix)
|
||
var _segOscCos: Double = 0.0
|
||
var _segOscSin: Double = 0.0
|
||
var _segOscCosStep: Double = 1.0
|
||
var _segOscSinStep: Double = 0.0
|
||
var _segRange: Double = 0.0
|
||
var _segStartLevel: Double = 0.0
|
||
|
||
|
||
/// - Parameters:
|
||
/// - envelope: The `Envelope` descriptor that defines segments, levels, and curves.
|
||
/// - levelScale: Scales all output levels multiplicatively. Default `1.0`.
|
||
/// - levelBias: Offset added to all output levels after scaling. Default `0.0`.
|
||
/// - timeScale: Multiplies each segment's duration before sample-count conversion.
|
||
/// Default `1.0`. Read once per block; applied at the next segment entry — the
|
||
/// segment currently in progress is not re-timed mid-flight. Negative values
|
||
/// clamp to `0` (snaps the affected segment to its end level).
|
||
/// - gate: Holds the envelope at `releaseNode` / loops at `loopNode` while `> 0`.
|
||
/// Read once per block via `floatValue(graph:)` — block-constant, not per-sample.
|
||
/// Pass a `Double` literal or `ParameterNode` — do NOT pass a `String` key,
|
||
/// as `String.floatValue(graph:)` performs a `Dictionary` lookup on the RT thread.
|
||
/// - doneAction: Action taken when the envelope completes. Default `.nothing`.
|
||
init(
|
||
envelope: Envelope,
|
||
levelScale: any ValidGeneratorInput = 1.0 as Double,
|
||
levelBias: any ValidGeneratorInput = 0.0 as Double,
|
||
timeScale: any ValidGeneratorInput = 1.0 as Double,
|
||
gate: any ValidGeneratorInput = 1.0 as Double,
|
||
doneAction: DoneAction = .nothing
|
||
) {
|
||
let resolvedLevelScale: any ValidGeneratorInput = levelScale._resolvedInput()
|
||
let resolvedLevelBias: any ValidGeneratorInput = levelBias._resolvedInput()
|
||
let resolvedTimeScale: any ValidGeneratorInput = timeScale._resolvedInput()
|
||
let resolvedGate: any ValidGeneratorInput = gate._resolvedInput()
|
||
self._packet = EnvelopePacket(from: envelope)
|
||
self.levelScaleInput = resolvedLevelScale
|
||
self.levelBiasInput = resolvedLevelBias
|
||
self.timeScaleInput = resolvedTimeScale
|
||
self.gateInput = resolvedGate
|
||
self._doneAction = doneAction
|
||
}
|
||
|
||
// MARK: - Runtime envelope swap
|
||
|
||
/// Replace the envelope at runtime. Safe to call from the main thread at any time.
|
||
///
|
||
/// The new envelope is delivered to the RT thread lock-free via an internal queue
|
||
/// and takes effect at the start of the next audio block. Playback state is preserved
|
||
/// in-place: `currentSegment` and `samplePos` are kept, clamped to the new segment
|
||
/// count if needed. The `_released` gate latch is not cleared.
|
||
///
|
||
/// - Precondition: `envelope.segmentCount <= EnvelopePacket.maxSegments` (32)
|
||
public func setEnvelope(_ envelope: Envelope) {
|
||
_ = _envInQueue.enqueue(EnvelopePacket(from: envelope))
|
||
}
|
||
|
||
/// Called at the start of each `_computeSamples` block (RT thread).
|
||
/// Swaps in a pending packet if one is available, keeping playback state in-place.
|
||
func _checkEnvelopeSwap() {
|
||
guard let pkt: EnvelopePacket = _envInQueue.dequeue() else { return }
|
||
_packet = pkt // pure value copy (~832 bytes), no heap, no ARC
|
||
if currentSegment >= _packet.segmentCount {
|
||
currentSegment = max(0, _packet.segmentCount - 1)
|
||
samplePos = 0
|
||
}
|
||
_heldAtRelease = false
|
||
_segCachedIndex = -1
|
||
isDone = false
|
||
}
|
||
|
||
// MARK: - Segment management
|
||
|
||
func initSegmentCache(sampleRate: Double, timeScale: Double) {
|
||
guard currentSegment < _packet.segmentCount else { return }
|
||
|
||
_segCachedIndex = currentSegment
|
||
_segCachedSampleRate = sampleRate
|
||
_segStartLevel = _packet.level(at: currentSegment)
|
||
_segRange = _packet.level(at: currentSegment + 1) - _segStartLevel
|
||
_segSamples = _packet.duration(at: currentSegment) * timeScale * sampleRate
|
||
|
||
_segCurve = EnvelopeSegmentCurve(curve: _packet.curve(at: currentSegment))
|
||
|
||
switch _segCurve.kind {
|
||
case .parametric:
|
||
_segDenom = _segCurve.denom
|
||
_segEndExp = _segCurve.endExp
|
||
_segStep = _segCurve.rtStep(segmentSamples: _segSamples)
|
||
_segCurrentExp = _segSamples > 0 ? _segStep : _segCurve.endExp
|
||
|
||
case .trueExponential:
|
||
let endLevel: Double = _segStartLevel + _segRange
|
||
if _segStartLevel != 0, endLevel != 0,
|
||
_segStartLevel.sign == endLevel.sign, _segSamples > 0 {
|
||
_segStep = pow(endLevel / _segStartLevel, 1.0 / _segSamples)
|
||
// _segCurrentExp represents startLevel × step^(samplePos+1) at time of use.
|
||
// Initialise to the first-step value so the pattern matches .parametric.
|
||
_segCurrentExp = _segStartLevel * _segStep
|
||
_segEndExp = endLevel
|
||
} else {
|
||
// Degenerate (zero crossing or zero level) — fall back to linear.
|
||
// Reset multiplicative-step fields to safe identity values so they don't
|
||
// confuse future audits; computeCurrentSample dispatches on _segCurve.kind
|
||
// and will take the .linear path, never reading these fields.
|
||
_segStep = 1.0
|
||
_segCurrentExp = _segStartLevel
|
||
_segEndExp = _segStartLevel + _segRange
|
||
_segCurve = EnvelopeSegmentCurve(curve: .lin)
|
||
}
|
||
|
||
case .sine:
|
||
// Digital oscillator: angle advances by π/N per sample (N = _segSamples).
|
||
// Avoids cos() per sample — only two multiplies and two adds in steady state.
|
||
// Initial state is the value at samplePos=0 → pos=1/N.
|
||
if _segSamples > 0 {
|
||
let theta: Double = Double.pi / _segSamples
|
||
_segOscCosStep = Foundation.cos(theta)
|
||
_segOscSinStep = Foundation.sin(theta)
|
||
_segOscCos = _segOscCosStep // cos(π/N)
|
||
_segOscSin = _segOscSinStep // sin(π/N)
|
||
}
|
||
|
||
case .welch:
|
||
// Digital oscillator: angle advances by π/(2N) per sample.
|
||
if _segSamples > 0 {
|
||
let theta: Double = Double.pi / (2.0 * _segSamples)
|
||
_segOscCosStep = Foundation.cos(theta)
|
||
_segOscSinStep = Foundation.sin(theta)
|
||
_segOscCos = _segOscCosStep // cos(π/(2N))
|
||
_segOscSin = _segOscSinStep // sin(π/(2N))
|
||
}
|
||
|
||
default:
|
||
break // squared, cubed, step, hold, linear: pure arithmetic, no precomputation
|
||
}
|
||
}
|
||
|
||
func computeCurrentSample(
|
||
sampleRate: Double,
|
||
scale: Double,
|
||
bias: Double,
|
||
timeScale: Double,
|
||
gate: Double = 1.0
|
||
) -> Double? {
|
||
guard currentSegment < _packet.segmentCount else { return nil }
|
||
|
||
if currentSegment != _segCachedIndex || sampleRate != _segCachedSampleRate {
|
||
initSegmentCache(sampleRate: sampleRate, timeScale: timeScale)
|
||
}
|
||
|
||
let pos: Double
|
||
if _segSamples > 0 {
|
||
pos = min(Double(samplePos + 1) / _segSamples, 1.0)
|
||
} else {
|
||
pos = 1.0
|
||
}
|
||
|
||
// Hot-path dispatch. Three stepping strategies, no trig per sample:
|
||
// .parametric / .trueExponential — multiplicative exp step (_segCurrentExp *= _segStep)
|
||
// .sine / .welch — digital oscillator rotation (two mul + two add)
|
||
// all others — pure arithmetic via EnvelopeSegmentCurve.value()
|
||
let rawLevel: Double
|
||
switch _segCurve.kind {
|
||
case .parametric:
|
||
let expTerm: Double = pos >= 1.0 ? _segEndExp : _segCurrentExp
|
||
rawLevel = _segStartLevel + _segRange * (1.0 - expTerm) / _segDenom
|
||
if pos < 1.0 { _segCurrentExp *= _segStep }
|
||
|
||
case .trueExponential:
|
||
rawLevel = pos >= 1.0 ? _segEndExp : _segCurrentExp
|
||
if pos < 1.0 { _segCurrentExp *= _segStep }
|
||
|
||
case .sine:
|
||
// cos(π) = −1 → (1−(−1))/2 = 1 → endLevel at pos=1.0
|
||
let cosVal: Double = pos >= 1.0 ? -1.0 : _segOscCos
|
||
rawLevel = _segStartLevel + _segRange * (1.0 - cosVal) / 2.0
|
||
if pos < 1.0 {
|
||
let c: Double = _segOscCos * _segOscCosStep - _segOscSin * _segOscSinStep
|
||
_segOscSin = _segOscSin * _segOscCosStep + _segOscCos * _segOscSinStep
|
||
_segOscCos = c
|
||
}
|
||
|
||
case .welch:
|
||
// Rising (range ≥ 0): sin(π/2) = 1 → endLevel at pos=1.0
|
||
// Falling (range < 0): cos(π/2) = 0 → (1−0) = 1 → endLevel at pos=1.0
|
||
if _segRange >= 0 {
|
||
let sinVal: Double = pos >= 1.0 ? 1.0 : _segOscSin
|
||
rawLevel = _segStartLevel + _segRange * sinVal
|
||
} else {
|
||
let cosVal: Double = pos >= 1.0 ? 0.0 : _segOscCos
|
||
rawLevel = _segStartLevel + _segRange * (1.0 - cosVal)
|
||
}
|
||
if pos < 1.0 {
|
||
let c: Double = _segOscCos * _segOscCosStep - _segOscSin * _segOscSinStep
|
||
_segOscSin = _segOscSin * _segOscCosStep + _segOscCos * _segOscSinStep
|
||
_segOscCos = c
|
||
}
|
||
|
||
default:
|
||
// .squared, .cubed, .step, .hold, .linear — pure arithmetic, no trig
|
||
rawLevel = _segCurve.value(startLevel: _segStartLevel, range: _segRange, pos: pos)
|
||
}
|
||
|
||
let output: Double = rawLevel * scale + bias
|
||
|
||
// Advance samplePos *after* emitting the output so the last sample of a segment
|
||
// (pos = 1.0) is correctly emitted before the segment-boundary action fires.
|
||
samplePos += 1
|
||
if _segSamples <= 0 || Double(samplePos) >= _segSamples {
|
||
// gate is block-constant (_released permanently latches after first ≤0 read),
|
||
// so this check is stable for the duration of the current block.
|
||
let ln: Int = _packet.loopNode
|
||
let rn: Int = _packet.releaseNode
|
||
if ln != -1, currentSegment == ln, gate > 0 {
|
||
samplePos = 0
|
||
_segCachedIndex = -1 // triggers initSegmentCache on next call
|
||
} else if rn != -1, currentSegment == rn, gate > 0 {
|
||
_heldAtRelease = true
|
||
_heldRawLevel = _packet.level(at: rn + 1)
|
||
} else {
|
||
currentSegment += 1
|
||
samplePos = 0
|
||
}
|
||
}
|
||
|
||
return output
|
||
}
|
||
|
||
func handleDone() {
|
||
switch doneAction {
|
||
case .nothing:
|
||
isDone = true
|
||
case .freeNode:
|
||
isDone = true
|
||
_needsFree.store(true, ordering: .releasing)
|
||
case .loop:
|
||
currentSegment = 0
|
||
samplePos = 0
|
||
_segCachedIndex = -1
|
||
_heldAtRelease = false
|
||
// _released is NOT reset — permanent-latch must survive a .loop restart
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Audio
|
||
|
||
/// Audio-rate multi-segment envelope generator.
|
||
///
|
||
/// Evaluates one envelope sample per output sample, giving full per-sample shape resolution.
|
||
/// Use this when the envelope drives amplitude or any signal where click-free, sample-accurate
|
||
/// transitions matter.
|
||
///
|
||
/// ## Gate, releaseNode, loopNode
|
||
///
|
||
/// Pass a `gate` at init (`ValidGeneratorInput`, default `1.0`). Gate is read once per block.
|
||
/// - If `envelope.releaseNode` is set and `gate > 0`, the generator holds at the sustain level
|
||
/// after completing that segment. Set `gate ≤ 0` to release.
|
||
/// - If `envelope.loopNode` is set and `gate > 0`, the generator loops that segment indefinitely.
|
||
/// Set `gate ≤ 0` to exit the loop and play through the remaining segments.
|
||
/// - Once `gate` goes `≤ 0` the release is permanent — the envelope will not re-hold or re-loop
|
||
/// if `gate` returns to `> 0` later.
|
||
///
|
||
/// ## Done-action / freeNode integration
|
||
///
|
||
/// When `doneAction == .freeNode`, the RT thread stores `true` into `needsFree` via
|
||
/// a releasing atomic store. Read `needsFree` from a non-RT context after `processBlock`
|
||
/// returns and post a remove event to `pendingQueue` from there.
|
||
///
|
||
/// ## RT-allocation model
|
||
///
|
||
/// `_result` is pre-allocated in `init`. No heap allocation in steady state.
|
||
///
|
||
/// ## Usage
|
||
/// ```swift
|
||
/// let env = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential])
|
||
/// let gen = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
|
||
/// // After processBlock: if gen.needsFree { engine.remove(synth) }
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - envelope: The `Envelope` descriptor that defines segments, levels, and curves.
|
||
/// - levelScale: Scales all output levels multiplicatively. Default `1.0`.
|
||
/// - levelBias: Offset added to all output levels after scaling. Default `0.0`.
|
||
/// - timeScale: Multiplies each segment's duration before sample-count conversion.
|
||
/// Default `1.0`. Read once per block; applied at the next segment entry. Negative
|
||
/// values clamp to `0`.
|
||
/// - gate: Holds at `releaseNode` / loops at `loopNode` while `> 0`. Default `1.0`.
|
||
/// - doneAction: Action taken when the envelope completes. Default `.nothing`.
|
||
public final class Audio: _Base, AudioGenerator, DoneActionWatchable {
|
||
|
||
public override var doneAction: DoneAction { super.doneAction }
|
||
public override var needsFree: Bool { super.needsFree }
|
||
|
||
|
||
/// - Parameters:
|
||
/// - envelope: The `Envelope` descriptor that defines segments, levels, and curves.
|
||
/// - levelScale: Scales all output levels multiplicatively. Default `1.0`.
|
||
/// - levelBias: Offset added to all output levels after scaling. Default `0.0`.
|
||
/// - timeScale: Multiplies each segment's duration before sample-count conversion.
|
||
/// Default `1.0`. Read once per block; applied at the next segment entry. Negative
|
||
/// values clamp to `0`.
|
||
/// - gate: Holds at `releaseNode` / loops at `loopNode` while `> 0`. Default `1.0`.
|
||
/// - doneAction: Action taken when the envelope completes. Default `.nothing`.
|
||
public override init(
|
||
envelope: Envelope,
|
||
levelScale: any ValidGeneratorInput = 1.0 as Double,
|
||
levelBias: any ValidGeneratorInput = 0.0 as Double,
|
||
timeScale: any ValidGeneratorInput = 1.0 as Double,
|
||
gate: any ValidGeneratorInput = 1.0 as Double,
|
||
doneAction: DoneAction = .nothing
|
||
) {
|
||
super.init(
|
||
envelope: envelope,
|
||
levelScale: levelScale,
|
||
levelBias: levelBias,
|
||
timeScale: timeScale,
|
||
gate: gate,
|
||
doneAction: doneAction
|
||
)
|
||
_registerAutoFreeIfNeeded(doneAction)
|
||
}
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
// AudioGenerator.calculatedSamples fan-out cache (via _segmentSerial) guarantees
|
||
// _computeSamples is called at most once per audio block — no serial gate needed.
|
||
_checkEnvelopeSwap()
|
||
|
||
let sampleRate: Double = graph.engine.sampleRate
|
||
let scale: Double = levelScaleInput.floatValue(graph: graph)
|
||
let bias: Double = levelBiasInput.floatValue(graph: graph)
|
||
let timeScale: Double = max(timeScaleInput.floatValue(graph: graph), 0.0)
|
||
let finalLevel: Double = _packet.level(at: _packet.segmentCount) * scale + bias
|
||
|
||
let gateVal: Double
|
||
if _packet.loopNode != -1 || _packet.releaseNode != -1 {
|
||
if !_released {
|
||
let rawGate: Double = gateInput.floatValue(graph: graph)
|
||
if rawGate <= 0 { _released = true }
|
||
gateVal = _released ? 0.0 : rawGate
|
||
} else {
|
||
gateVal = 0.0
|
||
}
|
||
} else {
|
||
gateVal = 1.0
|
||
}
|
||
|
||
for i: Int in 0..<count {
|
||
if isDone {
|
||
_result[0][i] = finalLevel
|
||
continue
|
||
}
|
||
|
||
if _heldAtRelease {
|
||
if gateVal <= 0 {
|
||
_heldAtRelease = false
|
||
let rn: Int = _packet.releaseNode
|
||
guard rn != -1 else { currentSegment += 1; break }
|
||
currentSegment = rn + 1
|
||
samplePos = 0
|
||
_segCachedIndex = -1
|
||
} else {
|
||
_result[0][i] = _heldRawLevel * scale + bias
|
||
continue
|
||
}
|
||
}
|
||
|
||
if currentSegment >= _packet.segmentCount {
|
||
handleDone()
|
||
_result[0][i] = isDone
|
||
? finalLevel
|
||
: (computeCurrentSample(sampleRate: sampleRate, scale: scale, bias: bias, timeScale: timeScale, gate: gateVal) ?? finalLevel)
|
||
continue
|
||
}
|
||
|
||
_result[0][i] = computeCurrentSample(sampleRate: sampleRate, scale: scale, bias: bias, timeScale: timeScale, gate: gateVal) ?? finalLevel
|
||
}
|
||
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control
|
||
|
||
/// Control-rate multi-segment envelope generator — advances the envelope once per block
|
||
/// and produces a smooth linear ramp, allowing downstream audio-rate consumers to receive
|
||
/// a full-block buffer.
|
||
///
|
||
/// The envelope state is advanced by `count` samples each block (so envelope timing is
|
||
/// identical to `EnvelopeGen.Audio`). Only the final envelope value per block is used as
|
||
/// the ramp target; intra-block shape detail is lost. Use `EnvelopeGen.Audio` when
|
||
/// per-sample accuracy matters (amplitude envelopes, click-free fade-outs).
|
||
///
|
||
/// ## Gate, releaseNode, loopNode
|
||
///
|
||
/// Same semantics as `EnvelopeGen.Audio`. Gate is read once per block (block-constant).
|
||
/// - `envelope.releaseNode` set + `gate > 0`: holds at sustain level; releases on `gate ≤ 0`.
|
||
/// - `envelope.loopNode` set + `gate > 0`: loops that segment; exits on `gate ≤ 0`.
|
||
/// - Release is permanent — once `gate ≤ 0`, hold and loop are disabled for the instance lifetime.
|
||
///
|
||
/// ## Typical use
|
||
/// ```swift
|
||
/// let ampEnv = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode) // amplitude
|
||
/// let filtEnv = EnvelopeGen.Control(envelope: filterEnv) // filter cutoff
|
||
/// let filter = RBJLowPass.Audio(input: osc, freq: filtEnv * 2000.0 + 200.0, q: 0.707)
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - envelope: The `Envelope` descriptor that defines segments, levels, and curves.
|
||
/// - levelScale: Scales all output levels multiplicatively. Default `1.0`.
|
||
/// - levelBias: Offset added to all output levels after scaling. Default `0.0`.
|
||
/// - timeScale: Multiplies each segment's duration before sample-count conversion.
|
||
/// Default `1.0`. Read once per block; applied at the next segment entry. Negative
|
||
/// values clamp to `0`.
|
||
/// - gate: Holds at `releaseNode` / loops at `loopNode` while `> 0`. Default `1.0`.
|
||
/// - doneAction: Action taken when the envelope completes. Default `.nothing`.
|
||
public final class Control: _Base, ControlGenerator, DoneActionWatchable {
|
||
|
||
public var previousOutputValue: Double = 0.0
|
||
private var _rampTarget: Double = 0.0
|
||
|
||
public override var doneAction: DoneAction { super.doneAction }
|
||
public override var needsFree: Bool { super.needsFree }
|
||
|
||
|
||
/// - Parameters:
|
||
/// - envelope: The `Envelope` descriptor that defines segments, levels, and curves.
|
||
/// - levelScale: Scales all output levels multiplicatively. Default `1.0`.
|
||
/// - levelBias: Offset added to all output levels after scaling. Default `0.0`.
|
||
/// - timeScale: Multiplies each segment's duration before sample-count conversion.
|
||
/// Default `1.0`. Read once per block; applied at the next segment entry. Negative
|
||
/// values clamp to `0`.
|
||
/// - gate: Holds at `releaseNode` / loops at `loopNode` while `> 0`. Default `1.0`.
|
||
/// - doneAction: Action taken when the envelope completes. Default `.nothing`.
|
||
public override init(
|
||
envelope: Envelope,
|
||
levelScale: any ValidGeneratorInput = 1.0 as Double,
|
||
levelBias: any ValidGeneratorInput = 0.0 as Double,
|
||
timeScale: any ValidGeneratorInput = 1.0 as Double,
|
||
gate: any ValidGeneratorInput = 1.0 as Double,
|
||
doneAction: DoneAction = .nothing
|
||
) {
|
||
super.init(
|
||
envelope: envelope,
|
||
levelScale: levelScale,
|
||
levelBias: levelBias,
|
||
timeScale: timeScale,
|
||
gate: gate,
|
||
doneAction: doneAction
|
||
)
|
||
_setupSubBlockBuffer()
|
||
_registerAutoFreeIfNeeded(doneAction)
|
||
}
|
||
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
// Drain at most one packet per audio block. In sub-block mode _computeSamples is
|
||
// called N times per block; the serial gate ensures only the first call dequeues,
|
||
// preventing mid-block packet swaps that would corrupt the assembled ramp.
|
||
let blockSerial: UInt64 = graph.engine.segmentSerial
|
||
if _swapSerial != blockSerial { _swapSerial = blockSerial; _checkEnvelopeSwap() }
|
||
|
||
let sampleRate: Double = graph.engine.sampleRate
|
||
let scale: Double = levelScaleInput.floatValue(graph: graph)
|
||
let bias: Double = levelBiasInput.floatValue(graph: graph)
|
||
let timeScale: Double = max(timeScaleInput.floatValue(graph: graph), 0.0)
|
||
let finalLevel: Double = _packet.level(at: _packet.segmentCount) * scale + bias
|
||
|
||
let gateVal: Double
|
||
if _packet.loopNode != -1 || _packet.releaseNode != -1 {
|
||
if !_released {
|
||
let rawGate: Double = gateInput.floatValue(graph: graph)
|
||
if rawGate <= 0 { _released = true }
|
||
gateVal = _released ? 0.0 : rawGate
|
||
} else {
|
||
gateVal = 0.0
|
||
}
|
||
} else {
|
||
gateVal = 1.0
|
||
}
|
||
|
||
if _heldAtRelease {
|
||
if gateVal <= 0 {
|
||
_heldAtRelease = false
|
||
let rn: Int = _packet.releaseNode
|
||
if rn != -1 {
|
||
currentSegment = rn + 1
|
||
}
|
||
samplePos = 0
|
||
_segCachedIndex = -1
|
||
} else {
|
||
let heldOutput: Double = _heldRawLevel * scale + bias
|
||
fillScalarRampedResult(
|
||
into: &_result,
|
||
previousOutputValue: &_rampTarget,
|
||
target: heldOutput,
|
||
count: count
|
||
)
|
||
previousOutputValue = heldOutput
|
||
return _result
|
||
}
|
||
}
|
||
|
||
let target: Double
|
||
if isDone || _packet.segmentCount == 0 {
|
||
target = finalLevel
|
||
} else {
|
||
var lastSample: Double = _rampTarget
|
||
for _ in 0..<count {
|
||
if _heldAtRelease { break }
|
||
if currentSegment >= _packet.segmentCount {
|
||
handleDone()
|
||
if isDone { break }
|
||
continue
|
||
}
|
||
if let v: Double = computeCurrentSample(sampleRate: sampleRate, scale: scale, bias: bias, timeScale: timeScale, gate: gateVal) {
|
||
lastSample = v
|
||
}
|
||
}
|
||
if _heldAtRelease {
|
||
target = _heldRawLevel * scale + bias
|
||
} else {
|
||
target = isDone ? finalLevel : lastSample
|
||
}
|
||
}
|
||
|
||
fillScalarRampedResult(
|
||
into: &_result,
|
||
previousOutputValue: &_rampTarget,
|
||
target: target,
|
||
count: count
|
||
)
|
||
previousOutputValue = target
|
||
return _result
|
||
}
|
||
}
|
||
}
|
||
|
||
extension EnvelopeGen: GeneratorEnum {
|
||
public typealias AudioType = EnvelopeGen.Audio
|
||
public typealias ControlType = EnvelopeGen.Control
|
||
}
|