Skip to main content

qualia_audio/features/framing/
frame_cutter.rs

1//! Explicit framing geometry: how many complete frames a signal yields, and a
2//! caller-buffered cutter that copies one frame into a supplied buffer.
3//!
4//! Zero-heap: [`frame_count`] is pure integer arithmetic; [`cut_frame`] copies
5//! into a caller-owned `&mut [f32]` with no allocation.
6
7use crate::types::AudioError;
8
9/// Number of **complete** frames of length `frame_size` obtainable from a signal
10/// of `signal_len` samples advancing by `hop` each step.
11///
12/// Matches the standard STFT geometry `(signal_len − frame_size) / hop + 1` when
13/// the signal is at least one frame long, and `0` otherwise. Partial trailing
14/// frames (fewer than `frame_size` samples) are not counted.
15///
16/// A `hop` of `0` is meaningless (frames never advance); it returns `0` rather
17/// than looping forever. A `frame_size` of `0` also returns `0`.
18#[must_use]
19pub fn frame_count(signal_len: usize, frame_size: usize, hop: usize) -> usize {
20    if frame_size == 0 || hop == 0 || signal_len < frame_size {
21        return 0;
22    }
23    (signal_len - frame_size) / hop + 1
24}
25
26/// Copy frame `index` of a signal (window position `index * hop`) into `out`.
27///
28/// - `signal`: the source samples.
29/// - `frame_size`: number of samples per frame; `out` must be at least this long.
30/// - `hop`: sample advance between consecutive frames.
31/// - `index`: which frame to extract (0-based).
32///
33/// Only the first `frame_size` slots of `out` are written. Returns
34/// [`AudioError::InvalidParameter`] for a zero `frame_size`/`hop` or if the
35/// requested frame runs past the end of `signal`, and
36/// [`AudioError::OutputBufferTooSmall`] if `out` is shorter than `frame_size`.
37pub fn cut_frame(
38    signal: &[f32],
39    frame_size: usize,
40    hop: usize,
41    index: usize,
42    out: &mut [f32],
43) -> Result<(), AudioError> {
44    if frame_size == 0 || hop == 0 {
45        return Err(AudioError::InvalidParameter);
46    }
47    if out.len() < frame_size {
48        return Err(AudioError::OutputBufferTooSmall);
49    }
50    let start = index.saturating_mul(hop);
51    let end = start
52        .checked_add(frame_size)
53        .ok_or(AudioError::InvalidParameter)?;
54    if end > signal.len() {
55        return Err(AudioError::InvalidParameter);
56    }
57    out[..frame_size].copy_from_slice(&signal[start..end]);
58    Ok(())
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn frame_count_matches_closed_form() {
67        // Golden: (len - frame) / hop + 1 for len >= frame.
68        for &(len, frame, hop) in &[
69            (1024usize, 256usize, 128usize),
70            (1000, 256, 128),
71            (256, 256, 128),
72            (300, 128, 64),
73            (48_000, 1024, 512),
74        ] {
75            let expected = (len - frame) / hop + 1;
76            assert_eq!(
77                frame_count(len, frame, hop),
78                expected,
79                "len={len} frame={frame} hop={hop}"
80            );
81        }
82    }
83
84    #[test]
85    fn shorter_than_a_frame_yields_zero() {
86        assert_eq!(frame_count(100, 256, 128), 0);
87        assert_eq!(frame_count(0, 256, 128), 0);
88    }
89
90    #[test]
91    fn degenerate_params_yield_zero() {
92        assert_eq!(frame_count(1000, 0, 128), 0);
93        assert_eq!(frame_count(1000, 256, 0), 0);
94    }
95
96    #[test]
97    fn cut_frame_copies_correct_window() {
98        let signal: Vec<f32> = (0..20).map(|i| i as f32).collect();
99        let mut out = [0.0f32; 8];
100        cut_frame(&signal, 8, 4, 2, &mut out).unwrap(); // start = 8
101        let expected: Vec<f32> = (8..16).map(|i| i as f32).collect();
102        assert_eq!(&out[..8], expected.as_slice());
103    }
104
105    #[test]
106    fn cut_frame_writes_only_frame_size_slots() {
107        let signal: Vec<f32> = (0..16).map(|i| i as f32).collect();
108        let mut out = [-1.0f32; 10];
109        cut_frame(&signal, 6, 3, 0, &mut out).unwrap();
110        assert_eq!(&out[..6], &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
111        assert_eq!(&out[6..], &[-1.0, -1.0, -1.0, -1.0]); // untouched
112    }
113
114    #[test]
115    fn cut_frame_past_end_is_invalid() {
116        let signal = [0.0f32; 10];
117        let mut out = [0.0f32; 8];
118        assert_eq!(
119            cut_frame(&signal, 8, 4, 1, &mut out),
120            Err(AudioError::InvalidParameter)
121        );
122    }
123
124    #[test]
125    fn cut_frame_short_output_is_too_small() {
126        let signal = [0.0f32; 16];
127        let mut out = [0.0f32; 4];
128        assert_eq!(
129            cut_frame(&signal, 8, 4, 0, &mut out),
130            Err(AudioError::OutputBufferTooSmall)
131        );
132    }
133
134    #[test]
135    fn cut_frame_covers_all_frame_count_frames() {
136        // Every index in 0..frame_count must succeed; the next one must fail.
137        let signal: Vec<f32> = (0..1000).map(|i| i as f32).collect();
138        let (frame, hop) = (256usize, 128usize);
139        let n = frame_count(signal.len(), frame, hop);
140        let mut out = vec![0.0f32; frame];
141        for i in 0..n {
142            cut_frame(&signal, frame, hop, i, &mut out).expect("frame in range");
143        }
144        assert_eq!(
145            cut_frame(&signal, frame, hop, n, &mut out),
146            Err(AudioError::InvalidParameter)
147        );
148    }
149}