1use crate::midi::Note;
4
5const CHORD_COUNT: u8 = 16;
6const CHORDS: [(&str, &[u8]); CHORD_COUNT as usize] = [
7 ("Maj", &[0, 4, 7]),
8 ("Min", &[0, 3, 7]),
9 ("Maj7", &[0, 4, 7, 11]),
10 ("m7", &[0, 3, 7, 10]),
11 ("7", &[0, 4, 7, 10]),
12 ("Sus2", &[0, 2, 7]),
13 ("Sus4", &[0, 5, 7]),
14 ("Dim", &[0, 3, 6]),
15 ("Aug", &[0, 4, 8]),
16 ("6", &[0, 4, 7, 9]),
17 ("m6", &[0, 3, 7, 9]),
18 ("Dim7", &[0, 3, 6, 9]),
19 ("m7b5", &[0, 3, 6, 10]),
20 ("mMaj7", &[0, 3, 7, 11]),
21 ("Add9", &[0, 4, 7, 14]),
22 ("mAdd9", &[0, 3, 7, 14]),
23];
24
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27pub struct Chord(u8);
28
29impl Chord {
30 pub const MAJOR: Self = Self(0);
32
33 #[must_use]
35 pub fn name(self) -> &'static str {
36 CHORDS[usize::from(self.0)].0
37 }
38
39 #[must_use]
41 pub fn turn(self, delta: i8) -> Self {
42 let i = i16::from(self.0).saturating_add(i16::from(delta));
43 Self(i.rem_euclid(i16::from(CHORD_COUNT)).to_le_bytes()[0])
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub enum VoiceMode {
50 #[default]
52 Poly,
53 Chord(Chord),
55 Unison,
57}
58
59#[derive(Clone, Copy, Debug)]
61pub struct Keyboard {
62 pub mode: VoiceMode,
64 held: [Option<Note>; 4],
65}
66
67impl Keyboard {
68 pub const EMPTY: Self = Self {
70 mode: VoiceMode::Poly,
71 held: [None; 4],
72 };
73
74 pub fn press(&mut self, note: Note) {
76 let index = self
77 .held
78 .iter()
79 .position(|n| n.is_some_and(|n| n.number == note.number))
80 .unwrap_or(3);
81 self.held[..=index].rotate_right(1);
82 self.held[0] = Some(note);
83 }
84
85 pub fn release(&mut self, note: u8) -> bool {
87 let Some(index) = self
88 .held
89 .iter()
90 .position(|n| n.is_some_and(|n| n.number == note))
91 else {
92 return false;
93 };
94 self.held[index..].rotate_left(1);
95 self.held[3] = None;
96 index == 0
97 }
98
99 pub fn clear(&mut self) {
101 self.held.fill(None);
102 }
103
104 #[must_use]
106 pub fn voice(&self, slot: usize) -> Option<Note> {
107 let root = self.held[0]?;
108 match self.mode {
109 VoiceMode::Poly => self.held.get(slot).copied().flatten(),
110 VoiceMode::Unison => (slot < 4).then_some(root),
111 VoiceMode::Chord(chord) => {
112 let offset = *CHORDS[usize::from(chord.0)].1.get(slot)?;
113 let number = root.number.checked_add(offset)?;
114 (number < 128).then_some(Note { number, ..root })
115 }
116 }
117 }
118
119 #[must_use]
122 pub fn step(&self, slot: usize, base: u32) -> u32 {
123 if self.mode != VoiceMode::Unison {
124 return base;
125 }
126 let step = match slot {
127 0 => base.saturating_sub(base >> 8),
128 1 => base.saturating_sub(base >> 10),
129 2 => base.saturating_add(base >> 10),
130 _ => base.saturating_add(base >> 8),
131 };
132 if step < (1 << 31) { step } else { 0 }
133 }
134}