1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use super::{Hz, Cents};
const A440: Hz = Hz(440.0);
pub trait Tuning {
fn reference_pitch(&self) -> Hz;
fn pitch(&self, step: i32) -> Option<Hz>;
fn interval(&self, from: i32, to: i32) -> Option<Cents> {
match (self.pitch(from), self.pitch(to)) {
(Some(to), Some(from)) => Some(to / from),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Edo {
cardinality: u16,
reference: Hz,
}
impl Edo {
pub fn new(cardinality: u16, reference: Hz) -> Self {
Edo {
cardinality, reference
}
}
pub fn new_a440(cardinality: u16) -> Self {
Self::new(cardinality, A440)
}
}
impl Tuning for Edo {
fn reference_pitch(&self) -> Hz {
self.reference
}
fn pitch(&self, step: i32) -> Option<Hz> {
let int = Cents(1200.0 / self.cardinality as f32) * step as f32;
Some(self.reference + int)
}
fn interval(&self, from: i32, to: i32) -> Option<Cents> {
let delta = (to - from) as f32;
Some(Cents(1200.0 / self.cardinality as f32 * delta))
}
}
#[derive(Debug, Clone)]
pub struct EqualSteps {
step: Cents,
reference: Hz,
}
impl EqualSteps {
pub fn new(step: Cents, reference: Hz) -> Self {
EqualSteps {
step, reference
}
}
pub fn new_a440(step: Cents) -> Self {
Self::new(step, A440)
}
}
impl Tuning for EqualSteps {
fn reference_pitch(&self) -> Hz {
self.reference
}
fn pitch(&self, step: i32) -> Option<Hz> {
let int = self.step * step as f32;
Some(self.reference + int)
}
}
#[derive(Debug, Clone)]
pub struct MidiTuning {
pitches: Vec<Hz>,
}
impl MidiTuning {
pub fn from_tuning<T: Tuning>(tuning: T, refkey: u8) -> Option<Self> {
assert!(refkey < 127);
let mut pitches = Vec::with_capacity(127);
for i in 0..127 {
if let Some(hz) = tuning.pitch(i - refkey as i32) {
pitches.push(hz)
}
else {
return None
}
}
Some(MidiTuning {
pitches
})
}
pub fn from_pitches(hzs: &[Hz]) -> Option<Self> {
if hzs.len() < 127 { return None }
let pitches = hzs[0..127].to_owned();
Some(MidiTuning {
pitches
})
}
}
impl ::std::default::Default for MidiTuning {
fn default() -> Self {
let mut pitches = Vec::with_capacity(127);
pitches.extend((0..127).map(|i| A440 + Cents((i - 69) as f32 * 100.0)));
MidiTuning {
pitches
}
}
}
impl Tuning for MidiTuning {
fn reference_pitch(&self) -> Hz {
self.pitches[0]
}
fn pitch(&self, step: i32) -> Option<Hz> {
if step < 0 { return None }
self.pitches.get(step as usize).cloned()
}
}
impl ::std::ops::Index<usize> for MidiTuning {
type Output = Hz;
fn index(&self, index: usize) -> &Hz {
&self.pitches[index]
}
}