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
//! Sliding-window utilities for batch and streaming pipelines.
//!
//! [`WindowIter`] iterates over `(start, end)` sample ranges.
//! [`WindowBuffer`] buffers incoming samples and yields full windows.
/// Iterator over fixed-size (or partial trailing) windows.
///
/// Yields `(start_sample, end_sample)` pairs. `end_sample` is exclusive.
#[derive(Debug, Clone)]
pub struct WindowIter {
start: usize,
total: usize,
win: usize,
hop: usize,
include_partial: bool,
}
impl WindowIter {
/// Create a new iterator.
///
/// * `total` — total number of samples in the audio region.
/// * `win` — window size in samples.
/// * `hop` — hop size in samples.
pub fn new(total: usize, win: usize, hop: usize) -> Self {
Self {
start: 0,
total,
win,
hop,
include_partial: false,
}
}
/// Include a final partial window if the region does not divide evenly.
pub fn include_partial(mut self) -> Self {
self.include_partial = true;
self
}
}
impl Iterator for WindowIter {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
if self.start >= self.total {
return None;
}
let end = if self.include_partial {
(self.start + self.win).min(self.total)
} else if self.start + self.win > self.total {
return None;
} else {
self.start + self.win
};
let item = (self.start, end);
self.start += self.hop;
Some(item)
}
}
/// Streaming buffer that accumulates samples and yields full windows.
///
/// Maintains an internal ring-like buffer. Call [`extend`](Self::extend)
/// with incoming chunks, then repeatedly call [`try_pop`](Self::try_pop)
/// to consume every window that is ready.
#[derive(Debug, Clone)]
pub struct WindowBuffer {
buf: Vec<f32>,
win: usize,
hop: usize,
next_start: usize,
}
impl WindowBuffer {
/// Create a new buffer.
///
/// * `win` — window size in samples.
/// * `hop` — hop size in samples.
pub fn new(win: usize, hop: usize) -> Self {
Self {
buf: Vec::new(),
win,
hop,
next_start: 0,
}
}
/// Append samples to the buffer.
pub fn extend(&mut self, samples: &[f32]) {
self.buf.extend_from_slice(samples);
}
/// Return the next full window if one is available.
///
/// Returns `Some((global_start, buf[..win].to_vec()))` where `global_start` is the
/// sample offset of this window relative to the start of the stream.
/// The window is cloned so that the internal buffer can advance immediately.
pub fn try_pop(&mut self) -> Option<(usize, Vec<f32>)> {
if self.buf.len() < self.win {
return None;
}
let start = self.next_start;
let window = self.buf[..self.win].to_vec();
self.next_start += self.hop;
self.buf.drain(..self.hop);
Some((start, window))
}
/// Zero-pad the remaining buffer to `win` and return the final window.
///
/// Returns `None` if the buffer is empty.
pub fn flush(&mut self) -> Option<(usize, Vec<f32>)> {
if self.buf.is_empty() {
return None;
}
let start = self.next_start;
let mut padded = self.buf.clone();
if padded.len() < self.win {
padded.resize(self.win, 0.0f32);
}
self.buf.clear();
Some((start, padded))
}
/// Whether the buffer is currently empty.
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
/// Current length of the buffered samples.
pub fn len(&self) -> usize {
self.buf.len()
}
/// Clear all buffered samples and reset the next-start offset.
pub fn clear(&mut self) {
self.buf.clear();
}
/// Reset the next-start offset to `0`. The buffer itself is **not** cleared.
pub fn reset_start(&mut self) {
self.next_start = 0;
}
/// Set the next-start offset to a specific value.
pub fn set_next_start(&mut self, start: usize) {
self.next_start = start;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn window_iter_complete_only() {
let ranges: Vec<_> = WindowIter::new(10, 3, 2).collect();
assert_eq!(ranges, vec![(0, 3), (2, 5), (4, 7), (6, 9)]);
}
#[test]
fn window_iter_include_partial() {
let ranges: Vec<_> = WindowIter::new(10, 3, 2).include_partial().collect();
assert_eq!(ranges, vec![(0, 3), (2, 5), (4, 7), (6, 9), (8, 10)]);
}
#[test]
fn window_iter_empty() {
let ranges: Vec<_> = WindowIter::new(0, 3, 2).collect();
assert!(ranges.is_empty());
}
#[test]
fn window_iter_shorter_than_win() {
let ranges: Vec<_> = WindowIter::new(2, 3, 2).collect();
assert!(ranges.is_empty());
let ranges: Vec<_> = WindowIter::new(2, 3, 2).include_partial().collect();
assert_eq!(ranges, vec![(0, 2)]);
}
#[test]
fn window_buffer_pop_and_flush() {
let mut buf = WindowBuffer::new(4, 2);
buf.extend(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let (s1, w1) = buf.try_pop().unwrap();
assert_eq!(s1, 0);
assert_eq!(w1, vec![1.0, 2.0, 3.0, 4.0]);
let (s2, w2) = buf.try_pop().unwrap();
assert_eq!(s2, 2);
assert_eq!(w2, vec![3.0, 4.0, 5.0, 6.0]);
assert!(buf.try_pop().is_none());
let (s3, w3) = buf.flush().unwrap();
assert_eq!(s3, 4);
assert_eq!(w3, vec![5.0, 6.0, 0.0, 0.0]);
}
#[test]
fn window_buffer_flush_empty() {
let mut buf = WindowBuffer::new(4, 2);
assert!(buf.flush().is_none());
}
}