rt-fft-convolver 0.2.0

A high-performance, zero-latency partitioned convolution engine. Designed specifically for real-time guitar cabinet simulation and reverb effects with SIMD optimizations and anti-denormal protection.
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
//! WAV file loading and sample-rate conversion for impulse responses.
//!
//! # Overview
//!
//! Impulse response (IR) files are typically recorded at a fixed sample rate
//! (44 100 Hz or 48 000 Hz) but must match the host's current session sample
//! rate before convolution.  This module provides:
//!
//! - [`load_ir`] — open a WAV file and, if necessary, resample it to the
//!   target rate in one call.
//! - [`resample`] — resample a raw `f32` slice between any two integer rates.
//! - [`IrData`] — the result type carrying deinterleaved per-channel samples.
//! - [`LoadError`] — unified error type covering I/O, WAV decoding, and
//!   resampling failures.
//!
//! # Example
//!
//! ```rust,no_run
//! # use rt_fft_convolver::{load_ir, LoadError};
//! let ir = load_ir("cabinet.wav", 48_000)?;
//! assert_eq!(ir.sample_rate, 48_000);
//! assert_eq!(ir.num_channels, 1); // mono IR
//! let samples: &[f32] = &ir.channels[0];
//! # Ok::<(), LoadError>(())
//! ```

use std::path::Path;

// rubato re-exports `audioadapter_buffers` so we can reach it through
// the rubato namespace without adding an extra Cargo dependency.
use rubato::audioadapter_buffers::direct::InterleavedSlice;
use rubato::{Fft, FixedSync, Resampler, WindowFunction};

use crate::LoadError;

// ─── Public types ─────────────────────────────────────────────────────────────

/// Deinterleaved impulse response data returned by [`load_ir`].
///
/// Each element of `channels` holds the `f32` samples for one audio channel:
/// - index 0 = left (or mono)
/// - index 1 = right
/// - indices 2 / 3 = extra channels for true-stereo IRs recorded as 4-ch WAV
#[derive(Debug, Clone)]
pub struct IrData {
    /// One `Vec<f32>` per channel, deinterleaved from the source file.
    pub channels: Vec<Vec<f32>>,
    /// Number of audio channels (1 = mono, 2 = stereo, 4 = true stereo, …).
    pub num_channels: u16,
    /// Sample rate of the stored samples — equals the `target_sample_rate`
    /// argument passed to [`load_ir`].
    pub sample_rate: u32,
}

// ─── Public functions ─────────────────────────────────────────────────────────

/// Load a WAV file and resample it to `target_sample_rate` if necessary.
///
/// All common WAV variants are supported:
/// - 16-bit integer PCM (most common for guitar cab IRs)
/// - 24-bit and 32-bit integer PCM
/// - 32-bit IEEE float PCM
///
/// The returned [`IrData`] contains one `Vec<f32>` per channel, deinterleaved
/// and normalised to the `[-1.0, 1.0]` range.
///
/// # Errors
///
/// Returns [`LoadError`] if the file cannot be opened, decoded, or resampled.
pub fn load_ir(path: impl AsRef<Path>, target_sample_rate: u32) -> Result<IrData, LoadError> {
    let reader = hound::WavReader::open(path).map_err(LoadError::Hound)?;
    load_ir_from_reader(reader, target_sample_rate)
}

/// Resample `samples` from `from_rate` Hz to `to_rate` Hz.
///
/// Uses rubato's FFT-based resampler ([`rubato::Fft`] with fixed input chunks)
/// for high spectral quality.  Suitable for non-real-time use (IR
/// preparation); **not** intended for the audio render thread — allocates.
///
/// Returns the input unchanged (cloned) when `from_rate == to_rate` or when
/// the input is empty.
///
/// # Errors
///
/// Returns [`LoadError::Resample`] if rubato rejects the rate pair, or
/// [`LoadError::ResampleProcess`] on a buffer-size mismatch.
pub fn resample(samples: &[f32], from_rate: u32, to_rate: u32) -> Result<Vec<f32>, LoadError> {
    if from_rate == to_rate || samples.is_empty() {
        return Ok(samples.to_vec());
    }

    let mut resampler = make_resampler(from_rate, to_rate)?;
    let mut out = Vec::new();
    resample_into(&mut resampler, samples, &mut out)?;
    Ok(out)
}

