355 lines
15 KiB
Swift
355 lines
15 KiB
Swift
// MulAdd.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Accelerate
|
||
|
||
// MARK: - Block-constant generator read helper
|
||
|
||
/// Reads the last sample of a generator's block output, or returns the scalar
|
||
/// `floatValue` when the input is not a Generator. RT-safe.
|
||
///
|
||
/// Use for block-constant parameters that must still capture `ParameterNode` ramps:
|
||
/// the last-sample read picks up the ramp endpoint while keeping coefficient math
|
||
/// at block-rate.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
|
||
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
|
||
/// - graph: The current synthesis graph.
|
||
/// - count: Number of samples in the current block.
|
||
/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty;
|
||
/// `input.floatValue(graph:)` otherwise.
|
||
@_spi(LyrebirdExtensions)
|
||
@inline(__always)
|
||
public func lastGeneratorSampleOrFloat(
|
||
_ input: any ValidGeneratorInput,
|
||
isGenerator: Bool,
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> Double {
|
||
guard isGenerator else { return input.floatValue(graph: graph) }
|
||
guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first,
|
||
count > 0 else {
|
||
return input.floatValue(graph: graph)
|
||
}
|
||
return buf[count - 1]
|
||
}
|
||
|
||
// MARK: - Scalar extraction
|
||
|
||
/// Returns the constant value for compile-time-known scalar inputs, nil for generators/strings.
|
||
/// Used at init time to detect the identity case (mul==1.0, add==0.0) without a graph.
|
||
@_spi(LyrebirdExtensions)
|
||
public func extractScalar(_ input: any ValidGeneratorInput) -> Double? {
|
||
if let d: Double = input as? Double { return d }
|
||
if let i: Int = input as? Int { return Double(i) }
|
||
if let c: ConstantGeneratorInput = input as? ConstantGeneratorInput { return c.value }
|
||
return nil
|
||
}
|
||
|
||
// MARK: - MulAddSpec
|
||
|
||
/// Stores mul/add inputs with precomputed identity flag for zero-cost fast path.
|
||
///
|
||
/// Add as a stored property in every signal-producing generator:
|
||
/// ```swift
|
||
/// private let _mulAdd: MulAddSpec
|
||
/// ```
|
||
/// Apply at the end of `_computeSamples` (before the final `return _result`):
|
||
/// ```swift
|
||
/// _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
/// ```
|
||
/// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site
|
||
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` does not call
|
||
/// through this struct — it computes its scalar `target = input * mulFloat + addFloat`
|
||
/// before the ramp, documented in `docs/protocols/writing-generators.md` §13.
|
||
@_spi(LyrebirdExtensions)
|
||
public struct MulAddSpec {
|
||
public let mulInput: any ValidGeneratorInput
|
||
public let addInput: any ValidGeneratorInput
|
||
public let mulIsGenerator: Bool
|
||
public let addIsGenerator: Bool
|
||
/// True iff scalar mul==1.0 AND scalar add==0.0 — one Bool check per block, zero further work.
|
||
public let isIdentity: Bool
|
||
|
||
public init(
|
||
mul: any ValidGeneratorInput,
|
||
add: any ValidGeneratorInput
|
||
) {
|
||
// Resolve at this helper boundary so every Generator constructing a
|
||
// `MulAddSpec` automatically supports `GeneratorInputProvider` for
|
||
// mul/add without touching the Generator's own init. `_resolvedInput()`
|
||
// returns `self` for non-provider inputs; pure scalars and Generators
|
||
// pass through unchanged. Provider returns a fresh `make()` result.
|
||
let resolvedMul: any ValidGeneratorInput = mul._resolvedInput()
|
||
let resolvedAdd: any ValidGeneratorInput = add._resolvedInput()
|
||
mulInput = resolvedMul
|
||
addInput = resolvedAdd
|
||
mulIsGenerator = resolvedMul is any Generator
|
||
addIsGenerator = resolvedAdd is any Generator
|
||
let mulId: Bool = !mulIsGenerator && (extractScalar(resolvedMul) == 1.0)
|
||
let addId: Bool = !addIsGenerator && (extractScalar(resolvedAdd) == 0.0)
|
||
isIdentity = mulId && addId
|
||
}
|
||
|
||
/// Pre-built identity spec (`mul == 1.0`, `add == 0.0`). Use for generators that
|
||
/// do not expose `mul:` / `add:` parameters — avoids reconstructing the spec per
|
||
/// block. `MulAddSpec` is a value type so this is allocation-free.
|
||
/// `nonisolated(unsafe)` because `MulAddSpec` cannot be `Sendable` (its `any
|
||
/// ValidGeneratorInput` fields are existentials), but the value is constructed once
|
||
/// from `Double` literals (immutable, RT-safe to share across threads).
|
||
nonisolated(unsafe) public static let identity: MulAddSpec = MulAddSpec(mul: 1.0, add: 0.0)
|
||
|
||
/// Applies mul/add if non-identity; no-op otherwise.
|
||
///
|
||
/// Replaces the boilerplate `if !isIdentity { apply(...) }` guard at every call site.
|
||
@inline(__always)
|
||
public func applyIfNeeded(
|
||
to channels: inout [[Double]],
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) {
|
||
if !isIdentity { apply(to: &channels, graph: graph, count: count) }
|
||
}
|
||
|
||
/// Applies `(x × mul) + add` via vDSP to every channel in `channels`.
|
||
///
|
||
/// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or
|
||
/// `add` is a multi-row generator:
|
||
/// - **1 row → broadcasts to all output channels** (the historical scalar-gain
|
||
/// case; a mono `ParameterNode`, `Lag`, or any single-channel generator works
|
||
/// unchanged).
|
||
/// - **N rows where N == `channels.count` → element-wise** per-channel modulation.
|
||
/// - **M rows where M > 1 and M ≠ `channels.count` → `precondition` trap** at
|
||
/// the call site (this is the same shape-mismatch policy `BinaryOpGenerator`
|
||
/// uses; the trap fires on the RT thread but only when an explicitly mismatched
|
||
/// graph was assembled at build time, so this is a programmer error not an
|
||
/// RT-runtime hazard).
|
||
public func apply(
|
||
to channels: inout [[Double]],
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) {
|
||
let outChannels: Int = channels.count
|
||
|
||
// Pure-scalar fast path — most common case. No generator pull, no
|
||
// Optional<[Double]> juggling, no per-channel broadcast check.
|
||
if !mulIsGenerator && !addIsGenerator {
|
||
let mulScalar: Double = mulInput.floatValue(graph: graph)
|
||
let addScalar: Double = addInput.floatValue(graph: graph)
|
||
for i: Int in 0..<outChannels {
|
||
applyScalarMulAddToChannel(
|
||
&channels[i],
|
||
mulScalar: mulScalar,
|
||
addScalar: addScalar,
|
||
count: count
|
||
)
|
||
}
|
||
return
|
||
}
|
||
|
||
// General path — at least one of mul / add pulls a generator block.
|
||
let mulRows: [[Double]]? = mulIsGenerator
|
||
? mulInput.calculatedSamples(graph: graph, count: count)
|
||
: nil
|
||
let addRows: [[Double]]? = addIsGenerator
|
||
? addInput.calculatedSamples(graph: graph, count: count)
|
||
: nil
|
||
let mulScalar: Double = mulIsGenerator ? 1.0 : mulInput.floatValue(graph: graph)
|
||
let addScalar: Double = addIsGenerator ? 0.0 : addInput.floatValue(graph: graph)
|
||
|
||
// Mismatch checks — multi-row mul/add must either match output channel count
|
||
// or be 1-row (broadcast). Anything else is a programmer error.
|
||
if let mr: [[Double]] = mulRows {
|
||
precondition(
|
||
mr.count == 1 || mr.count == outChannels,
|
||
"MulAddSpec: mul has \(mr.count) channels but output has \(outChannels). "
|
||
+ "mul/add must be mono (broadcast) or match the output channel count."
|
||
)
|
||
}
|
||
if let ar: [[Double]] = addRows {
|
||
precondition(
|
||
ar.count == 1 || ar.count == outChannels,
|
||
"MulAddSpec: add has \(ar.count) channels but output has \(outChannels). "
|
||
+ "mul/add must be mono (broadcast) or match the output channel count."
|
||
)
|
||
}
|
||
|
||
// Broadcast decision is row-shape-driven and constant across the
|
||
// per-channel loop — hoist it out so the loop body branches once.
|
||
let mulBroadcast: Bool = (mulRows?.count == 1)
|
||
let addBroadcast: Bool = (addRows?.count == 1)
|
||
|
||
for i: Int in 0..<outChannels {
|
||
let mulSamples: [Double]? = mulRows.map { mulBroadcast ? $0[0] : $0[i] }
|
||
let addSamples: [Double]? = addRows.map { addBroadcast ? $0[0] : $0[i] }
|
||
applyMulAddToChannel(
|
||
&channels[i],
|
||
mulSamples: mulSamples, mulScalar: mulScalar,
|
||
addSamples: addSamples, addScalar: addScalar,
|
||
count: count
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Control-rate ramp helper
|
||
|
||
/// Fills `result[0][0..<count]` with a linear ramp from `rampStart` to `target`,
|
||
/// applies mulAdd if non-identity, and returns the new `previousOutputValue`.
|
||
///
|
||
/// Precondition: `count > 0`. The caller is responsible for the early-exit guard.
|
||
///
|
||
/// Usage in a ControlGenerator._computeSamples:
|
||
/// ```swift
|
||
/// let rampStart = _rampTarget
|
||
/// _rampTarget = target
|
||
/// guard count > 0 else { return _result }
|
||
/// previousOutputValue = fillRampedResult(
|
||
/// into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||
/// return _result
|
||
/// ```
|
||
@_spi(LyrebirdExtensions)
|
||
@inline(__always)
|
||
public func fillRampedResult(
|
||
into result: inout [[Double]],
|
||
from rampStart: Double,
|
||
to target: Double,
|
||
mulAdd: MulAddSpec,
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> Double {
|
||
let step: Double = (target - rampStart) / Double(count)
|
||
// Per-sample form `rampStart + step * Double(i+1)` (rather than a
|
||
// recursive accumulator like `vDSP_vrampD`) is required so that the
|
||
// last sample equals `target` algebraically, not within 1 ULP. Tests
|
||
// assert exact equality on both `previousOutputValue` and intermediate
|
||
// samples; an accumulator pattern reintroduces a prior accumulator-pattern regression.
|
||
for i: Int in 0..<count {
|
||
result[0][i] = rampStart + step * Double(i + 1)
|
||
}
|
||
if !mulAdd.isIdentity {
|
||
mulAdd.apply(to: &result, graph: graph, count: count)
|
||
return result[0][count - 1]
|
||
}
|
||
return target
|
||
}
|
||
|
||
/// Block-rate ramp from `previousOutputValue` to `target`, writing into `result[0]`
|
||
/// and updating `previousOutputValue` to `target`. No mulAdd application — the caller
|
||
/// has already folded mul/add into the scalar `target` (the documented exception path
|
||
/// for `Math.Control` generators where the scalar fast path is preferred over the
|
||
/// post-ramp `MulAddSpec.apply` used by `fillRampedResult`).
|
||
///
|
||
/// Usage in a Math-style ControlGenerator._computeSamples:
|
||
/// ```swift
|
||
/// var target = someScalarOp(input.floatValue(graph: graph))
|
||
/// if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||
/// + _mulAdd.addInput.floatValue(graph: graph) }
|
||
/// fillScalarRampedResult(
|
||
/// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||
/// return _result
|
||
/// ```
|
||
@_spi(LyrebirdExtensions)
|
||
@inline(__always)
|
||
public func fillScalarRampedResult(
|
||
into result: inout [[Double]],
|
||
previousOutputValue: inout Double,
|
||
target: Double,
|
||
count: Int
|
||
) {
|
||
guard count > 0 else { return }
|
||
precondition(!result.isEmpty,
|
||
"fillScalarRampedResult: result has no rows")
|
||
precondition(count <= result[0].count,
|
||
"fillScalarRampedResult: count exceeds result buffer")
|
||
let rampStart: Double = previousOutputValue
|
||
previousOutputValue = target
|
||
let step: Double = (target - rampStart) / Double(count)
|
||
// Per-sample form `rampStart + step * Double(i+1)` (rather than a
|
||
// recursive accumulator like `vDSP_vrampD`) is required so that the
|
||
// last sample equals `target` algebraically, not within 1 ULP. Tests
|
||
// assert exact equality on both `previousOutputValue` and intermediate
|
||
// samples; an accumulator pattern reintroduces a prior accumulator-pattern regression.
|
||
for i: Int in 0..<count {
|
||
result[0][i] = rampStart + step * Double(i + 1)
|
||
}
|
||
}
|
||
|
||
// MARK: - Per-channel vDSP dispatch
|
||
|
||
/// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional`
|
||
/// construction, no per-channel broadcast checks. Picks the cheapest vDSP
|
||
/// kernel for the (mulScalar, addScalar) combination:
|
||
/// - both identity → no-op (`MulAddSpec.applyIfNeeded` already filters this
|
||
/// case, but the guard here defends against a callable misuse)
|
||
/// - mul only → `vDSP_vsmulD`
|
||
/// - add only → `vDSP_vsaddD`
|
||
/// - both → `vDSP_vsmsaD` (fused `out = in * mul + add`)
|
||
@inline(__always)
|
||
private func applyScalarMulAddToChannel(
|
||
_ buf: inout [Double],
|
||
mulScalar: Double,
|
||
addScalar: Double,
|
||
count: Int
|
||
) {
|
||
let mulIdentity: Bool = (mulScalar == 1.0)
|
||
let addIdentity: Bool = (addScalar == 0.0)
|
||
if mulIdentity && addIdentity { return }
|
||
|
||
buf.withUnsafeMutableBufferPointer { dst in
|
||
guard let dstBase: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||
let n: vDSP_Length = vDSP_Length(count)
|
||
if !mulIdentity && !addIdentity {
|
||
// dst = dst * mulScalar + addScalar (fused). vDSP_vsmsaD allows
|
||
// src/dst aliasing — passing `dstBase` for both A and D is the
|
||
// documented in-place form.
|
||
var mul: Double = mulScalar
|
||
var add: Double = addScalar
|
||
vDSP_vsmsaD(dstBase, 1, &mul, &add, dstBase, 1, n)
|
||
} else if !mulIdentity {
|
||
var mul: Double = mulScalar
|
||
vDSP_vsmulD(dstBase, 1, &mul, dstBase, 1, n)
|
||
} else {
|
||
var add: Double = addScalar
|
||
vDSP_vsaddD(dstBase, 1, &add, dstBase, 1, n)
|
||
}
|
||
}
|
||
}
|
||
|
||
@inline(__always)
|
||
private func applyMulAddToChannel(
|
||
_ buf: inout [Double],
|
||
mulSamples: [Double]?,
|
||
mulScalar: Double,
|
||
addSamples: [Double]?,
|
||
addScalar: Double,
|
||
count: Int
|
||
) {
|
||
buf.withUnsafeMutableBufferPointer { dst in
|
||
guard let dstBase: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||
let n: vDSP_Length = vDSP_Length(count)
|
||
if let ms: [Double] = mulSamples {
|
||
ms.withUnsafeBufferPointer { src in
|
||
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
|
||
vDSP_vmulD(dstBase, 1, srcBase, 1, dstBase, 1, n)
|
||
}
|
||
} else if mulScalar != 1.0 {
|
||
var s: Double = mulScalar
|
||
vDSP_vsmulD(dstBase, 1, &s, dstBase, 1, n)
|
||
}
|
||
if let as_: [Double] = addSamples {
|
||
as_.withUnsafeBufferPointer { src in
|
||
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
|
||
vDSP_vaddD(dstBase, 1, srcBase, 1, dstBase, 1, n)
|
||
}
|
||
} else if addScalar != 0.0 {
|
||
var s: Double = addScalar
|
||
vDSP_vsaddD(dstBase, 1, &s, dstBase, 1, n)
|
||
}
|
||
}
|
||
}
|