audio_samples 1.0.7

A typed audio processing library for Rust that treats audio as a first-class, invariant-preserving object rather than an unstructured numeric buffer.
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
//! Perceptual band layout constructors and frequency-scale helpers.
//!
//! This module provides preset [`BandLayout`] constructors that partition the
//! audible spectrum into perceptually-motivated bands, along with the
//! conversion helpers that underpin them.
//!
//! Two scales are supported:
//!
//! - **Bark** – 24 critical bands derived from the Traunmüller (1990) formula.
//!   Closely models the ear's frequency resolution and is the foundation for
//!   most MPEG psychoacoustic models.
//! - **Mel** – linearly-spaced on the Mel scale (O'Shaughnessy formula).
//!   Commonly used for speech and music feature extraction.
//!
//! Each [`Band`] produced by these constructors stores:
//! - `start_bin` / `end_bin` — indices into the caller's frequency-bin array
//!   (MDCT or FFT, whichever was passed as `n_bins`).
//! - `centre_frequency` — centre frequency in Hz.
//! - `perceptual_position` — normalised position in [0, 1] on the respective scale.
//!
//! ## Example
//!
//! ```rust
//! # #[cfg(feature = "psychoacoustic")] {
//! use audio_samples::BandLayout;
//! use std::num::NonZeroUsize;
//!
//! // 24 Bark bands for a 44.1 kHz signal with 1024 MDCT bins.
//! let layout = BandLayout::bark(
//!     NonZeroUsize::new(24).unwrap(),
//!     44100.0,
//!     NonZeroUsize::new(1024).unwrap(),
//! );
//! assert_eq!(layout.len().get(), 24);
//! # }
//! ```

use std::num::NonZeroUsize;

use non_empty_slice::NonEmptySlice;

use super::{Band, BandLayout};

// ── Bark-scale helpers ────────────────────────────────────────────────────────

/// Converts a frequency in Hz to its Bark-scale value.
///
/// Uses the Traunmüller (1990) formula:
/// `bark = 26.81 * hz / (1960 + hz) − 0.53`
///
/// # Arguments
/// - `hz` – Frequency in hertz. Values ≤ 0 are clamped to 0 Hz before conversion.
///
/// # Returns
/// Bark value, clamped to a minimum of 0.0.
#[inline]
#[must_use]
pub fn hz_to_bark(hz: f32) -> f32 {
    if hz <= 0.0 {
        return 0.0;
    }
    (26.81_f32 * hz / (1960.0_f32 + hz) - 0.53_f32).max(0.0)
}

/// Converts a Bark-scale value back to a frequency in Hz.
///
/// Inverse of the Traunmüller (1990) formula.
///
/// # Arguments
/// - `bark` – Bark value. Values < 0 are clamped to 0 before conversion.
///
/// # Returns
/// Frequency in hertz, clamped to a minimum of 0.0 Hz.
#[inline]
#[must_use]
pub fn bark_to_hz(bark: f32) -> f32 {
    let bark = bark.max(0.0);
    (1960.0_f32 * (bark + 0.53_f32) / (26.28_f32 - bark)).max(0.0)
}

// ── Mel-scale helpers ─────────────────────────────────────────────────────────

/// Converts a frequency in Hz to its Mel-scale value.
///
/// Uses the O'Shaughnessy formula: `mel = 2595 × log10(1 + hz / 700)`.
///
/// # Arguments
/// - `hz` – Frequency in hertz. Values ≤ 0 are clamped to 0 Hz.
///
/// # Returns
/// Mel value, clamped to a minimum of 0.0.
#[inline]
#[must_use]
pub fn hz_to_mel(hz: f32) -> f32 {
    if hz <= 0.0 {
        return 0.0;
    }
    2595.0_f32 * (1.0_f32 + hz / 700.0_f32).log10()
}

/// Converts a Mel-scale value back to a frequency in Hz.
///
/// Inverse of the O'Shaughnessy formula: `hz = 700 × (10^(mel / 2595) − 1)`.
///
/// # Arguments
/// - `mel` – Mel value. Values < 0 are clamped to 0.
///
/// # Returns
/// Frequency in hertz, clamped to a minimum of 0.0 Hz.
#[inline]
#[must_use]
pub fn mel_to_hz(mel: f32) -> f32 {
    if mel <= 0.0 {
        return 0.0;
    }
    (700.0_f32 * (10.0_f32.powf(mel / 2595.0_f32) - 1.0_f32)).max(0.0)
}

