NeuralAmpModeler-rs 3.1.0

An opinionated, high-performance Neural Amp Modeler (NAM) client and core implementation in Rust for Linux/PipeWire and CLAP plugins.
Documentation
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Fábio Henrique de Lima Silva (fhl.bsb@gmail.com) All rights reserved.

//! CLAP audio processor.
//!
//! Submodules:
//! - `events`: SPSC event drainage (Main Thread → Audio Thread) and host events.
//! - `dsp`: DSP block proper (gate, inference, resampling, output).
//! - `state`: Processor struct definition.
//! - `gc`: Garbage collection (safe disposal from audio thread).

mod deactivated;
mod dsp;
mod events;
mod gc;
#[cfg(feature = "heap-audit")]
mod heap_audit;
mod params;
mod rollback;
mod state;

pub(crate) use deactivated::DeactivatedDspState;
pub(crate) use state::NamClapProcessor;

use crate::clap::plugin::{CommandConsumer, NamClapMainThread, NamClapShared};
use crate::common::params::RtPluginParams;
#[cfg(target_arch = "x86_64")]
use crate::common::tsc::rdtsc_nanos;
use crate::dsp::adaptive::AdaptiveCompute;
use crate::dsp::gate::{DynamicHysteresis, GateParams};
use crate::dsp::oversample::{OversampleEngine, OversampleFactor};
use crate::dsp::pipeline::MAX_RESAMP_BUF;
use crate::dsp::resampler::NamResampler;
use crate::dsp::smoother::ParamSmoother;
use crate::math::common::AlignedVec;
use crate::math::dsp::gain_lut::get_gain_lut;
use clack_plugin::prelude::*;
use std::sync::Arc;
use std::sync::atomic::Ordering;

/// Converts a panic payload into `PluginError` for `catch_unwind` guards (S5-E5-T03).
///
/// The panic hook has already written the full crash report to
/// `~/.cache/nam-rs/crash-*.txt`. This function extracts a human-readable
/// message from the payload so the host can display it.
#[cold]
fn panic_to_error(panic_info: Box<dyn std::any::Any + Send>) -> PluginError {
    if let Some(s) = panic_info.downcast_ref::<String>() {
        PluginError::Message(Box::leak(s.clone().into_boxed_str()))
    } else if let Some(s) = panic_info.downcast_ref::<&str>() {
        PluginError::Message(Box::leak(s.to_string().into_boxed_str()))
    } else {
        PluginError::Message("Plugin panicked — crash report saved to ~/.cache/nam-rs/")
    }
}

