Files
Lyrebird/Sources/Lyrebird/GeneratorCore/MulAdd.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00

370 lines
16 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// MulAdd.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
// 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` applies mul/add to
/// its scalar `target` before the ramp (not to the output buffer after) via `applyScalar`
/// below — 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 the scalar `(target × mul) + add` to a single block-constant value,
/// short-circuiting to `target` on identity. Reads `mul`/`add` at block rate via
/// `floatValue`.
///
/// For `Math.Control` paths that compute one scalar target per block and hand it to
/// `fillScalarRampedResult` — the documented exception to the buffer-based
/// `apply`/`applyIfNeeded`. Replaces the inline
/// `if !isIdentity { target = target * mulInput.floatValue + addInput.floatValue }`.
@inline(__always)
public func applyScalar(_ target: Double, graph: SynthGraph) -> Double {
guard !isIdentity else { return target }
return target * mulInput.floatValue(graph: graph) + addInput.floatValue(graph: graph)
}
/// 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))
/// target = _mulAdd.applyScalar(target, 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)
}
}
/// Fills `result[0]` with a single block-constant `value`, applies `mulAdd` if
/// non-identity, and sets `previousOutputValue` to the (post-mulAdd) last sample.
/// No-op when `count == 0` (leaving `previousOutputValue` unchanged).
///
/// The held counterpart of `fillScalarRampedResult`: block-rate `ControlGenerator`
/// paths whose output holds one value for the whole block — one-pole/leaky
/// smoothers (`Lag`, `Decay`, `LeakDC`, `Slew`, `Formlet`), block-constant analysis
/// outputs (`ZeroCrossing`, `Slope`, `RunningMin`/`Max`), and trigger/counter latches
/// (`Trig`, `Schmidt`, `PulseCount`, `Stepper`, …). Replaces the repeated
/// `vDSP_vfillD` (or per-sample constant fill) + `applyIfNeeded` + last-sample tail.
@_spi(LyrebirdExtensions)
@inline(__always)
public func fillHeldResult(
into result: inout [[Double]],
value: Double,
previousOutputValue: inout Double,
mulAdd: MulAddSpec,
graph: SynthGraph,
count: Int
) {
guard count > 0 else { return }
precondition(!result.isEmpty,
"fillHeldResult: result has no rows")
precondition(count <= result[0].count,
"fillHeldResult: count exceeds result buffer")
var fillValue: Double = value
result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer<Double>) 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)
previousOutputValue = result[0][count - 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)
}
}
}