Skip to content

Commit

Permalink
add some fft stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
owobred committed Jun 19, 2024
1 parent 81c9dfe commit cbea52c
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 0 deletions.
91 changes: 91 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[workspace]
members = ["pleep"]
resolver = "2"
9 changes: 9 additions & 0 deletions pleep/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "pleep"
version = "0.1.0"
edition = "2021"

[dependencies]
num-complex = "0.4.6"
num-traits = "0.2.19"
rustfft = "6.2.0"
1 change: 1 addition & 0 deletions pleep/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod spectrogram;
61 changes: 61 additions & 0 deletions pleep/src/spectrogram.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::sync::{Arc, Mutex};

use num_complex::Complex;
use rustfft::{Fft, FftPlanner};

pub trait Float: rustfft::FftNum + num_traits::Float {}
impl Float for f64 {}
impl Float for f32 {}

#[derive(Clone)]
pub struct Generator<T: Float> {
fft_planner: Arc<Mutex<FftPlanner<T>>>,
}

impl<T: Float> Generator<T> {
pub fn new() -> Self {
Self {
fft_planner: Arc::new(Mutex::new(rustfft::FftPlanner::new())),
}
}

pub fn generate_spectrogram(&self, samples: &[T], settings: &Settings) -> Vec<Vec<T>> {
let fft = self.get_forward_fft(settings.fft_len);
let scratch_size = fft.get_outofplace_scratch_len();
let mut scratch = vec![Complex::new(T::zero(), T::zero()); scratch_size];

let spectrogram = samples
.into_iter()
.map(|sample| Complex::new(*sample, T::zero()))
.collect::<Vec<_>>()
.windows(settings.fft_len)
.step_by(settings.fft_len - settings.fft_overlap)
.map(|sample_group| {
let mut group = sample_group.to_vec();
fft.process_with_scratch(&mut group, &mut scratch);
group
})
.map(|group| {
group
.into_iter()
.take(settings.fft_len / 2)
.map(|v| v.norm())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();

spectrogram
}

fn get_forward_fft(&self, len: usize) -> Arc<dyn Fft<T>> {
let mut planner = self.fft_planner.lock().unwrap();

planner.plan_fft_forward(len)
}
}

#[derive(Debug, Clone)]
pub struct Settings {
fft_len: usize,
fft_overlap: usize,
}

0 comments on commit cbea52c

Please sign in to comment.