227 lines
9.5 KiB
Swift
227 lines
9.5 KiB
Swift
// LFGauss.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Foundation
|
||
|
||
// MARK: - Shared constants
|
||
|
||
/// Exponent scale for the Gaussian `exp(-0.5 · (x / width)²)` — i.e. `−1 / (2σ²)`
|
||
/// folded into the `(x / width)²` form so `width` reads directly as the standard
|
||
/// deviation (in units of the half-period axis `x ∈ [−1, 1]`).
|
||
private let lfGaussExponentScale: Double = -0.5
|
||
|
||
/// Lower clamp on `width` to keep the Gaussian exponent finite (avoids divide-by-zero
|
||
/// as `width → 0`).
|
||
private let lfGaussMinWidth: Double = 1.0e-6
|
||
|
||
/// Lower clamp on `period` (seconds) so the phase increment stays finite.
|
||
private let lfGaussMinPeriod: Double = 1.0e-6
|
||
|
||
/// Evaluate the bell value for a normalised phase in `[0, 1)`.
|
||
///
|
||
/// Maps `phase` onto the symmetric axis `x = 2·phase − 1 ∈ [−1, 1)` so the peak
|
||
/// (`1.0`) lands at the period midpoint (`phase = 0.5`) and the troughs at the
|
||
/// period boundaries. `width` is the standard deviation on that axis.
|
||
@inline(__always)
|
||
private func lfGaussValue(phase: Double, width: Double) -> Double {
|
||
let w: Double = max(width, lfGaussMinWidth)
|
||
let x: Double = 2.0 * phase - 1.0
|
||
let a: Double = x / w
|
||
return exp(lfGaussExponentScale * a * a)
|
||
}
|
||
|
||
// MARK: - LFGauss
|
||
|
||
/// Gaussian bell-shaped oscillator. Raw output in `(0, 1]` (before `mul` / `add`).
|
||
///
|
||
/// Over each `period` the output traces a Gaussian bell: near `0` at the period
|
||
/// boundaries, peaking at `1.0` at the period midpoint. `width` is the standard
|
||
/// deviation as a fraction of the half-period (smaller → narrower spike). A smooth
|
||
/// non-band-limited LFO and a ready-made grain-window shape.
|
||
///
|
||
/// ```
|
||
/// x = 2·phase − 1 (phase ∈ [0, 1) advances 1 / (period · sr) per sample)
|
||
/// out = exp(−0.5 · (x / width)²)
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input.
|
||
/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`.
|
||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public enum LFGauss {
|
||
|
||
// MARK: - _Base
|
||
|
||
/// Shared state for `LFGauss.Audio` and `LFGauss.Control`.
|
||
public class _Base: GeneratorBase {
|
||
let periodInput: any ValidGeneratorInput
|
||
let widthInput: any ValidGeneratorInput
|
||
let periodIsGenerator: Bool
|
||
let widthIsGenerator: Bool
|
||
var _phase: Double
|
||
var _mulAdd: MulAddSpec
|
||
|
||
init(
|
||
period: any ValidGeneratorInput,
|
||
width: any ValidGeneratorInput,
|
||
phase: Double,
|
||
mul: any ValidGeneratorInput,
|
||
add: any ValidGeneratorInput
|
||
) {
|
||
let resolvedPeriod: any ValidGeneratorInput = period._resolvedInput()
|
||
let resolvedWidth: any ValidGeneratorInput = width._resolvedInput()
|
||
self.periodInput = resolvedPeriod
|
||
self.widthInput = resolvedWidth
|
||
self.periodIsGenerator = resolvedPeriod is any Generator
|
||
self.widthIsGenerator = resolvedWidth is any Generator
|
||
var p: Double = phase.truncatingRemainder(dividingBy: 1.0)
|
||
if p < 0 { p += 1.0 }
|
||
self._phase = p
|
||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||
}
|
||
}
|
||
|
||
// MARK: - Audio
|
||
|
||
/// Audio-rate Gaussian oscillator. Evaluates `period` / `width` per sample.
|
||
///
|
||
/// - Parameters:
|
||
/// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input.
|
||
/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`.
|
||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public final class Audio: _Base, AudioGenerator {
|
||
|
||
/// - Parameters:
|
||
/// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input.
|
||
/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`.
|
||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public override init(
|
||
period: any ValidGeneratorInput,
|
||
width: any ValidGeneratorInput = 0.1,
|
||
phase: Double = 0.0,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(period: period, width: width, phase: phase, mul: mul, add: add)
|
||
}
|
||
|
||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||
_checkCount(count)
|
||
guard count > 0 else { return _result }
|
||
|
||
let sampleRate: Double = Double(graph.engine.sampleRate)
|
||
|
||
let periodSamples: [Double]?
|
||
let scalarDt: Double
|
||
if periodIsGenerator {
|
||
periodSamples = periodInput.calculatedSamples(graph: graph, count: count).first
|
||
scalarDt = 0
|
||
} else {
|
||
periodSamples = nil
|
||
scalarDt = 1.0 / (max(periodInput.floatValue(graph: graph), lfGaussMinPeriod) * sampleRate)
|
||
}
|
||
|
||
let (widthSamples, scalarWidth) = resolveGeneratorOrScalar(
|
||
widthInput, isGenerator: widthIsGenerator, graph: graph, count: count)
|
||
|
||
for i: Int in 0..<count {
|
||
let dt: Double
|
||
if let ps: [Double] = periodSamples {
|
||
let period: Double = i < ps.count ? ps[i] : 0
|
||
dt = 1.0 / (max(period, lfGaussMinPeriod) * sampleRate)
|
||
} else {
|
||
dt = scalarDt
|
||
}
|
||
let width: Double = widthSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarWidth
|
||
|
||
_result[0][i] = lfGaussValue(phase: _phase, width: width)
|
||
|
||
_phase += dt
|
||
normalizeOscPhase(&_phase)
|
||
}
|
||
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control
|
||
|
||
/// Control-rate Gaussian oscillator. Advances phase once per audio block.
|
||
///
|
||
/// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly
|
||
/// once per audio block regardless of `controlBlockSize`. The block output ramps from the
|
||
/// previous bell value to the new one.
|
||
///
|
||
/// - Parameters:
|
||
/// - period: Bell period in seconds. Clamped to a small positive minimum.
|
||
/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`.
|
||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`.
|
||
/// - 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
|
||
private var _rampTarget: Double = 0.0
|
||
|
||
/// - Parameters:
|
||
/// - period: Bell period in seconds. Clamped to a small positive minimum.
|
||
/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`.
|
||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Output offset. Defaults to `0.0`.
|
||
public override init(
|
||
period: any ValidGeneratorInput,
|
||
width: any ValidGeneratorInput = 0.1,
|
||
phase: Double = 0.0,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(period: period, width: width, phase: phase, mul: mul, add: add)
|
||
_setupSubBlockBuffer()
|
||
}
|
||
|
||
// Bypass sub-block loop: phase 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)
|
||
guard count > 0 else { return _result }
|
||
|
||
let sampleRate: Double = Double(graph.engine.sampleRate)
|
||
let countFloat: Double = Double(count)
|
||
let period: Double = max(periodInput.floatValue(graph: graph), lfGaussMinPeriod)
|
||
let width: Double = widthInput.floatValue(graph: graph)
|
||
|
||
let dt: Double = 1.0 / (period * sampleRate)
|
||
_phase += dt * countFloat
|
||
normalizeOscPhase(&_phase)
|
||
|
||
let target: Double = lfGaussValue(phase: _phase, width: width)
|
||
let rampStart: Double = _rampTarget
|
||
_rampTarget = target
|
||
previousOutputValue = fillRampedResult(
|
||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||
return _result
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - GeneratorEnum
|
||
|
||
extension LFGauss: GeneratorEnum {
|
||
public typealias AudioType = LFGauss.Audio
|
||
public typealias ControlType = LFGauss.Control
|
||
}
|