Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ea0aa84ca7 | |||
| 3e33f09e07 | |||
| d6875da2cb | |||
| 5e6534a615 |
@@ -144,6 +144,17 @@
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
C8D00000000000000000013 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
@@ -162,17 +173,6 @@
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
C8D00000000000000000013 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C8D00000000000000000011 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
@@ -189,14 +189,14 @@
|
||||
C8D00000000000000000016 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -206,12 +206,14 @@
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
@@ -229,14 +231,14 @@
|
||||
C8D00000000000000000017 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
@@ -245,12 +247,14 @@
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
|
||||
@@ -13,9 +13,9 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.6.1</string>
|
||||
<string>1.6.3</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<string>3</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
|
||||
+86
@@ -7,6 +7,92 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.1 — Neural-amp model importer
|
||||
|
||||
A patch release. One backward-compatible addition:
|
||||
|
||||
- **`ProteusModelImporter`** — loads a GuitarML **Proteus / NeuralPi** model JSON (single-layer
|
||||
LSTM capture) into a `NeuralAmpModel` for `LSTMAmp`. The state-dict tensors map straight onto
|
||||
`NeuralAmpModel`'s layout (PyTorch gate order; `skip` → residual); unsupported topologies and
|
||||
inconsistent tensor shapes throw. Model files are user-supplied — none are bundled (GuitarML
|
||||
models are GPL-3.0). A binary NAM `.nam` importer remains future work.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
`LookAheadLimiter` gains a `releaseTime` parameter, independent of
|
||||
`lookAheadTime`:
|
||||
|
||||
```swift
|
||||
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||
```
|
||||
|
||||
Previously the gain-release one-pole coefficient was derived from
|
||||
`lookAheadTime` (default 5 ms), so the release was fast enough to modulate the
|
||||
gain within a single cycle of a low-frequency signal — audible as distortion on
|
||||
sustained bass when the limiter was driven hard. `releaseTime` (default
|
||||
`0.050`) is now a separate control, read per block from a `ValidGeneratorInput`
|
||||
so it can be driven by a live parameter / knob. The look-ahead window size and
|
||||
the no-overshoot ceiling guarantee are unchanged.
|
||||
|
||||
The new parameter has a default, so existing call sites are source-compatible.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.3 — Notarization-ready `macos-ui-xcode` template
|
||||
|
||||
A patch release. Project-scaffolding fixes; no library API changes.
|
||||
|
||||
The `macos-ui-xcode` template (`lyrebird new MyApp --template macos-ui-xcode`)
|
||||
now scaffolds a distributable, notarization-ready macOS performance app out of
|
||||
the box:
|
||||
|
||||
- **Entitlements shipped and wired** — `<name>.entitlements` grants
|
||||
`com.apple.security.device.audio-input` (wired via `CODE_SIGN_ENTITLEMENTS`
|
||||
in both build configs), plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||
Under the Hardened Runtime (already enabled) the OS hard-kills the process the
|
||||
moment the AUHAL input bus opens without these. They are harmless for
|
||||
output-only synths — no permission prompt fires until input is actually used.
|
||||
The app is deliberately **unsandboxed**: a live-performance app needs
|
||||
unrestricted audio-device / file / MIDI / OSC access the App Sandbox gates.
|
||||
|
||||
- **Compiles under Swift 6** — fixed a latent actor-isolation error that kept
|
||||
the generated project from building: `NoteController` (calls the engine's
|
||||
`@MainActor add(_:)`) and `AppDelegate` (constructs the main-actor controller
|
||||
and synth) are now `@MainActor`. Xcode app templates are excluded from the
|
||||
`swift build` CI matrix, so this had never been compile-checked; it is now
|
||||
verified end-to-end with `xcodebuild`.
|
||||
|
||||
A normal Lyrebird app needs no module-bundling: Lyrebird is statically linked
|
||||
from SPM source. (The swiftmodule / `LyrebirdC` bundling in `LyrebirdScratch`,
|
||||
added in 1.6.2, is unique to its runtime `swiftc` scratchpad.)
|
||||
|
||||
---
|
||||
|
||||
## 1.6.2 — Live Scratch: distributable / notarized app
|
||||
|
||||
A patch release. Live Scratch packaging only; no library API changes.
|
||||
|
||||
@@ -11,7 +11,11 @@ import Darwin
|
||||
/// the output never exceeds ±`maxAmplitude` regardless of transients.
|
||||
///
|
||||
/// The gain attack is instantaneous within the look-ahead window. Gain release uses
|
||||
/// a one-pole smoother with a time constant equal to `lookAheadTime`.
|
||||
/// a one-pole smoother whose time constant is `releaseTime`, decoupled from
|
||||
/// `lookAheadTime`. A too-fast release modulates the gain within a single cycle of a
|
||||
/// low-frequency signal, which distorts sustained bass; keeping release slow (tens of
|
||||
/// ms) while the look-ahead window stays short (a few ms) catches transients without
|
||||
/// that distortion.
|
||||
///
|
||||
/// ## Latency
|
||||
/// Output is delayed by exactly `lookAheadSamples = Int(lookAheadTime × sampleRate)`.
|
||||
@@ -42,18 +46,22 @@ import Darwin
|
||||
/// - maxAmplitude: Peak ceiling (absolute value). Output `|y|` never exceeds
|
||||
/// this value once the look-ahead window has filled. Default `1.0`.
|
||||
/// - lookAheadTime: Look-ahead and output delay in seconds. Fixed at init —
|
||||
/// determines ring buffer size and release time constant.
|
||||
/// Range `[0, ∞)`; values above ~50 ms waste memory.
|
||||
/// Default `0.005` (5 ms).
|
||||
/// determines ring buffer size. Range `[0, ∞)`; values above
|
||||
/// ~50 ms waste memory. Default `0.005` (5 ms).
|
||||
/// - releaseTime: Gain-release time constant in seconds. Clamped to ≥ 0. Read per block,
|
||||
/// so it may be driven by a live parameter. Independent of `lookAheadTime`.
|
||||
/// Keep it well above the period of the lowest frequency you expect
|
||||
/// (tens of ms) to avoid low-frequency distortion. Default `0.050`.
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer sizes and release coefficient
|
||||
/// are computed at init from this value and cannot be updated at runtime.
|
||||
/// Required — no default. Ring buffer sizes are computed at init from
|
||||
/// this value and cannot be updated at runtime.
|
||||
public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _maxAmpInput: any ValidGeneratorInput
|
||||
private let _releaseTimeInput: any ValidGeneratorInput
|
||||
private let _lookAheadSamples: Int
|
||||
|
||||
// MARK: - Pre-allocated delay ring
|
||||
@@ -80,8 +88,6 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
|
||||
private var _writePos: Int = 0
|
||||
private var _gain: Double = 1.0
|
||||
private let _releaseCoeff: Double
|
||||
private let _attackComp: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
@@ -90,30 +96,30 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
/// - maxAmplitude: Peak ceiling (absolute value). Output `|y|` never exceeds
|
||||
/// this value once the look-ahead window has filled. Default `1.0`.
|
||||
/// - lookAheadTime: Look-ahead and output delay in seconds. Fixed at init —
|
||||
/// determines ring buffer size and release time constant.
|
||||
/// Range `[0, ∞)`. Default `0.005` (5 ms).
|
||||
/// determines ring buffer size. Range `[0, ∞)`. Default `0.005` (5 ms).
|
||||
/// - releaseTime: Gain-release time constant in seconds. Clamped to ≥ 0. Read per block, so it may be
|
||||
/// driven by a live parameter. Independent of `lookAheadTime`. Default `0.050`.
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer sizes and the release coefficient
|
||||
/// are computed at init from this value and cannot be updated at runtime.
|
||||
/// Required — no default. Ring buffer sizes are computed at init from this
|
||||
/// value and cannot be updated at runtime.
|
||||
public init(
|
||||
in input: any ValidGeneratorInput,
|
||||
maxAmplitude: any ValidGeneratorInput = 1.0,
|
||||
lookAheadTime: Double = 0.005,
|
||||
releaseTime: any ValidGeneratorInput = 0.050,
|
||||
sampleRate: Double
|
||||
) {
|
||||
precondition(lookAheadTime >= 0, "LookAheadLimiter: lookAheadTime must be ≥ 0")
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedMaxAmp: any ValidGeneratorInput = maxAmplitude._resolvedInput()
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedMaxAmp: any ValidGeneratorInput = maxAmplitude._resolvedInput()
|
||||
let resolvedRelease: any ValidGeneratorInput = releaseTime._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_maxAmpInput = resolvedMaxAmp
|
||||
_releaseTimeInput = resolvedRelease
|
||||
_lookAheadSamples = Int(lookAheadTime * sampleRate)
|
||||
let bufferSize: Int = _lookAheadSamples + lyrebirdDefaultResultBufferSize + 1
|
||||
_ringSize = bufferSize
|
||||
_delayRing = [Double](repeating: 0.0, count: bufferSize)
|
||||
_releaseCoeff = lookAheadTime > 0
|
||||
? exp(-1.0 / (sampleRate * lookAheadTime))
|
||||
: 0.0
|
||||
_attackComp = 1.0 - _releaseCoeff
|
||||
// Deque capacity = max-live (_lookAheadSamples + 1) + 1 slot of slack
|
||||
// so push-before-front-pop on a wraparound step does not collide.
|
||||
_dequeCapacity = max(2, _lookAheadSamples + 2)
|
||||
@@ -136,9 +142,14 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
let maxAmp: Double = max(0.0, Double(_maxAmpInput.floatValue(graph: graph)))
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
// Release coefficient recomputed per block from the (possibly live) releaseTime.
|
||||
// Decoupled from lookAheadTime — a slow release avoids modulating the waveform.
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let releaseT: Double = max(0.0, Double(_releaseTimeInput.floatValue(graph: graph)))
|
||||
let releaseCoeff: Double = releaseT > 0 ? exp(-1.0 / (sr * releaseT)) : 0.0
|
||||
let attackComp: Double = 1.0 - releaseCoeff
|
||||
|
||||
let ringSize: Int = _ringSize
|
||||
let releaseCoeff: Double = _releaseCoeff
|
||||
let attackComp: Double = _attackComp
|
||||
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
// Pathological branch: upstream returned a 0-row matrix. Advance ring +
|
||||
|
||||
@@ -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<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
let b0: Double = _b0
|
||||
let b1: Double = _b1
|
||||
let b2: Double = _b2
|
||||
let b3: Double = _b3
|
||||
let a1: Double = _a1
|
||||
let a2: Double = _a2
|
||||
let a3: Double = _a3
|
||||
var x1: Double = _x1
|
||||
var x2: Double = _x2
|
||||
var x3: Double = _x3
|
||||
var y1: Double = _y1
|
||||
var y2: Double = _y2
|
||||
var y3: Double = _y3
|
||||
let inCount: Int = ins.count
|
||||
|
||||
ins.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||||
guard let srcP: UnsafePointer<Double> = src.baseAddress else { return }
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? srcP[i] : 0
|
||||
// Flush the feedback output every sample (as CombFilter / MoogLadder do —
|
||||
// stricter than the once-per-block flush used by the scalar-coefficient
|
||||
// biquads, since this 3rd-order recursion has more room to decay into
|
||||
// subnormal range). NRT and AUv3 render paths never arm hardware
|
||||
// flush-to-zero, so without this a fade-out would compute subnormal all block.
|
||||
let y: Double = denormalsToZero(
|
||||
b0 * x + b1 * x1 + b2 * x2 + b3 * x3 - a1 * y1 - a2 * y2 - a3 * y3)
|
||||
x3 = x2
|
||||
x2 = x1
|
||||
x1 = x
|
||||
y3 = y2
|
||||
y2 = y1
|
||||
y1 = y
|
||||
dstP[i] = y
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_x1 = x1
|
||||
_x2 = x2
|
||||
_x3 = x3
|
||||
_y1 = y1
|
||||
_y2 = y2
|
||||
_y3 = y3
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficients
|
||||
|
||||
/// Evaluates the analog tone-stack transfer function for the given control positions and
|
||||
/// discretizes it with the bilinear transform into normalized Direct-Form-I coefficients.
|
||||
private func recomputeCoefficients(
|
||||
l: Double,
|
||||
m: Double,
|
||||
t: Double,
|
||||
sampleRate: Double
|
||||
) {
|
||||
// Continuous-time numerator (b0 == 0) and denominator (a0 == 1) coefficients — the
|
||||
// Yeh/Smith closed form for the shared tone-stack network.
|
||||
let b1c: Double = t * c1 * r1 + m * c3 * r3 + l * (c1 * r2 + c2 * r2) + (c1 * r3 + c2 * r3)
|
||||
let b2c: Double = t * (c1 * c2 * r1 * r4 + c1 * c3 * r1 * r4)
|
||||
- m * m * (c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ m * (c1 * c3 * r1 * r3 + c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * (c1 * c2 * r1 * r2 + c1 * c2 * r2 * r4 + c1 * c3 * r2 * r4)
|
||||
+ l * m * (c1 * c3 * r2 * r3 + c2 * c3 * r2 * r3)
|
||||
+ (c1 * c2 * r1 * r3 + c1 * c2 * r3 * r4 + c1 * c3 * r3 * r4)
|
||||
let b3c: Double = l * m * (c1 * c2 * c3 * r1 * r2 * r3 + c1 * c2 * c3 * r2 * r3 * r4)
|
||||
- m * m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ t * c1 * c2 * c3 * r1 * r3 * r4 - t * m * c1 * c2 * c3 * r1 * r3 * r4
|
||||
+ t * l * c1 * c2 * c3 * r1 * r2 * r4
|
||||
|
||||
let a0c: Double = 1.0
|
||||
let a1c: Double = (c1 * r1 + c1 * r3 + c2 * r3 + c2 * r4 + c3 * r4)
|
||||
+ m * c3 * r3 + l * (c1 * r2 + c2 * r2)
|
||||
let a2c: Double = m * (c1 * c3 * r1 * r3 - c2 * c3 * r3 * r4 + c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * m * (c1 * c3 * r2 * r3 + c2 * c3 * r2 * r3)
|
||||
- m * m * (c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * (c1 * c2 * r2 * r4 + c1 * c2 * r1 * r2 + c1 * c3 * r2 * r4 + c2 * c3 * r2 * r4)
|
||||
+ (c1 * c2 * r1 * r4 + c1 * c3 * r1 * r4 + c1 * c2 * r3 * r4 + c1 * c2 * r1 * r3 + c1 * c3 * r3 * r4 + c2 * c3 * r3 * r4)
|
||||
let a3c: Double = l * m * (c1 * c2 * c3 * r1 * r2 * r3 + c1 * c2 * c3 * r2 * r3 * r4)
|
||||
- m * m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ m * (c1 * c2 * c3 * r3 * r3 * r4 + c1 * c2 * c3 * r1 * r3 * r3 - c1 * c2 * c3 * r1 * r3 * r4)
|
||||
+ l * c1 * c2 * c3 * r1 * r2 * r4
|
||||
+ c1 * c2 * c3 * r1 * r3 * r4
|
||||
|
||||
// Bilinear transform s = c·(1 − z⁻¹)/(1 + z⁻¹), c = 2·Fs. Multiplying numerator and
|
||||
// denominator by (1 + z⁻¹)³ and collecting powers of z⁻¹ uses the fixed binomial
|
||||
// expansions of (1 ± z⁻¹)ⁿ: 1·[1,3,3,1], s·[1,1,−1,−1], s²·[1,−1,−1,1], s³·[1,−3,3,−1].
|
||||
let cc: Double = 2.0 * sampleRate
|
||||
let cc2: Double = cc * cc
|
||||
let cc3: Double = cc2 * cc
|
||||
let three: Double = bilinearBinomialThree
|
||||
|
||||
// Numerator (b0c == 0).
|
||||
let bd0: Double = b1c * cc + b2c * cc2 + b3c * cc3
|
||||
let bd1: Double = b1c * cc - b2c * cc2 - three * b3c * cc3
|
||||
let bd2: Double = -b1c * cc - b2c * cc2 + three * b3c * cc3
|
||||
let bd3: Double = -b1c * cc + b2c * cc2 - b3c * cc3
|
||||
// Denominator.
|
||||
let ad0: Double = a0c + a1c * cc + a2c * cc2 + a3c * cc3
|
||||
let ad1: Double = three * a0c + a1c * cc - a2c * cc2 - three * a3c * cc3
|
||||
let ad2: Double = three * a0c - a1c * cc - a2c * cc2 + three * a3c * cc3
|
||||
let ad3: Double = a0c - a1c * cc + a2c * cc2 - a3c * cc3
|
||||
|
||||
let invA0: Double = ad0 != 0.0 ? 1.0 / ad0 : 0.0
|
||||
_b0 = bd0 * invA0
|
||||
_b1 = bd1 * invA0
|
||||
_b2 = bd2 * invA0
|
||||
_b3 = bd3 * invA0
|
||||
_a1 = ad1 * invA0
|
||||
_a2 = ad2 * invA0
|
||||
_a3 = ad3 * invA0
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func clamp01(_ value: Double) -> Double {
|
||||
Swift.min(1.0, Swift.max(0.0, value))
|
||||
}
|
||||
}
|
||||
@@ -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: Load a GuitarML Proteus / NeuralPi JSON model with ``ProteusModelImporter``, or
|
||||
/// > construct a ``NeuralAmpModel`` directly. A binary NAM `.nam` importer is a planned follow-up.
|
||||
///
|
||||
/// - 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..<combined.count { combined[r] = model.biasIH[r] + model.biasHH[r] }
|
||||
_bias = combined
|
||||
_h = [Double](repeating: 0.0, count: hidden)
|
||||
_c = [Double](repeating: 0.0, count: hidden)
|
||||
_pre = [Double](repeating: 0.0, count: NeuralAmpModel.gateCount * hidden)
|
||||
super.init()
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func sigmoid(_ z: Double) -> 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<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
let hidden: Int = _hiddenSize
|
||||
let gateForget: Int = hidden // gate offsets in `_pre` (order i, f, g, o)
|
||||
let gateCell: Int = 2 * hidden
|
||||
let gateOutput: Int = 3 * hidden
|
||||
let residual: Bool = _residual
|
||||
let denseBias: Double = _denseBias
|
||||
let inCount: Int = ins.count
|
||||
let rows: Int = NeuralAmpModel.gateCount * hidden
|
||||
|
||||
// Bind every array (weights + state + I/O) to a raw base pointer so the O(4·H²) inner
|
||||
// loop is bounds-check-free and ARC-free. The weight buffers are read-only (never
|
||||
// mutated → no COW); `_pre`/`_h`/`_c` mutate in place.
|
||||
_weightIH.withUnsafeBufferPointer { (wihB: UnsafeBufferPointer<Double>) in
|
||||
_weightHH.withUnsafeBufferPointer { (whhB: UnsafeBufferPointer<Double>) in
|
||||
_bias.withUnsafeBufferPointer { (biasB: UnsafeBufferPointer<Double>) in
|
||||
_denseWeight.withUnsafeBufferPointer { (woutB: UnsafeBufferPointer<Double>) in
|
||||
ins.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_pre.withUnsafeMutableBufferPointer { (preB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_h.withUnsafeMutableBufferPointer { (hB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_c.withUnsafeMutableBufferPointer { (cB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let weightIH: UnsafePointer<Double> = wihB.baseAddress,
|
||||
let weightHH: UnsafePointer<Double> = whhB.baseAddress,
|
||||
let bias: UnsafePointer<Double> = biasB.baseAddress,
|
||||
let denseWeight: UnsafePointer<Double> = woutB.baseAddress,
|
||||
let srcP: UnsafePointer<Double> = src.baseAddress,
|
||||
let dstP: UnsafeMutablePointer<Double> = dst.baseAddress,
|
||||
let pre: UnsafeMutablePointer<Double> = preB.baseAddress,
|
||||
let h: UnsafeMutablePointer<Double> = hB.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = cB.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? srcP[i] : 0
|
||||
// Gate pre-activations from the *previous* hidden state.
|
||||
for r: Int in 0..<rows {
|
||||
var acc: Double = bias[r] + weightIH[r] * x
|
||||
let rowBase: Int = r * hidden
|
||||
for j: Int in 0..<hidden {
|
||||
acc += weightHH[rowBase + j] * h[j]
|
||||
}
|
||||
pre[r] = acc
|
||||
}
|
||||
// Cell + hidden update and dense readout.
|
||||
var outAcc: Double = denseBias
|
||||
for u: Int in 0..<hidden {
|
||||
let inputGate: Double = sigmoid(pre[u])
|
||||
let forgetGate: Double = sigmoid(pre[gateForget + u])
|
||||
let cellGate: Double = tanh(pre[gateCell + u])
|
||||
let outputGate: Double = sigmoid(pre[gateOutput + u])
|
||||
let cu: Double = denormalsToZero(forgetGate * c[u] + inputGate * cellGate)
|
||||
c[u] = cu
|
||||
let hu: Double = outputGate * tanh(cu)
|
||||
h[u] = hu
|
||||
outAcc += denseWeight[u] * hu
|
||||
}
|
||||
if residual { outAcc += x }
|
||||
dstP[i] = outAcc
|
||||
}
|
||||
} } } } } } } } }
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// NeuralAmpModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Weights for a single-layer LSTM guitar-amp capture, consumed by ``LSTMAmp``.
|
||||
///
|
||||
/// This matches the GuitarML "Proteus" / NeuralPi topology: a single `LSTM(inputSize: 1,
|
||||
/// hiddenSize: H)` followed by a `Linear(H, 1)`, optionally with an input skip
|
||||
/// (`y = x + dense(h)`), run one audio sample at a time.
|
||||
///
|
||||
/// ## Weight layout
|
||||
///
|
||||
/// All arrays are flat `Double`s. Gates use the PyTorch order **input, forget, cell, output**
|
||||
/// (`i, f, g, o`), stacked so gate `q ∈ 0…3`, hidden unit `u ∈ 0…H-1` lives at row `q·H + u`:
|
||||
///
|
||||
/// - `weightIH` — input→gate weights, `4·H` entries (input size is 1), row `q·H + u`.
|
||||
/// - `weightHH` — recurrent gate weights, `4·H · H` entries, element `(q·H + u)·H + j`.
|
||||
/// - `biasIH`, `biasHH` — `4·H` each (PyTorch keeps two bias vectors; they are summed).
|
||||
/// - `denseWeight` — `H` entries, `denseBias` — scalar.
|
||||
///
|
||||
/// This is Lyrebird's native, `Codable` container. Load a GuitarML Proteus / NeuralPi JSON
|
||||
/// model onto this layout with ``ProteusModelImporter``; a binary NAM `.nam` importer is a
|
||||
/// planned follow-up.
|
||||
public struct NeuralAmpModel: Codable, Sendable {
|
||||
|
||||
/// Number of LSTM hidden units.
|
||||
public let hiddenSize: Int
|
||||
|
||||
/// When `true`, the dry input is added to the dense output (`y = x + dense(h)`).
|
||||
public let residual: Bool
|
||||
|
||||
/// Input→gate weights, `4·hiddenSize` entries (input size 1), gate-major (`q·H + u`).
|
||||
public let weightIH: [Double]
|
||||
|
||||
/// Recurrent gate weights, `4·hiddenSize·hiddenSize` entries, element `(q·H + u)·H + j`.
|
||||
public let weightHH: [Double]
|
||||
|
||||
/// Input-side gate biases, `4·hiddenSize` entries.
|
||||
public let biasIH: [Double]
|
||||
|
||||
/// Hidden-side gate biases, `4·hiddenSize` entries (summed with `biasIH`).
|
||||
public let biasHH: [Double]
|
||||
|
||||
/// Dense output weights, `hiddenSize` entries.
|
||||
public let denseWeight: [Double]
|
||||
|
||||
/// Dense output bias.
|
||||
public let denseBias: Double
|
||||
|
||||
/// Number of gates in an LSTM cell (input, forget, cell, output).
|
||||
public static let gateCount: Int = 4
|
||||
|
||||
/// Creates a model, validating all array shapes against `hiddenSize`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hiddenSize: LSTM hidden-unit count. Must be `> 0`.
|
||||
/// - residual: Add the dry input to the dense output. Defaults to `true` (Proteus-style).
|
||||
/// - weightIH: `4·hiddenSize` input→gate weights.
|
||||
/// - weightHH: `4·hiddenSize·hiddenSize` recurrent weights.
|
||||
/// - biasIH: `4·hiddenSize` input-side biases.
|
||||
/// - biasHH: `4·hiddenSize` hidden-side biases.
|
||||
/// - denseWeight: `hiddenSize` dense weights.
|
||||
/// - denseBias: Dense bias.
|
||||
public init(
|
||||
hiddenSize: Int,
|
||||
residual: Bool = true,
|
||||
weightIH: [Double],
|
||||
weightHH: [Double],
|
||||
biasIH: [Double],
|
||||
biasHH: [Double],
|
||||
denseWeight: [Double],
|
||||
denseBias: Double
|
||||
) {
|
||||
precondition(hiddenSize > 0, "NeuralAmpModel: hiddenSize must be > 0")
|
||||
let gated: Int = NeuralAmpModel.gateCount * hiddenSize
|
||||
precondition(weightIH.count == gated, "NeuralAmpModel: weightIH must be 4·hiddenSize")
|
||||
precondition(weightHH.count == gated * hiddenSize, "NeuralAmpModel: weightHH must be 4·hiddenSize·hiddenSize")
|
||||
precondition(biasIH.count == gated, "NeuralAmpModel: biasIH must be 4·hiddenSize")
|
||||
precondition(biasHH.count == gated, "NeuralAmpModel: biasHH must be 4·hiddenSize")
|
||||
precondition(denseWeight.count == hiddenSize, "NeuralAmpModel: denseWeight must be hiddenSize")
|
||||
self.hiddenSize = hiddenSize
|
||||
self.residual = residual
|
||||
self.weightIH = weightIH
|
||||
self.weightHH = weightHH
|
||||
self.biasIH = biasIH
|
||||
self.biasHH = biasHH
|
||||
self.denseWeight = denseWeight
|
||||
self.denseBias = denseBias
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case hiddenSize, residual, weightIH, weightHH, biasIH, biasHH, denseWeight, denseBias
|
||||
}
|
||||
|
||||
/// Decodes and **validates** array shapes against `hiddenSize`, throwing on a mismatch.
|
||||
///
|
||||
/// External model files are the primary source for this type, so a malformed/hand-edited
|
||||
/// JSON must fail loudly at load — not decode silently and crash later in `LSTMAmp.init` or,
|
||||
/// worse, in the RT render loop on an out-of-bounds weight read. (The synthesized decoder
|
||||
/// would bypass the memberwise init's shape `precondition`s, hence this explicit override.)
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let hiddenSize: Int = try container.decode(Int.self, forKey: .hiddenSize)
|
||||
let residual: Bool = try container.decode(Bool.self, forKey: .residual)
|
||||
let weightIH: [Double] = try container.decode([Double].self, forKey: .weightIH)
|
||||
let weightHH: [Double] = try container.decode([Double].self, forKey: .weightHH)
|
||||
let biasIH: [Double] = try container.decode([Double].self, forKey: .biasIH)
|
||||
let biasHH: [Double] = try container.decode([Double].self, forKey: .biasHH)
|
||||
let denseWeight: [Double] = try container.decode([Double].self, forKey: .denseWeight)
|
||||
let denseBias: Double = try container.decode(Double.self, forKey: .denseBias)
|
||||
|
||||
func fail(_ key: CodingKeys, _ message: String) -> DecodingError {
|
||||
DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: message)
|
||||
}
|
||||
guard hiddenSize > 0 else { throw fail(.hiddenSize, "hiddenSize must be > 0") }
|
||||
let gated: Int = NeuralAmpModel.gateCount * hiddenSize
|
||||
guard weightIH.count == gated else { throw fail(.weightIH, "weightIH must be 4·hiddenSize (\(gated)); got \(weightIH.count)") }
|
||||
guard weightHH.count == gated * hiddenSize else { throw fail(.weightHH, "weightHH must be 4·hiddenSize·hiddenSize (\(gated * hiddenSize)); got \(weightHH.count)") }
|
||||
guard biasIH.count == gated else { throw fail(.biasIH, "biasIH must be 4·hiddenSize (\(gated)); got \(biasIH.count)") }
|
||||
guard biasHH.count == gated else { throw fail(.biasHH, "biasHH must be 4·hiddenSize (\(gated)); got \(biasHH.count)") }
|
||||
guard denseWeight.count == hiddenSize else { throw fail(.denseWeight, "denseWeight must be hiddenSize (\(hiddenSize)); got \(denseWeight.count)") }
|
||||
|
||||
self.hiddenSize = hiddenSize
|
||||
self.residual = residual
|
||||
self.weightIH = weightIH
|
||||
self.weightHH = weightHH
|
||||
self.biasIH = biasIH
|
||||
self.biasHH = biasHH
|
||||
self.denseWeight = denseWeight
|
||||
self.denseBias = denseBias
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// ProteusModelImporter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Imports a GuitarML **Proteus / NeuralPi** model JSON into a ``NeuralAmpModel``.
|
||||
///
|
||||
/// Those tools export a single-layer PyTorch LSTM as JSON with two objects:
|
||||
///
|
||||
/// ```json
|
||||
/// { "model_data": { "unit_type": "LSTM", "input_size": 1, "hidden_size": 20,
|
||||
/// "num_layers": 1, "skip": 1, "output_size": 1 },
|
||||
/// "state_dict": { "rec.weight_ih_l0": [[…]], // 4H × input_size
|
||||
/// "rec.weight_hh_l0": [[…]], // 4H × H
|
||||
/// "rec.bias_ih_l0": [ … ], // 4H
|
||||
/// "rec.bias_hh_l0": [ … ], // 4H
|
||||
/// "lin.weight": [[…]], // output_size × H
|
||||
/// "lin.bias": [ … ] } } // output_size
|
||||
/// ```
|
||||
///
|
||||
/// PyTorch stacks the LSTM gates in the order **input, forget, cell, output** (i, f, g, o) —
|
||||
/// the same order ``NeuralAmpModel`` documents — so the tensors flatten straight onto its
|
||||
/// layout. `skip == 1` maps to ``NeuralAmpModel/residual``.
|
||||
///
|
||||
/// Only the single-layer, `input_size == 1`, `output_size == 1`, `unit_type == "LSTM"` shape
|
||||
/// (the Proteus/NeuralPi capture topology `LSTMAmp` runs) is supported; anything else throws.
|
||||
///
|
||||
/// > The model files themselves are **not** redistributed with Lyrebird — this only parses a
|
||||
/// > file the user supplies. GuitarML models are GPL-licensed; keep them out of MIT bundles.
|
||||
public enum ProteusModelImporter {
|
||||
|
||||
/// Errors thrown while importing a Proteus/NeuralPi model.
|
||||
public enum ImportError: Error, Equatable {
|
||||
/// `model_data.unit_type` was not `"LSTM"` (the only recurrent unit `LSTMAmp` runs).
|
||||
case unsupportedUnitType(String)
|
||||
/// A tensor shape (or `input_size`/`output_size`/`num_layers`) was inconsistent with the
|
||||
/// single-layer, mono LSTM topology or with `hidden_size`. The message names the field.
|
||||
case unsupportedShape(String)
|
||||
}
|
||||
|
||||
private static let supportedInputSize: Int = 1
|
||||
private static let supportedOutputSize: Int = 1
|
||||
private static let supportedLayerCount: Int = 1
|
||||
|
||||
/// Parses Proteus/NeuralPi model JSON into a validated ``NeuralAmpModel``.
|
||||
///
|
||||
/// - Parameter data: The raw JSON file contents.
|
||||
/// - Returns: The imported model.
|
||||
/// - Throws: `DecodingError` if the JSON is malformed, or ``ImportError`` if the topology is
|
||||
/// unsupported or a tensor shape is inconsistent with `hidden_size`.
|
||||
public static func model(fromProteusJSON data: Data) throws -> NeuralAmpModel {
|
||||
let file: ProteusFile = try JSONDecoder().decode(ProteusFile.self, from: data)
|
||||
let meta: ProteusFile.ModelData = file.modelData
|
||||
let dict: ProteusFile.StateDict = file.stateDict
|
||||
|
||||
guard meta.unitType.uppercased() == "LSTM" else {
|
||||
throw ImportError.unsupportedUnitType(meta.unitType)
|
||||
}
|
||||
let hidden: Int = meta.hiddenSize
|
||||
guard hidden > 0 else { throw ImportError.unsupportedShape("hidden_size must be > 0; got \(hidden)") }
|
||||
guard meta.numLayers == supportedLayerCount else {
|
||||
throw ImportError.unsupportedShape("only num_layers == 1 is supported; got \(meta.numLayers)")
|
||||
}
|
||||
guard meta.inputSize == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("only input_size == 1 is supported; got \(meta.inputSize)")
|
||||
}
|
||||
guard meta.outputSize == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("only output_size == 1 is supported; got \(meta.outputSize)")
|
||||
}
|
||||
|
||||
let gated: Int = NeuralAmpModel.gateCount * hidden
|
||||
|
||||
// rec.weight_ih_l0: 4H × input_size(1) → 4H (take the single column).
|
||||
guard dict.weightIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 rows must be 4·hidden (\(gated)); got \(dict.weightIH.count)")
|
||||
}
|
||||
var weightIH: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightIH[r].count == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 row \(r) must have input_size (1) columns; got \(dict.weightIH[r].count)")
|
||||
}
|
||||
weightIH[r] = dict.weightIH[r][0]
|
||||
}
|
||||
|
||||
// rec.weight_hh_l0: 4H × H → flatten row-major to (r·H + j).
|
||||
guard dict.weightHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 rows must be 4·hidden (\(gated)); got \(dict.weightHH.count)")
|
||||
}
|
||||
var weightHH: [Double] = [Double](repeating: 0.0, count: gated * hidden)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightHH[r].count == hidden else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 row \(r) must have hidden (\(hidden)) columns; got \(dict.weightHH[r].count)")
|
||||
}
|
||||
let base: Int = r * hidden
|
||||
for j: Int in 0..<hidden { weightHH[base + j] = dict.weightHH[r][j] }
|
||||
}
|
||||
|
||||
guard dict.biasIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_ih_l0 must be 4·hidden (\(gated)); got \(dict.biasIH.count)")
|
||||
}
|
||||
guard dict.biasHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_hh_l0 must be 4·hidden (\(gated)); got \(dict.biasHH.count)")
|
||||
}
|
||||
|
||||
// lin.weight: output_size(1) × H → H.
|
||||
guard dict.linWeight.count == supportedOutputSize, dict.linWeight[0].count == hidden else {
|
||||
throw ImportError.unsupportedShape("lin.weight must be 1 × hidden (\(hidden))")
|
||||
}
|
||||
guard dict.linBias.count == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("lin.bias must have output_size (1) entries; got \(dict.linBias.count)")
|
||||
}
|
||||
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: hidden,
|
||||
residual: meta.skip != 0,
|
||||
weightIH: weightIH,
|
||||
weightHH: weightHH,
|
||||
biasIH: dict.biasIH,
|
||||
biasHH: dict.biasHH,
|
||||
denseWeight: dict.linWeight[0],
|
||||
denseBias: dict.linBias[0])
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodable mirror of the Proteus/NeuralPi model-file schema.
|
||||
private struct ProteusFile: Decodable {
|
||||
let modelData: ModelData
|
||||
let stateDict: StateDict
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case modelData = "model_data"
|
||||
case stateDict = "state_dict"
|
||||
}
|
||||
|
||||
struct ModelData: Decodable {
|
||||
let unitType: String
|
||||
let inputSize: Int
|
||||
let hiddenSize: Int
|
||||
let numLayers: Int
|
||||
let outputSize: Int
|
||||
let skip: Int
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case unitType = "unit_type"
|
||||
case inputSize = "input_size"
|
||||
case hiddenSize = "hidden_size"
|
||||
case numLayers = "num_layers"
|
||||
case outputSize = "output_size"
|
||||
case skip
|
||||
}
|
||||
}
|
||||
|
||||
struct StateDict: Decodable {
|
||||
let weightIH: [[Double]]
|
||||
let weightHH: [[Double]]
|
||||
let biasIH: [Double]
|
||||
let biasHH: [Double]
|
||||
let linWeight: [[Double]]
|
||||
let linBias: [Double]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case weightIH = "rec.weight_ih_l0"
|
||||
case weightHH = "rec.weight_hh_l0"
|
||||
case biasIH = "rec.bias_ih_l0"
|
||||
case biasHH = "rec.bias_hh_l0"
|
||||
case linWeight = "lin.weight"
|
||||
case linBias = "lin.bias"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// TriodeStage.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// A tube-style preamp gain stage: an asymmetric saturating nonlinearity driven by `drive`
|
||||
/// and offset by a grid `bias`, evaluated at 2×/4× oversampling, followed by an output
|
||||
/// coupling (DC-blocking) high-pass.
|
||||
///
|
||||
/// A single triode stage is characterized less by hard clipping than by *asymmetry*: the
|
||||
/// operating-point bias makes the transfer curve steeper on one side than the other, which
|
||||
/// generates even-order harmonics (the "warmth" of a single-ended tube stage) and a
|
||||
/// program-dependent DC shift that the following coupling capacitor removes. This stage models
|
||||
/// that behavior with a biased `tanh` soft-clip — `tanh(drive·x + bias) − tanh(bias)` — so the
|
||||
/// static operating point is subtracted while the dynamic asymmetry (and its even harmonics)
|
||||
/// remains, then a one-pole DC blocker emulates the coupling cap.
|
||||
///
|
||||
/// The nonlinearity is evaluated at an oversampled rate so the harmonics it generates settle
|
||||
/// below the upsampled Nyquist instead of aliasing back into the audible band.
|
||||
///
|
||||
/// This is a musically-voiced static waveshaper, not a SPICE-accurate circuit solve; a true
|
||||
/// bidirectional wave-digital triode model is a separate, heavier path.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// > Note: `drive` and `bias` are read once per block (control rate); audio-rate modulation of
|
||||
/// > them is quantized to block boundaries.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to drive through the stage.
|
||||
/// - drive: Input gain into the tube. Higher pushes harder into saturation. Defaults to `1.0`.
|
||||
/// - bias: Grid-bias offset controlling asymmetry / even-harmonic content. `0` is symmetric.
|
||||
/// Practical range roughly `[-1, 1]`. Defaults to `0.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `4`.
|
||||
public final class TriodeStage: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _driveInput: any ValidGeneratorInput
|
||||
private let _biasInput: any ValidGeneratorInput
|
||||
private let _driveIsGenerator: Bool
|
||||
private let _biasIsGenerator: Bool
|
||||
|
||||
private let _oversampleFactor: Int
|
||||
|
||||
// MARK: - Oversampling state
|
||||
|
||||
private var _upsampler2x: HalfbandUpsampler2x
|
||||
private var _downsampler2x: HalfbandDownsampler2x
|
||||
private var _upsampler4x: HalfbandUpsampler4x
|
||||
private var _downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
// MARK: - DC-block (coupling) state
|
||||
|
||||
private var _dcX1: Double = 0.0
|
||||
private var _dcY1: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Coupling-cap DC-blocker pole. Shared with `LeakDC`'s audio default so the two stay in
|
||||
/// sync if it is ever retuned. The corner is sample-rate-dependent (≈ a few tens of Hz at
|
||||
/// 44.1 / 48 kHz), matching the `LeakDC` convention.
|
||||
private let couplingPole: Double = leakDCDefaultAudioCoef
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to drive through the stage.
|
||||
/// - drive: Input gain into the tube. Defaults to `1.0`.
|
||||
/// - bias: Grid-bias offset controlling asymmetry. `0` = symmetric. Defaults to `0.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `4`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
drive: any ValidGeneratorInput = 1.0,
|
||||
bias: any ValidGeneratorInput = 0.0,
|
||||
oversample: Int = 4
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"TriodeStage: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput()
|
||||
let resolvedBias: any ValidGeneratorInput = bias._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_driveInput = resolvedDrive
|
||||
_biasInput = resolvedBias
|
||||
_driveIsGenerator = resolvedDrive is any Generator
|
||||
_biasIsGenerator = resolvedBias is any Generator
|
||||
_oversampleFactor = oversample
|
||||
_upsampler2x = HalfbandUpsampler2x()
|
||||
_downsampler2x = HalfbandDownsampler2x()
|
||||
_upsampler4x = HalfbandUpsampler4x()
|
||||
_downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let drive: Double = lastGeneratorSampleOrFloat(
|
||||
_driveInput, isGenerator: _driveIsGenerator, graph: graph, count: count)
|
||||
let bias: Double = lastGeneratorSampleOrFloat(
|
||||
_biasInput, isGenerator: _biasIsGenerator, graph: graph, count: count)
|
||||
// Subtract the static operating point so only the dynamic (asymmetric) response passes.
|
||||
let biasOffset: Double = tanh(bias)
|
||||
let pole: Double = couplingPole
|
||||
let useFourX: Bool = _oversampleFactor == 4
|
||||
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
var dcX1: Double = _dcX1
|
||||
var dcY1: Double = _dcY1
|
||||
let inCount: Int = ins.count
|
||||
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? ins[i] : 0
|
||||
let shaped: Double
|
||||
if useFourX {
|
||||
let (a, b, c, d) = _upsampler4x.process(x)
|
||||
shaped = _downsampler4x.process(
|
||||
tanh(drive * a + bias) - biasOffset,
|
||||
tanh(drive * b + bias) - biasOffset,
|
||||
tanh(drive * c + bias) - biasOffset,
|
||||
tanh(drive * d + bias) - biasOffset)
|
||||
} else {
|
||||
let (a, b) = _upsampler2x.process(x)
|
||||
shaped = _downsampler2x.process(
|
||||
tanh(drive * a + bias) - biasOffset,
|
||||
tanh(drive * b + bias) - biasOffset)
|
||||
}
|
||||
// One-pole DC blocker (coupling cap): y = x − x1 + pole·y1.
|
||||
let y: Double = denormalsToZero(shaped - dcX1 + pole * dcY1)
|
||||
dcX1 = shaped
|
||||
dcY1 = y
|
||||
dstP[i] = y
|
||||
}
|
||||
}
|
||||
|
||||
_dcX1 = dcX1
|
||||
_dcY1 = dcY1
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// ToneStackModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A passive guitar-amplifier tone-stack topology, selecting the resistor/capacitor values
|
||||
/// used by ``ToneStack``.
|
||||
///
|
||||
/// All three classic stacks share the same circuit; only the component values differ. The
|
||||
/// values here match the widely-used Yeh/Smith reference set (the same set used by the Faust
|
||||
/// `tonestacks` library).
|
||||
///
|
||||
/// - `fender`: Fender Bassman / Twin — scooped mids, bright.
|
||||
/// - `marshall`: Marshall JCM800 — more mid, tighter low end.
|
||||
/// - `vox`: Vox AC30 — a different taper, chimey top.
|
||||
public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case fender
|
||||
case marshall
|
||||
case vox
|
||||
|
||||
/// Human-readable name for pickers.
|
||||
public var displayName: String {
|
||||
switch self {
|
||||
case .fender: return "Fender"
|
||||
case .marshall: return "Marshall"
|
||||
case .vox: return "Vox"
|
||||
}
|
||||
}
|
||||
|
||||
/// Resistor values in ohms: `(R1, R2, R3, R4)`.
|
||||
var resistors: (r1: Double, r2: Double, r3: Double, r4: Double) {
|
||||
switch self {
|
||||
case .fender: return (250_000.0, 1_000_000.0, 25_000.0, 56_000.0)
|
||||
case .marshall: return (220_000.0, 1_000_000.0, 22_000.0, 33_000.0)
|
||||
case .vox: return (1_000_000.0, 1_000_000.0, 10_000.0, 100_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Capacitor values in farads: `(C1, C2, C3)`.
|
||||
var capacitors: (c1: Double, c2: Double, c3: Double) {
|
||||
switch self {
|
||||
case .fender: return (250.0e-12, 20.0e-9, 20.0e-9)
|
||||
case .marshall: return (470.0e-12, 22.0e-9, 22.0e-9)
|
||||
case .vox: return (50.0e-12, 22.0e-9, 22.0e-9)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ extension ProjectScaffolder {
|
||||
/* Begin PBXFileReference section */
|
||||
\t\t\(pbxAppProductRef) /* \(name).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \(name).app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
\t\t\(pbxInfoPlistRef) /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
\t\t\(pbxAppEntitlementsRef) /* \(name).entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = \(name).entitlements; sourceTree = "<group>"; };
|
||||
\t\t\(pbxMainSwiftRef) /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxAppDelegateRef) /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxSynthRef) /* \(name)Synth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)Synth.swift; sourceTree = "<group>"; };
|
||||
@@ -85,6 +86,7 @@ extension ProjectScaffolder {
|
||||
\t\t\t\t\(pbxNoteControllerRef) /* NoteController.swift */,
|
||||
\t\t\t\t\(pbxViewRef) /* \(name)View.swift */,
|
||||
\t\t\t\t\(pbxInfoPlistRef) /* Info.plist */,
|
||||
\t\t\t\t\(pbxAppEntitlementsRef) /* \(name).entitlements */,
|
||||
\t\t\t);
|
||||
\t\t\tpath = \(name);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
@@ -177,6 +179,7 @@ extension ProjectScaffolder {
|
||||
\t\t\(pbxAppDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)/\(name).entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
@@ -197,6 +200,7 @@ extension ProjectScaffolder {
|
||||
\t\t\(pbxAppReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)/\(name).entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
|
||||
@@ -122,6 +122,8 @@ extension ProjectScaffolder {
|
||||
let files: [(String, String)] = [
|
||||
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
macOSAppInfoPlist(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name).entitlements"),
|
||||
macOSAppEntitlements()),
|
||||
((appGroupDir as NSString).appendingPathComponent("main.swift"),
|
||||
macOSAppMainSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
@@ -146,6 +148,35 @@ extension ProjectScaffolder {
|
||||
appInfoPlist(name: name, platform: .macOS)
|
||||
}
|
||||
|
||||
/// Entitlements for the standalone macOS performance app.
|
||||
///
|
||||
/// Not sandboxed — a live-performance app needs unrestricted access to
|
||||
/// audio devices, files (buffer load/render), MIDI, and OSC networking,
|
||||
/// which the App Sandbox would gate. The one entitlement granted is
|
||||
/// microphone / line-in: under the Hardened Runtime (enabled in the
|
||||
/// pbxproj, and required for notarization) the OS hard-kills the process
|
||||
/// the moment the AUHAL input bus opens unless this is present. It only
|
||||
/// prompts the user when input is actually opened
|
||||
/// (`numInputChannels > 0`), so it is harmless for output-only synths.
|
||||
///
|
||||
/// If a project needs to load dynamic libraries signed by a different
|
||||
/// team (e.g. a bundled `.dylib`), add
|
||||
/// `com.apple.security.cs.disable-library-validation`. If it must ship on
|
||||
/// the Mac App Store, add `com.apple.security.app-sandbox` and the
|
||||
/// specific resource entitlements the piece uses instead.
|
||||
static func macOSAppEntitlements() -> String {
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppMainSwift(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
@@ -178,6 +209,9 @@ extension ProjectScaffolder {
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// `@MainActor`: constructs the main-actor `NoteController` and synth,
|
||||
/// and `NSApplicationDelegate` callbacks already run on the main actor.
|
||||
@MainActor
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let controller: NoteController
|
||||
@@ -246,6 +280,11 @@ extension ProjectScaffolder {
|
||||
|
||||
/// Owns engine + synth + scope; mediates start/stop from the UI so the
|
||||
/// engine isn't kicked until user is ready (avoids first-block dropouts).
|
||||
///
|
||||
/// `@MainActor`: this drives SwiftUI and calls the engine's
|
||||
/// main-actor-isolated `add(_:)`, so the whole controller lives on the
|
||||
/// main actor.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
@@ -385,9 +424,15 @@ extension ProjectScaffolder {
|
||||
case .macOS:
|
||||
minOSKey = "LSMinimumSystemVersion"
|
||||
minOSValue = "$(MACOSX_DEPLOYMENT_TARGET)"
|
||||
// The mic usage string is required whenever the app opens the
|
||||
// AUHAL input bus: macOS crashes a Hardened-Runtime process on
|
||||
// audio-input access if this key is absent. Harmless for
|
||||
// output-only synths (no prompt fires until input opens).
|
||||
extras = """
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>\(name) uses audio input for live signal processing.</string>
|
||||
"""
|
||||
case .iOS:
|
||||
minOSKey = "MinimumOSVersion"
|
||||
|
||||
@@ -3332,6 +3332,7 @@ extension DSLBuiltinRegistry {
|
||||
DSLParameter(label: "in", hasDefault: false),
|
||||
DSLParameter(label: "maxAmplitude", hasDefault: true),
|
||||
DSLParameter(label: "lookAheadTime", hasDefault: true),
|
||||
DSLParameter(label: "releaseTime", hasDefault: true),
|
||||
DSLParameter(label: "sampleRate", hasDefault: false),
|
||||
],
|
||||
make: { args in
|
||||
@@ -3339,6 +3340,7 @@ extension DSLBuiltinRegistry {
|
||||
in: try DSLArgument.input(args["in"], "LookAheadLimiter", "in"),
|
||||
maxAmplitude: try DSLArgument.input(args["maxAmplitude"] ?? .signal(1.0), "LookAheadLimiter", "maxAmplitude"),
|
||||
lookAheadTime: try DSLArgument.double(args["lookAheadTime"] ?? .signal(0.005), "LookAheadLimiter", "lookAheadTime"),
|
||||
releaseTime: try DSLArgument.input(args["releaseTime"] ?? .signal(0.050), "LookAheadLimiter", "releaseTime"),
|
||||
sampleRate: try DSLArgument.double(args["sampleRate"], "LookAheadLimiter", "sampleRate")
|
||||
)
|
||||
}
|
||||
@@ -5626,6 +5628,24 @@ extension DSLBuiltinRegistry {
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "ToneStack",
|
||||
rate: .audio,
|
||||
parameters: [
|
||||
DSLParameter(label: "input", hasDefault: false),
|
||||
DSLParameter(label: "bass", hasDefault: true),
|
||||
DSLParameter(label: "mid", hasDefault: true),
|
||||
DSLParameter(label: "treble", hasDefault: true),
|
||||
],
|
||||
make: { args in
|
||||
ToneStack(
|
||||
input: try DSLArgument.input(args["input"], "ToneStack", "input"),
|
||||
bass: try DSLArgument.input(args["bass"] ?? .signal(0.5), "ToneStack", "bass"),
|
||||
mid: try DSLArgument.input(args["mid"] ?? .signal(0.5), "ToneStack", "mid"),
|
||||
treble: try DSLArgument.input(args["treble"] ?? .signal(0.5), "ToneStack", "treble")
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "Trig",
|
||||
rate: .audio,
|
||||
@@ -5754,6 +5774,24 @@ extension DSLBuiltinRegistry {
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "TriodeStage",
|
||||
rate: .audio,
|
||||
parameters: [
|
||||
DSLParameter(label: "input", hasDefault: false),
|
||||
DSLParameter(label: "drive", hasDefault: true),
|
||||
DSLParameter(label: "bias", hasDefault: true),
|
||||
DSLParameter(label: "oversample", hasDefault: true),
|
||||
],
|
||||
make: { args in
|
||||
TriodeStage(
|
||||
input: try DSLArgument.input(args["input"], "TriodeStage", "input"),
|
||||
drive: try DSLArgument.input(args["drive"] ?? .signal(1.0), "TriodeStage", "drive"),
|
||||
bias: try DSLArgument.input(args["bias"] ?? .signal(0.0), "TriodeStage", "bias"),
|
||||
oversample: try DSLArgument.int(args["oversample"] ?? .signal(4), "TriodeStage", "oversample")
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "TuneablePitchShift",
|
||||
rate: .audio,
|
||||
|
||||
@@ -280,6 +280,7 @@ struct ProjectScaffolderTests {
|
||||
"MyMac/NoteController.swift",
|
||||
"MyMac/MyMacView.swift",
|
||||
"MyMac/Info.plist",
|
||||
"MyMac/MyMac.entitlements",
|
||||
]
|
||||
for rel: String in expected {
|
||||
let path: String = (root as NSString).appendingPathComponent(rel)
|
||||
@@ -299,6 +300,15 @@ struct ProjectScaffolderTests {
|
||||
#expect(src.contains("engine.remove(synth)"))
|
||||
}
|
||||
|
||||
@Test func macOSAppControllerAndDelegateAreMainActor() {
|
||||
// Both call the engine's @MainActor `add(_:)` / a main-actor synth
|
||||
// init; without @MainActor the template fails to compile under Swift 6.
|
||||
let controller: String = ProjectScaffolder.macOSAppNoteControllerSwift(name: "Foo")
|
||||
#expect(controller.contains("@MainActor"))
|
||||
let delegate: String = ProjectScaffolder.macOSAppDelegateSwift(name: "Foo")
|
||||
#expect(delegate.contains("@MainActor"))
|
||||
}
|
||||
|
||||
@Test func macOSAppViewHasStartStopButtons() {
|
||||
let src: String = ProjectScaffolder.macOSAppViewSwift(name: "Foo")
|
||||
#expect(src.contains("Start Engine"))
|
||||
@@ -576,6 +586,29 @@ struct ProjectScaffolderTests {
|
||||
#expect(pbx.contains("/local/Lyrebird"))
|
||||
}
|
||||
|
||||
@Test func macOSAppPBXProjWiresEntitlementsAndHardenedRuntime() {
|
||||
let pbx: String = ProjectScaffolder.macOSAppPBXProj(name: "Perf")
|
||||
// Hardened Runtime + entitlements are both required for a notarized,
|
||||
// distributable performance app that opens the AUHAL input bus.
|
||||
#expect(pbx.contains("ENABLE_HARDENED_RUNTIME = YES"))
|
||||
#expect(pbx.contains("CODE_SIGN_ENTITLEMENTS = Perf/Perf.entitlements;"))
|
||||
#expect(pbx.contains("Perf.entitlements */ = {isa = PBXFileReference"))
|
||||
}
|
||||
|
||||
@Test func macOSAppEntitlementsGrantAudioInputAndAreNotSandboxed() {
|
||||
let ent: String = ProjectScaffolder.macOSAppEntitlements()
|
||||
#expect(ent.contains("com.apple.security.device.audio-input"))
|
||||
// A live-performance app must not be sandboxed — it needs free file /
|
||||
// device / MIDI / OSC access the sandbox would gate.
|
||||
#expect(!ent.contains("com.apple.security.app-sandbox"))
|
||||
}
|
||||
|
||||
@Test func macOSAppInfoPlistHasMicrophoneUsageDescription() {
|
||||
let plist: String = ProjectScaffolder.macOSAppInfoPlist(name: "Perf")
|
||||
// Absent, a Hardened-Runtime process crashes on audio-input access.
|
||||
#expect(plist.contains("NSMicrophoneUsageDescription"))
|
||||
}
|
||||
|
||||
@Test func iOSAppPBXProjReferencesIPhoneOS() {
|
||||
let pbx: String = ProjectScaffolder.iOSAppPBXProj(name: "Foo")
|
||||
#expect(pbx.contains("SDKROOT = iphoneos"))
|
||||
|
||||
@@ -480,6 +480,34 @@ struct LookAheadLimiterTests {
|
||||
let tailMax: Double = tail.map { abs($0) }.max() ?? 0
|
||||
#expect(tailMax < maxAmp * 10.0) // generous bound; really we want "small"
|
||||
}
|
||||
|
||||
/// `releaseTime` is decoupled from `lookAheadTime`: with the look-ahead window held
|
||||
/// fixed, two different release times must produce different gain-recovery behaviour
|
||||
/// (hence different output) on a low-frequency signal that crosses the ceiling on its
|
||||
/// peaks and dips below between them — while both still respect the ceiling.
|
||||
@Test func releaseTimeIndependentOfLookAhead() {
|
||||
let maxAmp: Double = 0.3
|
||||
func run(_ releaseTime: Double) -> [Double] {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 60.0, mul: 1.0)
|
||||
let lim: LookAheadLimiter = LookAheadLimiter(
|
||||
in: sine, maxAmplitude: maxAmp,
|
||||
lookAheadTime: 0.005, releaseTime: releaseTime, sampleRate: sr)
|
||||
return collectBlocks(lim, engine: engine, blocks: 100)
|
||||
}
|
||||
let fast: [Double] = run(0.005)
|
||||
let slow: [Double] = run(0.200)
|
||||
// Ceiling holds for both release settings.
|
||||
#expect(fast.allSatisfy { abs($0) <= maxAmp + 0.001 })
|
||||
#expect(slow.allSatisfy { abs($0) <= maxAmp + 0.001 })
|
||||
// Different release → different waveform.
|
||||
let tailFast: [Double] = Array(fast.suffix(engine.blockSize * 50))
|
||||
let tailSlow: [Double] = Array(slow.suffix(engine.blockSize * 50))
|
||||
let ssd: Double = zip(tailFast, tailSlow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = pair.0 - pair.1
|
||||
return acc + diff * diff
|
||||
}
|
||||
#expect(ssd > 0, "releaseTime had no effect on limiter output")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Compressor Tests
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// ToneStackTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Darwin
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("ToneStack")
|
||||
struct ToneStackTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100.0
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func rms(_ samples: [Double]) -> Double {
|
||||
guard !samples.isEmpty else { return 0 }
|
||||
let sumSq: Double = samples.reduce(0.0) { $0 + $1 * $1 }
|
||||
return (sumSq / Double(samples.count)).squareRoot()
|
||||
}
|
||||
|
||||
/// Steady-state output RMS for a sine at `freqHz` through the tone stack at the given settings.
|
||||
private func steadyRMS(
|
||||
freqHz: Double,
|
||||
bass: Double,
|
||||
mid: Double,
|
||||
treble: Double,
|
||||
model: ToneStackModel = .fender
|
||||
) -> [Double] {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: freqHz, mul: 1.0)
|
||||
let stack: ToneStack = ToneStack(
|
||||
input: sine, bass: bass, mid: mid, treble: treble, model: model)
|
||||
return collectBlocks(stack, engine: engine, blocks: 200)
|
||||
}
|
||||
|
||||
@Test func bassControlBoostsLowEnd() {
|
||||
let lowFreq: Double = 100.0
|
||||
let bassDown: Double = rms(Array(steadyRMS(freqHz: lowFreq, bass: 0.0, mid: 0.5, treble: 0.5).suffix(engine.blockSize * 100)))
|
||||
let bassUp: Double = rms(Array(steadyRMS(freqHz: lowFreq, bass: 1.0, mid: 0.5, treble: 0.5).suffix(engine.blockSize * 100)))
|
||||
#expect(bassUp > bassDown, "bass control did not boost 100 Hz (up=\(bassUp) down=\(bassDown))")
|
||||
}
|
||||
|
||||
@Test func trebleControlBoostsHighEnd() {
|
||||
let highFreq: Double = 4000.0
|
||||
let trebleDown: Double = rms(Array(steadyRMS(freqHz: highFreq, bass: 0.5, mid: 0.5, treble: 0.0).suffix(engine.blockSize * 100)))
|
||||
let trebleUp: Double = rms(Array(steadyRMS(freqHz: highFreq, bass: 0.5, mid: 0.5, treble: 1.0).suffix(engine.blockSize * 100)))
|
||||
#expect(trebleUp > trebleDown, "treble control did not boost 4 kHz (up=\(trebleUp) down=\(trebleDown))")
|
||||
}
|
||||
|
||||
@Test func outputStaysFiniteAndBoundedAcrossSettings() {
|
||||
let settings: [(Double, Double, Double)] = [
|
||||
(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (1.0, 0.0, 1.0), (0.0, 1.0, 0.0), (0.5, 0.5, 0.5),
|
||||
]
|
||||
for (bass, mid, treble): (Double, Double, Double) in settings {
|
||||
for model: ToneStackModel in ToneStackModel.allCases {
|
||||
let out: [Double] = steadyRMS(freqHz: 220.0, bass: bass, mid: mid, treble: treble, model: model)
|
||||
#expect(out.allSatisfy { $0.isFinite }, "non-finite output at \(model) b=\(bass) m=\(mid) t=\(treble)")
|
||||
let peak: Double = out.map { abs($0) }.max() ?? 0
|
||||
// Passive stack: never amplifies above the ±1 input by more than a small margin.
|
||||
#expect(peak <= 1.5, "tone stack blew up (peak=\(peak)) at \(model) b=\(bass) m=\(mid) t=\(treble)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func modelsProduceDifferentResponse() {
|
||||
let freq: Double = 800.0
|
||||
let fender: Double = rms(Array(steadyRMS(freqHz: freq, bass: 0.5, mid: 0.5, treble: 0.5, model: .fender).suffix(engine.blockSize * 100)))
|
||||
let vox: Double = rms(Array(steadyRMS(freqHz: freq, bass: 0.5, mid: 0.5, treble: 0.5, model: .vox).suffix(engine.blockSize * 100)))
|
||||
// Different component sets must give a materially different response, not just any
|
||||
// float difference — require at least a 5% relative gap.
|
||||
let relativeDiff: Double = abs(fender - vox) / Swift.max(fender, vox)
|
||||
#expect(relativeDiff > 0.05, "Fender vs Vox 800 Hz response too close: rel=\(relativeDiff)")
|
||||
}
|
||||
|
||||
@Test func blocksDCInSteadyState() {
|
||||
// The passive tone stack has series coupling caps → exactly zero DC gain (the numerator
|
||||
// has no constant term; the discretized B0…B3 sum to 0). A constant input must decay to
|
||||
// ~0. This is an analytic invariant independent of the exact coefficient values, so it
|
||||
// guards the transcribed Yeh/Smith numerator against a DC-introducing transcription error.
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.7)
|
||||
let stack: ToneStack = ToneStack(input: dc, bass: 0.6, mid: 0.5, treble: 0.4, model: .fender)
|
||||
let out: [Double] = collectBlocks(stack, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(out.suffix(engine.blockSize * 100))
|
||||
let meanAbs: Double = tail.reduce(0.0) { $0 + abs($1) } / Double(tail.count)
|
||||
#expect(meanAbs < 1.0e-3, "tone stack did not block DC (meanAbs=\(meanAbs))")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// LSTMAmpTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import Darwin
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("LSTMAmp")
|
||||
struct LSTMAmpTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
// MARK: - Model construction helpers
|
||||
|
||||
/// A deterministic (RNG-free) model of the given hidden size, for reproducible golden tests.
|
||||
private func makeDeterministicModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
var wih: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
var bih: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
var bhh: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
for k: Int in 0..<gated {
|
||||
wih[k] = 0.2 * sin(Double(k) + 1.0)
|
||||
bih[k] = 0.01 * Double(k)
|
||||
bhh[k] = -0.005 * Double(k)
|
||||
}
|
||||
var whh: [Double] = [Double](repeating: 0.0, count: gated * h)
|
||||
for k: Int in 0..<(gated * h) {
|
||||
whh[k] = 0.1 * cos(Double(k) + 1.0)
|
||||
}
|
||||
var wout: [Double] = [Double](repeating: 0.0, count: h)
|
||||
for u: Int in 0..<h {
|
||||
wout[u] = 0.3 * sin(Double(u) + 0.5)
|
||||
}
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: h, residual: residual,
|
||||
weightIH: wih, weightHH: whh, biasIH: bih, biasHH: bhh,
|
||||
denseWeight: wout, denseBias: 0.05)
|
||||
}
|
||||
|
||||
private func zeroModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: h, residual: residual,
|
||||
weightIH: [Double](repeating: 0.0, count: gated),
|
||||
weightHH: [Double](repeating: 0.0, count: gated * h),
|
||||
biasIH: [Double](repeating: 0.0, count: gated),
|
||||
biasHH: [Double](repeating: 0.0, count: gated),
|
||||
denseWeight: [Double](repeating: 0.0, count: h),
|
||||
denseBias: 0.0)
|
||||
}
|
||||
|
||||
/// Independent, plainly-written LSTM step matching `NeuralAmpModel`'s documented layout —
|
||||
/// the golden reference the flat-indexed generator kernel is checked against.
|
||||
private func referenceStep(
|
||||
_ model: NeuralAmpModel,
|
||||
x: Double,
|
||||
h: inout [Double],
|
||||
c: inout [Double]
|
||||
) -> Double {
|
||||
let hid: Int = model.hiddenSize
|
||||
func sig(_ z: Double) -> Double { 1.0 / (1.0 + exp(-z)) }
|
||||
var pre: [Double] = [Double](repeating: 0.0, count: NeuralAmpModel.gateCount * hid)
|
||||
for r: Int in 0..<pre.count {
|
||||
var acc: Double = model.biasIH[r] + model.biasHH[r] + model.weightIH[r] * x
|
||||
for j: Int in 0..<hid {
|
||||
acc += model.weightHH[r * hid + j] * h[j]
|
||||
}
|
||||
pre[r] = acc
|
||||
}
|
||||
var out: Double = model.denseBias
|
||||
for u: Int in 0..<hid {
|
||||
let ig: Double = sig(pre[u])
|
||||
let fg: Double = sig(pre[hid + u])
|
||||
let gg: Double = tanh(pre[2 * hid + u])
|
||||
let og: Double = sig(pre[3 * hid + u])
|
||||
c[u] = fg * c[u] + ig * gg
|
||||
h[u] = og * tanh(c[u])
|
||||
out += model.denseWeight[u] * h[u]
|
||||
}
|
||||
if model.residual { out += x }
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Test func matchesReferenceTrajectory() {
|
||||
// Full sample-by-sample golden match over a DC-excited trajectory (exercises the
|
||||
// recurrence + state persistence across blocks). Guards gate order, recurrence indexing,
|
||||
// dense readout, and residual against the flat-array kernel.
|
||||
let hidden: Int = 3
|
||||
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: hidden, residual: true)
|
||||
let xval: Double = 0.5
|
||||
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(xval), model: model)
|
||||
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 5)
|
||||
|
||||
var h: [Double] = [Double](repeating: 0.0, count: hidden)
|
||||
var c: [Double] = [Double](repeating: 0.0, count: hidden)
|
||||
for i: Int in 0..<got.count {
|
||||
let expected: Double = referenceStep(model, x: xval, h: &h, c: &c)
|
||||
#expect(abs(got[i] - expected) < 1.0e-9, "sample \(i): got \(got[i]) expected \(expected)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func zeroWeightsResidualPassesInputThrough() {
|
||||
// All-zero weights → the LSTM contributes nothing; with residual the output equals input.
|
||||
let model: NeuralAmpModel = zeroModel(hiddenSize: 4, residual: true)
|
||||
let xval: Double = 0.3
|
||||
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(xval), model: model)
|
||||
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 3)
|
||||
#expect(got.allSatisfy { abs($0 - xval) < 1.0e-12 }, "residual passthrough failed")
|
||||
}
|
||||
|
||||
@Test func zeroWeightsNoResidualIsSilent() {
|
||||
let model: NeuralAmpModel = zeroModel(hiddenSize: 4, residual: false)
|
||||
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(0.3), model: model)
|
||||
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 3)
|
||||
#expect(got.allSatisfy { abs($0) < 1.0e-12 }, "no-residual zero model was not silent")
|
||||
}
|
||||
|
||||
@Test func finiteBoundedOnSine() {
|
||||
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 8, residual: true)
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 0.8)
|
||||
let amp: LSTMAmp = LSTMAmp(input: sine, model: model)
|
||||
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 50)
|
||||
#expect(got.allSatisfy { $0.isFinite }, "non-finite output")
|
||||
#expect(got.contains { abs($0) > 1.0e-4 }, "output was silent")
|
||||
}
|
||||
|
||||
@Test func malformedModelJSONThrows() throws {
|
||||
// A hand-edited / externally-authored model with a mis-sized weight array must fail at
|
||||
// decode (the validating init(from:)) rather than decode silently and crash later.
|
||||
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 3, residual: true)
|
||||
let data: Data = try JSONEncoder().encode(model)
|
||||
guard var object: [String: Any] = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
Issue.record("encoded model was not a JSON object")
|
||||
return
|
||||
}
|
||||
object["weightHH"] = [1.0, 2.0, 3.0] // wrong length for hiddenSize 3
|
||||
let bad: Data = try JSONSerialization.data(withJSONObject: object)
|
||||
#expect(throws: DecodingError.self) {
|
||||
_ = try JSONDecoder().decode(NeuralAmpModel.self, from: bad)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func modelCodableRoundTrips() throws {
|
||||
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 5, residual: true)
|
||||
let data: Data = try JSONEncoder().encode(model)
|
||||
let decoded: NeuralAmpModel = try JSONDecoder().decode(NeuralAmpModel.self, from: data)
|
||||
#expect(decoded.hiddenSize == model.hiddenSize)
|
||||
#expect(decoded.residual == model.residual)
|
||||
#expect(decoded.weightHH == model.weightHH)
|
||||
#expect(decoded.denseWeight == model.denseWeight)
|
||||
#expect(decoded.denseBias == model.denseBias)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// ProteusModelImporterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("ProteusModelImporter")
|
||||
struct ProteusModelImporterTests {
|
||||
|
||||
private func makeModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
let wih: [Double] = (0..<gated).map { 0.2 * Double($0 + 1) }
|
||||
let whh: [Double] = (0..<(gated * h)).map { -0.05 * Double($0 + 1) }
|
||||
let bih: [Double] = (0..<gated).map { 0.01 * Double($0) }
|
||||
let bhh: [Double] = (0..<gated).map { 0.02 * Double($0) }
|
||||
let wout: [Double] = (0..<h).map { 0.3 * Double($0 + 1) }
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: h, residual: residual,
|
||||
weightIH: wih, weightHH: whh, biasIH: bih, biasHH: bhh,
|
||||
denseWeight: wout, denseBias: 0.07)
|
||||
}
|
||||
|
||||
/// Serializes a `NeuralAmpModel` back into the Proteus/NeuralPi file schema (the inverse of
|
||||
/// the importer), so a round-trip proves the flatten/gate mapping is consistent.
|
||||
private func proteusData(from m: NeuralAmpModel, unitType: String = "LSTM") throws -> Data {
|
||||
let h: Int = m.hiddenSize
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
let weightIH: [[Double]] = (0..<gated).map { [m.weightIH[$0]] }
|
||||
let weightHH: [[Double]] = (0..<gated).map { r in (0..<h).map { m.weightHH[r * h + $0] } }
|
||||
let linWeight: [[Double]] = [m.denseWeight]
|
||||
let object: [String: Any] = [
|
||||
"model_data": [
|
||||
"unit_type": unitType, "input_size": 1, "hidden_size": h,
|
||||
"num_layers": 1, "output_size": 1, "skip": m.residual ? 1 : 0,
|
||||
],
|
||||
"state_dict": [
|
||||
"rec.weight_ih_l0": weightIH,
|
||||
"rec.weight_hh_l0": weightHH,
|
||||
"rec.bias_ih_l0": m.biasIH,
|
||||
"rec.bias_hh_l0": m.biasHH,
|
||||
"lin.weight": linWeight,
|
||||
"lin.bias": [m.denseBias],
|
||||
],
|
||||
]
|
||||
return try JSONSerialization.data(withJSONObject: object)
|
||||
}
|
||||
|
||||
private func expectClose(_ a: [Double], _ b: [Double], _ label: String) {
|
||||
#expect(a.count == b.count, "\(label): count \(a.count) != \(b.count)")
|
||||
for i: Int in 0..<Swift.min(a.count, b.count) {
|
||||
#expect(abs(a[i] - b[i]) < 1.0e-12, "\(label)[\(i)]: \(a[i]) != \(b[i])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func importRoundTripsModel() throws {
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 20, residual: true)
|
||||
let data: Data = try proteusData(from: original)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
|
||||
#expect(imported.hiddenSize == original.hiddenSize)
|
||||
#expect(imported.residual == original.residual)
|
||||
expectClose(imported.weightIH, original.weightIH, "weightIH")
|
||||
expectClose(imported.weightHH, original.weightHH, "weightHH")
|
||||
expectClose(imported.biasIH, original.biasIH, "biasIH")
|
||||
expectClose(imported.biasHH, original.biasHH, "biasHH")
|
||||
expectClose(imported.denseWeight, original.denseWeight, "denseWeight")
|
||||
#expect(abs(imported.denseBias - original.denseBias) < 1.0e-12)
|
||||
}
|
||||
|
||||
@Test func skipZeroMapsToNoResidual() throws {
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 4, residual: false)
|
||||
let data: Data = try proteusData(from: original)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
#expect(imported.residual == false)
|
||||
}
|
||||
|
||||
@Test func unsupportedUnitTypeThrows() throws {
|
||||
let data: Data = try proteusData(from: makeModel(hiddenSize: 4, residual: true), unitType: "GRU")
|
||||
#expect(throws: ProteusModelImporter.ImportError.self) {
|
||||
_ = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func inconsistentShapeThrows() throws {
|
||||
// hidden_size says 4 but the recurrent matrix rows won't be 16 → shape error.
|
||||
let object: [String: Any] = [
|
||||
"model_data": [
|
||||
"unit_type": "LSTM", "input_size": 1, "hidden_size": 4,
|
||||
"num_layers": 1, "output_size": 1, "skip": 1,
|
||||
],
|
||||
"state_dict": [
|
||||
"rec.weight_ih_l0": [[0.1], [0.2]], // 2 rows, expected 16
|
||||
"rec.weight_hh_l0": [[0.1, 0.2, 0.3, 0.4]],
|
||||
"rec.bias_ih_l0": [0.0, 0.0],
|
||||
"rec.bias_hh_l0": [0.0, 0.0],
|
||||
"lin.weight": [[0.1, 0.2, 0.3, 0.4]],
|
||||
"lin.bias": [0.0],
|
||||
],
|
||||
]
|
||||
let data: Data = try JSONSerialization.data(withJSONObject: object)
|
||||
#expect(throws: ProteusModelImporter.ImportError.self) {
|
||||
_ = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func importedModelRunsInLSTMAmp() throws {
|
||||
// The imported model must drive LSTMAmp without shape errors and produce finite output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 8, residual: true)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: proteusData(from: original))
|
||||
let amp: LSTMAmp = LSTMAmp(input: OscSin.Audio(freq: 220.0, mul: 0.5), model: imported)
|
||||
let out: [Double] = collectBlocks(amp, engine: engine, blocks: 20)
|
||||
#expect(out.allSatisfy { $0.isFinite })
|
||||
#expect(out.contains { abs($0) > 1.0e-6 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// TriodeStageTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Darwin
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("TriodeStage")
|
||||
struct TriodeStageTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100.0
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
private func goertzel(_ x: [Double], cyclesPerSample: Double) -> Double {
|
||||
let omega: Double = 2.0 * Double.pi * cyclesPerSample
|
||||
let cosine: Double = cos(omega)
|
||||
let sine: Double = sin(omega)
|
||||
let coeff: Double = 2.0 * cosine
|
||||
var s1: Double = 0.0
|
||||
var s2: Double = 0.0
|
||||
for v: Double in x {
|
||||
let s0: Double = v + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
let real: Double = s1 - s2 * cosine
|
||||
let imag: Double = s2 * sine
|
||||
return (real * real + imag * imag).squareRoot()
|
||||
}
|
||||
|
||||
private func steadyTail(_ gen: any Generator, blocks: Int = 200) -> [Double] {
|
||||
let all: [Double] = collectBlocks(gen, engine: engine, blocks: blocks)
|
||||
return Array(all.suffix(engine.blockSize * 100))
|
||||
}
|
||||
|
||||
@Test func buildsNonSilentAndBounded() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 0.8)
|
||||
let stage: TriodeStage = TriodeStage(input: sine, drive: 2.0, bias: 0.2)
|
||||
let tail: [Double] = steadyTail(stage)
|
||||
#expect(tail.contains { abs($0) > 1.0e-4 }, "TriodeStage was silent")
|
||||
#expect(tail.allSatisfy { $0.isFinite }, "non-finite output")
|
||||
let peak: Double = tail.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "TriodeStage output not bounded near ±1: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func biasAddsEvenHarmonics() {
|
||||
// A symmetric (bias 0) tanh produces only odd harmonics → the 2nd harmonic is ~0.
|
||||
// Grid bias makes the transfer asymmetric → a real 2nd harmonic appears (tube warmth).
|
||||
let fundamental: Double = 1000.0
|
||||
func secondHarmonic(bias: Double) -> Double {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: fundamental, mul: 0.8)
|
||||
let stage: TriodeStage = TriodeStage(input: sine, drive: 3.0, bias: bias, oversample: 4)
|
||||
return goertzel(steadyTail(stage), cyclesPerSample: 2.0 * fundamental / sr)
|
||||
}
|
||||
let unbiased: Double = secondHarmonic(bias: 0.0)
|
||||
let biased: Double = secondHarmonic(bias: 0.5)
|
||||
#expect(biased > unbiased * 3.0, "bias did not add 2nd-harmonic content (biased=\(biased) unbiased=\(unbiased))")
|
||||
}
|
||||
|
||||
@Test func couplingBlocksDC() {
|
||||
// The output coupling (DC blocker) must remove the standing offset a biased stage adds
|
||||
// to a constant input — steady output decays to ~0.
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
|
||||
let stage: TriodeStage = TriodeStage(input: dc, drive: 2.0, bias: 0.3)
|
||||
let tail: [Double] = steadyTail(stage, blocks: 300)
|
||||
let meanAbs: Double = tail.reduce(0.0) { $0 + abs($1) } / Double(tail.count)
|
||||
#expect(meanAbs < 1.0e-3, "coupling did not block DC (meanAbs=\(meanAbs))")
|
||||
}
|
||||
|
||||
@Test func oversamplingReducesAliasing() {
|
||||
// 0.3·Fs driven hard: the odd harmonics (3·f0 = 0.9·Fs) fold to a 0.1·Fs alias at base
|
||||
// rate. Measure alias energy relative to the fundamental vs a naive base-rate stage.
|
||||
let fundamental: Double = 0.3 * sr
|
||||
let drive: Double = 3.0
|
||||
let pole: Double = 0.995
|
||||
let fundBin: Double = 0.3
|
||||
let aliasBin: Double = 0.1
|
||||
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: fundamental, mul: 0.9)
|
||||
let stage: TriodeStage = TriodeStage(input: sine, drive: drive, bias: 0.0, oversample: 4)
|
||||
let osTail: [Double] = steadyTail(stage)
|
||||
let osRatio: Double = goertzel(osTail, cyclesPerSample: aliasBin)
|
||||
/ goertzel(osTail, cyclesPerSample: fundBin)
|
||||
|
||||
// Naive base-rate reference: tanh(drive·x) then the same DC blocker, no oversampling.
|
||||
let cyclesPerSample: Double = fundamental / sr
|
||||
var naive: [Double] = [Double](repeating: 0.0, count: osTail.count)
|
||||
var x1: Double = 0.0
|
||||
var y1: Double = 0.0
|
||||
for n: Int in 0..<naive.count {
|
||||
let x: Double = 0.9 * sin(2.0 * Double.pi * cyclesPerSample * Double(n))
|
||||
let shaped: Double = tanh(drive * x)
|
||||
let y: Double = shaped - x1 + pole * y1
|
||||
x1 = shaped
|
||||
y1 = y
|
||||
naive[n] = y
|
||||
}
|
||||
let naiveRatio: Double = goertzel(naive, cyclesPerSample: aliasBin)
|
||||
/ goertzel(naive, cyclesPerSample: fundBin)
|
||||
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(osRatio < naiveRatio * 0.5, "oversampling did not reduce aliasing: os=\(osRatio) naive=\(naiveRatio)")
|
||||
}
|
||||
}
|
||||
@@ -105,7 +105,7 @@ File: `Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift`
|
||||
Delays the output by `lookAheadTime` seconds and uses the look-ahead window to detect peaks before they arrive, guaranteeing the output never exceeds `±maxAmplitude`. No overshoot.
|
||||
|
||||
```swift
|
||||
LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
|
||||
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||
```
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
@@ -113,6 +113,7 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
|
||||
| `in` | `ValidGeneratorInput` | — | Signal to limit |
|
||||
| `maxAmplitude` | `ValidGeneratorInput` | `1.0` | Peak ceiling (absolute value) |
|
||||
| `lookAheadTime` | `Double` | `0.005` | Delay in seconds. Set at init. |
|
||||
| `releaseTime` | `ValidGeneratorInput` | `0.050` | Gain-release time constant (seconds), read per block; decoupled from `lookAheadTime`. Clamped to ≥ 0. Keep it above the period of the lowest expected frequency to avoid low-frequency distortion. |
|
||||
| `sampleRate` | `Double` | `44100.0` | Used to size ring buffers at init. |
|
||||
|
||||
**Output:** single channel, delayed by `lookAheadSamples = Int(lookAheadTime × sampleRate)`.
|
||||
@@ -122,7 +123,7 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
|
||||
2. Scan the look-ahead window (`lookAheadSamples`) for peak.
|
||||
3. Required gain = `min(1, maxAmplitude / peak)`.
|
||||
4. Attack is **instantaneous** (gain can always be reduced within the window).
|
||||
5. Release smoothed: `releaseCoeff = exp(−1 / (sr × lookAheadTime))`.
|
||||
5. Release smoothed: `releaseCoeff = exp(−1 / (sr × releaseTime))`, recomputed per block (so `releaseTime` may track a live parameter) rather than fixed at init.
|
||||
6. Output = delayed sample × current gain.
|
||||
|
||||
**Pre-allocated buffers:**
|
||||
@@ -134,7 +135,8 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
|
||||
|
||||
**Usage:**
|
||||
```swift
|
||||
let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005)
|
||||
let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005,
|
||||
releaseTime: 0.050, sampleRate: engine.sampleRate)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -447,6 +447,20 @@ MuTronIII.Control(input: guitar, sensitivity: 1.0, peak: 3.0)
|
||||
- `attackTime` / `releaseTime`: Envelope time constants in seconds.
|
||||
- Companion types: `MuTronIIIMode`, `MuTronIIISweep`.
|
||||
|
||||
#### ToneStack
|
||||
Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender / Marshall / Vox EQ network, not three independent bands, so the controls load each other exactly as on the real amp. The selected model's continuous-time transfer function (Yeh & Smith closed form) is bilinear-discretized to a 3rd-order IIR; coefficients recompute only when a control changes. Audio-only, mono output.
|
||||
|
||||
```swift
|
||||
ToneStack(input: sig, bass: 0.6, mid: 0.4, treble: 0.7) // Fender (default)
|
||||
ToneStack(input: sig, bass: 0.5, mid: 0.7, treble: 0.5, model: .marshall)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `input`: Signal to filter.
|
||||
- `bass` / `mid` / `treble`: Controls in `[0, 1]` (clamped). Bass uses an exponential taper; mid/treble are linear. Default `0.5`.
|
||||
- `model`: `ToneStackModel` — `.fender` / `.marshall` / `.vox` (component values). Set at init. Default `.fender`.
|
||||
- Companion type: `ToneStackModel`.
|
||||
|
||||
---
|
||||
|
||||
### Envelopes
|
||||
@@ -2575,8 +2589,18 @@ Transfer-function and stochastic distortion generators. Source files live in
|
||||
| `Waveshaper` | `Shaper` | yes | yes | Table-lookup transfer-function waveshaper. Input clamped to `[-1, 1]` before linear-interpolated table lookup. RT-safe live table swap via `setTable(_:engine:)`. |
|
||||
| `CrossoverDistortion` | `CrossoverDistortion` | yes | yes | Dead-zone / crossover distortion. Signals in `[-amp, amp]` are silenced; signals outside that range are shifted toward zero. Optional C¹ smooth knee. |
|
||||
| `Disintegrator` | `Disintegrator` | yes | — | Stochastic sample-dropping distortion. Each sample is independently disintegrated (replaced by `input × multiplier`) with probability `probability`. Audio-only. |
|
||||
| `TriodeStage` | — | yes | — | Tube-style preamp stage: biased asymmetric `tanh` soft-clip (`drive` gain, `bias` grid offset → even harmonics), evaluated at 2×/4× oversampling, with an output coupling (DC-block) high-pass. Audio-only. |
|
||||
|
||||
`Waveshaper` and `CrossoverDistortion` conform to `GeneratorEnum`. `Disintegrator` is Audio-only and does not.
|
||||
`Waveshaper` and `CrossoverDistortion` conform to `GeneratorEnum`. `Disintegrator` and `TriodeStage` are Audio-only and do not.
|
||||
|
||||
### TriodeStage
|
||||
|
||||
A single tube preamp stage. A grid `bias` makes the `tanh` transfer asymmetric — generating even-order harmonics (single-ended tube warmth) and a program-dependent DC shift the output coupling removes. The nonlinearity is oversampled so its harmonics don't alias. A musically-voiced static waveshaper, not a SPICE circuit solve.
|
||||
|
||||
```swift
|
||||
TriodeStage(input: sig, drive: 3.0, bias: 0.3) // 4× oversampled (default)
|
||||
TriodeStage(input: sig, drive: 5.0, bias: 0.0, oversample: 2) // symmetric, 2×
|
||||
```
|
||||
|
||||
### Waveshaper (SC `Shaper`)
|
||||
|
||||
@@ -2636,3 +2660,44 @@ let det = Disintegrator.Audio(input: signal, probability: 0.5, seed: 42)
|
||||
- `mul` / `add`: applied after disintegration to all samples (including undisintegrated ones).
|
||||
|
||||
---
|
||||
|
||||
## Neural amp modeling
|
||||
|
||||
Real-time neural inference of guitar-amp/pedal captures. Source files live in
|
||||
`Sources/Lyrebird/Generators/Neural/`.
|
||||
|
||||
### LSTMAmp
|
||||
|
||||
Runs a single-layer LSTM amp capture one audio sample at a time — the GuitarML "Proteus" /
|
||||
NeuralPi topology (`LSTM(inputSize: 1, hiddenSize: H)` → `Linear(H, 1)`, optional input skip).
|
||||
Weights come from a `NeuralAmpModel` (a `Codable` weight container) and are copied into
|
||||
contiguous storage at init; the render path does only pre-allocated scalar math (no allocation
|
||||
or locks), costing `O(4·H²)` multiply-adds per sample, so keep `H` modest (Proteus captures are
|
||||
typically `H = 20…40`). Audio-only, mono. Does not clamp — a well-trained capture stays near
|
||||
`[-1, 1]`.
|
||||
|
||||
```swift
|
||||
let model = NeuralAmpModel(hiddenSize: 20, residual: true,
|
||||
weightIH: ih, weightHH: hh, biasIH: bih, biasHH: bhh,
|
||||
denseWeight: dw, denseBias: db)
|
||||
let amp = LSTMAmp(input: di, model: model)
|
||||
```
|
||||
|
||||
GuitarML Proteus / NeuralPi JSON models load via `ProteusModelImporter` (below). A binary NAM
|
||||
`.nam` importer remains a planned follow-up.
|
||||
|
||||
### ProteusModelImporter
|
||||
|
||||
Imports a GuitarML **Proteus / NeuralPi** model JSON (single-layer PyTorch LSTM, `unit_type`
|
||||
`"LSTM"`, `input_size`/`output_size` 1) into a `NeuralAmpModel` for `LSTMAmp`. The tensors flatten
|
||||
straight onto `NeuralAmpModel`'s layout (PyTorch gate order i,f,g,o); `skip == 1` → `residual`.
|
||||
Unsupported topologies or inconsistent tensor shapes throw.
|
||||
|
||||
```swift
|
||||
let data = try Data(contentsOf: modelURL) // a user-supplied .json
|
||||
let model = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
let amp = LSTMAmp(input: di, model: model)
|
||||
```
|
||||
|
||||
> Model files are **not** redistributed with Lyrebird — this only parses a file the user
|
||||
> supplies. GuitarML models are GPL-licensed; keep them out of MIT-licensed bundles.
|
||||
|
||||
@@ -49,7 +49,7 @@ Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't
|
||||
|
||||
| Template | Command | Description |
|
||||
|---|---|---|
|
||||
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime |
|
||||
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth. Notarization-ready: hardened runtime + `.entitlements` (audio-input) + mic usage string, unsandboxed for performance |
|
||||
| `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family |
|
||||
| `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) |
|
||||
|
||||
@@ -62,7 +62,7 @@ Each Xcode-project template lays out:
|
||||
│ └── xcshareddata/xcschemes/<name>.xcscheme
|
||||
├── <name>.xcworkspace/
|
||||
│ └── contents.xcworkspacedata (references <name>.xcodeproj)
|
||||
├── <name>/ (app target sources + Info.plist [+ entitlements for auv3])
|
||||
├── <name>/ (app target sources + Info.plist [+ .entitlements for macos-ui-xcode / auv3])
|
||||
│ └── ...
|
||||
└── <name>Extension/ (auv3 only — extension target + Info.plist + .entitlements)
|
||||
└── ...
|
||||
@@ -70,20 +70,26 @@ Each Xcode-project template lays out:
|
||||
|
||||
Lyrebird is pulled in via a remote SPM dependency on `https://realizedsound.mooo.com/josh/Lyrebird` (configurable via `ProjectScaffolder.lyrebirdPackageURL`). The scaffolded project lives anywhere on disk and does not need a local checkout.
|
||||
|
||||
### Microphone input — not pre-wired in any template
|
||||
### Distribution & microphone input
|
||||
|
||||
No template adds `NSMicrophoneUsageDescription` to the generated `Info.plist`, no template adds the hardened-runtime / sandbox audio-input capability, and the `ios-ui` template's `AVAudioSession` category is `.playback` (output only). Most pieces don't read live input, so the templates default to "no mic capability" rather than triggering a permission prompt on every first run.
|
||||
The `macos-ui-xcode` template is **notarization-ready and distributable for performance out of the box**. It ships:
|
||||
- **Hardened Runtime** enabled (required for Developer-ID notarization), and
|
||||
- `<name>.entitlements` granting `com.apple.security.device.audio-input`, plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||
|
||||
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph), the project owner must add these themselves:
|
||||
The app is deliberately **not sandboxed** — a live-performance app needs unrestricted audio-device / file / MIDI / OSC access that the App Sandbox would gate. Nothing else is required to move the signed `.app` to another machine and run it: Lyrebird is statically linked (compiled from the SPM source), so there is no external module to bundle. (The bundled-swiftmodule dance in `LyrebirdScratch` is unique to its *runtime* `swiftc` scratchpad and does not apply to a normal Lyrebird app.)
|
||||
|
||||
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver.
|
||||
The audio-input entitlement + usage string are **harmless for output-only synths**: no permission prompt fires until the AUHAL input bus actually opens (`numInputChannels > 0`). They exist so a piece that *does* take live input works without the OS hard-killing the Hardened-Runtime process on first input access.
|
||||
|
||||
**macOS** (`macos-ui-xcode`, `ui-demo` opened in Xcode, any AppKit/SwiftUI app):
|
||||
- Add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Required since macOS 10.14 — without it the OS silently denies input access and `CoreAudioDriver` reads zeros.
|
||||
- If the app is sandboxed: add `com.apple.security.device.audio-input` to the `.entitlements` file. The `macos-ui-xcode` template ships unsandboxed; the `auv3` host app is sandboxed and will need the entitlement before the host can read mic in addition to hosting the plugin.
|
||||
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph):
|
||||
|
||||
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver. On `macos-ui-xcode` the mic entitlement + usage string are already present, so the first `start()` after that triggers the permission prompt directly.
|
||||
|
||||
**Other knobs:**
|
||||
- **Mac App Store** target: add `com.apple.security.app-sandbox` to `<name>.entitlements` plus the specific resource entitlements the piece uses. (Sandboxing is off by default precisely because most performance work is Developer-ID / direct-distribution, not App Store.)
|
||||
- **Loading a differently-signed dynamic library** (a bundled `.dylib`): add `com.apple.security.cs.disable-library-validation`.
|
||||
|
||||
**iOS** (`ios-ui`):
|
||||
- Add `NSMicrophoneUsageDescription` to the app `Info.plist`.
|
||||
- Add `NSMicrophoneUsageDescription` to the app `Info.plist` (not pre-wired — the iOS template is output-only by default).
|
||||
- Change the `AVAudioSession` category in the generated `AppDelegate` / `App` activation block from `.playback` to `.playAndRecord` (typically `mode: .default` or `.measurement`, options `[.defaultToSpeaker, .allowBluetooth]` depending on routing needs). `.playback` is output-only and will return zero-filled input buffers regardless of the engine's `numInputChannels`.
|
||||
|
||||
The first `start()` call after these are in place triggers the system permission prompt. Until the user grants, input frames remain zero — a scope tap on input buses will draw a flat line.
|
||||
|
||||
@@ -460,64 +460,64 @@ docs/stdlib/dynamics.md 10 39990cca834ef94b none
|
||||
docs/stdlib/dynamics.md 11 5d1c9341b961abf3 none
|
||||
docs/stdlib/dynamics.md 3 18e5f09cf5013cc9 member
|
||||
docs/stdlib/generators.md 10 0d0d88baf0522e3b none
|
||||
docs/stdlib/generators.md 107 c5ce3d51f57142aa none
|
||||
docs/stdlib/generators.md 108 c5ce3d51f57142aa none
|
||||
docs/stdlib/generators.md 11 629f3ca37b259db8 none
|
||||
docs/stdlib/generators.md 12 902788477d67e7f4 none
|
||||
docs/stdlib/generators.md 120 565f622549fd3c38 none
|
||||
docs/stdlib/generators.md 123 1dd6b5c06b6ae556 none
|
||||
docs/stdlib/generators.md 124 5dcaf7fb2afc8dc2 none
|
||||
docs/stdlib/generators.md 126 411d623132b2b06c none
|
||||
docs/stdlib/generators.md 129 c28dc931674491ee engine
|
||||
docs/stdlib/generators.md 121 565f622549fd3c38 none
|
||||
docs/stdlib/generators.md 124 1dd6b5c06b6ae556 none
|
||||
docs/stdlib/generators.md 125 5dcaf7fb2afc8dc2 none
|
||||
docs/stdlib/generators.md 127 411d623132b2b06c none
|
||||
docs/stdlib/generators.md 13 67cc75d3eb9457c8 none
|
||||
docs/stdlib/generators.md 137 13470432dc7e4bd8 engine
|
||||
docs/stdlib/generators.md 138 6105618f7bf5ea7a engine
|
||||
docs/stdlib/generators.md 139 5c99a5185ecff98d engine
|
||||
docs/stdlib/generators.md 130 c28dc931674491ee engine
|
||||
docs/stdlib/generators.md 138 13470432dc7e4bd8 engine
|
||||
docs/stdlib/generators.md 139 6105618f7bf5ea7a engine
|
||||
docs/stdlib/generators.md 14 f8ee2300f36e16b0 none
|
||||
docs/stdlib/generators.md 140 087425f3135c84ff engine
|
||||
docs/stdlib/generators.md 140 5c99a5185ecff98d engine
|
||||
docs/stdlib/generators.md 141 087425f3135c84ff engine
|
||||
docs/stdlib/generators.md 16 1cadbc5e52b0ed19 none
|
||||
docs/stdlib/generators.md 161 5bd373d66ce35eba none
|
||||
docs/stdlib/generators.md 162 5bd373d66ce35eba none
|
||||
docs/stdlib/generators.md 17 1c7e9c58cf70ac8b none
|
||||
docs/stdlib/generators.md 18 62bb868ca02fccba none
|
||||
docs/stdlib/generators.md 31 674976c5b3d7e9dc none
|
||||
docs/stdlib/generators.md 33 6196c99aa22cfbfd none
|
||||
docs/stdlib/generators.md 34 58f37f05cdc8511b none
|
||||
docs/stdlib/generators.md 35 767c7e181286481f none
|
||||
docs/stdlib/generators.md 47 0b03884f890b5438 none
|
||||
docs/stdlib/generators.md 48 b1b1c7300f8f9abf none
|
||||
docs/stdlib/generators.md 49 44090861a5f3f0ab none
|
||||
docs/stdlib/generators.md 32 674976c5b3d7e9dc none
|
||||
docs/stdlib/generators.md 34 6196c99aa22cfbfd none
|
||||
docs/stdlib/generators.md 35 58f37f05cdc8511b none
|
||||
docs/stdlib/generators.md 36 767c7e181286481f none
|
||||
docs/stdlib/generators.md 48 0b03884f890b5438 none
|
||||
docs/stdlib/generators.md 49 b1b1c7300f8f9abf none
|
||||
docs/stdlib/generators.md 5 fe5eeb6b8c9468bc none
|
||||
docs/stdlib/generators.md 50 a5a4ceae4e8d0f04 member
|
||||
docs/stdlib/generators.md 53 11b583d435ae3fec none
|
||||
docs/stdlib/generators.md 56 4b324b59c6e2d036 engine
|
||||
docs/stdlib/generators.md 58 f03496e55afd8c09 member
|
||||
docs/stdlib/generators.md 50 44090861a5f3f0ab none
|
||||
docs/stdlib/generators.md 51 a5a4ceae4e8d0f04 member
|
||||
docs/stdlib/generators.md 54 11b583d435ae3fec none
|
||||
docs/stdlib/generators.md 57 4b324b59c6e2d036 engine
|
||||
docs/stdlib/generators.md 59 f03496e55afd8c09 member
|
||||
docs/stdlib/generators.md 6 6f95f2595f21269d none
|
||||
docs/stdlib/generators.md 63 4f73f9175480bb9d none
|
||||
docs/stdlib/generators.md 64 c95aba6700244981 none
|
||||
docs/stdlib/generators.md 65 1ad8a7a4bcf35578 none
|
||||
docs/stdlib/generators.md 66 3e128c4a0c0ed44f none
|
||||
docs/stdlib/generators.md 68 e68b3297e3811b06 none
|
||||
docs/stdlib/generators.md 64 4f73f9175480bb9d none
|
||||
docs/stdlib/generators.md 65 c95aba6700244981 none
|
||||
docs/stdlib/generators.md 66 1ad8a7a4bcf35578 none
|
||||
docs/stdlib/generators.md 67 3e128c4a0c0ed44f none
|
||||
docs/stdlib/generators.md 69 e68b3297e3811b06 none
|
||||
docs/stdlib/generators.md 7 e0fc33b99cfbfad3 none
|
||||
docs/stdlib/generators.md 70 4058bd1e443015c3 none
|
||||
docs/stdlib/generators.md 77 5b5368aaa517dfa7 none
|
||||
docs/stdlib/generators.md 78 ec2d381f2bb9b8ed none
|
||||
docs/stdlib/generators.md 79 d7340b239481a865 none
|
||||
docs/stdlib/generators.md 71 4058bd1e443015c3 none
|
||||
docs/stdlib/generators.md 78 5b5368aaa517dfa7 none
|
||||
docs/stdlib/generators.md 79 ec2d381f2bb9b8ed none
|
||||
docs/stdlib/generators.md 8 88db18751b293c9d none
|
||||
docs/stdlib/generators.md 81 73a12cfe64ff0f69 none
|
||||
docs/stdlib/generators.md 83 380ed79e0cdee46c none
|
||||
docs/stdlib/generators.md 84 5293eff3b9430f29 none
|
||||
docs/stdlib/generators.md 85 da9268f81a456ea6 none
|
||||
docs/stdlib/generators.md 86 9bf9cf3a6a2db438 none
|
||||
docs/stdlib/generators.md 87 dea487b351e98274 none
|
||||
docs/stdlib/generators.md 89 4fd57872628e530e none
|
||||
docs/stdlib/generators.md 80 d7340b239481a865 none
|
||||
docs/stdlib/generators.md 82 73a12cfe64ff0f69 none
|
||||
docs/stdlib/generators.md 84 380ed79e0cdee46c none
|
||||
docs/stdlib/generators.md 85 5293eff3b9430f29 none
|
||||
docs/stdlib/generators.md 86 da9268f81a456ea6 none
|
||||
docs/stdlib/generators.md 87 9bf9cf3a6a2db438 none
|
||||
docs/stdlib/generators.md 88 dea487b351e98274 none
|
||||
docs/stdlib/generators.md 9 d9220f1546ebb2fa none
|
||||
docs/stdlib/generators.md 90 f65e4bbe38e99cc8 none
|
||||
docs/stdlib/generators.md 91 c69991ded1dd3d6a none
|
||||
docs/stdlib/generators.md 92 e014ebea17d7fc65 none
|
||||
docs/stdlib/generators.md 93 c92ba501869bd44a none
|
||||
docs/stdlib/generators.md 94 8af8941e718f5611 none
|
||||
docs/stdlib/generators.md 95 17567f7a1d480962 none
|
||||
docs/stdlib/generators.md 96 f321afc74caaf987 none
|
||||
docs/stdlib/generators.md 97 1fa567c7e6d9eda1 none
|
||||
docs/stdlib/generators.md 90 4fd57872628e530e none
|
||||
docs/stdlib/generators.md 91 f65e4bbe38e99cc8 none
|
||||
docs/stdlib/generators.md 92 c69991ded1dd3d6a none
|
||||
docs/stdlib/generators.md 93 e014ebea17d7fc65 none
|
||||
docs/stdlib/generators.md 94 c92ba501869bd44a none
|
||||
docs/stdlib/generators.md 95 8af8941e718f5611 none
|
||||
docs/stdlib/generators.md 96 17567f7a1d480962 none
|
||||
docs/stdlib/generators.md 97 f321afc74caaf987 none
|
||||
docs/stdlib/generators.md 98 1fa567c7e6d9eda1 none
|
||||
docs/stdlib/granular.md 0 a2b73804b66ffb4e none
|
||||
docs/stdlib/multichannel.md 1 08e247ae6b98bf62 none
|
||||
docs/stdlib/multichannel.md 2 1420e89a6b21dffd member
|
||||
|
||||
Reference in New Issue
Block a user