/// Note: the entire `PluginAudioProcessor` impl must live in a single block
/// (Rust E0119 — trait impls cannot be split across modules).
impl<'a> PluginAudioProcessor<'a, NamClapShared, NamClapMainThread<'a>> for NamClapProcessor<'a> {
    /// `activate` is the ONLY allocation site — kept out of `process`.
    fn activate(
        host: HostAudioProcessorHandle<'a>,
        main_thread: &mut NamClapMainThread<'a>,
        shared: &'a NamClapShared,
        audio_config: PluginAudioConfiguration,
    ) -> Result<Self, PluginError> {
        // S5-E5-T03: catch panics from this instance so they don't
        // crash the host or other active instances.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            #[cfg(feature = "heap-audit")]
            {
                if std::env::var("NAM_HEAP_AUDIT").is_ok() {
                    crate::common::alloc_audit::AUDIT_ENABLED.store(true, Ordering::Relaxed);
                }
            }
            // 1. SPSC channel extraction from Shared (ownership transfer)
            // S1-E1-T04: extracted resources are held in a rollback guard.
            // If any later allocation fails, Drop restores everything into ColdShared.
            let param_rx = shared
                .cold
                .param_rx
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .take()
                .ok_or_else(|| {
                    PluginError::Message("param_rx consumer has already been extracted")
                })?;

            let mut rollback = rollback::ActivateRollbackGuard::new(shared);
            rollback.param_rx = Some(param_rx);

            let gc_tx = shared
                .cold
                .gc_tx
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .take()
                .ok_or_else(|| PluginError::Message("gc_tx producer has already been extracted"))?;
            rollback.gc_tx = Some(gc_tx);

            let slimmable_rx = shared
                .cold
                .slimmable_rx
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .take()
                .ok_or_else(|| {
                    PluginError::Message("slimmable_rx consumer has already been extracted")
                })?;
            rollback.slimmable_rx = Some(slimmable_rx);

            // 2. Intermediate buffer pre-allocation (Disjoint Stages)
            let buf_capacity = (audio_config.max_frames_count as usize)
                .max(MAX_RESAMP_BUF)
                .max(1024)
                * 2;
            let buf_host_l = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of host buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_host_r = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of host buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_mid_l = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of mid buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_mid_r = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of mid buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_model_l = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of model buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_model_r = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of model buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_out_l = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of output buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;
            let buf_out_r = AlignedVec::new(buf_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of output buffer failed: {e:?}").into_boxed_str(),
                ))
            })?;

            // 2b. Oversample buffer pre-allocation (MAX_RESAMP_BUF * 4 for X4)
            let os_capacity = MAX_RESAMP_BUF * 4;
            let buf_os_in_l = AlignedVec::new(os_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of oversample input buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;
            let buf_os_in_r = AlignedVec::new(os_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of oversample input buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;
            let buf_os_model_l = AlignedVec::new(os_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of oversample model buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;
            let buf_os_model_r = AlignedVec::new(os_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of oversample model buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;

            // 2c. Bypass crossfade dry storage (one sub-block of input samples, max_frames_count).
            let xfade_capacity = audio_config.max_frames_count as usize;
            let buf_xfade_dry_l = AlignedVec::new(xfade_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of bypass xfade dry buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;
            let buf_xfade_dry_r = AlignedVec::new(xfade_capacity, 0.0f32).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!("pre-allocation of bypass xfade dry buffer failed: {e:?}")
                        .into_boxed_str(),
                ))
            })?;

            // 3. DSP component initialization
            let model_rate = shared.cold.model_sample_rate.load(Ordering::Relaxed);
            let model_rate = if model_rate == 0 { 48000 } else { model_rate };
            let host_rate = audio_config.sample_rate as u32;
            let host_buffer = audio_config.max_frames_count;

            // S1-E1-T01: Restore heavy DSP resources from DeactivatedDspState if
            // available, validating sample rate and buffer size invariants. Model
            // weights are always reusable; resampler and conv-engine require
            // matching audio configuration.
            //
            // S1-E1-T04: DeactivatedDspState is extracted into the rollback guard
            // immediately after `.take()`. If any later allocation fails, the
            // guard restores it — avoiding loss of expensive model/engine state.
            rollback.deactivated = shared
                .cold
                .deactivated_dsp
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .take();
            let deactivated = rollback.deactivated.take();

            // S4-E4-T02: Resolve the oversampling factor for this activation.
            // Priority: pending restart > UiToRt atomic > Off (fresh).
            let os_factor = {
                let pending = shared
                    .cold
                    .pending_restart_os_factor
                    .swap(0, Ordering::Acquire);
                if pending != 0 {
                    OversampleFactor::from_f32(pending as f32)
                } else {
                    OversampleFactor::from_f32(
                        shared.ui_to_rt.param_oversample.load(Ordering::Relaxed) as f32,
                    )
                }
            };

            let (
                model_l,
                resampler,
                os_l,
                os_r,
                cabsim_adapter,
                model_input_mult_adj,
                model_output_mult_adj,
            ) = if let Some(deact) = deactivated {
                let rate_matches = deact.sample_rate == host_rate;
                let buf_matches = deact.buffer_size == host_buffer;

                // Resampler: reuse only if host sample rate matches the preserved rate.
                let resampler = if rate_matches {
                    deact.resampler
                } else {
                    Box::new(
                        NamResampler::new(host_rate, model_rate, buf_capacity).map_err(|e| {
                            PluginError::Message(Box::leak(
                                format!("Failed to create NamResampler: {:?}", e).into_boxed_str(),
                            ))
                        })?,
                    )
                };

                // CabSimAdapter: rebuild if buffer size OR sample rate changed.
                // Rate changes require resampling ir_raw_samples to the new host rate.
                let cabsim_adapter =
                    if deact.cabsim_adapter.is_some() && (!buf_matches || !rate_matches) {
                        #[cfg(any(feature = "standalone", feature = "clap-plugin", test))]
                        {
                            build_cab_sim_from_raw_samples(
                                shared,
                                audio_config.max_frames_count as usize,
                                host_rate,
                            )?
                        }
                        #[cfg(not(any(feature = "standalone", feature = "clap-plugin", test)))]
                        {
                            None
                        }
                    } else {
                        deact.cabsim_adapter
                    };

                // Oversample engines: reuse only if the factor hasn't changed
                // (structural change → rebuild). Otherwise rebuild for the resolved
                // factor (S4-E4-T02).
                let os_l = if deact.os_factor == os_factor {
                    deact.os_l
                } else {
                    Box::new(
                        OversampleEngine::new(os_factor, MAX_RESAMP_BUF).map_err(|e| {
                            PluginError::Message(Box::leak(
                                format!("Failed to create oversample engine (L): {:?}", e)
                                    .into_boxed_str(),
                            ))
                        })?,
                    )
                };
                let os_r = if deact.os_factor == os_factor {
                    deact.os_r
                } else {
                    Box::new(
                        OversampleEngine::new(os_factor, MAX_RESAMP_BUF).map_err(|e| {
                            PluginError::Message(Box::leak(
                                format!("Failed to create oversample engine (R): {:?}", e)
                                    .into_boxed_str(),
                            ))
                        })?,
                    )
                };

                // Model weights: always reusable (independent of rates/buffers).
                (
                    deact.model_l,
                    resampler,
                    os_l,
                    os_r,
                    cabsim_adapter,
                    deact.model_input_mult_adj,
                    deact.model_output_mult_adj,
                )
            } else {
                // Fresh build: construct all DSP resources from scratch.
                let resampler = Box::new(
                    NamResampler::new(host_rate, model_rate, buf_capacity).map_err(|e| {
                        PluginError::Message(Box::leak(
                            format!("Failed to create NamResampler: {:?}", e).into_boxed_str(),
                        ))
                    })?,
                );

                #[cfg(any(feature = "standalone", feature = "clap-plugin", test))]
                let cabsim_adapter = {
                    build_cab_sim_from_raw_samples(
                        shared,
                        audio_config.max_frames_count as usize,
                        host_rate,
                    )?
                };
                #[cfg(not(any(feature = "standalone", feature = "clap-plugin", test)))]
                let cabsim_adapter = None;

                let os_l = Box::new(OversampleEngine::new(os_factor, MAX_RESAMP_BUF).map_err(
                    |e| {
                        PluginError::Message(Box::leak(
                            format!("Failed to create oversample engine (L): {:?}", e)
                                .into_boxed_str(),
                        ))
                    },
                )?);
                let os_r = Box::new(OversampleEngine::new(os_factor, MAX_RESAMP_BUF).map_err(
                    |e| {
                        PluginError::Message(Box::leak(
                            format!("Failed to create oversample engine (R): {:?}", e)
                                .into_boxed_str(),
                        ))
                    },
                )?);

                (None, resampler, os_l, os_r, cabsim_adapter, 1.0, 1.0)
            };

            let silence_hyst = DynamicHysteresis::new();
            let mono_hyst = DynamicHysteresis::new();

            // 4. Smoother initialization (Sample-Accurate)
            // Warm reset from shared atomics to avoid transient jump on reactivation
            // when gain differs from 0 dB (1.0).
            let gain_lut = get_gain_lut();
            let input_db = f32::from_bits(shared.ui_to_rt.param_input_gain.load(Ordering::Relaxed));
            let output_db =
                f32::from_bits(shared.ui_to_rt.param_output_gain.load(Ordering::Relaxed));
            let smoother_in = ParamSmoother::new(
                gain_lut.db_to_linear(input_db),
                audio_config.sample_rate as f32,
                20.0,
            );
            let smoother_out = ParamSmoother::new(
                gain_lut.db_to_linear(output_db),
                audio_config.sample_rate as f32,
                20.0,
            );

            // S1-E1-T03: Build an atomic snapshot for params that drive smoothers
            // from UiToRt atomics BEFORE constructing the RT processor. This
            // guarantees that self.params starts in sync with the smoother state
            // (both read from the same gain atomics) — no one-block window where
            // params.input_gain_db lags behind smoother_in.target.
            //
            // Non-smoother params (gate, bypass, adaptive_compute, etc.) are left
            // at their defaults and will be synced on the first process events
            // call (SPSC drain or GUI generation guard). Full-param snapshot
            // would trigger AdaptiveCompute::set_mode log on audio thread when
            // values differ from SPSC-delivered state — a pre-existing log-on-RT
            // violation tracked as S5-E5-T02.
            let params = RtPluginParams {
                input_gain_db: input_db,
                output_gain_db: output_db,
                oversample: os_factor,
                ..RtPluginParams::default()
            };
            debug_assert!(
                (smoother_in.current_value() - gain_lut.db_to_linear(params.input_gain_db)).abs()
                    < f32::EPSILON * 10.0,
                "S1-E1-T03 invariant: smoother_in must start from the same input_gain_db atomics"
            );
            debug_assert!(
                (smoother_out.current_value() - gain_lut.db_to_linear(params.output_gain_db)).abs()
                    < f32::EPSILON * 10.0,
                "S1-E1-T03 invariant: smoother_out must start from the same output_gain_db atomics"
            );

            // 5. Report initial latency to shared state
            let mut initial_latency = resampler.latency_samples(audio_config.sample_rate as u32);
            initial_latency += os_l.latency_samples() as u32;
            #[cfg(any(feature = "standalone", feature = "clap-plugin", test))]
            {
                if let Some(ref adapter) = cabsim_adapter {
                    initial_latency += adapter.latency_samples() as u32;
                }
            }
            shared
                .rt_to_ui
                .current_latency
                .store(initial_latency, Ordering::Relaxed);
            shared
                .cold
                .sample_rate
                .store(audio_config.sample_rate as u32, Ordering::Relaxed);
            shared
                .cold
                .buffer_size
                .store(audio_config.max_frames_count, Ordering::Relaxed);

            // F3: flush any model deferred by load_model() (state-restore-before-activate).
            // This calls set_max_buffer_size on the main thread before process() starts.
            main_thread.flush_pending_model()?;

            // S1-E1-T04: defuse the rollback guard — transfers SPSC channel
            // ownership back for processor construction. Guard Drop is now a no-op.
            let channels = rollback.defuse();

            let cmd_consumer = CommandConsumer::new(channels.param_rx, &shared.cold.cmd_last_ack);

            let cabsim_tail_initial = cabsim_adapter.as_ref().map_or(0, |a| a.tail_samples());

            Ok(Self {
                model_l,
                cabsim_adapter,
                resampler,
                os_l,
                os_r,
                params,
                buf_host_l,
                buf_host_r,
                buf_mid_l,
                buf_mid_r,
                buf_model_l,
                buf_model_r,
                buf_out_l,
                buf_out_r,
                buf_os_in_l,
                buf_os_in_r,
                buf_os_model_l,
                buf_os_model_r,
                buf_xfade_dry_l,
                buf_xfade_dry_r,
                silence_hyst,
                mono_hyst,
                process_mono: true,
                scheduled_events: Vec::with_capacity(4096),
                bypass_xfade: state::BypassCrossfader::new(params.bypass),
                rt_status: Arc::clone(&shared.cold.rt_status),
                adaptive_compute: AdaptiveCompute::new(
                    crate::common::params::AdaptiveComputeMode::Conservative,
                ),
                shared,
                smoother_in,
                smoother_out,
                model_input_mult_adj,
                model_output_mult_adj,
                cmd_consumer,
                gc_tx: channels.gc_tx,
                slimmable_rx: channels.slimmable_rx,
                gc_overflow: Arc::clone(&shared.cold.gc_overflow),
                parking_lot: Default::default(),
                mod_input_gain: 0.0,
                mod_output_gain: 0.0,
                mod_gate_thresh: 0.0,
                cached_threshold_open_sq: 0.0,
                cached_threshold_close_sq: 0.0,
                cached_gate_params: GateParams::default(),
                gate_dirty: true,
                cycles_since_telemetry: 0,
                prio_checked: false,
                last_seen_generation: 0,
                max_frames_count: audio_config.max_frames_count as usize,
                last_render_mode: 0,
                realtime_activation: crate::common::params::ActivationPrecision::Standard,
                gain_lut: get_gain_lut(),
                cabsim_tail_remaining: cabsim_tail_initial,
                host,
            })
        }));
        match result {
            Ok(r) => r,
            Err(err) => Err(panic_to_error(err)),
        }
    }

    fn deactivate(self, _main_thread: &mut NamClapMainThread<'a>) {
        // S5-E5-T03: isolate panics during cleanup.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut param_rx_guard = self
                .shared
                .cold
                .param_rx
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            *param_rx_guard = Some(self.cmd_consumer.into_inner());

            let mut gc_tx_guard = self
                .shared
                .cold
                .gc_tx
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            *gc_tx_guard = Some(self.gc_tx);

            let mut slimmable_rx_guard = self
                .shared
                .cold
                .slimmable_rx
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            *slimmable_rx_guard = Some(self.slimmable_rx);

            // S1-E1-T01: Preserve heavy DSP resources across deactivate/activate
            // cycles to avoid I/O, filter-bank recompute, and FFT setup on the
            // next activate(). Resources are validated on restore against the
            // current audio configuration.
            let deactivated = DeactivatedDspState {
                model_l: self.model_l,
                cabsim_adapter: self.cabsim_adapter,
                resampler: self.resampler,
                os_l: self.os_l,
                os_r: self.os_r,
                os_factor: self.params.oversample,
                sample_rate: self.shared.cold.sample_rate.load(Ordering::Relaxed),
                buffer_size: self.shared.cold.buffer_size.load(Ordering::Relaxed),
                model_input_mult_adj: self.model_input_mult_adj,
                model_output_mult_adj: self.model_output_mult_adj,
            };
            *self
                .shared
                .cold
                .deactivated_dsp
                .lock()
                .unwrap_or_else(|e| e.into_inner()) = Some(deactivated);

            _main_thread.drain_gc_final();
        }));
        if let Err(err) = result {
            // Deactivate panicked — resources may leak but crash report
            // was already written. Drop the payload silently.
            drop(err);
        }
    }

    fn process(
        &mut self,
        _process: Process,
        mut audio: Audio,
        events: Events,
    ) -> Result<ProcessStatus, PluginError> {
        // S5-E5-T03: isolate panics in this instance's audio callback.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            #[cfg(feature = "heap-audit")]
            let _guard = if crate::common::alloc_audit::AUDIT_ENABLED.load(Ordering::Relaxed) {
                Some(crate::common::alloc_audit::TrackingGuard::new())
            } else {
                None
            };

            // S5-E5-T01: Per-instance activation precision via TLS.
            // Activation updates within process() (host events, SPSC, GUI sync, offline↔realtime)
            // call set_activation_tls() to reflect the new value. The scope guard clears TLS on
            // return so the next invocation re-arms from self.params.activation_precision.
            let _activation_guard = crate::math::activations::set_thread_local_activation_precision(
                Some(self.params.activation_precision),
            );

            let should_measure = self.cycles_since_telemetry & 0xF == 0;
            self.cycles_since_telemetry = self.cycles_since_telemetry.wrapping_add(1);
            let start_nanos = if should_measure { rdtsc_nanos() } else { 0 };

            // One-time thread priority query on the first processed block
            if !self.prio_checked {
                self.prio_checked = true;
                // SAFETY: `pthread_self()` returns a valid thread handle for the
                // calling thread. `pthread_getschedparam()` reads scheduling
                // attributes into stack-local variables using FFI defined by POSIX.
                unsafe {
                    let thread_id = libc::pthread_self();
                    let mut policy = 0i32;
                    let mut param: libc::sched_param = std::mem::zeroed();
                    if libc::pthread_getschedparam(thread_id, &mut policy, &mut param) == 0 {
                        self.rt_status
                            .rt_priority
                            .store(param.sched_priority, Ordering::Relaxed);
                        self.rt_status
                            .confirmed_priority
                            .store(param.sched_priority, Ordering::Relaxed);
                        self.rt_status.rt_policy.store(policy, Ordering::Relaxed);
                        if policy == libc::SCHED_FIFO || policy == libc::SCHED_RR {
                            self.rt_status
                                .set_flag(crate::common::spsc::RT_STATUS_RT_IS_FIFO);
                        }
                    }
                    let cpu = libc::sched_getcpu();
                    self.rt_status.rt_cpu.store(cpu, Ordering::Relaxed);
                    crate::math::common::set_daz_ftz();
                }
            }

            // Periodic DAZ/FTZ reapplication: hosts may reset MXCSR after callbacks
            // (e.g. during GUI repaints or parameter flushes from another thread).
            // Reassert DAZ+FTZ every 1024 blocks using the existing telemetry counter
            // — the conditional is a single bit-test (1 cycle; cold branch).
            // SAFETY: DAZ+FTZ are SSE2 control bits on x86-64 — unconditionally safe.
            if self.cycles_since_telemetry & 0x3FF == 0 {
                unsafe {
                    crate::math::common::set_daz_ftz();
                }
            }

            // Event drainage (SPSC + Host + GUI sync + Latency)
            self.process_events(events.output);

            // DSP block (gate, inference, resampling, output, telemetry)
            // Host parameter events are handled sample-accurately via block-splitting.
            self.process_dsp_audio(&mut audio, events.input, start_nanos)
        }));
        match result {
            Ok(r) => r,
            Err(err) => Err(panic_to_error(err)),
        }
    }
}

