denoize 0.40.0

Pure-Rust audio denoiser with classical DSP and optional RNNoise
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
//! `denoize` — pure-Rust audio denoiser built for the world's highest fidelity.
//!
//! Goal: transparent, artifact-free restoration that preserves timbre,
//! transients, dynamics, and "air" better than any classical offline tool.
//!
//! ## Implemented technologies
//!
//! ### Classical DSP (always available)
//! - STFT/ISTFT + Perfect Reconstruction OLA(高オーバーラップ対応)
//! - IMCRA/MCRA ノイズ推定 + Spectral Flatness プロファイル + Anchoring
//! - Ephraim-Malah Decision-Directed SNR
//! - 8種類のゲイン推定器(OMLSA, LogMMSE, MMSE-STSA, Wiener, SpecSub + 非線形/幾何学的)
//! - Attack/Release + Cepstral Smoothing + Transient Protection
//! - 高度窓関数: Kaiser / Flat-top / DPSS
//! - マルチバンドスペクトルサブトラクション
//! - 知覚重み付け(Bark帯域)+ 音楽ノイズ抑制ポストフィルタ
//!
//! ### Input / output codecs (built-in, no ffmpeg)
//! - **Decode**: WAV / MP3 (`symphonia`, including Xing/LAME gapless timing,
//!   with a bounded raw-stream compatibility fallback) / M4A (Pure Rust AAC-LC)
//! - **Encode**: WAV / MP3 (`shine-rs`) / M4A (`oxideav-aac` Pure-Rust AAC-LC)
//! - Decoded to `f64` PCM at native sample rate (no extra quantisation)
//!
//! ### Optional AI backends (feature-gated)
//! - `rnnoise` feature: RNNoise via nnnoiseless (pure-Rust)
//! - `deepfilter` feature: DeepFilterNet v3 via tract ONNX
//! - `onnx` feature: user-supplied waveform ONNX models via tract
//! - `mpsenet` feature: MP-SENet compressed-magnitude/phase ONNX adapter
//! - `bsrnn` feature: ESPnet BSRNN spectral ONNX adapter
//! - `mossformer2` feature: ClearerVoice MossFormer2 48 kHz ONNX adapter
//! - `sgmse` feature: SGMSE+ iterative diffusion ONNX adapter
//!
//! Build with all backends: `cargo build --release --features full`

pub mod atomic_output;
pub mod audio;
pub mod backend;
#[doc(hidden)]
pub mod batch_resume;
pub mod benchmark;
pub mod bessel;
pub mod channel_layout;
pub mod config;
pub mod decode;
pub mod denoiser;
pub mod encode;
pub mod fft;
pub mod gain;
#[cfg(feature = "live")]
pub mod live;
pub mod loudness;
pub mod metadata;
pub mod models;
pub mod noise;
pub mod perceptual;
pub mod postfilter;
pub mod quality;
pub mod resample;
pub mod service;
pub mod stft;
mod stoi_resample;
pub mod stream;
pub mod vad;
pub mod window;

pub use atomic_output::{AtomicOutput, CommitMode};
pub use audio::{
    ensure_memory_limit, estimate_audio_memory_bytes, estimate_audio_working_set_bytes,
    estimate_file_memory_bytes, estimate_stream_memory_bytes, estimate_stream_memory_bytes_checked,
    read_audio, read_wav, read_wav_bytes, sanitize_sample, write_audio, write_wav, write_wav_bytes,
    write_wav_channel_mask, Audio, WavStreamReader, WavStreamWriter,
};
pub use backend::{
    decode_mid_side, encode_mid_side, Backend, BackendOptions, ChannelMode, OnnxModelConfig,
    SgmseProfile,
};
pub use benchmark::{ArtifactReport, BenchmarkReport, ComparisonReport};
pub use channel_layout::{ChannelLayout, ChannelMask, ChannelPosition, PanInfo};
pub use config::{ConfigError, ResourcePlan};
pub use decode::{decode_file, probe_file, AudioCodec, AudioFormat, AudioProbe, DecodedPcm};
pub use denoiser::{Denoiser, DenoiserConfig, Preset, ProcessingMode, StreamingDenoiser};
pub use encode::{AacEncoder, DownmixMode, EncodeOptions, OutputFormat};
pub use gain::{Algorithm, SpecSubLaw};
pub use quality::QualityMetrics;
pub use window::{WindowParams, WindowType};

