audio-resample-bsd 0.2.1

RT-safe audio resampling crate (rubato-based) — the only processing interface callable directly from the real-time audio thread
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
//! RT-safe [`Resampler`] standard implementation backed by the rubato `Fft`
//! synchronous resampler.
//!
//! [`RubatoResampler`] operates at a fixed input ratio (`FixedSync::Input`). To
//! keep the processing path ([`Resampler::process_into_buffer`]) **zero-copy and
//! allocation-free**, the caller-provided planar-flat slice is wrapped directly
//! with a [`rubato::audioadapter_buffers::direct::SequentialSlice`] adapter and
//! handed to rubato. The "sequential" layout of `SequentialSlice`
//! (`[ch0_frames..., ch1_frames...]`) matches the planar-flat layout of the
//! [`Resampler`] contract exactly, so no deinterleave/re-interleave copy is
//! needed.
//!
//! # Real-time safety
//!
//! `process_into_buffer` may be called directly from the RT thread:
//! - **No heap allocation** — rubato `Fft` documents an allocation-free
//!   processing path.
//! - **No copy** — `SequentialSlice` wraps the caller's slice by reference.
//! - **No panic** — all length validation returns a [`ResampleError`].
//!
//! [`Resampler::set_rate`] rebuilds the inner `Fft`, so it **allocates** and is
//! not RT-safe (call only between audio cycles).

use rubato::{
    audioadapter_buffers::direct::SequentialSlice, Fft, FixedSync,
    Resampler as RubatoResamplerTrait,
};

use crate::{ResampleError, Resampler};

/// Upper bound for sample rates. It far exceeds any real audio sample rate
/// (up to ~384 kHz) and guards the `f64` -> `usize` conversion against loss.
const MAX_RATE: f64 = 4_000_000.0;

/// RT-safe resampler backed by the rubato `Fft` synchronous resampler.
///
/// It operates at a fixed input ratio (`FixedSync::Input`). On the processing
/// path ([`process_into_buffer`][Resampler::process_into_buffer]) it wraps the
/// caller-provided planar-flat slice directly with a [`SequentialSlice`] adapter
/// and hands it to rubato **zero-copy and allocation-free**.
///
/// # Panics
///
/// No method on this type panics. Every error on the processing path is
/// returned as a [`ResampleError`].
#[derive(Debug)]
pub struct RubatoResampler {
    inner: Fft<f32>,
    channels: usize,
    chunk_size: usize,
    input_rate: f64,
    output_rate: f64,
}

impl RubatoResampler {
    /// Creates a new resampler. **Call this before entering the RT thread** so
    /// that all internal state is prepared.
    ///
    /// `input_rate`/`output_rate` must be positive finite values (>= 1.0 Hz,
    /// <= `MAX_RATE`, representable as integer Hz without loss). `channels >= 1`
    /// and `chunk_size >= 1` are required.
    ///
    /// # Errors
    ///
    /// - rate <= 0, non-finite, or > `MAX_RATE` ->
    ///   [`ResampleError::InvalidSampleRate`].
    /// - `channels == 0` -> [`ResampleError::InvalidChannelCount`].
    /// - `chunk_size == 0` -> [`ResampleError::InvalidChunkSize`].
    /// - rubato `Fft` construction failure -> [`ResampleError::ResampleFailed`].
    pub fn new(
        input_rate: f64,
        output_rate: f64,
        channels: usize,
        chunk_size: usize,
    ) -> Result<Self, ResampleError> {
        if !is_valid_rate(input_rate) {
            return Err(ResampleError::InvalidSampleRate { rate: input_rate });
        }
        if !is_valid_rate(output_rate) {
            return Err(ResampleError::InvalidSampleRate { rate: output_rate });
        }
        if channels == 0 {
            return Err(ResampleError::InvalidChannelCount(channels));
        }
        if chunk_size == 0 {
            return Err(ResampleError::InvalidChunkSize(chunk_size));
        }
        let rate_in = rate_to_usize(input_rate)
            .ok_or(ResampleError::InvalidSampleRate { rate: input_rate })?;
        let rate_out = rate_to_usize(output_rate)
            .ok_or(ResampleError::InvalidSampleRate { rate: output_rate })?;
        let inner = Fft::<f32>::new(rate_in, rate_out, chunk_size, channels, FixedSync::Input)
            .map_err(|e| ResampleError::ResampleFailed(e.to_string()))?;
        Ok(Self {
            inner,
            channels,
            chunk_size,
            input_rate,
            output_rate,
        })
    }

