NeuralAmpModeler-rs 3.0.1

An opinionated, high-performance Neural Amp Modeler (NAM) client and core implementation in Rust for Linux/PipeWire and CLAP plugins.
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Fábio Henrique de Lima Silva (fhl.bsb@gmail.com) All rights reserved.

//! Adaptive compute: soft-degrade sob CPU pressure (graceful fallback).
//!
//! Monitors DSP block latency and gracefully reduces model complexity
//! when CPU pressure is detected, preventing audible xruns.
//!
//! ## Cohesion justification
//!
//! This file is intentionally kept as a single module (not split) because:
//!
//! - `AdaptiveState` and `CrossfadePhase` are internal implementation details of
//!   the hysteresis FSM — exposing them in separate modules would break
//!   encapsulation of the adaptive compute unit.
//! - `AdaptiveComputeMode` is the sole user-facing configuration type driving the
//!   FSM behavior; it has zero consumers outside the adaptive degradation pipeline.
//! - All threshold constants (`THRESHOLD_*`, `DEGRADE_CONSECUTIVE`,
//!   `RECOVER_CONSECUTIVE`, `CROSSFADE_DURATION_MS`) are private and tightly
//!   coupled to `AdaptiveCompute::update()`.
//! - The entire module forms a single algorithmic unit (hysteresis FSM +
//!   crossfade + layer reduction) with no independent consumers for any
//!   sub-component.
//! - Splitting would create artificial module boundaries that increase cognitive
//!   overhead without enabling reuse, test isolation, or independent compilation.
//!
//! ## Hysteresis FSM
//!
//! - **Full → Reduced**: 3 consecutive blocks with `latency > 0.70 * budget` (Conservative)
//!   or `latency > 0.55 * budget` (Aggressive).
//! - **Reduced → Minimal**: 3 consecutive blocks with `latency > 0.85 * budget` (Conservative)
//!   or `latency > 0.70 * budget` (Aggressive).
//! - **Reverse path**: 5 consecutive blocks below recovery threshold.
//!
//! ## Crossfade
//!
//! 32 ms linear ramp between states to avoid audible artifacts.

use crate::common::spsc::RtStatusFlags;
use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::sync::atomic::Ordering;

/// Manual slim override — forces a fixed quality level, bypassing the FSM.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[repr(u8)]
pub enum SlimOverride {
    /// FSM decides quality level automatically.
    #[default]
    Auto = 0,
    /// Force full-quality processing regardless of CPU pressure.
    ForceFull = 1,
    /// Force lite (reduced) processing regardless of CPU pressure.
    ForceLite = 2,
}

impl SlimOverride {
    /// Creates a `SlimOverride` from a floating-point value.
    pub fn from_f32(val: f32) -> Self {
        match val.round() as i32 {
            1 => Self::ForceFull,
            2 => Self::ForceLite,
            _ => Self::Auto,
        }
    }
}

/// Adaptive compute mode — user-facing parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[repr(u8)]
pub enum AdaptiveComputeMode {
    /// Adaptive compute disabled (passthrough).
    #[default]
    Off = 0,
    /// Conservative threshold — late degradation.
    Conservative = 1,
    /// Aggressive threshold — early degradation.
    Aggressive = 2,
}

impl AdaptiveComputeMode {
    /// Creates an `AdaptiveComputeMode` from a floating-point value.
    pub fn from_f32(val: f32) -> Self {
        match val.round() as i32 {
            1 => Self::Conservative,
            2 => Self::Aggressive,
            _ => Self::Off,
        }
    }

    /// Converts the mode to its corresponding floating-point representation.
    pub fn to_f32(self) -> f32 {
        self as u8 as f32
    }
}

/// Degradation level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum AdaptiveState {
    /// Full processing — all model layers active.
    Full = 0,
    /// Reduced processing — fewer layers.
    Reduced = 1,
    /// Minimal processing — maximum reduction.
    Minimal = 2,
}

/// Crossfade phase between degradation stages.
///
/// Duration and progress are tracked by `crossfade_total` and `crossfade_elapsed`
/// on `AdaptiveCompute` directly; no payload is needed in the variant.
#[derive(Debug, Clone, Copy, PartialEq)]
enum CrossfadePhase {
    /// No crossfade in progress.
    Idle,
    /// Actively crossfading; see `crossfade_total` / `crossfade_elapsed`.
    Active,
}