/// Encode audio and optional metadata into a staged file, then publish it in
/// one filesystem commit.
pub fn write_audio_transactional(
    output: impl AsRef<std::path::Path>,
    audio: &Audio,
    encode_options: EncodeOptions,
    metadata_snapshot: Option<metadata::Metadata>,
    commit_mode: CommitMode,
) -> Result<(), String> {
    let output = output.as_ref();
    let format = OutputFormat::from_path(output)?;
    write_audio_transactional_as(
        output,
        format,
        audio,
        encode_options,
        metadata_snapshot,
        commit_mode,
    )
}

/// Encode audio using a format selected during preflight, then publish it in
/// one filesystem commit without re-inferring the codec from the path.
pub fn write_audio_transactional_as(
    output: impl AsRef<std::path::Path>,
    format: OutputFormat,
    audio: &Audio,
    encode_options: EncodeOptions,
    metadata_snapshot: Option<metadata::Metadata>,
    commit_mode: CommitMode,
) -> Result<(), String> {
    let output = output.as_ref();
    format.validate_config(audio, &encode_options)?;
    let mut transaction = AtomicOutput::new(output)?;
    encode::write_audio_to_file(transaction.file_mut(), format, audio, encode_options)?;
    if let Some(metadata_snapshot) = metadata_snapshot {
        metadata::write_extended_to_file(metadata_snapshot, transaction.file_mut())?;
    }
    transaction.commit(commit_mode)
}

/// Denoise a WAV file end-to-end, writing the result to `output`.
pub fn denoise_file<P1, P2>(input: P1, output: P2, config: DenoiserConfig) -> Result<Audio, String>
where
    P1: AsRef<std::path::Path>,
    P2: AsRef<std::path::Path>,
{
    denoise_file_with_backend(input, output, config, Backend::Classical)
}

/// Denoise with an explicit backend (classical / rnnoise / deepfilter).
pub fn denoise_file_with_backend<P1, P2>(
    input: P1,
    output: P2,
    config: DenoiserConfig,
    backend: Backend,
) -> Result<Audio, String>
where
    P1: AsRef<std::path::Path>,
    P2: AsRef<std::path::Path>,
{
    denoise_file_with_backend_opts(input, output, config, backend, EncodeOptions::default())
}

/// Denoise with explicit backend and output encode options.
pub fn denoise_file_with_backend_opts<P1, P2>(
    input: P1,
    output: P2,
    config: DenoiserConfig,
    backend: Backend,
    encode_opts: EncodeOptions,
) -> Result<Audio, String>
where
    P1: AsRef<std::path::Path>,
    P2: AsRef<std::path::Path>,
{
    denoise_file_with_backend_config(
        input,
        output,
        config,
        backend,
        encode_opts,
        BackendOptions::default(),
    )
}

/// Denoise with explicit backend, encoder, and backend-specific model options.
pub fn denoise_file_with_backend_config<P1, P2>(
    input: P1,
    output: P2,
    config: DenoiserConfig,
    backend: Backend,
    encode_opts: EncodeOptions,
    backend_options: BackendOptions,
) -> Result<Audio, String>
where
    P1: AsRef<std::path::Path>,
    P2: AsRef<std::path::Path>,
{
    let input = input.as_ref();
    let output = output.as_ref();
    // The file's decoded rate replaces the caller's placeholder rate. Validate
    // every rate-independent field before touching the filesystem while using
    // a harmless valid rate solely for this preflight pass.
    let mut preflight_config = config.clone();
    preflight_config.sample_rate = 1;
    preflight_config
        .validate_config()
        .map_err(|error| error.to_string())?;
    backend_options
        .validate_resolved_config(backend)
        .map_err(|error| error.to_string())?;
    let format = OutputFormat::from_path(output)?;
    encode_opts.validate_options(format)?;
    backend_options.validate_resolved_resources(backend)?;
    let metadata = metadata::read_extended(input)?;
    let mut audio = read_audio(input)?;
    format.validate_config(&audio, &encode_opts)?;
    denoise_audio_with_backend_config(&mut audio, config, backend, &backend_options)?;
    write_audio_transactional_as(
        output,
        format,
        &audio,
        encode_opts,
        metadata,
        CommitMode::Replace,
    )?;
    Ok(audio)
}