    /// Returns the fixed number of input frames (per channel).
    #[must_use]
    pub fn input_chunk_size(&self) -> usize {
        self.chunk_size
    }

    /// Returns the upper bound on output frames (per channel). The RT caller
    /// must pre-allocate the output buffer to at least this size.
    #[must_use]
    pub fn output_frames_max(&self) -> usize {
        self.inner.output_frames_max()
    }

    /// Returns the channel count.
    #[must_use]
    pub fn channels(&self) -> usize {
        self.channels
    }

    /// Returns the input sample rate (Hz).
    #[must_use]
    pub fn input_rate(&self) -> f64 {
        self.input_rate
    }

    /// Returns the output sample rate (Hz).
    #[must_use]
    pub fn output_rate(&self) -> f64 {
        self.output_rate
    }

    /// Returns the resampler's group delay, in output frames.
    ///
    /// rubato `Fft` introduces a **fixed delay** equal to half the internal FFT
    /// block size, expressed in output frames. For offline / full-clip
    /// processing the caller may trim this many leading output frames to align
    /// output with input. For RT streaming the caller absorbs the delay through
    /// buffering.
    ///
    /// This is a read-only query, so it is safe on the RT path (no allocation,
    /// no locking).
    #[must_use]
    pub fn output_delay(&self) -> usize {
        self.inner.output_delay()
    }
}

impl Resampler for RubatoResampler {
    fn process_into_buffer(
        &mut self,
        input: &[f32],
        output: &mut [f32],
    ) -> Result<usize, ResampleError> {
        // 1. Validate input length (fixed input = channels × chunk_size).
        let expected = self.channels * self.chunk_size;
        if input.len() != expected {
            return Err(ResampleError::InputLengthMismatch {
                expected,
                actual: input.len(),
            });
        }
        // 2. Query this call's output frame count + validate the output buffer.
        let out_n = self.inner.output_frames_next();
        let needed = self.channels * out_n;
        if output.len() < needed {
            return Err(ResampleError::BufferTooSmall {
                needed,
                have: output.len(),
            });
        }
        // 3. Wrap the planar-flat slice zero-copy with SequentialSlice and run
        //    rubato. The SequentialSlice layout ([ch0.., ch1..]) matches this
        //    contract, so no copy/deinterleave is needed. RT path: no
        //    allocation, no copy, no panic.
        let input_adapter = SequentialSlice::new(input, self.channels, self.chunk_size)
            .map_err(|e| ResampleError::ResampleFailed(e.to_string()))?;
        let mut output_adapter = SequentialSlice::new_mut(output, self.channels, out_n)
            .map_err(|e| ResampleError::ResampleFailed(e.to_string()))?;
        let (_frames_read, frames_written) = self
            .inner
            .process_into_buffer(&input_adapter, &mut output_adapter, None)
            .map_err(|e| ResampleError::ResampleFailed(e.to_string()))?;
        Ok(frames_written)
    }

    fn set_rate(&mut self, input_rate: f64, output_rate: f64) {
        // Non-RT path: rebuilds the inner Fft (allocates). Invalid rates are
        // silently ignored.
        if !is_valid_rate(input_rate) || !is_valid_rate(output_rate) {
            return;
        }
        let Some(rate_in) = rate_to_usize(input_rate) else {
            return;
        };
        let Some(rate_out) = rate_to_usize(output_rate) else {
            return;
        };
        let Ok(new_inner) = Fft::<f32>::new(
            rate_in,
            rate_out,
            self.chunk_size,
            self.channels,
            FixedSync::Input,
        ) else {
            return;
        };
        self.inner = new_inner;
        self.input_rate = input_rate;
        self.output_rate = output_rate;
    }
}

