204 lines
7.1 KiB
Swift
204 lines
7.1 KiB
Swift
// Slope.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Accelerate
|
||
|
||
/// File-scope zero-fill block for Slope — fallback when upstream returns no channel.
|
||
private let slopeZeroBlock: [Double] = [Double](
|
||
repeating: 0,
|
||
count: lyrebirdDefaultResultBufferSize
|
||
)
|
||
|
||
/// Per-second rate-of-change estimator. Equivalent to SuperCollider `Slope`.
|
||
///
|
||
/// Computes `out[n] = (input[n] − input[n−1]) × sampleRate` (audio rate) or
|
||
/// `out = (input − prevInput) × controlRate` (control rate). On the very first
|
||
/// sample/block, the output is `0.0` and `prevInput` is initialised to the first input
|
||
/// value — this prevents the startup spike that would occur if `prevInput` were `0`.
|
||
///
|
||
/// ```swift
|
||
/// let rate = Slope.Audio(input: envelope) // audio-rate differentiation
|
||
/// let rate = Slope.Control(input: $cv) // block-rate differentiation
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to differentiate.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public enum Slope {
|
||
|
||
// MARK: - Shared base
|
||
|
||
/// Shared stored properties for `Slope.Audio` and `Slope.Control`.
|
||
public class _Base: GeneratorBase {
|
||
let _input: any ValidGeneratorInput
|
||
let _inputIsGenerator: Bool
|
||
let _mulAdd: MulAddSpec
|
||
|
||
/// Previous sample value. Initialised on the first call (lazy init).
|
||
var _prevSample: Double = 0.0
|
||
/// `false` until the first sample/block is processed; avoids the startup spike.
|
||
var _initialized: Bool = false
|
||
|
||
init(
|
||
input: any ValidGeneratorInput,
|
||
mul: any ValidGeneratorInput,
|
||
add: any ValidGeneratorInput
|
||
) {
|
||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||
_input = resolvedInput
|
||
_inputIsGenerator = resolvedInput is any Generator
|
||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||
super.init()
|
||
}
|
||
}
|
||
|
||
// MARK: - Audio rate
|
||
|
||
/// Audio-rate per-second rate-of-change estimator.
|
||
///
|
||
/// On the first sample, the output is `0.0` and `prevSample` is set to that sample's
|
||
/// value. From the second sample onward, `out[n] = (x[n] − x[n−1]) × sampleRate`.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to differentiate.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public final class Audio: _Base, AudioGenerator {
|
||
|
||
/// - Parameters:
|
||
/// - input: Signal to differentiate.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public override init(
|
||
input: any ValidGeneratorInput,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(input: input, mul: mul, add: add)
|
||
}
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
let inputSamples: [Double] = _input.calculatedSamples(
|
||
graph: graph, count: count).first ?? slopeZeroBlock
|
||
let sr: Double = graph.engine.sampleRate
|
||
|
||
var prev: Double = _prevSample
|
||
var initialized: Bool = _initialized
|
||
|
||
for i: Int in 0..<count {
|
||
let x: Double = inputSamples[i]
|
||
if !initialized {
|
||
prev = x
|
||
initialized = true
|
||
_result[0][i] = 0.0
|
||
} else {
|
||
_result[0][i] = (x - prev) * sr
|
||
prev = x
|
||
}
|
||
}
|
||
|
||
_prevSample = prev
|
||
_initialized = initialized
|
||
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control rate
|
||
|
||
/// Control-rate per-second rate-of-change estimator.
|
||
///
|
||
/// Advances one differentiation step per audio block using the control rate
|
||
/// (`sampleRate / blockSize`). On the first block, the output is `0.0` and
|
||
/// `prevInput` is set to the block's input value. Subsequent blocks compute
|
||
/// `slope = (x − prevInput) × controlRate`.
|
||
///
|
||
/// Bypasses the sub-block loop — state must advance exactly once per audio block.
|
||
///
|
||
/// The output block is flat (constant). For smoothly interpolated output, use
|
||
/// `Slope.Audio`.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to differentiate.
|
||
/// - 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 differentiate.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public override init(
|
||
input: any ValidGeneratorInput,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(input: input, mul: mul, add: add)
|
||
_setupSubBlockBuffer()
|
||
}
|
||
|
||
/// Bypass sub-block loop: slope state must advance exactly once per audio block.
|
||
public func calculatedSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||
}
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize)
|
||
// Sample the input at block end (captures ParameterNode ramp endpoints),
|
||
// matching the block-constant-input convention of other control-rate generators.
|
||
let x: Double = lastGeneratorSampleOrFloat(
|
||
_input, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||
|
||
let slope: Double
|
||
if !_initialized {
|
||
_prevSample = x
|
||
_initialized = true
|
||
slope = 0.0
|
||
} else {
|
||
slope = (x - _prevSample) * controlRate
|
||
_prevSample = x
|
||
}
|
||
|
||
var fillValue: Double = slope
|
||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||
}
|
||
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
|
||
guard count > 0 else { return _result }
|
||
previousOutputValue = _result[0][count - 1]
|
||
return _result
|
||
}
|
||
|
||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||
}
|
||
}
|
||
|
||
// MARK: - GeneratorEnum
|
||
|
||
extension Slope: GeneratorEnum {
|
||
public typealias AudioType = Slope.Audio
|
||
public typealias ControlType = Slope.Control
|
||
}
|