1#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22
23use std::error::Error as StdError;
24use std::fmt;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28#[repr(u8)]
29pub enum NoteName {
30 C = 0,
32 CSharp = 1,
34 D = 2,
36 DSharp = 3,
38 E = 4,
40 F = 5,
42 FSharp = 6,
44 G = 7,
46 GSharp = 8,
48 A = 9,
50 ASharp = 10,
52 B = 11,
54}
55
56impl NoteName {
57 pub const fn from_pitch_class(value: u8) -> Self {
59 match value % 12 {
60 0 => Self::C,
61 1 => Self::CSharp,
62 2 => Self::D,
63 3 => Self::DSharp,
64 4 => Self::E,
65 5 => Self::F,
66 6 => Self::FSharp,
67 7 => Self::G,
68 8 => Self::GSharp,
69 9 => Self::A,
70 10 => Self::ASharp,
71 _ => Self::B,
72 }
73 }
74
75 pub const fn pitch_class(self) -> u8 {
77 self as u8
78 }
79
80 pub fn transpose(self, semitones: i16) -> Self {
82 let value = (i16::from(self.pitch_class()) + semitones).rem_euclid(12) as u8;
83 Self::from_pitch_class(value)
84 }
85}
86
87impl fmt::Display for NoteName {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 let name = match self {
90 Self::C => "C",
91 Self::CSharp => "C#",
92 Self::D => "D",
93 Self::DSharp => "D#",
94 Self::E => "E",
95 Self::F => "F",
96 Self::FSharp => "F#",
97 Self::G => "G",
98 Self::GSharp => "G#",
99 Self::A => "A",
100 Self::ASharp => "A#",
101 Self::B => "B",
102 };
103 f.write_str(name)
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
109pub enum Solfege {
110 Do,
112 Re,
114 Mi,
116 Fa,
118 Sol,
120 La,
122 Ti,
124}
125
126impl Solfege {
127 pub const fn degree(self) -> u8 {
129 match self {
130 Self::Do => 1,
131 Self::Re => 2,
132 Self::Mi => 3,
133 Self::Fa => 4,
134 Self::Sol => 5,
135 Self::La => 6,
136 Self::Ti => 7,
137 }
138 }
139
140 pub const fn fixed_note_name(self) -> NoteName {
142 match self {
143 Self::Do => NoteName::C,
144 Self::Re => NoteName::D,
145 Self::Mi => NoteName::E,
146 Self::Fa => NoteName::F,
147 Self::Sol => NoteName::G,
148 Self::La => NoteName::A,
149 Self::Ti => NoteName::B,
150 }
151 }
152}
153
154impl fmt::Display for Solfege {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 let value = match self {
157 Self::Do => "Do",
158 Self::Re => "Re",
159 Self::Mi => "Mi",
160 Self::Fa => "Fa",
161 Self::Sol => "Sol",
162 Self::La => "La",
163 Self::Ti => "Ti",
164 };
165 f.write_str(value)
166 }
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
171pub struct Pitch(u8);
172
173impl Pitch {
174 pub const fn from_midi(midi: u8) -> Self {
176 Self(midi)
177 }
178
179 pub fn la(octave: i8) -> Result<Self, Error> {
184 Self::from_note(NoteName::A, octave)
185 }
186
187 pub fn from_note(note: NoteName, octave: i8) -> Result<Self, Error> {
189 let midi = (i16::from(octave) + 1)
190 .checked_mul(12)
191 .and_then(|value| value.checked_add(i16::from(note.pitch_class())))
192 .ok_or(Error::PitchOutOfRange)?;
193 let midi = u8::try_from(midi).map_err(|_| Error::PitchOutOfRange)?;
194 if midi > 127 {
195 return Err(Error::PitchOutOfRange);
196 }
197 Ok(Self(midi))
198 }
199
200 pub const fn midi(self) -> u8 {
202 self.0
203 }
204
205 pub const fn note_name(self) -> NoteName {
207 NoteName::from_pitch_class(self.0 % 12)
208 }
209
210 pub const fn octave(self) -> i8 {
212 (self.0 / 12) as i8 - 1
213 }
214
215 pub fn transpose(self, semitones: i16) -> Result<Self, Error> {
217 let midi = i16::from(self.0)
218 .checked_add(semitones)
219 .ok_or(Error::PitchOutOfRange)?;
220 if !(0..=127).contains(&midi) {
221 return Err(Error::PitchOutOfRange);
222 }
223 Ok(Self(midi as u8))
224 }
225
226 pub const fn semitones_from(self, reference: Self) -> i16 {
228 self.0 as i16 - reference.0 as i16
229 }
230}
231
232impl fmt::Display for Pitch {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 write!(f, "{}{}", self.note_name(), self.octave())
235 }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum Mode {
241 Major,
243 NaturalMinor,
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
249pub struct Key {
250 tonic: NoteName,
251 mode: Mode,
252}
253
254impl Key {
255 pub const fn new(tonic: NoteName, mode: Mode) -> Self {
257 Self { tonic, mode }
258 }
259
260 pub const fn tonic(self) -> NoteName {
262 self.tonic
263 }
264
265 pub const fn mode(self) -> Mode {
267 self.mode
268 }
269
270 pub fn note_for(self, syllable: Solfege) -> NoteName {
272 let index = usize::from(syllable.degree() - 1);
273 let offsets = match self.mode {
274 Mode::Major => [0_i16, 2, 4, 5, 7, 9, 11],
275 Mode::NaturalMinor => [0_i16, 2, 3, 5, 7, 8, 10],
276 };
277 self.tonic.transpose(offsets[index])
278 }
279
280 pub fn la(self) -> NoteName {
282 self.note_for(Solfege::La)
283 }
284}
285
286#[derive(Debug, Clone, Copy, PartialEq)]
288pub struct Tuning {
289 a4_hz: f64,
290}
291
292impl Tuning {
293 pub fn new(a4_hz: f64) -> Result<Self, Error> {
295 if !a4_hz.is_finite() || a4_hz <= 0.0 {
296 return Err(Error::InvalidFrequency(a4_hz));
297 }
298 Ok(Self { a4_hz })
299 }
300
301 pub const fn concert_pitch() -> Self {
303 Self { a4_hz: 440.0 }
304 }
305
306 pub const fn a4_hz(self) -> f64 {
308 self.a4_hz
309 }
310
311 pub fn frequency(self, pitch: Pitch) -> f64 {
313 self.a4_hz * 2.0_f64.powf((f64::from(pitch.midi()) - 69.0) / 12.0)
314 }
315
316 pub fn la_frequency(self, octave: i8) -> Result<f64, Error> {
318 Ok(self.frequency(Pitch::la(octave)?))
319 }
320
321 pub fn analyze(self, frequency_hz: f64) -> Result<FrequencyAnalysis, Error> {
323 if !frequency_hz.is_finite() || frequency_hz <= 0.0 {
324 return Err(Error::InvalidFrequency(frequency_hz));
325 }
326 let exact_midi = 69.0 + 12.0 * (frequency_hz / self.a4_hz).log2();
327 let rounded = exact_midi.round();
328 if !(0.0..=127.0).contains(&rounded) {
329 return Err(Error::PitchOutOfRange);
330 }
331 let pitch = Pitch::from_midi(rounded as u8);
332 let cents_offset = 1_200.0 * (frequency_hz / self.frequency(pitch)).log2();
333 Ok(FrequencyAnalysis {
334 pitch,
335 cents_offset,
336 })
337 }
338}
339
340#[derive(Debug, Clone, Copy, PartialEq)]
342pub struct FrequencyAnalysis {
343 pitch: Pitch,
344 cents_offset: f64,
345}
346
347impl FrequencyAnalysis {
348 pub const fn pitch(self) -> Pitch {
350 self.pitch
351 }
352
353 pub const fn cents_offset(self) -> f64 {
355 self.cents_offset
356 }
357}
358
359#[derive(Debug, Clone, Copy, PartialEq)]
361pub struct LaRelation {
362 pitch: Pitch,
363 la: Pitch,
364 semitones: i16,
365 frequency_ratio: f64,
366}
367
368impl LaRelation {
369 pub fn new(pitch: Pitch) -> Result<Self, Error> {
371 let la = Pitch::la(pitch.octave())?;
372 let semitones = pitch.semitones_from(la);
373 let frequency_ratio = 2.0_f64.powf(f64::from(semitones) / 12.0);
374 Ok(Self {
375 pitch,
376 la,
377 semitones,
378 frequency_ratio,
379 })
380 }
381
382 pub const fn pitch(self) -> Pitch {
384 self.pitch
385 }
386
387 pub const fn la(self) -> Pitch {
389 self.la
390 }
391
392 pub const fn semitones(self) -> i16 {
394 self.semitones
395 }
396
397 pub const fn frequency_ratio(self) -> f64 {
399 self.frequency_ratio
400 }
401}
402
403#[derive(Debug, Clone, PartialEq)]
405#[non_exhaustive]
406pub enum Error {
407 PitchOutOfRange,
409 InvalidFrequency(f64),
411}
412
413impl fmt::Display for Error {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 match self {
416 Self::PitchOutOfRange => f.write_str("pitch is outside MIDI range 0..=127"),
417 Self::InvalidFrequency(value) => write!(f, "invalid frequency: {value}"),
418 }
419 }
420}
421
422impl StdError for Error {}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 fn close(left: f64, right: f64, tolerance: f64) {
429 assert!((left - right).abs() <= tolerance, "{left} != {right}");
430 }
431
432 #[test]
433 fn fixed_do_la_is_a() {
434 assert_eq!(Solfege::La.degree(), 6);
435 assert_eq!(Solfege::La.fixed_note_name(), NoteName::A);
436 assert_eq!(Solfege::La.to_string(), "La");
437 }
438
439 #[test]
440 fn la4_is_midi_69_and_440_hz() {
441 let la = Pitch::la(4).unwrap();
442 assert_eq!(la.midi(), 69);
443 assert_eq!(la.to_string(), "A4");
444 close(Tuning::concert_pitch().frequency(la), 440.0, 1e-12);
445 }
446
447 #[test]
448 fn equal_temperament_doubles_each_octave() {
449 let tuning = Tuning::concert_pitch();
450 close(tuning.la_frequency(3).unwrap(), 220.0, 1e-10);
451 close(tuning.la_frequency(5).unwrap(), 880.0, 1e-10);
452 }
453
454 #[test]
455 fn transposition_wraps_note_names_and_checks_pitch_range() {
456 assert_eq!(NoteName::A.transpose(3), NoteName::C);
457 assert_eq!(NoteName::C.transpose(-3), NoteName::A);
458 assert_eq!(
459 Pitch::la(4).unwrap().transpose(12).unwrap().to_string(),
460 "A5"
461 );
462 assert!(matches!(
463 Pitch::from_midi(127).transpose(1),
464 Err(Error::PitchOutOfRange)
465 ));
466 }
467
468 #[test]
469 fn movable_do_la_depends_on_key_and_mode() {
470 assert_eq!(Key::new(NoteName::C, Mode::Major).la(), NoteName::A);
471 assert_eq!(Key::new(NoteName::A, Mode::NaturalMinor).la(), NoteName::F);
472 assert_eq!(Key::new(NoteName::D, Mode::Major).la(), NoteName::B);
473 }
474
475 #[test]
476 fn frequency_analysis_reports_nearest_pitch_and_cents() {
477 let tuning = Tuning::concert_pitch();
478 let exact = tuning.analyze(440.0).unwrap();
479 assert_eq!(exact.pitch(), Pitch::la(4).unwrap());
480 close(exact.cents_offset(), 0.0, 1e-12);
481 let sharp = tuning.analyze(445.0).unwrap();
482 assert_eq!(sharp.pitch(), Pitch::la(4).unwrap());
483 assert!(sharp.cents_offset() > 19.0 && sharp.cents_offset() < 20.0);
484 }
485
486 #[test]
487 fn custom_la_reference_changes_all_frequencies() {
488 let tuning = Tuning::new(442.0).unwrap();
489 close(tuning.frequency(Pitch::la(4).unwrap()), 442.0, 1e-12);
490 close(tuning.frequency(Pitch::la(3).unwrap()), 221.0, 1e-10);
491 }
492
493 #[test]
494 fn la_relation_is_signed_and_octave_local() {
495 let c5 = Pitch::from_note(NoteName::C, 5).unwrap();
496 let relation = LaRelation::new(c5).unwrap();
497 assert_eq!(relation.la(), Pitch::la(5).unwrap());
498 assert_eq!(relation.semitones(), -9);
499 close(relation.frequency_ratio(), 2.0_f64.powf(-9.0 / 12.0), 1e-12);
500 }
501
502 #[test]
503 fn invalid_frequencies_and_octaves_are_rejected() {
504 assert!(matches!(Tuning::new(0.0), Err(Error::InvalidFrequency(_))));
505 assert!(matches!(
506 Tuning::concert_pitch().analyze(f64::NAN),
507 Err(Error::InvalidFrequency(_))
508 ));
509 assert!(matches!(Pitch::la(-2), Err(Error::PitchOutOfRange)));
510 assert!(matches!(Pitch::la(10), Err(Error::PitchOutOfRange)));
511 }
512}