#[cfg(any(feature = "standalone", feature = "clap-plugin", test))]
fn build_cab_sim_from_raw_samples(
    shared: &NamClapShared,
    partition_size: usize,
    host_rate: u32,
) -> Result<Option<crate::dsp::cabsim::adapter::CabSimAdapter>, PluginError> {
    use crate::dsp::cabsim::loader::CabSimIr;
    use std::sync::atomic::Ordering;

    let raw_guard = shared.cold.ir_raw_samples.lock().map_err(|e| {
        PluginError::Message(Box::leak(
            format!("ir_raw_samples lock poisoned: {e}").into_boxed_str(),
        ))
    })?;
    let Some(ref samples) = *raw_guard else {
        return Ok(None);
    };

    let stored_rate = shared.cold.ir_raw_sample_rate.load(Ordering::Relaxed);

    let resolved_samples: std::borrow::Cow<'_, [f32]> =
        if stored_rate > 0 && stored_rate != host_rate {
            let resampled = CabSimIr::resample(samples, stored_rate, host_rate).map_err(|e| {
                PluginError::Message(Box::leak(
                    format!(
                        "IR resample failed: {} Hz → {} Hz: {e}",
                        stored_rate, host_rate
                    )
                    .into_boxed_str(),
                ))
            })?;
            std::borrow::Cow::Owned(resampled)
        } else {
            std::borrow::Cow::Borrowed(samples)
        };

    if partition_size == 0 {
        return Ok(None);
    }

    let engine = crate::dsp::cabsim::conv::ConvEngine::new(&resolved_samples, partition_size)
        .map_err(|e| {
            PluginError::Message(Box::leak(
                format!("ConvEngine allocation failed: {e:?}").into_boxed_str(),
            ))
        })?;

    Ok(Some(
        crate::dsp::cabsim::adapter::CabSimAdapter::new(Box::new(engine)).map_err(|e| {
            PluginError::Message(Box::leak(
                format!("CabSimAdapter allocation failed: {e:?}").into_boxed_str(),
            ))
        })?,
    ))
}

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

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

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

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

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

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

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

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

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

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

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