/// Hysteresis-driven adaptive compute FSM.
///
/// Uses asymmetric hysteresis:
/// - Upgrade (degrade): 3 consecutive blocks above threshold.
/// - Downgrade (recover): 5 consecutive blocks below threshold.
pub struct AdaptiveCompute {
    /// Current degradation state.
    state: AdaptiveState,
    /// Previous degradation state (during crossfade).
    prev_state: AdaptiveState,
    /// Consecutive overload counter for degradation.
    overload_counter: u32,
    /// Consecutive underload counter for recovery.
    recovery_counter: u32,
    /// Crossfade phase.
    crossfade: CrossfadePhase,
    /// Current user mode.
    mode: AdaptiveComputeMode,
    /// Crossfade total samples (fixed duration for linear progress).
    crossfade_total: usize,
    /// Crossfade elapsed samples.
    crossfade_elapsed: usize,
    /// Manual slim override (Auto = FSM decides).
    slim_override: SlimOverride,
    /// Original (full-quality) channel count of the loaded WaveNet model.
    /// `None` until a WaveNet model is detected via `set_wavenet_full_ch`.
    wavenet_full_ch: Option<usize>,
    /// Current slimmable channel count of the active WaveNet model.
    /// Tracks the last value applied via `take_slimmable_rebuild`.
    wavenet_slim_ch_current: Option<usize>,
}

const DEGRADE_CONSECUTIVE: u32 = 3;
const RECOVER_CONSECUTIVE: u32 = 5;

const THRESHOLD_FULL_TO_REDUCED_CONSERVATIVE: f32 = 0.70;
const THRESHOLD_REDUCED_TO_MINIMAL_CONSERVATIVE: f32 = 0.85;
const THRESHOLD_FULL_TO_REDUCED_AGGRESSIVE: f32 = 0.55;
const THRESHOLD_REDUCED_TO_MINIMAL_AGGRESSIVE: f32 = 0.70;

/// Crossfade duration in samples at 48 kHz = 32 ms.
/// At other sample rates, this is scaled proportionally.
const CROSSFADE_DURATION_MS: f32 = 32.0;

impl AdaptiveCompute {
    /// Creates a new `AdaptiveCompute` instance with the given mode.
    #[cold]
    pub fn new(mode: AdaptiveComputeMode) -> Self {
        debug!("[Adaptive] FSM initialized: mode={:?}, state=Full", mode);
        Self {
            state: AdaptiveState::Full,
            prev_state: AdaptiveState::Full,
            overload_counter: 0,
            recovery_counter: 0,
            crossfade: CrossfadePhase::Idle,
            mode,
            crossfade_total: 0,
            crossfade_elapsed: 0,
            slim_override: SlimOverride::Auto,
            wavenet_full_ch: None,
            wavenet_slim_ch_current: None,
        }
    }

    /// Sets the user-facing adaptive compute mode.
    #[inline]
    pub fn set_mode(&mut self, mode: AdaptiveComputeMode, rt_status: &RtStatusFlags) {
        info!("[Adaptive] Mode changed to {:?}", mode);
        self.mode = mode;
        if mode == AdaptiveComputeMode::Off {
            self.state = AdaptiveState::Full;
            self.prev_state = AdaptiveState::Full;
            self.overload_counter = 0;
            self.recovery_counter = 0;
            self.crossfade = CrossfadePhase::Idle;
            self.crossfade_total = 0;
            self.crossfade_elapsed = 0;
            rt_status.clear_flag(crate::common::spsc::RT_STATUS_DEGRADE_REDUCED);
            rt_status.clear_flag(crate::common::spsc::RT_STATUS_DEGRADE_MINIMAL);
        }
    }

    /// Returns the current adaptive compute mode.
    pub fn mode(&self) -> AdaptiveComputeMode {
        self.mode
    }

    /// Sets the manual slim override, forcing a fixed quality level.
    #[inline]
    pub fn set_slim_override(&mut self, ov: SlimOverride) {
        info!("[Adaptive] Slim override: {:?}", ov);
        self.slim_override = ov;
    }

    /// Returns the current slim override.
    pub fn slim_override(&self) -> SlimOverride {
        self.slim_override
    }

    /// Returns the current degradation state of the FSM, respecting manual override.
    pub fn state(&self) -> AdaptiveState {
        match self.slim_override {
            SlimOverride::ForceFull => AdaptiveState::Full,
            SlimOverride::ForceLite => AdaptiveState::Reduced,
            SlimOverride::Auto => self.state,
        }
    }

