Skip to main content

laxury_eu/
lib.rs

1//! The musical logic of **La**.
2//!
3//! `laxury-eu` relates fixed-do La (the note A), movable-do scale degree six,
4//! concert-pitch tuning, twelve-tone equal temperament, transposition, and
5//! frequency analysis. It performs no audio I/O and has no dependencies.
6//!
7//! # Example
8//!
9//! ```
10//! use laxury_eu::{Pitch, Solfege, Tuning};
11//!
12//! let tuning = Tuning::concert_pitch();
13//! let la4 = Pitch::la(4)?;
14//! assert_eq!(la4.midi(), 69);
15//! assert_eq!(Solfege::La.fixed_note_name().to_string(), "A");
16//! assert!((tuning.frequency(la4) - 440.0).abs() < 1e-12);
17//! # Ok::<(), laxury_eu::Error>(())
18//! ```
19
20#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22
23use std::error::Error as StdError;
24use std::fmt;
25
26/// The twelve pitch classes, spelled with sharps for chromatic notes.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28#[repr(u8)]
29pub enum NoteName {
30    /// C.
31    C = 0,
32    /// C sharp.
33    CSharp = 1,
34    /// D.
35    D = 2,
36    /// D sharp.
37    DSharp = 3,
38    /// E.
39    E = 4,
40    /// F.
41    F = 5,
42    /// F sharp.
43    FSharp = 6,
44    /// G.
45    G = 7,
46    /// G sharp.
47    GSharp = 8,
48    /// A, fixed-do La.
49    A = 9,
50    /// A sharp.
51    ASharp = 10,
52    /// B.
53    B = 11,
54}
55
56impl NoteName {
57    /// Creates a note name from a chromatic pitch class, wrapping modulo 12.
58    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    /// Returns the chromatic pitch class from C = 0 through B = 11.
76    pub const fn pitch_class(self) -> u8 {
77        self as u8
78    }
79
80    /// Transposes a note name by signed semitones, wrapping by octave.
81    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/// The seven unaltered solfège syllables.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
109pub enum Solfege {
110    /// Do, scale degree 1.
111    Do,
112    /// Re, scale degree 2.
113    Re,
114    /// Mi, scale degree 3.
115    Mi,
116    /// Fa, scale degree 4.
117    Fa,
118    /// Sol, scale degree 5.
119    Sol,
120    /// La, scale degree 6.
121    La,
122    /// Ti, scale degree 7.
123    Ti,
124}
125
126impl Solfege {
127    /// Returns the one-based diatonic scale degree.
128    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    /// Returns the fixed-do note name; La maps to A.
141    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/// A MIDI-representable equal-tempered pitch from 0 through 127.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
171pub struct Pitch(u8);
172
173impl Pitch {
174    /// Creates a pitch from a MIDI note number.
175    pub const fn from_midi(midi: u8) -> Self {
176        Self(midi)
177    }
178
179    /// Creates fixed-do La/A in a scientific-pitch octave.
180    ///
181    /// `Pitch::la(4)` is A4/MIDI 69. Octaves outside the MIDI range return an
182    /// error rather than wrapping.
183    pub fn la(octave: i8) -> Result<Self, Error> {
184        Self::from_note(NoteName::A, octave)
185    }
186
187    /// Creates a pitch from a note name and scientific-pitch octave.
188    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    /// Returns the MIDI note number.
201    pub const fn midi(self) -> u8 {
202        self.0
203    }
204
205    /// Returns the sharp-spelled note name.
206    pub const fn note_name(self) -> NoteName {
207        NoteName::from_pitch_class(self.0 % 12)
208    }
209
210    /// Returns the scientific-pitch octave.
211    pub const fn octave(self) -> i8 {
212        (self.0 / 12) as i8 - 1
213    }
214
215    /// Transposes within the MIDI range.
216    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    /// Returns signed semitones from another pitch.
227    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/// Major or natural-minor movable-do interval structure.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum Mode {
241    /// Major: 0, 2, 4, 5, 7, 9, 11 semitones.
242    Major,
243    /// Natural minor: 0, 2, 3, 5, 7, 8, 10 semitones.
244    NaturalMinor,
245}
246
247/// A movable-do key defined by tonic pitch class and mode.
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
249pub struct Key {
250    tonic: NoteName,
251    mode: Mode,
252}
253
254impl Key {
255    /// Creates a movable-do key.
256    pub const fn new(tonic: NoteName, mode: Mode) -> Self {
257        Self { tonic, mode }
258    }
259
260    /// Returns the tonic, which acts as Do.
261    pub const fn tonic(self) -> NoteName {
262        self.tonic
263    }
264
265    /// Returns the scale mode.
266    pub const fn mode(self) -> Mode {
267        self.mode
268    }
269
270    /// Resolves an unaltered movable-do syllable to a note name.
271    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    /// Returns movable-do La, scale degree six, in this key.
281    pub fn la(self) -> NoteName {
282        self.note_for(Solfege::La)
283    }
284}
285
286/// A twelve-tone equal-temperament tuning anchored by A4/La4.
287#[derive(Debug, Clone, Copy, PartialEq)]
288pub struct Tuning {
289    a4_hz: f64,
290}
291
292impl Tuning {
293    /// Creates tuning from the frequency of A4/La4.
294    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    /// Returns the common concert-pitch reference A4 = 440 Hz.
302    pub const fn concert_pitch() -> Self {
303        Self { a4_hz: 440.0 }
304    }
305
306    /// Returns the A4/La4 reference frequency.
307    pub const fn a4_hz(self) -> f64 {
308        self.a4_hz
309    }
310
311    /// Returns a pitch frequency using twelve-tone equal temperament.
312    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    /// Returns the frequency of fixed-do La/A in the given octave.
317    pub fn la_frequency(self, octave: i8) -> Result<f64, Error> {
318        Ok(self.frequency(Pitch::la(octave)?))
319    }
320
321    /// Finds the nearest MIDI pitch and signed cents offset for a frequency.
322    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/// The nearest equal-tempered pitch and its tuning deviation.
341#[derive(Debug, Clone, Copy, PartialEq)]
342pub struct FrequencyAnalysis {
343    pitch: Pitch,
344    cents_offset: f64,
345}
346
347impl FrequencyAnalysis {
348    /// Returns the nearest MIDI-representable pitch.
349    pub const fn pitch(self) -> Pitch {
350        self.pitch
351    }
352
353    /// Returns signed cents above (positive) or below (negative) that pitch.
354    pub const fn cents_offset(self) -> f64 {
355        self.cents_offset
356    }
357}
358
359/// A pitch expressed in relation to La/A within the same octave.
360#[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    /// Builds a relation to La/A in `pitch`'s scientific-pitch octave.
370    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    /// Returns the related pitch.
383    pub const fn pitch(self) -> Pitch {
384        self.pitch
385    }
386
387    /// Returns La/A in the related pitch's octave.
388    pub const fn la(self) -> Pitch {
389        self.la
390    }
391
392    /// Returns signed semitones from La.
393    pub const fn semitones(self) -> i16 {
394        self.semitones
395    }
396
397    /// Returns the equal-tempered frequency ratio `pitch / La`.
398    pub const fn frequency_ratio(self) -> f64 {
399        self.frequency_ratio
400    }
401}
402
403/// Pitch and tuning validation errors.
404#[derive(Debug, Clone, PartialEq)]
405#[non_exhaustive]
406pub enum Error {
407    /// A note and octave or transposition exceeded MIDI 0 through 127.
408    PitchOutOfRange,
409    /// A frequency was zero, negative, NaN, or infinite.
410    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}