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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use crate::dsp::Voice;
use crate::{Event, ProcessError, TimedEvent, VoiceId};
/// Fixed-capacity polyphonic synthesizer.
///
/// `VOICES` is the maximum number of simultaneous instrument layers. Buffer
/// size is inferred from the output slice supplied to [`Self::process`].
pub struct Synth<const VOICES: usize = 32> {
sample_rate: f32,
voices: [Voice; VOICES],
age: u64,
}
impl<const VOICES: usize> Synth<VOICES> {
/// Create a silent engine with a fixed sample rate.
///
/// Construction is a setup operation and is not part of the real-time API.
///
/// # Errors
///
/// Returns [`ProcessError::InvalidSampleRate`] for a non-finite rate or one
/// outside 1–768,000 Hz, and [`ProcessError::ZeroVoices`] when `VOICES` is 0.
pub fn new(sample_rate: f32) -> Result<Self, ProcessError> {
if !sample_rate.is_finite() || !(1.0..=768_000.0).contains(&sample_rate) {
return Err(ProcessError::InvalidSampleRate);
}
if VOICES == 0 {
return Err(ProcessError::ZeroVoices);
}
Ok(Self {
sample_rate,
voices: [Voice::EMPTY; VOICES],
age: 0,
})
}
/// Return the configured sample rate in hertz.
#[must_use]
pub const fn sample_rate(&self) -> f32 {
self.sample_rate
}
/// Return the number of voices that have not yet become silent.
#[must_use]
pub fn active_voice_count(&self) -> usize {
self.voices.iter().filter(|voice| voice.active).count()
}
/// Immediately clear all voice and oscillator DSP state.
///
/// The sample rate and other engine configuration are preserved. This is
/// suitable for a host's panic/reset action and performs no allocation.
pub fn reset_dsp(&mut self) {
self.voices.fill(Voice::EMPTY);
self.age = 0;
}
/// Alias for [`Self::reset_dsp`] named after the conventional host action.
pub fn panic(&mut self) {
self.reset_dsp();
}
/// Apply one event immediately, before the next generated sample.
///
/// This method performs no allocation or locking.
///
/// # Errors
///
/// Returns [`ProcessError::InvalidFrequency`] or
/// [`ProcessError::InvalidGain`] for invalid note-on settings. No state is
/// changed when validation fails.
pub fn dispatch(&mut self, event: Event) -> Result<(), ProcessError> {
validate_event(event)?;
self.dispatch_validated(event);
Ok(())
}
/// Fill a mono output block and apply ordered, sample-timed events.
///
/// The method validates the complete event slice before changing engine or
/// output state. It performs no allocation or locking. Output is always in
/// `-1.0..=1.0` when processing succeeds. Frequencies above the representable
/// audio band are deterministically clamped below Nyquist by each voice.
///
/// # Errors
///
/// Returns a [`ProcessError`] if note settings are invalid, event offsets
/// are unordered, or an offset exceeds `output.len()`. Validation happens
/// before output or engine state changes.
pub fn process(
&mut self,
output: &mut [f32],
events: &[TimedEvent],
) -> Result<(), ProcessError> {
validate_events(events, output.len())?;
let mut cursor = 0;
for timed in events {
self.render(&mut output[cursor..timed.sample_offset]);
self.dispatch_validated(timed.event);
cursor = timed.sample_offset;
}
self.render(&mut output[cursor..]);
Ok(())
}
pub(crate) fn render(&mut self, output: &mut [f32]) {
for sample in output {
*sample = self.next_sample();
}
}
pub(crate) fn next_sample(&mut self) -> f32 {
self.voices
.iter_mut()
.map(Voice::next_sample)
.sum::<f32>()
.clamp(-1.0, 1.0)
}
pub(crate) fn dispatch_validated(&mut self, event: Event) {
match event {
Event::NoteOn {
id,
instrument,
frequency_hz,
gain,
} => {
self.stop_id(id);
let index = self.voice_for_start();
self.age = self.age.wrapping_add(1);
self.voices[index].start(
id,
instrument,
frequency_hz,
gain,
self.sample_rate,
self.age,
);
}
Event::NoteOff(id) => self.release_id(id),
Event::AllNotesOff => {
for voice in &mut self.voices {
voice.release();
}
}
}
}
pub(crate) fn release_id(&mut self, id: VoiceId) {
for voice in &mut self.voices {
if voice.active && voice.id == id {
voice.release();
}
}
}
pub(crate) fn stop_id(&mut self, id: VoiceId) {
for voice in &mut self.voices {
if voice.active && voice.id == id {
voice.stop();
}
}
}
fn voice_for_start(&self) -> usize {
if let Some(index) = self.voices.iter().position(|voice| !voice.active) {
return index;
}
self.voices
.iter()
.enumerate()
.filter(|(_, voice)| voice.released)
.min_by_key(|(_, voice)| voice.started_at)
.or_else(|| {
self.voices
.iter()
.enumerate()
.min_by_key(|(_, voice)| voice.started_at)
})
.map_or(0, |(index, _)| index)
}
}
pub(crate) fn validate_event(event: Event) -> Result<(), ProcessError> {
if let Event::NoteOn {
frequency_hz, gain, ..
} = event
{
if !frequency_hz.is_finite() || frequency_hz <= 0.0 {
return Err(ProcessError::InvalidFrequency);
}
if !gain.is_finite() || !(0.0..=1.0).contains(&gain) {
return Err(ProcessError::InvalidGain);
}
}
Ok(())
}
pub(crate) fn validate_events(
events: &[TimedEvent],
output_len: usize,
) -> Result<(), ProcessError> {
let mut previous = 0;
for event in events {
if event.sample_offset > output_len {
return Err(ProcessError::EventOutsideBlock);
}
if event.sample_offset < previous {
return Err(ProcessError::EventsNotOrdered);
}
validate_event(event.event)?;
previous = event.sample_offset;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::Synth;
use crate::{Event, Instrument, VoiceId};
fn note(id: u64) -> Event {
Event::NoteOn {
id: VoiceId(id),
instrument: Instrument::Sine,
frequency_hz: 440.0,
gain: 0.5,
}
}
#[test]
fn invalid_note_settings_do_not_change_state() {
let mut synth = Synth::<2>::new(48_000.0).unwrap();
let mut invalid = note(1);
if let Event::NoteOn {
ref mut frequency_hz,
..
} = invalid
{
*frequency_hz = f32::NAN;
}
assert_eq!(
synth.dispatch(invalid),
Err(crate::ProcessError::InvalidFrequency)
);
assert_eq!(synth.active_voice_count(), 0);
}
#[test]
fn stealing_prefers_released_then_oldest() {
let mut synth = Synth::<2>::new(48_000.0).unwrap();
synth.dispatch(note(1)).unwrap();
synth.dispatch(note(2)).unwrap();
synth.dispatch(Event::NoteOff(VoiceId(2))).unwrap();
synth.dispatch(note(3)).unwrap();
assert!(synth.voices.iter().any(|voice| voice.id == VoiceId(1)));
assert!(synth.voices.iter().any(|voice| voice.id == VoiceId(3)));
synth.dispatch(note(4)).unwrap();
assert!(synth.voices.iter().any(|voice| voice.id == VoiceId(3)));
assert!(synth.voices.iter().any(|voice| voice.id == VoiceId(4)));
}
}