Skip to content

Commit

Permalink
Replace samples_per_bin with bins_per_sec in config
Browse files Browse the repository at this point in the history
  • Loading branch information
uklotzde committed Jan 22, 2024
1 parent 07b87ab commit 4aac7dd
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@ use biquad::{Biquad as _, Coefficients, DirectForm2Transposed, Hertz, Q_BUTTERWO

use super::{FilteredWaveformBin, WaveformBin, WaveformVal};

// Only needed for initialization of the filter bank
// Only needed for default initialization.
const DEFAULT_SAMPLE_RATE_HZ: f32 = 44_100.0;

// Only needed for default initialization.
//
// Adopted from [Superpowered](https://docs.superpowered.com/reference/latest/analyzer>)
// which uses a resolution of 150 points/sec resolution.
const DEFAULT_BINS_PER_SEC: f32 = 150.0;

const MIN_SAMPLES_PER_BIN: u32 = 64;

/// Crossover low/mid (high pass)
///
/// Same boundary as used by both Rekordbox and
Expand Down Expand Up @@ -250,14 +258,14 @@ impl FilteredWaveformBinAccumulator {
#[derive(Debug, Clone, PartialEq)]
pub struct WaveformFilterConfig {
pub sample_rate_hz: f32,
pub samples_per_bin: u32,
pub bins_per_sec: f32,
pub filter_freqs: ThreeBandFilterFreqConfig,
}

impl WaveformFilterConfig {
pub const DEFAULT: Self = Self {
sample_rate_hz: DEFAULT_SAMPLE_RATE_HZ,
samples_per_bin: 0,
bins_per_sec: DEFAULT_BINS_PER_SEC,
filter_freqs: ThreeBandFilterFreqConfig::DEFAULT,
};
}
Expand All @@ -270,7 +278,8 @@ impl Default for WaveformFilterConfig {

#[derive(Debug)]
pub struct WaveformFilter {
samples_per_bin: u32,
sample_count: f64,
samples_per_bin: f64,
filter_bank: ThreeBandFilterBank,
filtered_accumulator: FilteredWaveformBinAccumulator,
}
Expand All @@ -287,11 +296,14 @@ impl WaveformFilter {
pub fn new(config: WaveformFilterConfig) -> Self {
let WaveformFilterConfig {
sample_rate_hz,
samples_per_bin,
bins_per_sec,
filter_freqs,
} = config;
let sample_rate = Hertz::<f32>::from_hz(sample_rate_hz).expect("valid sample rate");
let samples_per_bin = (f64::from(sample_rate_hz) / f64::from(bins_per_sec))
.max(f64::from(MIN_SAMPLES_PER_BIN));
Self {
sample_count: 0.0,
samples_per_bin,
filter_bank: ThreeBandFilterBank::new(sample_rate, filter_freqs),
filtered_accumulator: Default::default(),
Expand All @@ -303,7 +315,8 @@ impl WaveformFilter {
}

pub fn add_sample(&mut self, sample: f32) -> Option<FilteredWaveformBin> {
let next_bin = if self.filtered_accumulator.sample_count >= self.samples_per_bin {
self.sample_count += 1.0;
let next_bin = if self.sample_count % self.samples_per_bin < 1.0 {
self.finish_bin()
} else {
None
Expand Down

0 comments on commit 4aac7dd

Please sign in to comment.