    /// Returns the crossfade gain (`crossfade_elapsed / total`).
    /// `sample_rate` is used to compute the crossfade duration in samples.
    /// Returns the linear multiplier applied to the degradation path.
    /// Call this during the output stage.
    #[inline(always)]
    pub fn crossfade_multiplier(&mut self, _sample_rate: u32, frame_advance: usize) -> f32 {
        match self.crossfade {
            CrossfadePhase::Idle => {
                if self.state == AdaptiveState::Full {
                    0.0
                } else {
                    1.0
                }
            }
            CrossfadePhase::Active => {
                let total = self.crossfade_total;
                let progress = if total == 0 {
                    1.0
                } else {
                    (self.crossfade_elapsed as f32 / total as f32).min(1.0)
                };

                if self.crossfade_elapsed + frame_advance >= total {
                    self.crossfade = CrossfadePhase::Idle;
                    self.crossfade_elapsed = 0;
                    1.0
                } else {
                    self.crossfade_elapsed += frame_advance;
                    progress
                }
            }
        }
    }

    /// Returns `true` if a crossfade is in progress.
    #[inline(always)]
    pub fn is_crossfading(&self) -> bool {
        !matches!(self.crossfade, CrossfadePhase::Idle)
    }

    /// Feeds the FSM with the latest latency measurement.
    ///
    /// `latency_us` — processing time of this block in microseconds.
    /// `budget_us` — budget for this block in microseconds.
    /// `sample_rate` — sample rate for crossfade duration.
    pub fn update(
        &mut self,
        latency_us: u64,
        budget_us: u64,
        sample_rate: u32,
        rt_status: &RtStatusFlags,
    ) {
        if self.mode == AdaptiveComputeMode::Off
            || budget_us == 0
            || self.slim_override != SlimOverride::Auto
        {
            return;
        }

        let ratio = latency_us as f32 / budget_us as f32;
        let (full_to_reduced, reduced_to_minimal) = match self.mode {
            AdaptiveComputeMode::Conservative => (
                THRESHOLD_FULL_TO_REDUCED_CONSERVATIVE,
                THRESHOLD_REDUCED_TO_MINIMAL_CONSERVATIVE,
            ),
            AdaptiveComputeMode::Aggressive => (
                THRESHOLD_FULL_TO_REDUCED_AGGRESSIVE,
                THRESHOLD_REDUCED_TO_MINIMAL_AGGRESSIVE,
            ),
            AdaptiveComputeMode::Off => return,
        };

        let recovery_reduced = full_to_reduced * 0.5;
        let recovery_minimal = reduced_to_minimal * 0.5;

        match self.state {
            AdaptiveState::Full => {
                if ratio > full_to_reduced {
                    self.overload_counter = self.overload_counter.saturating_add(1);
                    self.recovery_counter = 0;
                    if self.overload_counter >= DEGRADE_CONSECUTIVE {
                        self.transition_to(AdaptiveState::Reduced, sample_rate, rt_status);
                    }
                } else {
                    self.overload_counter = 0;
                }
            }
            AdaptiveState::Reduced => {
                if ratio > reduced_to_minimal {
                    self.overload_counter = self.overload_counter.saturating_add(1);
                    self.recovery_counter = 0;
                    if self.overload_counter >= DEGRADE_CONSECUTIVE {
                        self.transition_to(AdaptiveState::Minimal, sample_rate, rt_status);
                    }
                } else if ratio < recovery_reduced {
                    self.recovery_counter = self.recovery_counter.saturating_add(1);
                    self.overload_counter = 0;
                    if self.recovery_counter >= RECOVER_CONSECUTIVE {
                        self.transition_to(AdaptiveState::Full, sample_rate, rt_status);
                        self.recovery_counter = 0;
                    }
                } else {
                    self.overload_counter = 0;
                    self.recovery_counter = 0;
                }
            }
            AdaptiveState::Minimal => {
                if ratio < recovery_minimal {
                    self.recovery_counter = self.recovery_counter.saturating_add(1);
                    if self.recovery_counter >= RECOVER_CONSECUTIVE {
                        self.transition_to(AdaptiveState::Reduced, sample_rate, rt_status);
                        self.recovery_counter = 0;
                    }
                } else {
                    self.recovery_counter = 0;
                }
            }
        }
    }

