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
use std::sync::Arc;
use audio_processor_traits::AudioContext;
use rustfft::num_complex::Complex;
pub use rustfft::FftDirection;
use rustfft::{Fft, FftPlanner};
use audio_processor_traits::simple_processor::MonoAudioProcessor;
use crate::window_functions::{make_window_vec, WindowFunctionType};
pub struct FftProcessorOptions {
pub size: usize,
pub direction: FftDirection,
pub overlap_ratio: f32,
pub window_function: WindowFunctionType,
}
impl Default for FftProcessorOptions {
fn default() -> Self {
Self {
size: 8192,
direction: FftDirection::Forward,
overlap_ratio: 0.0,
window_function: WindowFunctionType::Hann,
}
}
}
pub struct FftProcessor {
input_buffer: Vec<f32>,
fft_buffer: Vec<Complex<f32>>,
scratch: Vec<Complex<f32>>,
cursor: usize,
window: Vec<f32>,
step_len: usize,
size: usize,
fft: Arc<dyn Fft<f32>>,
has_changed: bool,
}
impl Default for FftProcessor {
fn default() -> Self {
Self::new(Default::default())
}
}
impl FftProcessor {
pub fn new(options: FftProcessorOptions) -> Self {
let FftProcessorOptions {
size,
direction,
overlap_ratio,
window_function,
} = options;
let mut planner = FftPlanner::new();
let fft = planner.plan_fft(size, direction);
let mut input_buffer = Vec::with_capacity(size);
input_buffer.resize(size, 0.0);
let mut fft_buffer = Vec::with_capacity(size);
fft_buffer.resize(size, 0.0.into());
let scratch_size = fft.get_inplace_scratch_len();
let mut scratch = Vec::with_capacity(scratch_size);
scratch.resize(scratch_size, 0.0.into());
let window = make_window_vec(size, window_function);
let step_len = Self::calculate_hop_size(size, overlap_ratio);
Self {
input_buffer,
fft_buffer,
window,
scratch,
size,
step_len,
cursor: 0,
fft,
has_changed: false,
}
}
fn calculate_hop_size(size: usize, overlap_ratio: f32) -> usize {
(size as f32 * (1.0 - overlap_ratio)) as usize
}
pub fn size(&self) -> usize {
self.size
}
pub fn buffer(&self) -> &Vec<Complex<f32>> {
&self.fft_buffer
}
pub fn buffer_mut(&mut self) -> &mut Vec<Complex<f32>> {
&mut self.fft_buffer
}
pub fn step_len(&self) -> usize {
self.step_len
}
pub fn process_fft_buffer(&mut self, samples: &mut [Complex<f32>]) {
self.fft.process_with_scratch(samples, &mut self.scratch);
}
pub fn has_changed(&self) -> bool {
self.has_changed
}
pub fn input_buffer_sum(&self) -> f32 {
self.input_buffer.iter().map(|f| f.abs()).sum()
}
#[inline]
pub fn perform_fft(&mut self, start_idx: usize) {
for i in 0..self.size {
let index = (start_idx + i) % self.size;
let sample = self.input_buffer[index];
let magnitude = sample * self.window[i];
assert!(!magnitude.is_nan());
let complex = Complex::new(magnitude, 0.0);
assert!(!complex.re.is_nan());
assert!(!complex.im.is_nan());
self.fft_buffer[i] = complex;
}
self.fft
.process_with_scratch(&mut self.fft_buffer, &mut self.scratch);
}
}
impl MonoAudioProcessor for FftProcessor {
type SampleType = f32;
#[inline]
fn m_process(
&mut self,
_context: &mut AudioContext,
sample: Self::SampleType,
) -> Self::SampleType {
self.has_changed = false;
self.input_buffer[self.cursor] = sample;
if self.cursor % self.step_len == 0 {
let start_idx = (self.cursor as i32 - self.size as i32) as usize % self.size;
self.perform_fft(start_idx);
self.has_changed = true;
}
self.cursor = (self.cursor + 1) % self.size;
sample
}
}
#[cfg(test)]
mod test {
use std::time::Duration;
use audio_processor_testing_helpers::{
charts::draw_vec_chart, oscillator_buffer, relative_path, sine_generator,
};
use audio_processor_traits::audio_buffer::VecAudioBuffer;
use audio_processor_traits::simple_processor::process_buffer;
use audio_processor_traits::AudioProcessorSettings;
use super::*;
#[test]
fn test_hop_size_is_correct() {
let hop_size = FftProcessor::calculate_hop_size(2048, 0.75);
assert_eq!(hop_size, 512);
let hop_size = FftProcessor::calculate_hop_size(2048, 0.875);
assert_eq!(hop_size, 256);
}
#[test]
fn test_draw_fft() {
println!("Generating signal");
let signal = oscillator_buffer(44100.0, 440.0, Duration::from_millis(1000), sine_generator);
let mut context = AudioContext::from(AudioProcessorSettings::new(44100.0, 1, 1, 512));
let signal_len = signal.len();
let mut signal = VecAudioBuffer::new_with(signal, 1, signal_len);
println!("Processing");
let mut fft_processor = FftProcessor::default();
process_buffer(&mut context, &mut fft_processor, &mut signal);
println!("Drawing chart");
let mut output: Vec<f32> = fft_processor
.buffer()
.iter()
.map(|c| 20.0 * (c.norm() / 10.0).log10())
.collect();
output.reverse();
let output: Vec<f32> = output.iter().take(1000).copied().collect();
draw_vec_chart(
&relative_path!("src/fft_processor.png"),
"FFT_sine_440Hz",
output,
);
}
#[test]
fn test_usize_cast() {
let i = -1;
let i = i as usize % 2;
assert_eq!(i, 1)
}
}