From 3e33f09e0719dad95750de7c2b604ae97a826584 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 1 Aug 2026 19:55:12 -0700 Subject: [PATCH] v1.7.0 release: amp-modeling core (ToneStack, TriodeStage, LSTMAmp) Co-Authored-By: Claude Opus 4.8 --- RELEASES.md | 21 ++ .../Generators/Filters/ToneStack.swift | 292 ++++++++++++++++++ .../Lyrebird/Generators/Neural/LSTMAmp.swift | 159 ++++++++++ .../Generators/Neural/NeuralAmpModel.swift | 135 ++++++++ .../Generators/Waveshaping/TriodeStage.swift | 163 ++++++++++ Sources/Lyrebird/Kinds/ToneStackModel.swift | 48 +++ .../Generated/GeneratedDSLRegistry.swift | 36 +++ .../Generators/Filters/ToneStackTests.swift | 94 ++++++ .../Generators/Neural/LSTMAmpTests.swift | 165 ++++++++++ .../Waveshaping/TriodeStageTests.swift | 113 +++++++ docs/stdlib/generators.md | 51 ++- scripts/doc-snippets-manifest.txt | 92 +++--- 12 files changed, 1322 insertions(+), 47 deletions(-) create mode 100644 Sources/Lyrebird/Generators/Filters/ToneStack.swift create mode 100644 Sources/Lyrebird/Generators/Neural/LSTMAmp.swift create mode 100644 Sources/Lyrebird/Generators/Neural/NeuralAmpModel.swift create mode 100644 Sources/Lyrebird/Generators/Waveshaping/TriodeStage.swift create mode 100644 Sources/Lyrebird/Kinds/ToneStackModel.swift create mode 100644 Tests/LyrebirdTests/Generators/Filters/ToneStackTests.swift create mode 100644 Tests/LyrebirdTests/Generators/Neural/LSTMAmpTests.swift create mode 100644 Tests/LyrebirdTests/Generators/Waveshaping/TriodeStageTests.swift diff --git a/RELEASES.md b/RELEASES.md index 7da3d98..c408ea0 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,27 @@ functionality in a backward-compatible way. --- +## 1.7.0 — Amp-modeling core: tone stack, triode stage, neural amp + +A minor release. Three new, backward-compatible generators — the DSP core for guitar-amp +modeling (consumed by the ShoeGaze 2.0 amp pedals): + +- **`ToneStack`** — passive Fender/Marshall/Vox tone stack (bass/mid/treble). Models the + interactive RC network as a whole (Yeh & Smith closed form → bilinear → 3rd-order IIR), so the + controls load each other exactly as on the real amp. Model-selectable via `ToneStackModel`. +- **`TriodeStage`** — tube-style preamp gain stage: a biased asymmetric `tanh` soft-clip (grid + bias → even-harmonic warmth) evaluated at 2×/4× oversampling, with an output coupling + (DC-block) high-pass. A musically-voiced static waveshaper; a full wave-digital triode remains + future work. +- **`LSTMAmp`** + `NeuralAmpModel` — real-time neural amp-capture inference (single-layer LSTM, + GuitarML Proteus / NeuralPi topology), pure Swift, RT-safe (pre-allocated weights, no + render-thread allocation). `NeuralAmpModel` is a `Codable` weight container with a validating + decoder. An importer for external NAM `.nam` / Proteus JSON files is planned for a later release. + +All three are additive; existing code is unaffected. + +--- + ## 1.6.4 — `LookAheadLimiter` release time decoupled from look-ahead A patch release. One backward-compatible library addition. diff --git a/Sources/Lyrebird/Generators/Filters/ToneStack.swift b/Sources/Lyrebird/Generators/Filters/ToneStack.swift new file mode 100644 index 0000000..9703384 --- /dev/null +++ b/Sources/Lyrebird/Generators/Filters/ToneStack.swift @@ -0,0 +1,292 @@ +// ToneStack.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Darwin + +/// Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender / +/// Marshall / Vox EQ network, not three independent bands. +/// +/// The continuous-time transfer function of the selected ``ToneStackModel``'s RC network is +/// evaluated symbolically from the component values and the three control positions, then +/// discretized with the bilinear transform into a 3rd-order IIR run in Direct Form I. Because +/// the network is modeled as a whole, the controls interact exactly as they do on the real amp +/// (e.g. the Fender mid-scoop, and treble/bass loading each other). +/// +/// Coefficient set follows the Yeh & Smith derivation ("Discretization of the '59 Fender +/// Bassman Tone Stack", DAFx-06); the same closed-form used by the Faust `tonestacks` library. +/// +/// The bass control uses an exponential taper (matching the audio-taper pot of the hardware); +/// mid and treble are linear. All three are clamped to `[0, 1]`. +/// +/// Coefficients are recomputed (off the inner loop) only when a control value changes, so a +/// static setting costs one recompute; an automated control recomputes at block rate. +/// +/// - Parameters: +/// - input: Signal to filter. +/// - bass: Bass control in `[0, 1]`. Defaults to `0.5`. +/// - mid: Mid control in `[0, 1]`. Defaults to `0.5`. +/// - treble: Treble control in `[0, 1]`. Defaults to `0.5`. +/// - model: Tone-stack topology (component values). Fixed at init. Defaults to `.fender`. +/// +/// The sample rate is read from the graph at render time, so it is not an init parameter. +/// +/// Output is mono: only channel 0 of the input is filtered. +public final class ToneStack: GeneratorBase, AudioGenerator { + + // MARK: - Inputs + + private let _input: any ValidGeneratorInput + private let _bassInput: any ValidGeneratorInput + private let _midInput: any ValidGeneratorInput + private let _trebleInput: any ValidGeneratorInput + private let _bassIsGenerator: Bool + private let _midIsGenerator: Bool + private let _trebleIsGenerator: Bool + + // MARK: - Component values (from the model, fixed at init) + + private let r1: Double + private let r2: Double + private let r3: Double + private let r4: Double + private let c1: Double + private let c2: Double + private let c3: Double + + // MARK: - Discretized coefficients (Direct Form I, normalized so A0 == 1) + + private var _b0: Double = 1.0 + private var _b1: Double = 0.0 + private var _b2: Double = 0.0 + private var _b3: Double = 0.0 + private var _a1: Double = 0.0 + private var _a2: Double = 0.0 + private var _a3: Double = 0.0 + + // MARK: - Filter state + + private var _x1: Double = 0.0 + private var _x2: Double = 0.0 + private var _x3: Double = 0.0 + private var _y1: Double = 0.0 + private var _y2: Double = 0.0 + private var _y3: Double = 0.0 + + // MARK: - Coefficient cache + + private var _coeffsValid: Bool = false + private var _lastL: Double = -1.0 + private var _lastM: Double = -1.0 + private var _lastT: Double = -1.0 + private var _lastSampleRate: Double = 0.0 + + // MARK: - Constants + + /// Exponential-taper exponent applied to the bass control (audio-taper pot emulation): + /// `l = exp((bass − 1) · bassTaperExponent)`. + private let bassTaperExponent: Double = 3.4 + /// Binomial coefficient from expanding `(1 ± z⁻¹)³` in the bilinear substitution. + private let bilinearBinomialThree: Double = 3.0 + + // MARK: - Init + + /// - Parameters: + /// - input: Signal to filter. + /// - bass: Bass control in `[0, 1]`. Defaults to `0.5`. + /// - mid: Mid control in `[0, 1]`. Defaults to `0.5`. + /// - treble: Treble control in `[0, 1]`. Defaults to `0.5`. + /// - model: Tone-stack topology. Fixed at init. Defaults to `.fender`. + public init( + input: any ValidGeneratorInput, + bass: any ValidGeneratorInput = 0.5, + mid: any ValidGeneratorInput = 0.5, + treble: any ValidGeneratorInput = 0.5, + model: ToneStackModel = .fender + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedBass: any ValidGeneratorInput = bass._resolvedInput() + let resolvedMid: any ValidGeneratorInput = mid._resolvedInput() + let resolvedTreble: any ValidGeneratorInput = treble._resolvedInput() + _input = resolvedInput + _bassInput = resolvedBass + _midInput = resolvedMid + _trebleInput = resolvedTreble + _bassIsGenerator = resolvedBass is any Generator + _midIsGenerator = resolvedMid is any Generator + _trebleIsGenerator = resolvedTreble is any Generator + let resistors: (r1: Double, r2: Double, r3: Double, r4: Double) = model.resistors + let capacitors: (c1: Double, c2: Double, c3: Double) = model.capacitors + r1 = resistors.r1 + r2 = resistors.r2 + r3 = resistors.r3 + r4 = resistors.r4 + c1 = capacitors.c1 + c2 = capacitors.c2 + c3 = capacitors.c3 + super.init() + } + + // MARK: - Render + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let sampleRate: Double = graph.engine.sampleRate + + let bassRaw: Double = lastGeneratorSampleOrFloat( + _bassInput, isGenerator: _bassIsGenerator, graph: graph, count: count) + let midRaw: Double = lastGeneratorSampleOrFloat( + _midInput, isGenerator: _midIsGenerator, graph: graph, count: count) + let trebleRaw: Double = lastGeneratorSampleOrFloat( + _trebleInput, isGenerator: _trebleIsGenerator, graph: graph, count: count) + + let l: Double = exp((clamp01(bassRaw) - 1.0) * bassTaperExponent) + let m: Double = clamp01(midRaw) + let t: Double = clamp01(trebleRaw) + + if !_coeffsValid || l != _lastL || m != _lastM || t != _lastT || sampleRate != _lastSampleRate { + recomputeCoefficients(l: l, m: m, t: t, sampleRate: sampleRate) + _lastL = l + _lastM = m + _lastT = t + _lastSampleRate = sampleRate + _coeffsValid = true + } + + let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count) + guard let ins: [Double] = inputSamples.first else { + _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in + guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } + for i: Int in 0..) in + guard let srcP: UnsafePointer = src.baseAddress else { return } + _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in + guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } + for i: Int in 0.. Double { + Swift.min(1.0, Swift.max(0.0, value)) + } +} diff --git a/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift b/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift new file mode 100644 index 0000000..f79eb47 --- /dev/null +++ b/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift @@ -0,0 +1,159 @@ +// LSTMAmp.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Darwin + +/// Real-time neural guitar-amp inference: a single-layer LSTM followed by a dense output, +/// run one audio sample at a time. This is the GuitarML "Proteus" / NeuralPi topology — +/// `LSTM(inputSize: 1, hiddenSize: H)` → `Linear(H, 1)`, optionally with an input skip. +/// +/// All weights come from a ``NeuralAmpModel`` and are copied into contiguous storage at `init`; +/// the hidden/cell state and gate scratch are pre-allocated. `_computeSamples` performs only +/// scalar arithmetic over that pre-allocated storage — no allocation, locks, or ARC-heavy work +/// on the render thread — the same discipline the physical models use. +/// +/// Cost is `O(4·H²)` multiply-adds per sample (the recurrent term dominates), so keep `H` +/// modest (Proteus captures are typically `H = 20…40`). +/// +/// Output is mono. The `Double` output is whatever the trained model produces; a well-trained +/// capture stays roughly in `[-1, 1]`, but this generator does not clamp. +/// +/// > Note: An importer for external NAM `.nam` / Proteus JSON model files onto +/// > ``NeuralAmpModel`` is a planned follow-up; construct a `NeuralAmpModel` directly for now. +/// +/// - Parameters: +/// - input: Signal to process (dry guitar DI). +/// - model: The trained ``NeuralAmpModel`` weights. Copied at init. +public final class LSTMAmp: GeneratorBase, AudioGenerator { + + private let _input: any ValidGeneratorInput + + // MARK: - Weights (copied at init) + + private let _hiddenSize: Int + private let _residual: Bool + private let _weightIH: [Double] // 4H + private let _weightHH: [Double] // 4H · H, element (q·H+u)·H + j + private let _bias: [Double] // 4H — biasIH + biasHH summed at init + private let _denseWeight: [Double] // H + private let _denseBias: Double + + // MARK: - Pre-allocated state / scratch + + private var _h: [Double] // hidden state, H + private var _c: [Double] // cell state, H + private var _pre: [Double] // gate pre-activations, 4H + + /// Creates a neural amp from trained weights. + /// + /// - Parameters: + /// - input: Signal to process (dry guitar DI). + /// - model: The trained ``NeuralAmpModel``. Its arrays are copied into contiguous storage. + public init( + input: any ValidGeneratorInput, + model: NeuralAmpModel + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + let hidden: Int = model.hiddenSize + _hiddenSize = hidden + _residual = model.residual + _weightIH = model.weightIH + _weightHH = model.weightHH + _denseWeight = model.denseWeight + _denseBias = model.denseBias + // Fold PyTorch's two bias vectors into one. + var combined: [Double] = [Double](repeating: 0.0, count: model.biasIH.count) + for r: Int in 0.. Double { + 1.0 / (1.0 + exp(-z)) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count) + guard let ins: [Double] = inputSamples.first else { + _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in + guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } + for i: Int in 0..