    fn transition_to(
        &mut self,
        new_state: AdaptiveState,
        sample_rate: u32,
        rt_status: &RtStatusFlags,
    ) {
        if self.state == new_state {
            return;
        }

        let current_progress = match self.crossfade {
            CrossfadePhase::Active if self.crossfade_total > 0 => {
                (self.crossfade_elapsed as f32 / self.crossfade_total as f32).min(1.0)
            }
            _ => 0.0,
        };

        if !matches!(self.crossfade, CrossfadePhase::Active) {
            self.prev_state = self.state;
        }
        self.state = new_state;
        self.overload_counter = 0;
        self.recovery_counter = 0;

        let crossfade_samples =
            (CROSSFADE_DURATION_MS / 1000.0 * sample_rate as f32).round() as usize;
        let new_total = crossfade_samples.max(1);
        self.crossfade = CrossfadePhase::Active;
        self.crossfade_total = new_total;
        self.crossfade_elapsed = (current_progress * new_total as f32).round() as usize;

        rt_status
            .degrade_transitions_total
            .fetch_add(1, Ordering::Relaxed);

        match new_state {
            AdaptiveState::Full => {
                rt_status.clear_flag(crate::common::spsc::RT_STATUS_DEGRADE_REDUCED);
                rt_status.clear_flag(crate::common::spsc::RT_STATUS_DEGRADE_MINIMAL);
            }
            AdaptiveState::Reduced => {
                rt_status.set_flag(crate::common::spsc::RT_STATUS_DEGRADE_REDUCED);
                rt_status.clear_flag(crate::common::spsc::RT_STATUS_DEGRADE_MINIMAL);
            }
            AdaptiveState::Minimal => {
                rt_status.set_flag(crate::common::spsc::RT_STATUS_DEGRADE_REDUCED);
                rt_status.set_flag(crate::common::spsc::RT_STATUS_DEGRADE_MINIMAL);
            }
        }
    }

    /// Fraction of WaveNet layers to skip: 0.0 (Full), 0.25 (Reduced), 0.50 (Minimal).
    pub fn wavenet_skip_fraction(&self) -> f32 {
        match self.state() {
            AdaptiveState::Full => 0.0,
            AdaptiveState::Reduced => 0.25,
            AdaptiveState::Minimal => 0.50,
        }
    }

    /// Effective number of WaveNet layers after reduction.
    #[inline(always)]
    pub fn wavenet_effective_layers(&self, total_layers: usize) -> usize {
        let skip = (total_layers as f32 * self.wavenet_skip_fraction()).round() as usize;
        total_layers.saturating_sub(skip).max(1)
    }

    /// Effective LSTM layers: 2 (Full), 1 (Reduced), 0 = passthrough (Minimal).
    pub fn lstm_effective_layers(&self, total_layers: usize) -> usize {
        match self.state() {
            AdaptiveState::Full => total_layers,
            AdaptiveState::Reduced => total_layers.min(1), // Keep at most 1
            AdaptiveState::Minimal => 0,                   // Passthrough
        }
    }

    /// Slimmable quality mapping for `SlimmableContainer` submodel selection.
    ///
    /// Returns a value in `[0.0, 1.0]` to be passed to `SlimmableModel::set_slimmable_size()`:
    /// - `Full` → `1.0` (highest-quality submodel — fallback, last in ordered list).
    /// - `Reduced` → `0.25` (mid-quality submodel — typically A2-Lite for 2-model containers).
    /// - `Minimal` → `0.0` (cheapest submodel — first in ordered list).
    ///
    /// For a typical 2-model container (Lite threshold 0.5, Full threshold 1.0):
    /// - `1.0` selects the Full model (≥0.5, falls through to last).
    /// - `0.25` selects the Lite model (<0.5, hits first threshold).
    /// - `0.0` selects the Lite model (<0.5).
    ///
    /// The container's internal threshold logic (`val < max_value`) picks the first
    /// submodel whose `max_value` is strictly greater than `val`.
    pub fn slimmable_size(&self) -> f32 {
        match self.slim_override {
            SlimOverride::ForceFull => 1.0,
            SlimOverride::ForceLite => 0.25,
            SlimOverride::Auto => match self.state {
                AdaptiveState::Full => 1.0,
                AdaptiveState::Reduced => 0.25,
                AdaptiveState::Minimal => 0.0,
            },
        }
    }