#[cfg(test)]
mod diagnostics_logging_tests {
    use crate::clap::test_util;
    use crate::common::spsc::{
        RT_STATUS_GC_OVERFLOW, RT_STATUS_HAS_CLIPPED, RT_STATUS_HUGEPAGE_OK,
        RT_STATUS_MODEL_LOAD_FAILED, RtStatusFlags,
    };
    use std::path::PathBuf;
    use std::sync::Arc;
    use std::sync::atomic::Ordering;

    // Task 4.3.1 — flag set/clear mechanism for emit_pending_logs
    #[test]
    fn test_flag_set_and_clear_mechanism() {
        let rt_status = Arc::new(RtStatusFlags::new());

        rt_status.set_flag(RT_STATUS_HAS_CLIPPED);
        rt_status.set_flag(RT_STATUS_GC_OVERFLOW);
        rt_status.set_flag(RT_STATUS_HUGEPAGE_OK);

        assert!(rt_status.check_flag(RT_STATUS_HAS_CLIPPED));
        assert!(rt_status.check_flag(RT_STATUS_GC_OVERFLOW));
        assert!(rt_status.check_flag(RT_STATUS_HUGEPAGE_OK));

        assert!(rt_status.check_and_clear_flag(RT_STATUS_HAS_CLIPPED));
        assert!(!rt_status.check_flag(RT_STATUS_HAS_CLIPPED));

        assert!(rt_status.check_and_clear_flag(RT_STATUS_GC_OVERFLOW));
        assert!(!rt_status.check_flag(RT_STATUS_GC_OVERFLOW));

        assert!(rt_status.check_and_clear_flag(RT_STATUS_HUGEPAGE_OK));
        assert!(!rt_status.check_flag(RT_STATUS_HUGEPAGE_OK));

        let flags_seen = rt_status.flags_seen.load(Ordering::Relaxed);
        assert_eq!(
            flags_seen,
            RT_STATUS_HAS_CLIPPED | RT_STATUS_GC_OVERFLOW | RT_STATUS_HUGEPAGE_OK,
            "flags_seen should accumulate all flags that were ever set"
        );
    }

