Skip to main content

wavegraph_core/
tuning.rs

1/// Equal-tempered phase increments and sample period for a device's clock.
2/// One table can be shared by all voices running at the same rate.
3#[derive(Debug)]
4pub struct Tuning {
5    steps: [u32; 128],
6    sample_period: f32,
7}
8
9impl Tuning {
10    /// Construct a table for `numerator / denominator` frames per second,
11    /// with MIDI note 69 at 440 Hz. Returns `None` for a zero clock component.
12    /// Pitches at or above Nyquist are silent.
13    #[must_use]
14    #[allow(
15        clippy::cast_possible_truncation,
16        clippy::cast_sign_loss,
17        reason = "The phase increment is positive and at most 2^31. The nonzero u32 clock ratio fits in f32."
18    )]
19    pub const fn new(numerator: u32, denominator: u32) -> Option<Self> {
20        if numerator == 0 || denominator == 0 {
21            return None;
22        }
23        let mut steps = [0; 128];
24        // MIDI note 0, in cycles of a 32-bit phase accumulator per frame.
25        let mut step =
26            8.175_798_915_643_707 * 4_294_967_296.0 * denominator as f64 / numerator as f64;
27        let mut note: usize = 0;
28        while note < steps.len() {
29            if step < 2_147_483_648.0 {
30                steps[note] = (step + 0.5) as u32;
31            }
32            step *= 1.059_463_094_359_295_3;
33            note = note.wrapping_add(1);
34        }
35        Some(Self {
36            steps,
37            sample_period: (denominator as f64 / numerator as f64) as f32,
38        })
39    }
40
41    /// Phase advance per output frame in units of 2⁻³² turns. Returns zero
42    /// for notes outside the MIDI range or at or above the output Nyquist limit.
43    #[must_use]
44    pub const fn phase_step(&self, note: u8) -> u32 {
45        if (note as usize) < self.steps.len() {
46            self.steps[note as usize]
47        } else {
48            0
49        }
50    }
51
52    /// Duration of one output frame in seconds.
53    #[must_use]
54    pub const fn sample_period(&self) -> f32 {
55        self.sample_period
56    }
57}