    /// Target channel count for WaveNet slimming, based on FSM state + override.
    ///
    /// Maps the adaptive degradation level to a fraction of the original channels:
    /// - `Full` → 100% (no reduction).
    /// - `Reduced` → 75% (3/4 of original channels).
    /// - `Minimal` → 50% (1/2 of original channels).
    /// - `ForceFull` → 100%, `ForceLite` → 75%.
    ///
    /// Clamped to `[4, original_ch]` (4 is the minimum viable channel count).
    pub fn wavenet_slimmable_ch_target(&self) -> Option<usize> {
        let original = self.wavenet_full_ch?;
        let fraction = match self.slim_override {
            SlimOverride::ForceFull => 1.0,
            SlimOverride::ForceLite => 0.75,
            SlimOverride::Auto => match self.state {
                AdaptiveState::Full => 1.0,
                AdaptiveState::Reduced => 0.75,
                AdaptiveState::Minimal => 0.50,
            },
        };
        let target = (original as f32 * fraction).round() as usize;
        Some(target.max(4).min(original))
    }

    /// Records the full-quality channel count of the currently loaded WaveNet model.
    ///
    /// Must be called once when a WaveNet model is first detected (cold load or
    /// initial `configure_adaptive_model`). Subsequent slimmable rebuilds update
    /// `wavenet_slim_ch_current` via `take_slimmable_rebuild`.
    pub fn set_wavenet_full_ch(&mut self, ch: usize) {
        info!("[Adaptive] WaveNet full channels set to {}", ch);
        self.wavenet_full_ch = Some(ch);
        self.wavenet_slim_ch_current = Some(ch);
    }

    /// Returns `Some(target_ch)` if a WaveNet slimmable rebuild is needed,
    /// i.e., the FSM/override demands a different channel count than what's
    /// currently loaded. Clears the pending flag and updates tracking.
    ///
    /// Must be called **before** DSP (in `process_events` / `receive_commands`)
    /// to perform the allocation-intensive `slice_channels` off the hot-path.
    pub fn take_slimmable_rebuild(&mut self) -> Option<usize> {
        let target = self.wavenet_slimmable_ch_target()?;
        let current = self.wavenet_slim_ch_current?;
        if current != target && target >= 4 {
            self.wavenet_slim_ch_current = Some(target);
            Some(target)
        } else {
            None
        }
    }

    /// Returns the previous degradation state.
    #[inline(always)]
    pub fn prev_state(&self) -> AdaptiveState {
        self.prev_state
    }

    /// Returns the current crossfade gain (`crossfade_elapsed / total`) without side effects.
    #[inline(always)]
    pub fn current_crossfade_multiplier(&self) -> f32 {
        match self.crossfade {
            CrossfadePhase::Idle => {
                if self.state() == AdaptiveState::Full {
                    0.0
                } else {
                    1.0
                }
            }
            CrossfadePhase::Active => {
                let total = self.crossfade_total;
                if total == 0 {
                    1.0
                } else {
                    (self.crossfade_elapsed as f32 / total as f32).min(1.0)
                }
            }
        }
    }

    /// Returns the fraction of WaveNet layers to skip for a given state: 0.0 (Full), 0.25 (Reduced), 0.50 (Minimal).
    #[inline(always)]
    pub fn wavenet_skip_fraction_for_state(&self, state: AdaptiveState) -> f32 {
        match state {
            AdaptiveState::Full => 0.0,
            AdaptiveState::Reduced => 0.25,
            AdaptiveState::Minimal => 0.50,
        }
    }

    /// Effective number of WaveNet layers after reduction for a given state, respecting overrides.
    #[inline(always)]
    pub fn wavenet_effective_layers_for_state(
        &self,
        state: AdaptiveState,
        total_layers: usize,
    ) -> usize {
        let state_to_use = match self.slim_override {
            SlimOverride::ForceFull => AdaptiveState::Full,
            SlimOverride::ForceLite => AdaptiveState::Reduced,
            SlimOverride::Auto => state,
        };
        let skip = (total_layers as f32 * self.wavenet_skip_fraction_for_state(state_to_use))
            .round() as usize;
        total_layers.saturating_sub(skip).max(1)
    }
}

#[cfg(test)]
#[path = "adaptive_test.rs"]
mod adaptive_test;