Files
Lyrebird/Sources/Lyrebird/Generators/PhysicalModels/ScannedSynthesizer.swift
T

423 lines
20 KiB
Swift

// ScannedSynthesizer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - ScannedSynthesizer constants
/// Maximum number of masses in a `ScannedSynthesizer` network.
///
/// Must be a power of two. Increasing this value raises memory usage at init
/// proportionally (two `Double` arrays of this length).
public let scannedSynthesizerMaxMassCount: Int = 1024
/// Default number of masses used when no `massCount` is supplied.
public let scannedSynthesizerDefaultMassCount: Int = 64
/// Width of the Gaussian initial displacement, expressed as a fraction of `massCount`.
private let scannedSynthesizerGaussianWidthFraction: Double = 0.15
// MARK: - ScannedSynthesizer
/// Scanned synthesis (Mathews/Verplank 2000) — 1D mass-spring network with audio-rate
/// scanning phasor.
///
/// A ring of `massCount` masses is connected by springs with optional viscous damping and
/// a centering (return-to-rest) spring. The network is updated once per audio block using a
/// forward-Euler step of the second-order ODE. A scanning phasor reads mass displacements
/// at audio rate as a continuously evolving wavetable, producing slowly morphing timbres
/// driven by the network's resonant modes.
///
/// ## Discrete update (once per audio block)
///
/// ```
/// accel[i] = stiffness * (x[i-1] - 2*x[i] + x[i+1]) // 1D discrete Laplacian (ring topology)
/// - damping * v[i] // viscous damping
/// + centeringForce * (-x[i]) // return-to-rest spring
/// + externalForce[i] // excitation
/// v[i] += accel[i] * dt
/// x[i] += v[i] * dt
/// ```
///
/// `dt` = `blockSize / sampleRate`.
///
/// ## Audio-rate scan
///
/// A phasor accumulates `freq * massCount / sampleRate` per sample and reads the
/// displacement array `x` with the selected interpolation mode. The result is the output
/// sample.
///
/// ## Example
///
/// ```swift
/// // let scanned = ScannedSynthesizer.Audio(
/// // excitation: Impulse.Audio(freq: 4.0),
/// // freq: 220.0,
/// // massCount: 64,
/// // stiffness: 200.0,
/// // damping: 0.05,
/// // centeringForce: 1.0,
/// // excitationIndex: 0,
/// // initialDisplacement: .gaussian
/// // )
/// ```
///
/// - Parameters:
/// - excitation: Excitation signal sampled once per audio block (last sample of the block
/// via `lastGeneratorSampleOrFloat`). The value is injected as an external force at mass
/// `excitationIndex`. Any rate.
/// - freq: Scanning phasor frequency in Hz. Determines how quickly the phasor traverses
/// the mass ring; analogous to fundamental pitch for harmonic waveforms. Read per sample
/// at audio rate. Defaults to `220.0`.
/// - massCount: Number of masses in the ring. Must be a power of two in `[4,
/// scannedSynthesizerMaxMassCount]`. Structural parameter set at init. Defaults to `64`.
/// - stiffness: Spring stiffness between adjacent masses. Higher values increase resonant
/// frequency of network modes, producing brighter, faster-evolving timbres. Read once per
/// audio block. Defaults to `200.0`.
/// - damping: Viscous damping coefficient. Higher values cause faster amplitude decay.
/// `0.0` = no damping (undamped oscillation). Defaults to `0.05`.
/// - centeringForce: Restoring spring coefficient pulling each mass toward zero.
/// Acts as a global pitch-raising and stability mechanism. `0.0` = none. Defaults to `1.0`.
/// - excitationIndex: Index of the mass that receives external force from `excitation`.
/// Must be in `0 ..< massCount`. Structural parameter set at init. Defaults to `0`.
/// - interpolation: Table interpolation mode for the scanning readout.
/// `.none` = nearest-sample, `.linear` = linear (default), `.cubic` = Catmull-Rom.
/// - initialDisplacement: Preset shape applied to `_positions` at init so the network has
/// energy to begin resonating immediately. Defaults to `.gaussian`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum ScannedSynthesizer {
// MARK: - Audio
/// Audio-rate scanned synthesis generator.
///
/// - Parameters:
/// - excitation: Excitation signal sampled once per audio block (last sample of the block
/// via `lastGeneratorSampleOrFloat`). The value is injected as an external force at mass
/// `excitationIndex`. Any rate.
/// - freq: Scanning phasor frequency in Hz. Determines how quickly the phasor traverses
/// the mass ring; analogous to fundamental pitch for harmonic waveforms. Read per sample
/// at audio rate. Defaults to `220.0`.
/// - massCount: Number of masses in the ring. Must be a power of two in `[4,
/// scannedSynthesizerMaxMassCount]`. Structural parameter set at init. Defaults to `64`.
/// - stiffness: Spring stiffness between adjacent masses. Higher values increase resonant
/// frequency of network modes. Read once per audio block. Defaults to `200.0`.
/// - damping: Viscous damping coefficient. `0.0` = no damping. Defaults to `0.05`.
/// - centeringForce: Restoring spring coefficient pulling each mass toward zero.
/// `0.0` = none. Defaults to `1.0`.
/// - excitationIndex: Index of the mass that receives external force from `excitation`.
/// Must be in `0 ..< massCount`. Structural parameter set at init. Defaults to `0`.
/// - interpolation: Table interpolation mode for the scanning readout. Defaults to `.linear`.
/// - initialDisplacement: Preset shape applied to positions at init. Defaults to `.gaussian`.
/// - sampleRate: Engine sample rate in Hz. Required structural parameter, no default.
/// Used to precompute the per-block simulation timestep `_dtPerBlock`.
/// - blockSize: Engine block size in samples. Required structural parameter, no default.
/// Used to precompute the per-block simulation timestep `_dtPerBlock`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: GeneratorBase, AudioGenerator {
// MARK: Inputs
private let _excitationSource: any ValidGeneratorInput
private let _excitationIsGenerator: Bool
private let _freqSource: any ValidGeneratorInput
private let _freqIsGenerator: Bool
private let _stiffnessSource: any ValidGeneratorInput
private let _stiffnessIsGenerator: Bool
private let _dampingSource: any ValidGeneratorInput
private let _dampingIsGenerator: Bool
private let _centeringForceSource: any ValidGeneratorInput
private let _centeringForceIsGenerator: Bool
// MARK: Structural parameters
private let _massCount: Int
private let _massCountFloat: Double
private let _excitationIndex: Int
private let _interpolation: TableInterpolation
// MARK: Precomputed per-block constant
/// `blockSize / sampleRate` — the simulation time step for each mass-network update.
private let _dtPerBlock: Double
// MARK: DSP state
/// Mass positions (displacements). Indexed `0 ..< _massCount`.
private var _positions: [Double]
/// Mass velocities. Indexed `0 ..< _massCount`.
private var _velocities: [Double]
/// Per-block scratch for accelerations. Pre-allocated to avoid in-place
/// Gauss-Seidel coupling: pass 1 fills this from old positions/velocities,
/// pass 2 applies the v/x updates so every mass sees the same starting state.
private var _accelerations: [Double]
/// Scanning phasor phase in `[0, massCount)`.
private var _phase: Double = 0.0
// MARK: Output
private let _mulAdd: MulAddSpec
// MARK: Init
/// - Parameters:
/// - excitation: Excitation signal sampled once per audio block (last sample of the block
/// via `lastGeneratorSampleOrFloat`). The value is injected as an external force at mass
/// `excitationIndex`. Any rate.
/// - freq: Scanning phasor frequency in Hz. Defaults to `220.0`.
/// - massCount: Number of masses in the ring. Must be a power of two in `[4,
/// scannedSynthesizerMaxMassCount]`. Defaults to `64`.
/// - stiffness: Spring stiffness between adjacent masses. Defaults to `200.0`.
/// - damping: Viscous damping coefficient. `0.0` = no damping. Defaults to `0.05`.
/// - centeringForce: Restoring spring pulling each mass toward zero. `0.0` = none.
/// Defaults to `1.0`.
/// - excitationIndex: Index of the mass that receives external force from `excitation`.
/// Must be in `0 ..< massCount`. Defaults to `0`.
/// - interpolation: Table interpolation mode for scanning readout. Defaults to `.linear`.
/// - initialDisplacement: Preset shape applied to positions at init. Defaults to `.gaussian`.
/// - sampleRate: Engine sample rate in Hz. Required structural parameter, no default.
/// - blockSize: Engine block size in samples. Required structural parameter, no default.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
excitation: any ValidGeneratorInput,
freq: any ValidGeneratorInput = 220.0,
massCount: Int = scannedSynthesizerDefaultMassCount,
stiffness: any ValidGeneratorInput = 200.0,
damping: any ValidGeneratorInput = 0.05,
centeringForce: any ValidGeneratorInput = 1.0,
excitationIndex: Int = 0,
interpolation: TableInterpolation = .linear,
initialDisplacement: ScannedSynthesizerShape = .gaussian,
sampleRate: Double,
blockSize: Int,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let minMassCount: Int = 4
precondition(
massCount >= minMassCount,
"ScannedSynthesizer: massCount \(massCount) must be >= \(minMassCount)."
)
precondition(
massCount <= scannedSynthesizerMaxMassCount,
"ScannedSynthesizer: massCount \(massCount) exceeds maximum "
+ "\(scannedSynthesizerMaxMassCount)."
)
precondition(
massCount.nonzeroBitCount == 1,
"ScannedSynthesizer: massCount \(massCount) must be a power of two."
)
precondition(
excitationIndex >= 0 && excitationIndex < massCount,
"ScannedSynthesizer: excitationIndex \(excitationIndex) is out of range "
+ "0 ..< \(massCount)."
)
let resolvedExcitation: any ValidGeneratorInput = excitation._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
let resolvedStiffness: any ValidGeneratorInput = stiffness._resolvedInput()
let resolvedDamping: any ValidGeneratorInput = damping._resolvedInput()
let resolvedCenteringForce: any ValidGeneratorInput = centeringForce._resolvedInput()
_excitationSource = resolvedExcitation
_excitationIsGenerator = resolvedExcitation is any Generator
_freqSource = resolvedFreq
_freqIsGenerator = resolvedFreq is any Generator
_stiffnessSource = resolvedStiffness
_stiffnessIsGenerator = resolvedStiffness is any Generator
_dampingSource = resolvedDamping
_dampingIsGenerator = resolvedDamping is any Generator
_centeringForceSource = resolvedCenteringForce
_centeringForceIsGenerator = resolvedCenteringForce is any Generator
_massCount = massCount
_massCountFloat = Double(massCount)
_excitationIndex = excitationIndex
_interpolation = interpolation
_dtPerBlock = Double(blockSize) / sampleRate
_positions = [Double](repeating: 0, count: massCount)
_velocities = [Double](repeating: 0, count: massCount)
_accelerations = [Double](repeating: 0, count: massCount)
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init()
// Apply initial displacement after super.init() so stored properties are set.
_applyInitialDisplacement(initialDisplacement)
}
// MARK: AudioGenerator
// MARK: _computeSamples
//
// The `Generator` protocol extension's segment-serial caching gateway around
// `_computeSamples` is sufficient for AudioGenerators with per-block state
// (per `writing-generators.md` §5: never override `calculatedSamples`). Same
// pattern as `KarplusStrong.Audio` / `BowedString.Audio`.
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// --- Block-rate parameter reads (once per audio block) ---
// Excitation: last sample of the block (or scalar).
let excitationForce: Double = lastGeneratorSampleOrFloat(
_excitationSource,
isGenerator: _excitationIsGenerator,
graph: graph,
count: count
)
let stiffness: Double = lastGeneratorSampleOrFloat(
_stiffnessSource,
isGenerator: _stiffnessIsGenerator,
graph: graph,
count: count
)
let damping: Double = lastGeneratorSampleOrFloat(
_dampingSource,
isGenerator: _dampingIsGenerator,
graph: graph,
count: count
)
let centeringForce: Double = lastGeneratorSampleOrFloat(
_centeringForceSource,
isGenerator: _centeringForceIsGenerator,
graph: graph,
count: count
)
// --- Mass-network update (once per audio block) ---
//
// Forward-Euler step of the second-order ODE:
// accel[i] = stiffness * (x[i-1] - 2*x[i] + x[i+1]) (1D discrete Laplacian)
// - damping * v[i] (viscous damping)
// - centeringForce * x[i] (return-to-rest spring)
// + externalForce[i] (excitation)
// v[i] += accel[i] * dt
// x[i] += v[i] * dt
//
// dt = blockSize / sampleRate (precomputed as _dtPerBlock).
// Indices are wrapped modulo massCount for ring topology.
let dt: Double = _dtPerBlock
let massCountLocal: Int = _massCount
let exIdx: Int = _excitationIndex
// Pass 1: compute all accelerations from the *old* positions and
// velocities. Done in a separate pass so every mass sees the same
// starting state (Jacobi-style explicit Euler), matching the
// documented forward-Euler scheme. In-place coupling would yield
// an asymmetric Gauss-Seidel update that breaks ring symmetry.
for i: Int in 0..<massCountLocal {
let iPrev: Int = (i - 1 + massCountLocal) % massCountLocal
let iNext: Int = (i + 1) % massCountLocal
let laplacian: Double = _positions[iPrev] - 2 * _positions[i] + _positions[iNext]
let extForce: Double = i == exIdx ? excitationForce : 0.0
let accel: Double = stiffness * laplacian
- damping * _velocities[i]
- centeringForce * _positions[i]
+ extForce
_accelerations[i] = accel
}
// Pass 2: integrate. v += a·dt, x += v·dt; flush denormals on every
// feedback-loop state write.
for i: Int in 0..<massCountLocal {
_velocities[i] = denormalsToZero(_velocities[i] + _accelerations[i] * dt)
_positions[i] = denormalsToZero(_positions[i] + _velocities[i] * dt)
}
// --- Audio-rate scan (per sample) ---
//
// The phasor advances freq * massCount / sampleRate per sample, traversing
// the mass ring. Position array is read as a wavetable with the chosen
// interpolation mode.
let sampleRate: Double = Double(graph.engine.sampleRate)
// Read freq input.
let freqSamples: [Double]?
let scalarPhaseInc: Double
if _freqIsGenerator {
freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first
scalarPhaseInc = 0
} else {
let f: Double = _freqSource.floatValue(graph: graph)
freqSamples = nil
scalarPhaseInc = f * _massCountFloat / sampleRate
}
let tableSize: Int = massCountLocal
let tableSizeFloat: Double = _massCountFloat
let interp: TableInterpolation = _interpolation
for i: Int in 0..<count {
let phaseInc: Double
if let fs: [Double] = freqSamples {
let f: Double = i < fs.count ? fs[i] : 0.0
phaseInc = f * tableSizeFloat / sampleRate
} else {
phaseInc = scalarPhaseInc
}
_result[0][i] = oscillatorTableRead(
_positions,
tableSize: tableSize,
phase: _phase,
interpolation: interp
)
_phase += phaseInc
if _phase >= tableSizeFloat { _phase -= tableSizeFloat }
if _phase < 0 { _phase += tableSizeFloat }
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: Private helpers
/// Applies the selected initial displacement shape to `_positions`.
/// Called once from `init` after `super.init()`. Not RT-safe (uses `sin`/`exp`)
/// but is only ever called at construction time.
private func _applyInitialDisplacement(_ shape: ScannedSynthesizerShape) {
let n: Int = _massCount
let nFloat: Double = _massCountFloat
switch shape {
case .zeros:
// Already zero from init.
break
case .sine:
for i: Int in 0..<n {
_positions[i] = sin(lyrebirdTwoPi * Double(i) / nFloat)
}
case .impulse:
_positions[_excitationIndex] = 1.0
case .gaussian:
// Bell curve centred at n/2 with sigma = gaussianWidthFraction * n.
let centre: Double = nFloat / 2.0
let sigma: Double = scannedSynthesizerGaussianWidthFraction * nFloat
let twoSigmaSq: Double = 2.0 * sigma * sigma
for i: Int in 0..<n {
let dx: Double = Double(i) - centre
_positions[i] = exp(-(dx * dx) / twoSigmaSq)
}
}
}
}
}
// MARK: - GeneratorEnum
// GeneratorEnum conformance is intentionally omitted for ScannedSynthesizer.
// GeneratorEnum requires distinct AudioType and ControlType conforming to ControlGenerator;
// ScannedSynthesizer is Audio-only. The mass-network update IS the per-block computation;
// a separate Control variant would be redundant (the network already runs at block rate).