// ── Shared bin-mapping helper ─────────────────────────────────────────────────

/// Maps a frequency in Hz to the nearest integer bin index.
///
/// Assumes a linear spacing from 0 Hz (bin 0) to Nyquist (bin `n_bins − 1`).
/// The result is clamped to `[0, n_bins − 1]`.
#[inline]
fn hz_to_bin(hz: f32, sample_rate_hz: f32, n_bins: usize) -> usize {
    let nyquist = sample_rate_hz / 2.0;
    let bin = (hz / nyquist * (n_bins - 1) as f32).round() as isize;
    bin.clamp(0, (n_bins - 1) as isize) as usize
}

// ── ERB-scale helpers ─────────────────────────────────────────────────────────

/// Converts a frequency in Hz to its ERB-bandwidth value (Glasberg & Moore, 1990).
///
/// `ERB(f) = 24.7 × (4.37 × f/1000 + 1)`
///
/// This gives the bandwidth of the equivalent rectangular auditory filter at `f`.
/// At 0 Hz the minimum value is 24.7. The function is linear in Hz, which makes
/// it a good approximation for spacing perceptual filters from low to high frequency.
///
/// # Arguments
/// - `hz` – Frequency in hertz. Negative values are clamped to 0.
///
/// # Returns
/// ERB-bandwidth value (always ≥ 24.7).
#[inline]
#[must_use]
pub fn hz_to_erb(hz: f32) -> f32 {
    24.7_f32 * (4.37_f32 * hz.max(0.0) / 1000.0_f32 + 1.0_f32)
}

/// Converts an ERB-bandwidth value back to a frequency in Hz.
///
/// Inverse of the Glasberg & Moore (1990) formula:
/// `f = 1000 × (erb/24.7 − 1) / 4.37`
///
/// # Arguments
/// - `erb` – ERB-bandwidth value. Values below 24.7 (the minimum, corresponding to 0 Hz)
///   are clamped to produce 0 Hz.
///
/// # Returns
/// Frequency in hertz, clamped to a minimum of 0.0.
#[inline]
#[must_use]
pub fn erb_to_hz(erb: f32) -> f32 {
    (1000.0_f32 * (erb / 24.7_f32 - 1.0_f32) / 4.37_f32).max(0.0)
}

// ── Derived layout helpers ────────────────────────────────────────────────────

/// Scales a [`BandLayout`] from one spectral-bin count to another.
///
/// Each band's `start_bin` and `end_bin` are scaled proportionally from
/// `from_n_bins` to `to_n_bins`, preserving the frequency mapping while
/// adapting to a different MDCT window size. This is used when window
/// switching re-analyses a transient region with a shorter window that
/// produces fewer spectral bins.
///
/// # Arguments
/// - `layout` – Layout to scale.
/// - `from_n_bins` – Bin count the layout was built for.
/// - `to_n_bins` – Target bin count.
///
/// # Returns
/// A new [`BandLayout`] with the same number of bands and scaled bin ranges.
#[must_use]
pub fn scale_band_layout(
    layout: &BandLayout,
    from_n_bins: NonZeroUsize,
    to_n_bins: NonZeroUsize,
) -> BandLayout {
    let from = from_n_bins.get();
    let to = to_n_bins.get();

    let bands: Vec<super::Band> = layout
        .as_slice()
        .iter()
        .map(|band| {
            let start = band.start_bin * to / from;
            let end = (band.end_bin * to / from).max(start + 1).min(to);
            // SAFETY: end > start is enforced by the .max(start + 1) above.
            unsafe { super::Band::new(start, end, band.centre_frequency, band.perceptual_position) }
        })
        .collect();

    // SAFETY: layout is non-empty (BandLayout invariant), so bands is non-empty.
    let ne = unsafe { NonEmptySlice::new_unchecked(&bands) };
    BandLayout::new(ne)
}

// ── BandLayout preset constructors ───────────────────────────────────────────

