Skip to main content

qualia_audio/features/pitch_midi/
pitch_to_midi.rs

1//! Frequency ↔ MIDI note-number conversion with parameterised reference tuning,
2//! delegated to [`etalon_signal::pitch`].
3
4/// The lowest legal MIDI note number.
5pub const MIDI_MIN: u8 = 0;
6/// The highest legal MIDI note number.
7pub const MIDI_MAX: u8 = 127;
8
9/// Convert a frequency in Hz to `(midi_note, cents_deviation)`.
10#[inline]
11pub fn hz_to_midi(freq_hz: f32, ref_a4_hz: f32) -> (u8, f32) {
12    etalon_signal::pitch::hz_to_midi_quantized(freq_hz, ref_a4_hz)
13}
14
15/// Convert an integer MIDI note number back to its frequency in Hz.
16#[inline]
17pub fn midi_to_hz(note: u8, ref_a4_hz: f32) -> f32 {
18    etalon_signal::pitch::midi_note_to_hz(note, ref_a4_hz)
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn a4_maps_to_69_in_tune() {
27        let (note, cents) = hz_to_midi(440.0, 440.0);
28        assert_eq!(note, 69);
29        assert!(cents.abs() < 1e-3, "cents={cents}");
30    }
31
32    #[test]
33    fn middle_c_maps_to_60() {
34        let (note, cents) = hz_to_midi(261.63, 440.0);
35        assert_eq!(note, 60);
36        assert!(cents.abs() < 1.0, "cents={cents}");
37    }
38
39    #[test]
40    fn sharp_442_is_69_plus_785_cents() {
41        let (note, cents) = hz_to_midi(442.0, 440.0);
42        assert_eq!(note, 69);
43        assert!((cents - 7.85).abs() < 0.05, "cents={cents}");
44    }
45
46    #[test]
47    fn alternate_reference_shifts_pitch() {
48        let (note, cents) = hz_to_midi(442.0, 442.0);
49        assert_eq!(note, 69);
50        assert!(cents.abs() < 1e-3, "cents={cents}");
51    }
52
53    #[test]
54    fn midi_to_hz_inverts_hz_to_midi() {
55        for &note in &[21u8, 60, 69, 108] {
56            let f = midi_to_hz(note, 440.0);
57            let (back, cents) = hz_to_midi(f, 440.0);
58            assert_eq!(back, note, "note={note} f={f}");
59            assert!(cents.abs() < 1e-2, "cents={cents}");
60        }
61    }
62
63    #[test]
64    fn a4_frequency_is_440() {
65        assert!((midi_to_hz(69, 440.0) - 440.0).abs() < 1e-3);
66    }
67
68    #[test]
69    fn out_of_range_inputs_are_safe() {
70        assert_eq!(hz_to_midi(0.0, 440.0), (0, 0.0));
71        assert_eq!(hz_to_midi(-5.0, 440.0), (0, 0.0));
72        assert_eq!(hz_to_midi(f32::NAN, 440.0), (0, 0.0));
73        assert_eq!(hz_to_midi(440.0, 0.0), (0, 0.0));
74        assert_eq!(midi_to_hz(69, 0.0), 0.0);
75    }
76
77    #[test]
78    fn extreme_frequencies_clamp_to_midi_range() {
79        let (hi, _) = hz_to_midi(40_000.0, 440.0);
80        assert_eq!(hi, 127);
81        let (lo, _) = hz_to_midi(1.0, 440.0);
82        assert_eq!(lo, 0);
83    }
84}