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
// Augmented Audio: Audio libraries and applications
// Copyright (c) 2022 Pedro Tacla Yamada
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! FFT processor implementation with windowing & overlap, wraps `rustfft`.
//!
//! `rustfft` audio-processor, forwards or backwards, real-time safe, FFT.
//!
//! Applies a Hann window by default. Several window functions are exported by [`audio_processor_analysis::window_functions`].
//!
//! 
//!
//! Then performs FFT with N bins.
//!
//! 
//!
//! Overlap is configurable
//!
//! 
use std::sync::Arc;
use rustfft::num_complex::Complex;
pub use rustfft::FftDirection;
use rustfft::{Fft, FftPlanner};
use audio_processor_traits::simple_processor::MonoAudioProcessor;
use audio_processor_traits::AudioContext;
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,
}
}
}
/// An FFT processor with overlap and windowing.
///
/// This processor will collect samples onto a circular buffer and perform FFTs whenever hop size is
/// reached.
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 {
/// Constructs a new `FftProcessor`
///
/// * size: Size of the FFT
/// * direction: Direction of the FFT
/// * overlap_ratio: 0.0 will do no overlap, 0.5 will do half a window of overlap and 0.75 will
/// do 3/4 window overlap
/// * window_function: The window function to use
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
}
/// The number of frequency bins this FFT processor operates with
pub fn size(&self) -> usize {
self.size
}
/// Get a reference to the FFT bins buffer
pub fn buffer(&self) -> &Vec<Complex<f32>> {
&self.fft_buffer
}
/// Get a reference to the rustfft instance
pub fn fft(&self) -> &Arc<dyn Fft<f32>> {
&self.fft
}
/// Get a mutable reference to the FFT bins buffer
pub fn buffer_mut(&mut self) -> &mut Vec<Complex<f32>> {
&mut self.fft_buffer
}
/// Get a mutable reference to the scratch buffer
pub fn scratch_mut(&mut self) -> &mut Vec<Complex<f32>> {
&mut self.scratch
}
/// Get the hop size of this processor. This is the number of samples between each FFT.
pub fn step_len(&self) -> usize {
self.step_len
}
/// Manually process an external FFT buffer in-place.
pub fn process_fft_buffer(&mut self, samples: &mut [Complex<f32>]) {
self.fft.process_with_scratch(samples, &mut self.scratch);
}
/// Returns true if an FFT has just been performed on the last call to `s_process`
pub fn has_changed(&self) -> bool {
self.has_changed
}
/// Returns the sum of the power of the current input buffer window.
pub fn input_buffer_sum(&self) -> f32 {
self.input_buffer.iter().map(|f| f.abs()).sum()
}
/// Manually perform an FFT; offset the input buffer by a certain index.
#[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 {
// Offset FFT so it's reading from the input buffer at the start of this window
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::simple_processor::process_buffer;
use audio_processor_traits::{AudioBuffer, 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 mut signal = AudioBuffer::from_interleaved(1, &signal);
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)
}
}