Files
oxydsp/oxydsp-dsp/src/units.rs
2026-03-17 17:34:42 +01:00

49 lines
1.2 KiB
Rust

use std::{f64::consts::PI, ops::Neg};
use crate::map;
// Represents digital frequency
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub struct DigitalFrequency(pub usize);
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub struct Phase(pub DigitalFrequency);
impl DigitalFrequency
{
pub fn from_rad(radians_per_sample: f64) -> Self
{
// Frequnecy wraps arround : Going at 2 pi radians per second
// Is like not oscillating at all
let f = radians_per_sample.rem_euclid(2. * PI);
// Then we map the [0, 2*PI] range into the 0 to usize range
DigitalFrequency(map(f, 0., 2. * PI, 0., usize::MAX as f64).floor() as usize)
}
pub fn from_time_frequency(hertz: f64, sample_rate: f64) -> Self
{
Self::from_rad(map(hertz, 0., sample_rate, 0., 2. * PI))
}
pub fn as_rad(&self) -> f64
{
map(self.0 as f64, 0., usize::MAX as f64, 0., 2. * PI)
}
pub fn as_time_frequency(&self, sample_rate: f64) -> f64
{
map(self.0 as f64, 0., usize::MAX as f64, 0., sample_rate)
}
}
impl Neg for DigitalFrequency
{
type Output = Self;
fn neg(self) -> Self::Output
{
DigitalFrequency(usize::MAX - self.0)
}
}