impl BandLayout {
    /// Creates a Bark-scale band layout.
    ///
    /// Divides the spectrum from 0 Hz to Nyquist into `n_bands` bands spaced
    /// evenly on the Bark scale. Bark bands closely model the ear's critical
    /// bands and are used by MPEG psychoacoustic models.
    ///
    /// `n_bins` is the number of spectral bins in the caller's frequency
    /// representation (e.g. `MdctParams::n_coefficients()` for MDCT, or
    /// `n_fft / 2 + 1` for a real FFT). Bin indices in the returned bands
    /// index into that array.
    ///
    /// # Arguments
    /// - `n_bands` – Number of bands. 24 covers the full audible range.
    /// - `sample_rate_hz` – Sample rate of the audio signal in Hz.
    /// - `n_bins` – Total number of spectral bins.
    ///
    /// # Returns
    /// A `BandLayout` with `n_bands` entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "psychoacoustic")] {
    /// use audio_samples::BandLayout;
    /// use std::num::NonZeroUsize;
    ///
    /// let layout = BandLayout::bark(
    ///     NonZeroUsize::new(24).unwrap(),
    ///     44100.0,
    ///     NonZeroUsize::new(1024).unwrap(),
    /// );
    /// assert_eq!(layout.len().get(), 24);
    /// // All bands fit within the bin range.
    /// for band in layout.as_slice().iter() {
    ///     assert!(band.end_bin <= 1024);
    ///     assert!(band.end_bin > band.start_bin);
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn bark(n_bands: NonZeroUsize, sample_rate_hz: f32, n_bins: NonZeroUsize) -> Self {
        let n = n_bands.get();
        let bins = n_bins.get();
        let nyquist = sample_rate_hz / 2.0;
        let max_bark = hz_to_bark(nyquist);

        let bands: Vec<Band> = (0..n)
            .map(|i| {
                let bark_start = i as f32 * max_bark / n as f32;
                let bark_end = (i + 1) as f32 * max_bark / n as f32;
                let bark_centre = (bark_start + bark_end) / 2.0;

                let hz_start = bark_to_hz(bark_start);
                let hz_end = bark_to_hz(bark_end);
                let hz_centre = bark_to_hz(bark_centre);

                let start_bin = hz_to_bin(hz_start, sample_rate_hz, bins);
                let end_bin_raw = hz_to_bin(hz_end, sample_rate_hz, bins);
                // Guarantee end_bin > start_bin per Band invariant.
                let end_bin = end_bin_raw.max(start_bin + 1).min(bins);

                let perceptual_position = bark_centre / max_bark;

                // SAFETY: end_bin > start_bin is enforced above.
                unsafe { Band::new(start_bin, end_bin, hz_centre, perceptual_position) }
            })
            .collect();

        // SAFETY: n_bands >= 1 guarantees at least one element.
        let bands_non_empty = unsafe { NonEmptySlice::new_unchecked(&bands) };
        Self::new(bands_non_empty)
    }

    /// Creates a Mel-scale band layout.
    ///
    /// Divides the spectrum from 0 Hz to Nyquist into `n_bands` bands spaced
    /// evenly on the Mel scale. Mel bands are commonly used for speech and music
    /// feature extraction.
    ///
    /// `n_bins` is the number of spectral bins in the caller's frequency
    /// representation. Bin indices in the returned bands index into that array.
    ///
    /// # Arguments
    /// - `n_bands` – Number of bands. 40–128 is typical for speech / music.
    /// - `sample_rate_hz` – Sample rate of the audio signal in Hz.
    /// - `n_bins` – Total number of spectral bins.
    ///
    /// # Returns
    /// A `BandLayout` with `n_bands` entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "psychoacoustic")] {
    /// use audio_samples::BandLayout;
    /// use std::num::NonZeroUsize;
    ///
    /// let layout = BandLayout::mel(
    ///     NonZeroUsize::new(40).unwrap(),
    ///     22050.0,
    ///     NonZeroUsize::new(512).unwrap(),
    /// );
    /// assert_eq!(layout.len().get(), 40);
    /// # }
    /// ```
    #[must_use]
    pub fn mel(n_bands: NonZeroUsize, sample_rate_hz: f32, n_bins: NonZeroUsize) -> Self {
        let n = n_bands.get();
        let bins = n_bins.get();
        let nyquist = sample_rate_hz / 2.0;
        let max_mel = hz_to_mel(nyquist);

        let bands: Vec<Band> = (0..n)
            .map(|i| {
                let mel_start = i as f32 * max_mel / n as f32;
                let mel_end = (i + 1) as f32 * max_mel / n as f32;
                let mel_centre = (mel_start + mel_end) / 2.0;

                let hz_start = mel_to_hz(mel_start);
                let hz_end = mel_to_hz(mel_end);
                let hz_centre = mel_to_hz(mel_centre);

                let start_bin = hz_to_bin(hz_start, sample_rate_hz, bins);
                let end_bin_raw = hz_to_bin(hz_end, sample_rate_hz, bins);
                let end_bin = end_bin_raw.max(start_bin + 1).min(bins);

                let perceptual_position = mel_centre / max_mel;

                // SAFETY: end_bin > start_bin is enforced above.
                unsafe { Band::new(start_bin, end_bin, hz_centre, perceptual_position) }
            })
            .collect();

        // SAFETY: n_bands >= 1 guarantees at least one element.
        let bands_non_empty = unsafe { NonEmptySlice::new_unchecked(&bands) };
        Self::new(bands_non_empty)
    }

