1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Fábio Henrique de Lima Silva (fhl.bsb@gmail.com) All rights reserved.
//! # Neural Amp Modeler (NAM-rs) — DSP Core Library
//!
//! **NeuralAmpModeler-rs** is the pure DSP kernel for high-performance,
//! real-time inference of [Neural Amp Modeler (NAM)](https://www.neuralampmodeler.com/)
//! neural network models (WaveNet A1 and A2, LSTM, ConvNet, Linear) and
//! impulse response (.wav) convolutions.
//!
//! This is an independent public library for the wider audio and Rust
//! communities. Its APIs and policies are host-agnostic: no particular
//! application, audio backend, plugin format, or downstream consumer owns
//! its architecture. Integration-specific behavior belongs in downstream
//! crates.
//!
//! The library provides:
//! - **SIMD-Accelerated Inference Kernels**: Native `x86-64-v3` (AVX2 + FMA)
//! and `AVX-512` math routines.
//! - **Flexible Model Loader**: Parser and builder for `.nam` (JSON) and
//! `.namb` (binary profile) files.
//! - **Lock-Free DSP Engine**: Zero heap allocations on the audio
//! processing hot-path.
//!
//! ---
//!
//! ## 🛠 Feature Flags & Recommended Dependency Setup
//!
//! > ⚠️ **Important for Library Integrators:**
//! > By default no feature flags are enabled. Enable only what you need.
//!
//! ### `Cargo.toml` Configuration Examples
//!
//! **Pure Core DSP & Model Inference:**
//! ```toml
//! [dependencies]
//! NeuralAmpModeler-rs = "0.1.0"
//! ```
//!
//! **Adding Off-RT Testing & Audio Signal Generators:**
//! ```toml
//! [dependencies]
//! NeuralAmpModeler-rs = { version = "0.1.0", features = ["testing"] }
//! ```
//!
//! ### Feature Flags Summary Table
//!
//! | Feature Flag | Default | Description |
//! |:------------ |:-------:|:------------------------------------------------------------------ |
//! | `stereo` | No | Enables multi-channel / stereo dual-model loader support. |
//! | `testing` | No | Exposes off-RT test utilities, audio signal generators, and |
//! | | | perceptual metrics (`testing` module). |
//! | `heap-audit` | No | Enables heap-allocation auditing infrastructure. |
//! | `long_bench` | No | Enables long-form inference benchmarks. |
//! | `pgo` | No | Build with PGO (Profile-Guided Optimization) support. |
//!
//! ---
//!
//! ## 🚀 Quick Start — Loading & Building a Model
//!
//! The [`loader::load_and_build_model`] function reads `.nam` (JSON) or
//! `.namb` (binary) files and constructs optimized [`models::StaticModel`]
//! instances ready for real-time execution.
//!
//! ```no_run
//! use std::path::Path;
//! use neural_amp_modeler_rs::loader::{load_and_build_model, LoadOptions};
//! use neural_amp_modeler_rs::SystemSnapshot;
//!
//! // Capture system capabilities (SIMD feature set, CPU topology)
//! let sys = SystemSnapshot::capture();
//!
//! // Load a model file (.nam or .namb)
//! let model_pair = load_and_build_model(
//! Path::new("path/to/model.nam"),
//! &sys,
//! false, // mono execution (set true for stereo)
//! LoadOptions::default(),
//! )
//! .expect("Failed to load model");
//!
//! println!("Loaded {} model", model_pair.architecture);
//! assert!(model_pair.model_l.is_some());
//! assert!(model_pair.model_r.is_none()); // Mono load: right channel is None
//! assert!(model_pair.sample_rate > 0);
//! ```
//!
//! ---
//!
//! ## ⚡ FastMath & SIMD Vector Activations
//!
//! High-performance scalar activation functions are available directly in
//! [`math::activations`]:
//!
//! ```rust
//! use neural_amp_modeler_rs::math::activations::{tanh, sigmoid};
//!
//! // Padé [5,4] rational approximant, clamped to [-1.0, 1.0]
//! let t = tanh(1.0);
//! assert!((t - 0.761594).abs() < 1e-3);
//! assert!(tanh(10.0) <= 1.0);
//! assert!(tanh(-10.0) >= -1.0);
//!
//! // Degree-17 minimax polynomial, clamped to [0.0, 1.0]
//! let s = sigmoid(0.0);
//! assert!((s - 0.5).abs() < 1e-2);
//! assert!(sigmoid(10.0) > 0.999);
//! assert!(sigmoid(-10.0) < 0.001);
//! ```
//!
//! For slice-based processing that automatically selects vectorized SIMD
//! kernels (AVX2/AVX-512), use `tanh_slice` and `sigmoid_slice` from
//! [`math::activations`].
//!
//! ---
//!
//! ## 🗺 Crate Module Map
//!
//! | Module | Purpose | Key Entry Points & Types |
//! |:---------- |:-------------------------------------------------- |:------------------------------------------------------ |
//! | [`loader`] | Model deserialization & construction (`.nam`, | [`loader::load_and_build_model`], |
//! | | `.namb`) | [`loader::LoadOptions`] |
//! | [`math`] | Mathematical primitives, SIMD kernels, & | [`math::activations`] |
//! | | activations | |
//! | [`models`] | Neural network architectures & static topologies | [`models::StaticModel`], WaveNet, LSTM, ConvNet |
//! | [`dsp`] | Digital signal processing engine & oversampling | [`dsp::gate::GateParams`], |
//! | | | [`dsp::oversample::OversampleEngine`] |
//! | [`common`] | Diagnostics, atomic bitmasks, & SPSC queues | [`common::RtStatusFlags`], |
//! | | | [`common::alloc_audit`] |
//! | `testing` | Off-RT test utilities & perceptual metrics | Audio validation and f64 Oracles |
//! | | (requires `testing`) | |
//!
//! ---
//!
//! ## 🛡 Real-Time Safety & Performance Guarantees
//!
//! NeuralAmpModeler-rs is engineered for **absolute real-time safety** on
//! the audio processing thread (`SCHED_FIFO`). The following guarantees
//! are enforced at the architecture level:
//!
//! ### 1. Zero Heap Allocations on Hot-Path
//! Heap objects (`Box`, `Vec`, `Arc`, `String`) are **never** allocated or
//! dropped on the real-time audio thread. All dynamic resources are
//! allocated off-RT and swapped via lock-free SPSC channels
//! ([`common::spsc`]). Compile-time allocation auditing is available via
//! [`common::alloc_audit`].
//!
//! ### 2. Zero Blocking I/O
//! No `println!`, `eprintln!`, `format!`, file I/O, or blocking
//! synchronization primitives are permitted on the RT thread. State
//! transitions are signaled atomically via [`common::RtStatusFlags`].
//!
//! ### 3. Denormal Protection (FTZ + DAZ)
//! Subnormal (denormal) floating-point numbers cause severe performance
//! degradation (up to 100× slowdown). NeuralAmpModeler-rs configures
//! **Flush-To-Zero (FTZ)** and **Denormals-Are-Zero (DAZ)** at
//! initialization and periodically reasserts them on the hot path
//! ([`math::common::set_daz_ftz`]).
//!
//! ### 4. Panic-Free Hot Path
//! Stack unwinding (panics) breaks hard real-time determinism. Processing
//! hot paths avoid `unwrap()`/`expect()` in favor of explicit fallback
//! bounds checks.
//!
//! ### 5. Lock-Free Cache-Isolated Concurrency
//! Shared structures RT ↔ Main use `#[repr(align(128))]` to eliminate
//! false sharing on CPU cache lines. Inter-thread SPSC buffers use
//! `Acquire`/`Release` atomic ordering.
//!
//! ---
//!
//! ## 📜 License
//!
//! Licensed under the **Apache License, Version 2.0**.
//! Official repository: <https://github.com/fabiohl/NeuralAmpModeler-rs>
compile_error!;
compile_error!;
pub use *;
// Backward compatibility with older GLIBC versions (e.g. for Flatpak/Bitwig).
// Redirects math symbols to the stable GLIBC_2.2.5 version.
// Since external dependencies use these symbols, we declare global wrappers
// that intercept calls and jump (jmp) via PLT to the compatible versions.
global_asm!;