    // Task 4.3.1 — verify flag-to-log messages reach LogBuffer
    #[test]
    fn test_emit_pending_logs_messages_reach_log_buffer() {
        let (_entry, _host_info, mut plugin_instance) = test_util::make_test_plugin();
        let shared = unsafe { &*test_util::extract_shared(&mut plugin_instance) };

        let snapshot_before = crate::common::diagnostics::logger::NamLogger::log_buffer()
            .expect("LogBuffer should be accessible")
            .len();

        shared
            .cold
            .rt_status
            .check_and_clear_flag(RT_STATUS_HAS_CLIPPED);
        log::warn!("NAM-rs: Output clipping detected!");

        shared
            .cold
            .rt_status
            .check_and_clear_flag(RT_STATUS_GC_OVERFLOW);
        log::error!("NAM-rs: GC channel overflow! Possible memory leak.");

        shared
            .cold
            .rt_status
            .check_and_clear_flag(RT_STATUS_MODEL_LOAD_FAILED);
        log::error!("NAM-rs: Critical failure! No active model for processing.");

        let snapshot_after = crate::common::diagnostics::logger::NamLogger::log_buffer()
            .expect("LogBuffer should be accessible")
            .len();
        assert!(
            snapshot_after > snapshot_before + 2,
            "LogBuffer should grow after log entries are emitted"
        );

        test_util::assert_log_buffer_contains("Output clipping detected");
        test_util::assert_log_buffer_contains("GC channel overflow");
        test_util::assert_log_buffer_contains("Critical failure! No active model for processing");
    }

