1use std::sync::Arc;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct TuningInfo {
13 pub id: u32,
15 pub name: String,
17 pub is_dynamic: bool,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct TuningEvent {
27 pub sample_offset: u32,
28 pub port_index: i16,
29 pub channel: i16,
30 pub tuning_id: u32,
31}
32
33pub trait TuningProvider: Send + Sync {
35 fn relative_offset(&self, port_index: i32, channel: i32, key: i32, sample_offset: u32) -> f64;
37
38 fn should_play(&self, port_index: i32, channel: i32, key: i32) -> bool;
40
41 fn apply(&self, _event: &TuningEvent) {}
43
44 fn tuning_count(&self) -> u32 {
46 0
47 }
48
49 fn tuning_info(&self, _index: u32) -> Option<TuningInfo> {
51 None
52 }
53}
54
55#[derive(Debug, Clone, Copy)]
57struct NullTuning;
58
59impl TuningProvider for NullTuning {
60 fn relative_offset(
61 &self,
62 _port_index: i32,
63 _channel: i32,
64 _key: i32,
65 _sample_offset: u32,
66 ) -> f64 {
67 0.0
68 }
69
70 fn should_play(&self, _port_index: i32, _channel: i32, _key: i32) -> bool {
71 true
72 }
73
74 fn tuning_count(&self) -> u32 {
75 0
76 }
77
78 fn tuning_info(&self, _index: u32) -> Option<TuningInfo> {
79 None
80 }
81}
82
83#[derive(Clone)]
85pub struct Tuning {
86 provider: Arc<dyn TuningProvider>,
87}
88
89impl Default for Tuning {
90 fn default() -> Self {
91 Self::disabled()
92 }
93}
94
95impl Tuning {
96 #[must_use]
98 pub fn new(provider: Arc<dyn TuningProvider>) -> Self {
99 Self { provider }
100 }
101
102 #[must_use]
104 pub fn disabled() -> Self {
105 Self {
106 provider: Arc::new(NullTuning),
107 }
108 }
109
110 pub fn apply_event(&self, event: &TuningEvent) {
112 self.provider.apply(event);
113 }
114
115 #[must_use]
118 pub fn relative_offset(
119 &self,
120 port_index: i32,
121 channel: i32,
122 key: i32,
123 sample_offset: u32,
124 ) -> f64 {
125 self.provider
126 .relative_offset(port_index, channel, key, sample_offset)
127 }
128
129 #[must_use]
131 pub fn should_play(&self, port_index: i32, channel: i32, key: i32) -> bool {
132 self.provider.should_play(port_index, channel, key)
133 }
134
135 #[must_use]
137 pub fn tuning_count(&self) -> u32 {
138 self.provider.tuning_count()
139 }
140
141 #[must_use]
143 pub fn tuning_info(&self, index: u32) -> Option<TuningInfo> {
144 self.provider.tuning_info(index)
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 #[test]
153 #[allow(clippy::float_cmp)]
154 fn disabled_is_zero_and_plays() {
155 let t = Tuning::disabled();
156 assert_eq!(t.relative_offset(0, 0, 60, 0), 0.0);
157 assert!(t.should_play(0, 0, 60));
158 }
159
160 #[test]
161 fn disabled_has_no_tunings() {
162 let t = Tuning::disabled();
163 assert_eq!(t.tuning_count(), 0);
164 assert!(t.tuning_info(0).is_none());
165 }
166}