// ─── Crate-internal helpers ───────────────────────────────────────────────────

/// Construct a mono FFT resampler for the `from_rate → to_rate` pair.
///
/// The returned resampler is stateful but reusable: call
/// [`Resampler::reset`](rubato::Resampler::reset) between independent signals
/// (e.g. successive IR channels) to clear its internal delay line, avoiding the
/// cost of rebuilding the FFT plans and scratch buffers per channel.
fn make_resampler(from_rate: u32, to_rate: u32) -> Result<Fft<f32>, LoadError> {
    // 1 024-frame chunks: good balance between quality and per-call overhead.
    // sub_chunks = 2 widens the internal FFT window for better stopband attenuation.
    const CHUNK: usize = 1024;
    // rubato 4.0 dropped `sub_chunks` from `Fft::new`; use `new_custom` to keep
    // explicit control over the sub-chunk count and anti-aliasing window.
    Fft::<f32>::new_custom(
        from_rate as usize,
        to_rate as usize,
        CHUNK,
        2, // sub-chunks (higher → better stopband, more memory)
        1, // mono — callers deinterleave before calling us
        WindowFunction::BlackmanHarris2,
        FixedSync::Input,
    )
    .map_err(LoadError::Resample)
}

/// Resample `samples` through `resampler`, writing the result into `out`.
///
/// `out` is fully overwritten — any prior contents are discarded — but its
/// **existing allocation is reused**: `resize` only re-mallocs when the buffer
/// must grow past its current capacity.  Feeding the same `out` back on
/// successive calls therefore amortises the output allocation across channels
/// (`vec![0.0; …]` would malloc a fresh buffer every time).
///
/// The caller is responsible for [`Resampler::reset`](rubato::Resampler::reset)
/// between independent signals.
fn resample_into(
    resampler: &mut Fft<f32>,
    samples: &[f32],
    out: &mut Vec<f32>,
) -> Result<(), LoadError> {
    let n_frames = samples.len(); // mono: 1 sample = 1 frame

    // Size the output for `process_all_into_buffer`, which needs room for the
    // resampler's internal delay plus a chunk of headroom.  clear()+resize on a
    // reused buffer keeps the prior allocation whenever capacity already fits.
    let out_buf_len = resampler.process_all_needed_output_len(n_frames);
    out.clear();
    out.resize(out_buf_len, 0.0);

    // Wrap the raw slices in adapters that the rubato Resampler trait accepts.
    let input = InterleavedSlice::new(samples, 1, n_frames)
        .map_err(|e| LoadError::UnsupportedFormat(e.to_string()))?;
    let mut output = InterleavedSlice::new_mut(out.as_mut_slice(), 1, out_buf_len)
        .map_err(|e| LoadError::UnsupportedFormat(e.to_string()))?;

    // `process_all_into_buffer` handles chunking, partial last chunk,
    // and trimming the leading silence caused by the resampler delay.
    // It returns (input_frames_consumed, output_frames_written).
    let (_, out_frames) = resampler
        .process_all_into_buffer(&input, &mut output, n_frames, None)
        .map_err(LoadError::ResampleProcess)?;

    out.truncate(out_frames);
    Ok(())
}

/// Core implementation shared between [`load_ir`] (file path) and the
/// in-memory path used in unit tests.
pub(crate) fn load_ir_from_reader<R: std::io::Read>(
    mut reader: hound::WavReader<R>,
    target_sample_rate: u32,
) -> Result<IrData, LoadError> {
    let spec = reader.spec();
    let file_sample_rate = spec.sample_rate;
    // hound::WavSpec uses `channels` (not `num_channels`)
    let num_channels = spec.channels;
    let num_ch = num_channels as usize;

    // ── Decode to interleaved f32 ─────────────────────────────────────────────
    let interleaved = decode_samples(&mut reader, &spec)?;

    // ── Deinterleave: [L0, R0, L1, R1, …] → [[L0, L1, …], [R0, R1, …]] ─────
    let mut channels: Vec<Vec<f32>> = (0..num_ch)
        .map(|ch| {
            interleaved
                .iter()
                .skip(ch)
                .step_by(num_ch)
                .copied()
                .collect()
        })
        .collect();

    // ── Resample each channel independently if the file rate differs ──────────
    if file_sample_rate != target_sample_rate {
        // Build the resampler once and reuse it for every channel (reset()
        // between channels clears its internal delay line).  This avoids
        // reconstructing the FFT plans and scratch buffers per channel — the
        // dominant allocation cost for multi-channel (true-stereo) IRs.
        let mut resampler = make_resampler(file_sample_rate, target_sample_rate)?;

        // `input_scratch` lets us resample each channel *back into its own Vec*
        // instead of allocating a fresh output buffer per channel: we swap the
        // channel's samples out into the scratch, then write the resampled
        // result into the channel's (reused) allocation.  The scratch buffer
        // itself is likewise reused across channels.
        let mut input_scratch: Vec<f32> = Vec::new();
        for ch in channels.iter_mut() {
            // ch ← empty (old scratch), input_scratch ← this channel's samples
            std::mem::swap(ch, &mut input_scratch);
            resampler.reset(); // clear state left by the previous channel
            resample_into(&mut resampler, &input_scratch, ch)?;
        }
    }

    Ok(IrData {
        channels,
        num_channels,
        sample_rate: target_sample_rate,
    })
}

