resampler/lib.rs
1//! # Audio resampling library
2//!
3//! Resampler is a small, zero-dependency crate for high-quality audio resampling between common sample rates.
4//! It provides both FFT-based and FIR-based resamplers optimized for different use cases.
5//!
6//! ## Usage Examples
7//!
8//! ### FFT-Based Resampler (Highest Quality)
9//!
10//! ```rust
11//! use resampler::{ResamplerFft, SampleRate};
12//!
13//! // Create a stereo resampler (2 channels) from 44.1 kHz to 48 kHz.
14//! let mut resampler = ResamplerFft::<2>::new(SampleRate::Hz44100, SampleRate::Hz48000);
15//!
16//! // Get required buffer sizes (already includes all channels).
17//! let input_size = resampler.chunk_size_input();
18//! let output_size = resampler.chunk_size_output();
19//!
20//! // Create input and output buffers (interleaved format: [L0, R0, L1, R1, ...]).
21//! let input = vec![0.0f32; input_size];
22//! let mut output = vec![0.0f32; output_size];
23//!
24//! resampler.resample(&input, &mut output).unwrap();
25//! ```
26//!
27//! ### FIR-Based Resampler (Low Latency, Streaming)
28//!
29//! ```rust
30//! use resampler::{Attenuation, Latency, ResamplerFir, SampleRate};
31//!
32//! // Create a stereo resampler with configurable latency (16, 32, or 64 samples).
33//! let mut resampler = ResamplerFir::<2>::new(
34//! SampleRate::Hz48000,
35//! SampleRate::Hz44100,
36//! Latency::Sample64,
37//! Attenuation::Db90,
38//! );
39//!
40//! // Streaming API - accepts arbitrary input buffer sizes.
41//! let input = vec![0.0f32; 512];
42//! let mut output = vec![0.0f32; resampler.buffer_size_output()];
43//!
44//! let (consumed, produced) = resampler.resample(&input, &mut output).unwrap();
45//! println!("Consumed {consumed} samples, produced {produced} samples");
46//! ```
47//!
48//! ## Choosing a Resampler
49//!
50//! Both resamplers provide good quality, but are optimized for different use cases:
51//!
52//! | Feature | [`ResamplerFft`] | [`ResamplerFir`] |
53//! |-------------|----------------------------------|------------------------------|
54//! | Quality | Very good (sharp rolloff) | Good (slow rolloff) |
55//! | Performance | Very fast | Fast (configurable) |
56//! | Latency | ~256 samples | 16-64 samples (configurable) |
57//! | API | Fixed chunk size | Flexible streaming |
58//! | Best for | Non-latency sensitive processing | Low-latency processing |
59//!
60//! Use [`ResamplerFft`] when:
61//! - You need the absolute highest quality
62//! - Latency is not a concern
63//! - Processing pre-recorded audio files
64//!
65//! Use [`ResamplerFir`] when:
66//! - You need low latency (real-time audio)
67//! - You can live with a slower rolloff
68//! - Working with streaming data
69//!
70//! ## FFT-Based Implementation
71//!
72//! The resampler uses an FFT-based overlap-add algorithm with Kaiser windowing for high-quality
73//! audio resampling. Key technical details:
74//!
75//! - Custom mixed-radix FFT with the Stockham Autosort algorithm.
76//! - SIMD optimizations: All butterflies have SSE2, SSE4.2, AVX+FMA, and ARM NEON implementations.
77//! - Stopband attenuation of -100 dB using the Kaiser windows function.
78//! - Latency around 256 samples.
79//!
80//! ## FIR-Based Implementation
81//!
82//! The FIR resampler uses a polyphase filter with linear interpolation for high-quality audio
83//! resampling with low latency. Key technical details:
84//!
85//! - Polyphase decomposition: 1024 phases with linear interpolation between phases.
86//! - SIMD optimizations: Convolution kernels optimized with SSE2, SSE4.2, AVX+FMA, AVX-512
87//! and ARM NEON.
88//! - Configurable filter length: 32, 64, or 128 taps (16, 32, or 64 samples latency).
89//! - Adjustable rolloff and stopband attenuation,
90//! - Streaming API: Accepts arbitrary input buffer sizes for flexible real-time processing,
91//!
92//! ## Performance
93//!
94//! Both resamplers include SIMD optimizations with runtime CPU feature detection for maximum
95//! performance and compatibility.
96//!
97//! But for up to 25% better performance on x86_64, compile with `target-cpu=x86-64-v3`
98//! (enables AVX2, FMA, and other optimizations).
99//!
100//! Overall the SIMD for x86_64 have four levels implemented, targeting four possible CPU
101//! generations that build up on each other:
102//!
103//! * x86-64-v1: 128-bit SSE2 (around 2003-2004)
104//! * x86-64-v2: 128-bit SSE4.2 (around 2008-2011)
105//! * x86-64-v3: 256-bit AVX+FMA (around 2013-2015)
106//! * x86-64-v4: 512-bit AVX-512 (around 2017-2022)
107//!
108//! ## no-std Compatibility
109//!
110//! The library supports `no-std` environments with `alloc`. To use the library in a `no-std`
111//! environment, enable the `no_std` feature:
112//!
113//! ```toml
114//! [dependencies]
115//! resampler = { version = "0.2", features = ["no_std"] }
116//! ```
117//!
118//! ### Behavior Differences
119//!
120//! When the `no_std` feature is enabled:
121//!
122//! - Caching: The library will not cache FFT and FIR objects globally to shorten resampler creation
123//! time and lower overall memory consumption for multiple resamplers.
124//!
125//! - No runtime detection of SIMD functionality. You need to activate SIMD via compile time target
126//! features.
127//!
128//! The default build (without `no_std` feature) has zero dependencies and uses the standard
129//! library for optimal performance and memory efficiency through global caching.
130//!
131//! ## Alternatives
132//!
133//! Other high-quality audio resampling libraries in Rust are:
134//!
135//! - [Rubato](https://github.com/HEnquist/rubato): The overlap-add resampling approach used in this
136//! library is based on Rubato's implementation.
137//!
138//! ## License
139//!
140//! Licensed under either of
141//!
142//! - Apache License, Version 2.0
143//! - MIT license
144//!
145//! at your option.
146#![cfg_attr(feature = "no_std", no_std)]
147#![forbid(missing_docs)]
148
149extern crate alloc;
150
151mod error;
152mod fft;
153mod fir;
154mod resampler_fft;
155mod resampler_fir;
156mod window;
157
158pub use error::ResampleError;
159pub(crate) use fft::*;
160pub use resampler_fft::*;
161pub use resampler_fir::{Attenuation, Latency, ResamplerFir};
162
163/// All sample rates the resampler can operate on.
164#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Hash)]
165pub enum SampleRate {
166 /// 22.5 kHz
167 Hz22050,
168 /// 16 kHz
169 Hz16000,
170 /// 32 kHz
171 Hz32000,
172 /// 44.1 kHz
173 Hz44100,
174 /// 48 kHz
175 Hz48000,
176 /// 88.2 kHz
177 Hz88200,
178 /// 96 kHz
179 Hz96000,
180 /// 176.4 kHz
181 Hz176400,
182 /// 192 kHz
183 Hz192000,
184 /// 384 kHz
185 Hz384000,
186}
187
188impl SampleRate {
189 pub(crate) fn family(self) -> SampleRateFamily {
190 match self {
191 SampleRate::Hz22050 => SampleRateFamily::Hz22050,
192 SampleRate::Hz16000 => SampleRateFamily::Hz16000,
193 SampleRate::Hz32000 => SampleRateFamily::Hz16000,
194 SampleRate::Hz44100 => SampleRateFamily::Hz22050,
195 SampleRate::Hz48000 => SampleRateFamily::Hz48000,
196 SampleRate::Hz88200 => SampleRateFamily::Hz22050,
197 SampleRate::Hz96000 => SampleRateFamily::Hz48000,
198 SampleRate::Hz176400 => SampleRateFamily::Hz22050,
199 SampleRate::Hz192000 => SampleRateFamily::Hz48000,
200 SampleRate::Hz384000 => SampleRateFamily::Hz48000,
201 }
202 }
203
204 /// Returns the multiplier of the actual sample rate relative to its base family.
205 ///
206 /// For example:
207 /// - 22050 is the base of its family, so it returns 1
208 /// - 44100 is 2× the base (22050), so it returns 2
209 /// - 96000 is 2× the base (48000), so it returns 2
210 pub(crate) fn family_multiplier(self) -> u32 {
211 let actual_rate: u32 = self.into();
212 let family_rate: u32 = self.family().into();
213 actual_rate / family_rate
214 }
215}
216
217impl From<SampleRate> for u32 {
218 fn from(value: SampleRate) -> Self {
219 match value {
220 SampleRate::Hz22050 => 22050,
221 SampleRate::Hz16000 => 16000,
222 SampleRate::Hz32000 => 32000,
223 SampleRate::Hz44100 => 44100,
224 SampleRate::Hz48000 => 48000,
225 SampleRate::Hz88200 => 88200,
226 SampleRate::Hz96000 => 96000,
227 SampleRate::Hz176400 => 176400,
228 SampleRate::Hz192000 => 192000,
229 SampleRate::Hz384000 => 384000,
230 }
231 }
232}
233
234impl TryFrom<u32> for SampleRate {
235 type Error = ();
236
237 fn try_from(value: u32) -> Result<Self, Self::Error> {
238 match value {
239 22050 => Ok(SampleRate::Hz22050),
240 16000 => Ok(SampleRate::Hz16000),
241 32000 => Ok(SampleRate::Hz32000),
242 44100 => Ok(SampleRate::Hz44100),
243 48000 => Ok(SampleRate::Hz48000),
244 88200 => Ok(SampleRate::Hz88200),
245 96000 => Ok(SampleRate::Hz96000),
246 176400 => Ok(SampleRate::Hz176400),
247 192000 => Ok(SampleRate::Hz192000),
248 384000 => Ok(SampleRate::Hz384000),
249 _ => Err(()),
250 }
251 }
252}
253
254/// The "family" of "lineage" that every sample rate must be a multiple of.
255#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Hash)]
256enum SampleRateFamily {
257 /// 22.5 kHz Family
258 Hz22050,
259 /// 16.0 kHz Family
260 Hz16000,
261 /// 48 kHz Family
262 Hz48000,
263}
264
265impl From<SampleRateFamily> for u32 {
266 fn from(value: SampleRateFamily) -> Self {
267 match value {
268 SampleRateFamily::Hz22050 => 22050,
269 SampleRateFamily::Hz16000 => 16000,
270 SampleRateFamily::Hz48000 => 48000,
271 }
272 }
273}