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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use std::cmp;
use std::sync::Arc;
use crate::midifile::MidiFile;
use crate::midifile::MidiMessage;
use crate::synthesizer::Synthesizer;
/// An instance of the MIDI file sequencer.
#[derive(Debug)]
#[non_exhaustive]
pub struct MidiFileSequencer {
synthesizer: Synthesizer,
speed: f64,
midi_file: Option<Arc<MidiFile>>,
play_loop: bool,
block_wrote: usize,
current_time: f64,
msg_index: usize,
loop_index: usize,
}
impl MidiFileSequencer {
/// Initializes a new instance of the sequencer.
///
/// # Arguments
///
/// * `synthesizer` - The synthesizer to be handled by the sequencer.
pub fn new(synthesizer: Synthesizer) -> Self {
Self {
synthesizer,
speed: 1.0,
midi_file: None,
play_loop: false,
block_wrote: 0,
current_time: 0.0,
msg_index: 0,
loop_index: 0,
}
}
/// Plays the MIDI file.
///
/// # Arguments
///
/// * `midi_file` - The MIDI file to be played.
/// * `play_loop` - If `true`, the MIDI file loops after reaching the end.
pub fn play(&mut self, midi_file: &Arc<MidiFile>, play_loop: bool) {
self.midi_file = Some(Arc::clone(midi_file));
self.play_loop = play_loop;
self.block_wrote = self.synthesizer.block_size;
self.current_time = 0.0;
self.msg_index = 0;
self.loop_index = 0;
self.synthesizer.reset()
}
/// Stops playing.
pub fn stop(&mut self) {
self.midi_file = None;
self.synthesizer.reset();
}
/// Renders the waveform.
///
/// # Arguments
///
/// * `left` - The buffer of the left channel to store the rendered waveform.
/// * `right` - The buffer of the right channel to store the rendered waveform.
///
/// # Remarks
///
/// The output buffers for the left and right must be the same length.
pub fn render(&mut self, left: &mut [f32], right: &mut [f32]) {
if left.len() != right.len() {
panic!("The output buffers for the left and right must be the same length.");
}
let left_length = left.len();
let mut wrote: usize = 0;
while wrote < left_length {
if self.block_wrote == self.synthesizer.block_size {
self.process_events();
self.block_wrote = 0;
self.current_time += self.speed * self.synthesizer.block_size as f64
/ self.synthesizer.sample_rate as f64;
}
let src_rem = self.synthesizer.block_size - self.block_wrote;
let dst_rem = left_length - wrote;
let rem = cmp::min(src_rem, dst_rem);
self.synthesizer.render(
&mut left[wrote..wrote + rem],
&mut right[wrote..wrote + rem],
);
self.block_wrote += rem;
wrote += rem;
}
}
fn process_events(&mut self) {
let midi_file = match self.midi_file.as_ref() {
Some(value) => value,
None => return,
};
while self.msg_index < midi_file.messages.len() {
let time = midi_file.times[self.msg_index];
let msg = midi_file.messages[self.msg_index];
if time <= self.current_time {
match msg {
MidiMessage::Normal {
status,
data1,
data2,
} => {
let channel = status & 0x0F;
let command = status & 0xF0;
self.synthesizer.process_midi_message(
channel as i32,
command as i32,
data1 as i32,
data2 as i32,
);
}
MidiMessage::LoopStart if self.play_loop => self.loop_index = self.msg_index,
// A loop that starts and ends at the same tick would rewind to the
// very message that is being processed and never let the render call
// finish, so a loop needs a non-empty tick range to be taken.
// https://github.com/sinshu/rustysynth/issues/57
MidiMessage::LoopEnd
if self.play_loop && time > midi_file.times[self.loop_index] =>
{
self.current_time = midi_file.times[self.loop_index];
self.msg_index = self.loop_index;
self.synthesizer.note_off_all(false);
}
_ => (),
}
self.msg_index += 1;
} else {
break;
}
}
if self.msg_index == midi_file.messages.len()
&& self.play_loop
&& self.loop_index < self.msg_index
&& midi_file.times[self.loop_index] < midi_file.times[self.msg_index - 1]
{
self.current_time = midi_file.times[self.loop_index];
self.msg_index = self.loop_index;
self.synthesizer.note_off_all(false);
}
}
/// Gets the synthesizer handled by the sequencer.
pub fn get_synthesizer(&self) -> &Synthesizer {
&self.synthesizer
}
/// Gets the currently playing MIDI file.
pub fn get_midi_file(&self) -> Option<&MidiFile> {
match &self.midi_file {
None => None,
Some(value) => Some(value),
}
}
/// Gets the current playback position in seconds.
pub fn get_position(&self) -> f64 {
self.current_time
}
/// Gets a value that indicates whether the current playback position is at the end of the sequence.
///
/// # Remarks
///
/// If the `play` method has not yet been called, this value will be `true`.
/// This value will never be `true` if loop playback is enabled.
pub fn end_of_sequence(&self) -> bool {
match &self.midi_file {
None => true,
Some(value) => self.msg_index == value.messages.len(),
}
}
/// Gets the current playback speed.
///
/// # Remarks
///
/// The default value is 1.
/// The tempo will be multiplied by this value during playback.
pub fn get_speed(&self) -> f64 {
self.speed
}
/// Sets the playback speed.
///
/// # Remarks
///
/// The value must be non-negative.
pub fn set_speed(&mut self, value: f64) {
if value < 0.0 {
panic!("The playback speed must be a non-negative value.");
}
self.speed = value;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(target_family = "wasm"))]
use std::sync::mpsc;
#[cfg(not(target_family = "wasm"))]
use std::thread;
#[cfg(not(target_family = "wasm"))]
use std::time::Duration;
use crate::test_font::*;
use crate::{SoundFont, SynthesizerSettings};
fn synthesizer() -> Synthesizer {
let mut reader = std::io::Cursor::new(build_sf2(&sample_spec(), 1));
let sound_font = Arc::new(SoundFont::new(&mut reader).unwrap());
let settings = SynthesizerSettings::new(44100);
Synthesizer::new(&sound_font, &settings).unwrap()
}
// A loop that starts and ends on the same tick used to rewind to the very
// message being processed, so a single render call never returned (#57).
#[test]
fn test_a_zero_length_loop_does_not_hang_the_sequencer() {
let midi_file = Arc::new(
MidiFile::new_with_events([
(0.0, MidiMessage::LoopStart),
(0.0, MidiMessage::LoopEnd),
(0.0, MidiMessage::EndOfTrack),
])
.unwrap(),
);
let render = move |midi_file: Arc<MidiFile>| {
let mut sequencer = MidiFileSequencer::new(synthesizer());
sequencer.play(&midi_file, true);
let mut left = vec![0_f32; 512];
let mut right = vec![0_f32; 512];
sequencer.render(&mut left, &mut right);
sequencer.end_of_sequence()
};
// The work runs on a thread so that a regression fails the test instead
// of hanging the test run forever, which is not an option where threads
// are not available.
#[cfg(not(target_family = "wasm"))]
{
let (sender, receiver) = mpsc::channel();
thread::spawn(move || {
sender.send(render(midi_file)).unwrap();
});
let end_of_sequence = receiver
.recv_timeout(Duration::from_secs(10))
.expect("the sequencer did not finish rendering");
assert!(end_of_sequence);
}
#[cfg(target_family = "wasm")]
assert!(render(midi_file));
}
// A loop with a range still repeats: rendering must not fall through to
// the end of the sequence.
#[test]
fn test_a_normal_loop_still_repeats() {
let midi_file = Arc::new(
MidiFile::new_with_events([
(0.0, MidiMessage::LoopStart),
(
0.0,
MidiMessage::Normal {
status: 0x90,
data1: 60,
data2: 100,
},
),
(1.0, MidiMessage::LoopEnd),
(2.0, MidiMessage::EndOfTrack),
])
.unwrap(),
);
let mut sequencer = MidiFileSequencer::new(synthesizer());
sequencer.play(&midi_file, true);
let mut left = vec![0_f32; 44100];
let mut right = vec![0_f32; 44100];
sequencer.render(&mut left, &mut right);
assert!(!sequencer.end_of_sequence());
assert!(sequencer.get_position() < 2.0);
}
}