/// Decode all samples from an open WAV reader into an interleaved `f32` vec.
///
/// Supported formats:
/// | WAV format       | hound type | normalisation          |
/// |------------------|------------|------------------------|
/// | 16-bit int PCM   | `i16`      | ÷ i16::MAX (≈ 3.1e-5)  |
/// | 24-bit int PCM   | `i32`      | ÷ 2^23                 |
/// | 32-bit int PCM   | `i32`      | ÷ 2^31                 |
/// | 32-bit float PCM | `f32`      | as-is                  |
fn decode_samples<R: std::io::Read>(
    reader: &mut hound::WavReader<R>,
    spec: &hound::WavSpec,
) -> Result<Vec<f32>, LoadError> {
    use hound::SampleFormat;

    match (spec.sample_format, spec.bits_per_sample) {
        // ── 32-bit float: no conversion needed ───────────────────────────────
        (SampleFormat::Float, 32) => reader
            .samples::<f32>()
            .map(|s| s.map_err(LoadError::Hound))
            .collect(),

        // ── 16-bit int: divide by i16::MAX ───────────────────────────────────
        (SampleFormat::Int, 16) => {
            let scale = 1.0 / i16::MAX as f32; // ≈ 3.05e-5
            reader
                .samples::<i16>()
                .map(|s| s.map(|x| x as f32 * scale).map_err(LoadError::Hound))
                .collect()
        }

        // ── 24-bit and 32-bit int: hound packs both into i32 ─────────────────
        // 2^(bits-1) gives the positive half-range for the bit depth.
        (SampleFormat::Int, bits @ (24 | 32)) => {
            let scale = 1.0 / (1_u64 << (bits - 1)) as f32;
            reader
                .samples::<i32>()
                .map(|s| s.map(|x| x as f32 * scale).map_err(LoadError::Hound))
                .collect()
        }

        (fmt, bits) => Err(LoadError::UnsupportedFormat(format!("{fmt:?} {bits}-bit"))),
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    // ── Helpers ───────────────────────────────────────────────────────────────

    /// Build a mono 16-bit WAV in memory containing `samples`.
    fn make_wav_mono_i16(sample_rate: u32, samples: &[f32]) -> Cursor<Vec<u8>> {
        let spec = hound::WavSpec {
            channels: 1,
            sample_rate,
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
        };
        let mut buf = Cursor::new(Vec::new());
        let mut w = hound::WavWriter::new(&mut buf, spec).unwrap();
        for &s in samples {
            w.write_sample((s * i16::MAX as f32) as i16).unwrap();
        }
        w.finalize().unwrap();
        buf.set_position(0);
        buf
    }

    /// Build a stereo 16-bit WAV in memory; `l` and `r` must have equal length.
    fn make_wav_stereo_i16(sample_rate: u32, l: &[f32], r: &[f32]) -> Cursor<Vec<u8>> {
        assert_eq!(l.len(), r.len());
        let spec = hound::WavSpec {
            channels: 2,
            sample_rate,
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
        };
        let mut buf = Cursor::new(Vec::new());
        let mut w = hound::WavWriter::new(&mut buf, spec).unwrap();
        for (&ls, &rs) in l.iter().zip(r.iter()) {
            w.write_sample((ls * i16::MAX as f32) as i16).unwrap();
            w.write_sample((rs * i16::MAX as f32) as i16).unwrap();
        }
        w.finalize().unwrap();
        buf.set_position(0);
        buf
    }

    /// Build an N-channel 16-bit WAV in memory from per-channel sample slices
    /// (all channels must share the same length).
    fn make_wav_multi_i16(sample_rate: u32, channels: &[&[f32]]) -> Cursor<Vec<u8>> {
        let num_ch = channels.len();
        assert!(num_ch > 0);
        let n = channels[0].len();
        assert!(
            channels.iter().all(|c| c.len() == n),
            "channels differ in length"
        );

        let spec = hound::WavSpec {
            channels: num_ch as u16,
            sample_rate,
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
        };
        let mut buf = Cursor::new(Vec::new());
        let mut w = hound::WavWriter::new(&mut buf, spec).unwrap();
        for i in 0..n {
            for ch in channels {
                w.write_sample((ch[i] * i16::MAX as f32) as i16).unwrap();
            }
        }
        w.finalize().unwrap();
        buf.set_position(0);
        buf
    }

    /// Build a mono 32-bit float WAV in memory.
    fn make_wav_mono_f32(sample_rate: u32, samples: &[f32]) -> Cursor<Vec<u8>> {
        let spec = hound::WavSpec {
            channels: 1,
            sample_rate,
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
        };
        let mut buf = Cursor::new(Vec::new());
        let mut w = hound::WavWriter::new(&mut buf, spec).unwrap();
        for &s in samples {
            w.write_sample(s).unwrap();
        }
        w.finalize().unwrap();
        buf.set_position(0);
        buf
    }

    // ── resample ──────────────────────────────────────────────────────────────

    /// Same rate → clone of input, no resampler constructed.
    #[test]
    fn resample_same_rate_is_identity() {
        let input: Vec<f32> = (0..64).map(|i| i as f32 / 64.0).collect();
        let output = resample(&input, 44_100, 44_100).unwrap();
        assert_eq!(output, input);
    }

    /// Empty input → empty output regardless of rates.
    #[test]
    fn resample_empty_returns_empty() {
        let out = resample(&[], 44_100, 48_000).unwrap();
        assert!(out.is_empty());
    }

    /// Upsampling 44 100 → 48 000: output length must match the ratio.
    #[test]
    fn resample_upsample_length() {
        let n = 4410_usize; // 100 ms at 44 100 Hz
        let input = vec![0.5_f32; n];
        let output = resample(&input, 44_100, 48_000).unwrap();
        let expected = (n as f64 * 48_000.0 / 44_100.0).round() as usize;
        assert_eq!(
            output.len(),
            expected,
            "upsample length mismatch: got {} expected {}",
            output.len(),
            expected
        );
    }

    /// Downsampling 48 000 → 44 100: output length must match the ratio.
    #[test]
    fn resample_downsample_length() {
        let n = 4800_usize; // 100 ms at 48 000 Hz
        let input = vec![0.5_f32; n];
        let output = resample(&input, 48_000, 44_100).unwrap();
        let expected = (n as f64 * 44_100.0 / 48_000.0).round() as usize;
        assert_eq!(
            output.len(),
            expected,
            "downsample length mismatch: got {} expected {}",
            output.len(),
            expected
        );
    }

    /// A DC signal (all 1.0) should remain approximately 1.0 after resampling.
    #[test]
    fn resample_dc_signal_preserved() {
        let input = vec![1.0_f32; 4096];
        let output = resample(&input, 44_100, 48_000).unwrap();
        // Skip the first and last portions (FIR filter transient / tail).
        let mid = &output[64..output.len().saturating_sub(64)];
        assert!(!mid.is_empty());
        for &s in mid {
            assert!(
                (s - 1.0).abs() < 0.01,
                "DC deviation too large: {s} (expected ≈ 1.0)"
            );
        }
    }

    // ── load_ir_from_reader — format decoding ─────────────────────────────────

    /// Mono 16-bit WAV loaded at the same sample rate: values round-trip.
    #[test]
    fn load_ir_mono_i16_same_rate() {
        let samples = vec![0.0_f32, 0.5, -0.5, 1.0, -1.0];
        let wav = make_wav_mono_i16(48_000, &samples);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, 48_000).unwrap();

        assert_eq!(ir.sample_rate, 48_000);
        assert_eq!(ir.num_channels, 1);
        assert_eq!(ir.channels.len(), 1);
        assert_eq!(ir.channels[0].len(), samples.len());

        // 16-bit round-trip error is at most 1 LSB ≈ 3.1e-5
        for (&got, &expected) in ir.channels[0].iter().zip(samples.iter()) {
            assert!(
                (got - expected).abs() < 1.0 / i16::MAX as f32 + 1e-6,
                "16-bit round-trip: got {got}, expected {expected}"
            );
        }
    }

    /// Stereo 16-bit WAV: channels are correctly deinterleaved.
    #[test]
    fn load_ir_stereo_i16_deinterleaved() {
        let left = vec![1.0_f32, 0.5, 0.0];
        let right = vec![0.0_f32, -0.5, -1.0];
        let wav = make_wav_stereo_i16(44_100, &left, &right);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, 44_100).unwrap();

        assert_eq!(ir.num_channels, 2);
        assert_eq!(ir.channels.len(), 2);
        assert_eq!(ir.channels[0].len(), left.len());
        assert_eq!(ir.channels[1].len(), right.len());

        let tol = 1.0 / i16::MAX as f32 + 1e-6;
        for i in 0..left.len() {
            assert!(
                (ir.channels[0][i] - left[i]).abs() < tol,
                "L[{i}]: got {}, expected {}",
                ir.channels[0][i],
                left[i]
            );
            assert!(
                (ir.channels[1][i] - right[i]).abs() < tol,
                "R[{i}]: got {}, expected {}",
                ir.channels[1][i],
                right[i]
            );
        }
    }

    /// 32-bit float WAV: values pass through without quantisation error.
    #[test]
    fn load_ir_float32_exact() {
        let samples = vec![0.123_456_78_f32, -0.987_654_3, 0.5];
        let wav = make_wav_mono_f32(48_000, &samples);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, 48_000).unwrap();

        assert_eq!(ir.channels[0], samples, "float32 round-trip must be exact");
    }

    // ── load_ir_from_reader — resampling ──────────────────────────────────────

    /// WAV recorded at 44 100 Hz loaded at 48 000 Hz: output length matches ratio.
    #[test]
    fn load_ir_resamples_mono() {
        let wav_sr = 44_100_u32;
        let target_sr = 48_000_u32;
        let n = 4410_usize; // 100 ms

        let input: Vec<f32> = (0..n).map(|i| i as f32 / n as f32).collect();
        let wav = make_wav_mono_i16(wav_sr, &input);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, target_sr).unwrap();

        let expected_len = (n as f64 * target_sr as f64 / wav_sr as f64).round() as usize;
        assert_eq!(ir.sample_rate, target_sr);
        assert_eq!(ir.num_channels, 1);
        assert_eq!(
            ir.channels[0].len(),
            expected_len,
            "resampled length mismatch"
        );
    }

    /// Stereo WAV at 44 100 Hz → 48 000 Hz: both channels resampled independently.
    #[test]
    fn load_ir_resamples_stereo_both_channels() {
        let wav_sr = 44_100_u32;
        let target_sr = 48_000_u32;
        let n = 2048_usize;

        let left = vec![0.5_f32; n];
        let right = vec![-0.5_f32; n];
        let wav = make_wav_stereo_i16(wav_sr, &left, &right);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, target_sr).unwrap();

        // rubato's process_all_into_buffer uses ceil() for the expected output length.
        let expected_len = (n as f64 * target_sr as f64 / wav_sr as f64).ceil() as usize;
        assert_eq!(ir.num_channels, 2);
        assert_eq!(ir.channels[0].len(), expected_len, "L channel length");
        assert_eq!(ir.channels[1].len(), expected_len, "R channel length");
    }

    /// When file rate equals target rate no resampler is invoked.
    #[test]
    fn load_ir_no_resample_when_rates_match() {
        let samples = vec![1.0_f32, -1.0, 0.5, -0.5];
        let wav = make_wav_mono_f32(48_000, &samples);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, 48_000).unwrap();
        assert_eq!(ir.channels[0], samples);
    }

    // ── output-buffer / resampler reuse ────────────────────────────────────────

    /// Reusing an `out` buffer must (a) produce exactly the one-shot result and
    /// (b) not reallocate on the second, same-sized call — the amortisation the
    /// per-channel loop relies on.
    #[test]
    fn resample_into_reuses_dirty_buffer() {
        let input: Vec<f32> = (0..2048).map(|i| (i as f32 * 0.01).sin()).collect();
        let expected = resample(&input, 44_100, 48_000).unwrap();

        let mut resampler = make_resampler(44_100, 48_000).unwrap();
        let mut out = Vec::new();

        // First call establishes the allocation (grown to the internal
        // delay+headroom size, then truncated to the valid frame count).
        resample_into(&mut resampler, &input, &mut out).unwrap();
        assert_eq!(out, expected, "first call must match one-shot output");
        let cap_after_first = out.capacity();

        // Dirty the surviving samples, then re-run the identical input: the
        // clear()+resize()+truncate() path must overwrite the junk, and the
        // existing capacity is enough so no reallocation occurs.
        out.iter_mut().for_each(|s| *s = 9.99);
        resampler.reset();
        resample_into(&mut resampler, &input, &mut out).unwrap();

        assert_eq!(out, expected, "reused buffer must match one-shot output");
        assert_eq!(
            out.capacity(),
            cap_after_first,
            "second same-sized call must reuse the allocation"
        );
    }

    /// A single resampler reset between signals must yield the same output as a
    /// fresh resampler per signal — the invariant `load_ir_from_reader` relies
    /// on when reusing one resampler across channels.
    #[test]
    fn reused_resampler_matches_fresh_per_signal() {
        let sig_a: Vec<f32> = (0..1500).map(|i| (i as f32 * 0.02).sin()).collect();
        let sig_b: Vec<f32> = (0..1500).map(|i| (i as f32 * 0.05).cos()).collect();

        let fresh_a = resample(&sig_a, 48_000, 44_100).unwrap();
        let fresh_b = resample(&sig_b, 48_000, 44_100).unwrap();

        let mut resampler = make_resampler(48_000, 44_100).unwrap();
        let mut out = Vec::new();

        resampler.reset();
        resample_into(&mut resampler, &sig_a, &mut out).unwrap();
        assert_eq!(out, fresh_a, "signal A after reuse must match fresh");
        let reused_a = out.clone();

        resampler.reset();
        resample_into(&mut resampler, &sig_b, &mut out).unwrap();
        assert_eq!(out, fresh_b, "signal B after reuse must match fresh");

        // Sanity: distinct inputs give distinct outputs (no stale carry-over).
        assert_ne!(reused_a, out);
    }

    /// True-stereo 4-channel IR: every channel is resampled correctly through
    /// the reused resampler (exercises `reset()` across more than two channels).
    #[test]
    fn load_ir_resamples_four_channels() {
        let wav_sr = 44_100_u32;
        let target_sr = 48_000_u32;
        // Long enough for the FFT resampler to reach steady state (matches the
        // proven `resample_dc_signal_preserved` test scale).
        let n = 4096_usize;

        let ch0: Vec<f32> = vec![0.25_f32; n];
        let ch1: Vec<f32> = vec![-0.25_f32; n];
        let ch2: Vec<f32> = vec![0.75_f32; n];
        let ch3: Vec<f32> = vec![-0.75_f32; n];
        let wav = make_wav_multi_i16(wav_sr, &[&ch0, &ch1, &ch2, &ch3]);
        let reader = hound::WavReader::new(wav).unwrap();
        let ir = load_ir_from_reader(reader, target_sr).unwrap();

        let expected_len = (n as f64 * target_sr as f64 / wav_sr as f64).ceil() as usize;
        assert_eq!(ir.num_channels, 4);
        assert_eq!(ir.channels.len(), 4);
        for (c, ch) in ir.channels.iter().enumerate() {
            assert_eq!(ch.len(), expected_len, "channel {c} length mismatch");
        }

        // Each DC channel should resample back to its constant level (skip the
        // FIR transient at head/tail).
        let levels = [0.25_f32, -0.25, 0.75, -0.75];
        let tol = 1.0 / i16::MAX as f32 + 0.02;
        for (ch, &level) in ir.channels.iter().zip(levels.iter()) {
            let mid = &ch[64..ch.len().saturating_sub(64)];
            assert!(!mid.is_empty());
            for &s in mid {
                assert!((s - level).abs() < tol, "expected ≈ {level}, got {s}");
            }
        }
    }
}