/// Process already-decoded audio in place. This is the path used by stdin and
/// embedders that do not have filesystem-backed input.
pub fn denoise_audio_with_backend_config(
    audio: &mut Audio,
    config: DenoiserConfig,
    backend: Backend,
    backend_options: &BackendOptions,
) -> Result<std::time::Duration, String> {
    let (processed, elapsed) =
        process_audio_copy_with_backend_config(audio, config, backend, backend_options)?;
    *audio = processed;
    Ok(elapsed)
}

/// Build a processed replacement without changing the caller's audio. This is
/// also used by delivery layers that have further fallible work, such as
/// loudness normalization, before committing the result.
pub(crate) fn process_audio_copy_with_backend_config(
    audio: &Audio,
    mut config: DenoiserConfig,
    backend: Backend,
    backend_options: &BackendOptions,
) -> Result<(Audio, std::time::Duration), String> {
    config.sample_rate = audio.sample_rate;
    config
        .validate_config()
        .map_err(|error| error.to_string())?;
    backend_options.validate_resolved_resources(backend)?;
    let mut input = audio.try_clone_fallible("denoising input")?;
    input.sanitize_samples();
    let t0 = std::time::Instant::now();
    let channels = if config.vad {
        process_with_vad(
            backend,
            &input.channels,
            input.sample_rate,
            &config,
            backend_options,
        )?
    } else {
        backend::process_channels(
            backend,
            &input.channels,
            input.sample_rate,
            &config,
            backend_options,
        )?
    };
    let mut processed = Audio {
        sample_rate: audio.sample_rate,
        channels,
        bits_per_sample: audio.bits_per_sample,
        sample_format: audio.sample_format,
        channel_mask: audio.channel_mask,
    };
    processed.sanitize_samples();
    let elapsed = t0.elapsed();
    eprintln!(
        "denoize: {:?} | {}ch x {} frames ({:.2}s) in {:.2?} ({:.1}x realtime)",
        backend,
        processed.channels(),
        processed.frames(),
        processed.frames() as f64 / processed.sample_rate as f64,
        elapsed,
        (processed.frames() as f64 / processed.sample_rate as f64)
            / elapsed.as_secs_f64().max(1e-9),
    );
    Ok((processed, elapsed))
}

fn process_with_vad(
    backend: Backend,
    channels: &[Vec<f64>],
    sample_rate: u32,
    config: &DenoiserConfig,
    backend_options: &BackendOptions,
) -> Result<Vec<Vec<f64>>, String> {
    let regions = vad::speech_regions(channels, sample_rate);
    let fade_frames = (sample_rate as usize / 50).max(1); // 20 ms
    let silence_gain = config.vad_silence_gain;
    let speech_mix = config.vad_speech_mix;
    let mut output: Vec<Vec<f64>> = channels
        .iter()
        .map(|channel| channel.iter().map(|sample| sample * silence_gain).collect())
        .collect();
    for region in regions {
        let input: Vec<Vec<f64>> = channels
            .iter()
            .map(|channel| {
                channel[region.start.min(channel.len())..region.end.min(channel.len())].to_vec()
            })
            .collect();
        let enhanced =
            backend::process_channels(backend, &input, sample_rate, config, backend_options)?;
        for (channel_index, enhanced_channel) in enhanced.iter().enumerate() {
            let Some(destination) = output.get_mut(channel_index) else {
                continue;
            };
            let original = &channels[channel_index];
            for (offset, sample) in enhanced_channel.iter().enumerate() {
                let index = region.start + offset;
                if index >= destination.len() || index >= original.len() || index >= region.end {
                    break;
                }
                let target = sample * speech_mix + original[index] * (1.0 - speech_mix);
                let weight = vad_mix_weight(offset, region.end - region.start, fade_frames);
                destination[index] = destination[index] * (1.0 - weight) + target * weight;
            }
        }
    }
    Ok(output)
}