    // Task 4.3.1 — verify state save emits confirmation log
    #[test]
    fn test_state_save_emits_confirmation_log() {
        use log::LevelFilter;

        let (_entry, _host_info, mut plugin_instance) = test_util::make_test_plugin();

        let logger = crate::common::diagnostics::logger::NamLogger::global()
            .expect("NamLogger should be initialized");
        let original_level = log::max_level();
        logger.set_max_level(LevelFilter::Debug);

        let mut model_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        model_path.push("tests/fixtures/models/BossWN-nano.nam");

        use crate::common::params::NamPluginParams;
        let params = NamPluginParams {
            model_path: Some(model_path),
            input_gain_db: 1.0,
            output_gain_db: -2.0,
            gate_threshold_db: -50.0,
            model_basename: Some("BossWN-nano.nam".to_string()),
            model_search_paths: vec![],
            model_hash: None,
            bypass: false,
            adaptive_compute: crate::common::params::AdaptiveComputeMode::Off,
            slim_override: Default::default(),
            oversample: crate::dsp::oversample::OversampleFactor::Off,
            ir_path: None,
            ir_hash: None,
            activation_precision: crate::common::params::ActivationPrecision::Standard,
        };
        let state_bytes = serde_json::to_vec(&params).unwrap();
        let state_ext = test_util::get_state_ext(&mut plugin_instance);
        let mut handle = plugin_instance.plugin_handle();
        state_ext
            .load(&mut handle, &mut state_bytes.as_slice())
            .expect("Failed to load state");

        let mut output = Vec::new();
        let mut handle = plugin_instance.plugin_handle();
        state_ext
            .save(&mut handle, &mut output)
            .expect("save should succeed");

        assert!(!output.is_empty(), "save output should not be empty");
        test_util::assert_log_buffer_contains("[State] Save completed:");
        test_util::assert_log_buffer_contains("bytes serialized.");

        logger.set_max_level(original_level);
    }
}