/// Checks that the sample rate is a valid positive finite value (>= 1.0).
const fn is_valid_rate(rate: f64) -> bool {
    rate.is_finite() && rate >= 1.0
}

/// Converts a validated sample rate (`f64`) to `usize`.
///
/// Assumes `is_valid_rate` has passed. Returns `None` if the value is outside
/// `[1.0, MAX_RATE]`. In-range values are stored in `usize` without loss of
/// magnitude or sign.
fn rate_to_usize(rate: f64) -> Option<usize> {
    if rate > MAX_RATE {
        return None;
    }
    // Guard passed: rate in [1.0, 4_000_000.0] -> lossless, positive usize.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let value = rate as usize;
    Some(value)
}

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

    /// Floating-point approximate equality (test helper).
    fn approx_eq(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-9
    }

    /// Generates a mono sine wave of `frames` samples (given freq/rate).
    /// `phase_offset` is a frame offset for producing consecutive chunks.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    fn sine_chunk(freq: f64, rate: f64, frames: usize, phase_offset: usize) -> Vec<f32> {
        let omega = 2.0_f64 * std::f64::consts::TAU * freq / rate;
        (0..frames)
            .map(|i| {
                let t = (i + phase_offset) as f64;
                (omega * t).sin() as f32
            })
            .collect()
    }

    #[test]
    fn new_rejects_zero_sample_rate() {
        let err = RubatoResampler::new(0.0, 48000.0, 1, 256).unwrap_err();
        assert_eq!(err, ResampleError::InvalidSampleRate { rate: 0.0 });
        let err = RubatoResampler::new(44100.0, 0.0, 1, 256).unwrap_err();
        assert_eq!(err, ResampleError::InvalidSampleRate { rate: 0.0 });
    }

    #[test]
    fn new_rejects_non_finite_sample_rate() {
        let err = RubatoResampler::new(f64::NAN, 48000.0, 1, 256).unwrap_err();
        assert!(err.to_string().contains("invalid sample rate"));
    }

    #[test]
    fn new_rejects_zero_channels() {
        let err = RubatoResampler::new(44100.0, 48000.0, 0, 256).unwrap_err();
        assert_eq!(err, ResampleError::InvalidChannelCount(0));
    }

    #[test]
    fn new_rejects_zero_chunk_size() {
        let err = RubatoResampler::new(44100.0, 48000.0, 1, 0).unwrap_err();
        assert_eq!(err, ResampleError::InvalidChunkSize(0));
    }

    #[test]
    fn process_into_buffer_rejects_wrong_input_length() {
        let mut rs = RubatoResampler::new(44100.0, 48000.0, 1, 256).unwrap();
        let input = vec![0.0_f32; 128]; // expects 256, got 128
        let mut output = vec![0.0_f32; rs.output_frames_max()];
        let err = rs.process_into_buffer(&input, &mut output).unwrap_err();
        assert_eq!(
            err,
            ResampleError::InputLengthMismatch {
                expected: 256,
                actual: 128,
            }
        );
    }

    #[test]
    fn process_into_buffer_rejects_small_output() {
        let mut rs = RubatoResampler::new(44100.0, 48000.0, 1, 256).unwrap();
        let input = vec![0.0_f32; 256];
        // Due to its group delay, rubato Fft may report an output frame count of
        // 0 on early calls (out_n==0 -> needed==0 -> any buffer suffices). Once
        // it starts producing output (out_n>0), a too-small buffer triggers
        // BufferTooSmall. Verify it triggers within a bounded number of calls.
        for _ in 0..256 {
            let mut tiny = vec![0.0_f32; 1];
            match rs.process_into_buffer(&input, &mut tiny) {
                Ok(_) => {} // out_n still 0 (or 1); keep priming.
                Err(ResampleError::BufferTooSmall { needed, have }) => {
                    assert_eq!(have, 1);
                    assert!(needed > 1, "out_n must exceed 1");
                    return;
                }
                Err(other) => panic!("unexpected error: {other:?}"),
            }
        }
        panic!("BufferTooSmall did not trigger within 256 iterations");
    }

    #[test]
    fn process_into_buffer_writes_something_for_sine() {
        // rubato Fft has a group delay (half the internal FFT block), so a
        // single chunk may yield all-zero output. Feed several chunks to flush
        // the delay, then assert the output is non-zero.
        let chunk = 1024;
        let mut rs = RubatoResampler::new(44100.0, 48000.0, 1, chunk).unwrap();
        let mut max_abs = 0.0_f32;
        for blk in 0..16_usize {
            let input = sine_chunk(1000.0, 44100.0, chunk, blk * chunk);
            let mut output = vec![0.0_f32; rs.output_frames_max()];
            let written = rs.process_into_buffer(&input, &mut output).unwrap();
            for s in &output[..written] {
                let abs = s.abs();
                if abs > max_abs {
                    max_abs = abs;
                }
            }
        }
        assert!(
            max_abs > 0.0,
            "output must not be all zero (max_abs={max_abs})"
        );
    }

    #[test]
    fn set_rate_changes_output_rate() {
        let mut rs = RubatoResampler::new(44100.0, 48000.0, 1, 256).unwrap();
        rs.set_rate(48000.0, 96000.0);
        assert!(approx_eq(rs.input_rate(), 48000.0));
        assert!(approx_eq(rs.output_rate(), 96000.0));
        // Confirm processing still works after the change.
        let input = sine_chunk(1000.0, 48000.0, 256, 0);
        let mut output = vec![0.0_f32; rs.output_frames_max()];
        let written = rs.process_into_buffer(&input, &mut output).unwrap();
        assert!(written > 0);
    }

    #[test]
    fn set_rate_ignores_invalid_rate() {
        let mut rs = RubatoResampler::new(44100.0, 48000.0, 1, 256).unwrap();
        rs.set_rate(0.0, 96000.0);
        assert!(approx_eq(rs.input_rate(), 44100.0));
        assert!(approx_eq(rs.output_rate(), 48000.0));
        rs.set_rate(-1.0, 96000.0);
        assert!(approx_eq(rs.input_rate(), 44100.0));
    }

    #[test]
    fn stereo_two_channels_processes_both() {
        let chunk = 512;
        let ch = 2;
        let mut rs = RubatoResampler::new(44100.0, 48000.0, ch, chunk).unwrap();
        // Channel 0 = 1 kHz, channel 1 = 2 kHz (distinct signals).
        let mut max0 = 0.0_f32;
        let mut max1 = 0.0_f32;
        for blk in 0..16_usize {
            let c0 = sine_chunk(1000.0, 44100.0, chunk, blk * chunk);
            let c1 = sine_chunk(2000.0, 44100.0, chunk, blk * chunk);
            let mut input = Vec::with_capacity(ch * chunk);
            input.extend_from_slice(&c0);
            input.extend_from_slice(&c1);
            let mut output = vec![0.0_f32; ch * rs.output_frames_max()];
            let written = rs.process_into_buffer(&input, &mut output).unwrap();
            // planar: output = [ch0(0..written), ch1(0..written)]
            for s in &output[..written] {
                let abs = s.abs();
                if abs > max0 {
                    max0 = abs;
                }
            }
            for s in &output[written..2 * written] {
                let abs = s.abs();
                if abs > max1 {
                    max1 = abs;
                }
            }
        }
        assert!(max0 > 0.0, "channel 0 processed (max0={max0})");
        assert!(max1 > 0.0, "channel 1 processed (max1={max1})");
    }

    #[test]
    fn accessors_return_construction_values() {
        let rs = RubatoResampler::new(44100.0, 48000.0, 2, 256).unwrap();
        assert_eq!(rs.channels(), 2);
        assert_eq!(rs.input_chunk_size(), 256);
        assert!(approx_eq(rs.input_rate(), 44100.0));
        assert!(approx_eq(rs.output_rate(), 48000.0));
        // output_frames_max is decided by rubato; only positivity is guaranteed.
        assert!(rs.output_frames_max() > 0);
    }
}