fn vad_mix_weight(offset: usize, length: usize, fade_frames: usize) -> f64 {
    // Start and end at the attenuated signal so a processed region cannot
    // introduce a discontinuity at either handoff.
    let from_start = offset.min(fade_frames) as f64 / fade_frames.max(1) as f64;
    let from_end =
        length.saturating_sub(offset + 1).min(fade_frames) as f64 / fade_frames.max(1) as f64;
    from_start.min(from_end).clamp(0.0, 1.0)
}

#[cfg(test)]
mod vad_mix_tests {
    use super::{process_with_vad, vad, vad_mix_weight, Backend, BackendOptions, DenoiserConfig};

    #[test]
    fn fades_vad_region_edges_without_exceeding_unity() {
        assert_eq!(vad_mix_weight(0, 100, 10), 0.0);
        assert_eq!(vad_mix_weight(99, 100, 10), 0.0);
        assert_eq!(vad_mix_weight(50, 100, 10), 1.0);
        assert!((vad_mix_weight(5, 100, 10) - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn fade_weights_are_bounded_monotonic_and_slope_limited() {
        let fade_frames = 10;
        let weights: Vec<_> = (0..100)
            .map(|offset| vad_mix_weight(offset, 100, fade_frames))
            .collect();

        assert!(weights.iter().all(|weight| (0.0..=1.0).contains(weight)));
        assert!(weights
            .windows(2)
            .all(|pair| { (pair[1] - pair[0]).abs() <= 1.0 / fade_frames as f64 + f64::EPSILON }));
        assert!(weights[..=fade_frames]
            .windows(2)
            .all(|pair| pair[1] >= pair[0]));
        assert!(weights[fade_frames..]
            .windows(2)
            .all(|pair| pair[1] <= pair[0]));
        assert_eq!(weights.first().copied(), Some(0.0));
        assert_eq!(weights.last().copied(), Some(0.0));
    }

    fn test_config(sample_rate: u32) -> DenoiserConfig {
        let mut config = DenoiserConfig::default(sample_rate);
        config.vad = true;
        config.vad_silence_gain = 0.2;
        config.vad_speech_mix = 0.0;
        config.sanitized()
    }

    #[test]
    fn vad_applies_configured_gain_to_non_speech_audio() {
        let sample_rate = 16_000;
        let input: Vec<f64> = (0..sample_rate)
            .map(|index| {
                1.0e-5
                    * (2.0 * std::f64::consts::PI * 37.0 * index as f64 / sample_rate as f64).sin()
            })
            .collect();
        assert!(vad::speech_regions(std::slice::from_ref(&input), sample_rate).is_empty());

        let output = process_with_vad(
            Backend::Classical,
            std::slice::from_ref(&input),
            sample_rate,
            &test_config(sample_rate),
            &BackendOptions::default(),
        )
        .unwrap();

        assert_eq!(output.len(), 1);
        assert_eq!(output[0].len(), input.len());
        for (actual, original) in output[0].iter().zip(&input) {
            assert!((actual - original * 0.2).abs() < 1e-20);
        }
    }

    #[test]
    fn vad_crossfade_matches_expected_edges_without_clicks() {
        let sample_rate = 16_000;
        let frames = sample_rate as usize * 2;
        let active_start = sample_rate as usize / 2;
        let active_end = sample_rate as usize * 3 / 2;
        let transition = sample_rate as usize / 20;
        let input: Vec<f64> = (0..frames)
            .map(|index| {
                let envelope = if index < active_start.saturating_sub(transition) {
                    0.0
                } else if index < active_start {
                    let position = (index - (active_start - transition)) as f64 / transition as f64;
                    let smooth = position * position * (3.0 - 2.0 * position);
                    0.3 * smooth
                } else if index < active_end {
                    0.3
                } else if index < active_end + transition {
                    let position = (index - active_end) as f64 / transition as f64;
                    let smooth = position * position * (3.0 - 2.0 * position);
                    0.3 * (1.0 - smooth)
                } else {
                    0.0
                };
                envelope
                    * (2.0 * std::f64::consts::PI * 80.0 * index as f64 / sample_rate as f64).sin()
            })
            .collect();
        let regions = vad::speech_regions(std::slice::from_ref(&input), sample_rate);
        assert!(!regions.is_empty());

        let output = process_with_vad(
            Backend::Classical,
            std::slice::from_ref(&input),
            sample_rate,
            &test_config(sample_rate),
            &BackendOptions::default(),
        )
        .unwrap();
        assert_eq!(output[0].len(), input.len());
        assert!(output[0].iter().all(|sample| sample.is_finite()));

        let silence_gain = 0.2;
        let mut expected: Vec<f64> = input.iter().map(|sample| sample * silence_gain).collect();
        for region in &regions {
            for offset in 0..region.end.saturating_sub(region.start) {
                let index = region.start + offset;
                if index >= expected.len() {
                    break;
                }
                let weight =
                    vad_mix_weight(offset, region.end - region.start, sample_rate as usize / 50);
                expected[index] = expected[index] * (1.0 - weight) + input[index] * weight;
            }
        }
        for (actual, expected) in output[0].iter().zip(expected) {
            assert!((actual - expected).abs() < 1e-12);
        }

        for region in regions {
            if region.start > 0 {
                let jump = (output[0][region.start] - output[0][region.start - 1]).abs();
                assert!(jump < 0.02, "VAD start boundary jump: {jump}");
            }
            if region.end < output[0].len() {
                let jump = (output[0][region.end] - output[0][region.end - 1]).abs();
                assert!(jump < 0.02, "VAD end boundary jump: {jump}");
            }
        }
    }
}

#[cfg(test)]
mod input_safety_tests {
    use super::*;

    #[test]
    fn high_level_processing_sanitizes_nonfinite_samples_and_keeps_empty_audio_safe() {
        let mut audio = Audio {
            sample_rate: 16_000,
            channels: vec![vec![f64::NAN, f64::INFINITY, -f64::INFINITY, 2.0, -2.0]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        denoise_audio_with_backend_config(
            &mut audio,
            DenoiserConfig::default(16_000),
            Backend::Classical,
            &BackendOptions::default(),
        )
        .unwrap();
        assert!(audio.channels[0].iter().all(|sample| sample.is_finite()));
        assert!(audio.channels[0].iter().all(|sample| sample.abs() <= 1.0));

        let mut empty = Audio {
            sample_rate: 16_000,
            channels: vec![Vec::new()],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        denoise_audio_with_backend_config(
            &mut empty,
            DenoiserConfig::default(16_000),
            Backend::Classical,
            &BackendOptions::default(),
        )
        .unwrap();
        assert_eq!(empty.frames(), 0);
    }

    #[test]
    fn classical_high_level_processing_rejects_invalid_dpss_bandwidth() {
        let mut audio = Audio {
            sample_rate: 16_000,
            channels: vec![vec![0.25; 512]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        let original = audio.channels.clone();
        let mut config = DenoiserConfig::default(audio.sample_rate);
        config.window = WindowType::Dpss;
        config.window_params.dpss_bandwidth = crate::window::MAX_DENOISER_DPSS_NW + 0.5;

        let error = denoise_audio_with_backend_config(
            &mut audio,
            config,
            Backend::Classical,
            &BackendOptions::default(),
        )
        .unwrap_err();

        assert!(
            error.contains("DPSS bandwidth"),
            "unexpected error: {error}"
        );
        assert_eq!(audio.channels, original);
    }

    #[test]
    fn invalid_decoded_config_leaves_audio_completely_unchanged() {
        let mut audio = Audio {
            sample_rate: 16_000,
            channels: vec![vec![2.0, -2.0, 0.25]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        let original = audio.clone();
        let mut config = DenoiserConfig::default(48_000);
        config.vad_speech_mix = f64::NAN;

        let error = denoise_audio_with_backend_config(
            &mut audio,
            config,
            Backend::Classical,
            &BackendOptions::default(),
        )
        .unwrap_err();

        assert!(
            error.contains("vad_speech_mix"),
            "unexpected error: {error}"
        );
        assert_eq!(audio.sample_rate, original.sample_rate);
        assert_eq!(audio.channels, original.channels);
        assert_eq!(audio.bits_per_sample, original.bits_per_sample);
        assert_eq!(audio.sample_format, original.sample_format);
        assert_eq!(audio.channel_mask, original.channel_mask);
    }

    #[test]
    fn decoded_effective_sample_rate_is_validated_before_mutation() {
        let mut audio = Audio {
            sample_rate: 0,
            channels: vec![vec![2.0]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        let original = audio.channels.clone();
        let error = denoise_audio_with_backend_config(
            &mut audio,
            DenoiserConfig::default(48_000),
            Backend::Classical,
            &BackendOptions::default(),
        )
        .unwrap_err();
        assert!(error.contains("sample_rate"), "unexpected error: {error}");
        assert_eq!(audio.channels, original);
    }

    #[cfg(feature = "onnx")]
    #[test]
    fn decoded_model_resource_is_validated_before_mutation() {
        let mut audio = Audio {
            sample_rate: 48_000,
            channels: vec![vec![2.0]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        let original = audio.channels.clone();
        let backend_options = BackendOptions {
            onnx: Some(OnnxModelConfig {
                path: "model-that-does-not-exist.onnx".into(),
                sample_rate: 48_000,
            }),
            ..BackendOptions::default()
        };

        let error = denoise_audio_with_backend_config(
            &mut audio,
            DenoiserConfig::default(48_000),
            Backend::Onnx,
            &backend_options,
        )
        .unwrap_err();

        assert!(
            error.contains("model does not exist"),
            "unexpected error: {error}"
        );
        assert_eq!(audio.channels, original);
    }

    #[cfg(feature = "onnx")]
    #[test]
    fn malformed_model_failure_does_not_mutate_decoded_audio() {
        let root = tempfile::tempdir().unwrap();
        let model = root.path().join("malformed.onnx");
        std::fs::write(&model, b"not an ONNX graph").unwrap();
        let mut audio = Audio {
            sample_rate: 48_000,
            channels: vec![vec![2.0, -2.0, 0.25]],
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
            channel_mask: None,
        };
        let original = audio.clone();
        let backend_options = BackendOptions {
            onnx: Some(OnnxModelConfig {
                path: model,
                sample_rate: 48_000,
            }),
            ..BackendOptions::default()
        };

        let error = denoise_audio_with_backend_config(
            &mut audio,
            DenoiserConfig::default(48_000),
            Backend::Onnx,
            &backend_options,
        )
        .unwrap_err();

        assert!(!error.is_empty());
        assert_eq!(audio.sample_rate, original.sample_rate);
        assert_eq!(audio.channels, original.channels);
        assert_eq!(audio.bits_per_sample, original.bits_per_sample);
        assert_eq!(audio.sample_format, original.sample_format);
        assert_eq!(audio.channel_mask, original.channel_mask);
    }

    #[test]
    fn file_processing_validates_dpss_before_reading_input() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.wav");
        let mut config = DenoiserConfig::default(16_000);
        config.window = WindowType::Dpss;
        config.window_params.dpss_bandwidth = crate::window::MAX_DENOISER_DPSS_NW + 0.5;

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            config,
            Backend::Classical,
            EncodeOptions::default(),
            BackendOptions::default(),
        )
        .unwrap_err();

        assert!(
            error.contains("DPSS bandwidth"),
            "unexpected error: {error}"
        );
        assert!(!output.exists());
    }

    #[test]
    fn file_processing_rejects_rate_independent_config_before_missing_input() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.wav");
        let mut config = DenoiserConfig::default(0);
        config.strength = f64::NAN;

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            config,
            Backend::Classical,
            EncodeOptions::default(),
            BackendOptions::default(),
        )
        .unwrap_err();

        assert!(error.contains("strength"), "unexpected error: {error}");
        assert!(!error.contains("sample_rate"));
        assert!(!output.exists());
    }

    #[test]
    fn file_preflight_does_not_reject_placeholder_sample_rate() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.wav");
        let config = DenoiserConfig::default(0);

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            config,
            Backend::Classical,
            EncodeOptions::default(),
            BackendOptions::default(),
        )
        .unwrap_err();

        assert!(!error.contains("sample_rate"), "unexpected error: {error}");
        assert!(!output.exists());
    }

    #[test]
    fn file_processing_validates_backend_options_before_missing_input() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.wav");
        let backend_options = BackendOptions {
            onnx: Some(OnnxModelConfig {
                path: root.path().join("model-that-must-not-be-opened.onnx"),
                sample_rate: 0,
            }),
            ..BackendOptions::default()
        };

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            DenoiserConfig::default(0),
            Backend::Classical,
            EncodeOptions::default(),
            backend_options,
        )
        .unwrap_err();

        assert!(
            error.contains("backend_options.onnx.sample_rate"),
            "unexpected error: {error}"
        );
        assert!(!output.exists());
    }

    #[cfg(feature = "onnx")]
    #[test]
    fn file_processing_validates_output_format_before_model_path_io() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.invalid");
        let backend_options = BackendOptions {
            onnx: Some(OnnxModelConfig {
                path: root.path().join("model-that-must-not-be-opened.onnx"),
                sample_rate: 48_000,
            }),
            ..BackendOptions::default()
        };

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            DenoiserConfig::default(0),
            Backend::Onnx,
            EncodeOptions::default(),
            backend_options,
        )
        .unwrap_err();

        assert!(
            error.contains("unsupported output format"),
            "unexpected error: {error}"
        );
        assert!(!error.contains("model does not exist"));
        assert!(!output.exists());
    }

    #[cfg(feature = "m4a-encode")]
    #[test]
    fn file_processing_validates_encode_options_before_missing_input() {
        let root = tempfile::tempdir().unwrap();
        let input = root.path().join("missing.wav");
        let output = root.path().join("output.aac");
        let mut encode_options = EncodeOptions::default();
        encode_options.m4a_bitrate_bps = 0;

        let error = denoise_file_with_backend_config(
            &input,
            &output,
            DenoiserConfig::default(0),
            Backend::Classical,
            encode_options,
            BackendOptions::default(),
        )
        .unwrap_err();

        assert!(error.contains("bitrate must be greater than zero"));
        assert!(!error.contains("missing.wav"));
        assert!(!output.exists());
    }

    #[test]
    fn transactional_encode_validation_precedes_output_staging() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("output.wav");
        std::fs::write(&output, b"existing output").unwrap();
        let invalid_audio = Audio {
            sample_rate: 48_000,
            channels: Vec::new(),
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
            channel_mask: None,
        };

        let error = write_audio_transactional_as(
            &output,
            OutputFormat::Wav,
            &invalid_audio,
            EncodeOptions::default(),
            None,
            CommitMode::Replace,
        )
        .unwrap_err();

        assert!(error.contains("at least one channel"));
        assert_eq!(std::fs::read(&output).unwrap(), b"existing output");
        assert!(std::fs::read_dir(root.path())
            .unwrap()
            .filter_map(Result::ok)
            .all(|entry| !entry.file_name().to_string_lossy().starts_with(".denoize-")));
    }
}