    /// Creates an ERB-scale band layout.
    ///
    /// Divides the spectrum from 0 Hz to Nyquist into `n_bands` bands spaced
    /// evenly on the ERB (Equivalent Rectangular Bandwidth) scale of Glasberg &
    /// Moore (1990). ERB bands more accurately model auditory filter widths than
    /// Bark bands, particularly at low frequencies, and are used in modern
    /// perceptual models (Opus, EVS).
    ///
    /// `n_bins` is the number of spectral bins in the caller's frequency
    /// representation. Bin indices in the returned bands index into that array.
    ///
    /// # Arguments
    /// - `n_bands` – Number of bands. 32–64 is typical.
    /// - `sample_rate_hz` – Sample rate of the audio signal in Hz.
    /// - `n_bins` – Total number of spectral bins.
    ///
    /// # Returns
    /// A `BandLayout` with `n_bands` entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "psychoacoustic")] {
    /// use audio_samples::BandLayout;
    /// use std::num::NonZeroUsize;
    ///
    /// let layout = BandLayout::erb(
    ///     NonZeroUsize::new(32).unwrap(),
    ///     44100.0,
    ///     NonZeroUsize::new(1024).unwrap(),
    /// );
    /// assert_eq!(layout.len().get(), 32);
    /// for band in layout.as_slice().iter() {
    ///     assert!(band.end_bin > band.start_bin);
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn erb(n_bands: NonZeroUsize, sample_rate_hz: f32, n_bins: NonZeroUsize) -> Self {
        let n = n_bands.get();
        let bins = n_bins.get();
        let nyquist = sample_rate_hz / 2.0;
        let erb_min = hz_to_erb(0.0);
        let erb_max = hz_to_erb(nyquist);
        let erb_range = erb_max - erb_min;

        let bands: Vec<Band> = (0..n)
            .map(|i| {
                let erb_start = erb_min + i as f32 * erb_range / n as f32;
                let erb_end = erb_min + (i + 1) as f32 * erb_range / n as f32;
                let erb_centre = (erb_start + erb_end) / 2.0;

                let hz_start = erb_to_hz(erb_start);
                let hz_end = erb_to_hz(erb_end);
                let hz_centre = erb_to_hz(erb_centre);

                let start_bin = hz_to_bin(hz_start, sample_rate_hz, bins);
                let end_bin_raw = hz_to_bin(hz_end, sample_rate_hz, bins);
                let end_bin = end_bin_raw.max(start_bin + 1).min(bins);

                let perceptual_position = (erb_centre - erb_min) / erb_range;

                // SAFETY: end_bin > start_bin is enforced above.
                unsafe { Band::new(start_bin, end_bin, hz_centre, perceptual_position) }
            })
            .collect();

        // SAFETY: n_bands >= 1 guarantees at least one element.
        let bands_non_empty = unsafe { NonEmptySlice::new_unchecked(&bands) };
        Self::new(bands_non_empty)
    }
}