Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
sequencer.hpp
Go to the documentation of this file.
1/**
2 * @file sequencer.hpp
3 * @brief Plays a Standard MIDI File into outputs
4 */
5
6#ifndef SBL_PROTOCOL_MIDI_SEQUENCER_HPP_
7#define SBL_PROTOCOL_MIDI_SEQUENCER_HPP_
8
9#include <cstdint>
10#include <numeric>
11
14
15namespace sbl::midi {
16
17/**
18 * @brief Plays a Standard MIDI File to a set of outputs
19 *
20 * The sequencer owns a playhead over an SmfReader's tracks. It is told how
21 * many ticks of the control clock have passed and never assumes a call
22 * rate: advance() walks every track in SMF tick order,
23 * converts SMF ticks to time through the tempo map, and hands each event that
24 * is due to a sink with the output it belongs to. Events come out in the call
25 * where they fall due, so their timing is as fine as the calls: to the clock
26 * tick if advance() is called per tick, to the base period if it is called
27 * from a 1 kHz scheduler.
28 *
29 * Time is exact integer arithmetic. SMF tick -> microseconds carries its
30 * remainder across segments, and "due" compares microseconds x (rate / g)
31 * against clock ticks x (10^6 / g), g = gcd(rate, 10^6), so nothing drifts
32 * over a long song or many loops. The reduction keeps a 1 MHz clock (g = 10^6)
33 * in plain ticks; scaling by 10^6 would overflow 64 bits in 213 days.
34 *
35 * Routing. A format 1 file's track 0 is the conductor (the tempo map): its
36 * tempo events apply, its channel events go nowhere unless mapped. Tracks
37 * 1..N go to outputs 0..N-1. A format 0 file has one track, so it is split
38 * by channel: channels 0..N-1 go to outputs 0..N-1. Either map can be
39 * changed, and an output can rewrite every event's channel to one channel.
40 *
41 * Transport is standard MIDI:
42 * - start(): play from the top. The outputs are silenced, every
43 * controller's first value in the file is sent to each output, then play
44 * begins. Each run from the top begins the same way.
45 * - stop(): stop where it is, the outputs silenced; the playhead is kept.
46 * - resume(): play on from the playhead (MIDI Continue).
47 *
48 * With loop on, reaching the end silences the outputs and plays again from
49 * the top; with loop off the sequencer stops and silences them.
50 *
51 * Silencing sends a Note Off for every note the sequencer has sounding, on
52 * the output and channel it went to, then All Notes Off (CC 123) on every
53 * channel each output uses. Some receivers ignore CC 123, so the Note Offs
54 * end each note on its own (sound-byte-libs#149). A note the file ends
55 * itself, with a Note Off or a Note On at velocity 0, is not sounding. Notes
56 * still sounding when a new file is loaded are released by the next
57 * silencing.
58 *
59 * A muted output sends nothing. Muting releases the output's sounding notes
60 * as silencing does; an output unmuted while the song plays joins at its next
61 * event, and the controller values it missed are not sent again.
62 *
63 * Program Changes play on the first pass of a Start only. A program is the
64 * voice's setup, not the song: a file names its sounds at tick 0, and a run
65 * from the top should load them so every run begins the same - but a loop
66 * wrap is the same run continuing, and a preset reloading on every wrap would
67 * undo any change the player has made since.
68 *
69 * The SmfReader's bytes must outlive the sequencer.
70 *
71 * Usage:
72 * @code
73 * void sink(void*, uint8_t output, const sbl::midi::MidiEvent& e) { ... }
74 * sbl::midi::Sequencer<4> seq(Clock::TICKS_PER_SECOND, sink, nullptr);
75 * seq.load(smf);
76 * seq.start();
77 * seq.advance(elapsed_ticks); // from the control tick
78 * @endcode
79 *
80 * @tparam Outputs Number of outputs, at least 1
81 */
82template<uint8_t Outputs = 4>
83class Sequencer {
84 static_assert(Outputs >= 1, "a sequencer needs an output");
85
86public:
87 static constexpr uint8_t OUTPUTS = Outputs; /**< outputs the sequencer plays into */
88 static constexpr uint8_t MAX_TRACKS = SmfReader::MAX_TRACKS; /**< tracks a file may have */
89 static constexpr uint8_t CHANNELS = 16; /**< MIDI channels */
90 static constexpr uint8_t NO_OUTPUT = 0xFF; /**< a track or channel mapped to no output */
91 static constexpr uint8_t KEEP_CHANNEL = 0xFF; /**< an output that leaves each event's channel */
92 static constexpr uint8_t MAX_SNAPSHOT = 64; /**< distinct (output, channel, controller) first values */
93 static constexpr uint32_t DEFAULT_TEMPO_US = 500000; /**< 120 bpm: the SMF default */
94 static constexpr uint8_t ALL_NOTES_OFF = 123; /**< the All Notes Off controller number */
95
96 /** @brief Receives each event the sequencer emits: the context pointer, the output index and the event */
97 using Sink = void (*)(void* context, uint8_t output, const MidiEvent& event);
98
99 /**
100 * @brief Construct a stopped sequencer with no file loaded
101 * @param tick_rate The clock's ticks per second, what advance() counts in
102 * (`Clock::TICKS_PER_SECOND`). Required, no default;
103 * a zero rate counts as one tick per second.
104 * @param sink Called for every event emitted
105 * @param context Passed to sink unchanged
106 */
107 Sequencer(uint32_t tick_rate, Sink sink, void* context) : sink_(sink), context_(context) {
108 const uint32_t rate = tick_rate > 0 ? tick_rate : 1;
109 const uint32_t g = std::gcd(rate, static_cast<uint32_t>(MICROS_PER_SECOND));
110 us_scale_ = rate / g;
111 tick_scale_ = static_cast<uint32_t>(MICROS_PER_SECOND) / g;
112 for (uint8_t o = 0; o < Outputs; ++o) {
113 output_channel_[o] = KEEP_CHANNEL;
114 }
115 }
116
117 /**
118 * @brief Take a parsed file and apply the default map. Stops playback.
119 * @param smf A reader whose parse() succeeded; the file's bytes must outlive the sequencer
120 * @return false if the file was not loaded
121 */
122 bool load(const SmfReader& smf) {
123 playing_ = false;
124 loaded_ = smf.error() == SmfError::None && smf.track_count() > 0;
125 if (!loaded_) {
126 return false;
127 }
128 format_ = smf.format();
129 track_count_ = smf.track_count();
130 ticks_per_quarter_ = smf.ticks_per_quarter();
131 for (uint8_t t = 0; t < MAX_TRACKS; ++t) {
132 tracks_[t] = t < track_count_ ? smf.track(t) : SmfTrack{};
133 track_output_[t] = (t >= 1 && t - 1 < Outputs) ? static_cast<uint8_t>(t - 1) : NO_OUTPUT;
134 }
135 for (uint8_t c = 0; c < CHANNELS; ++c) {
136 channel_output_[c] = c < Outputs ? c : NO_OUTPUT;
137 }
138 rewind();
139 scan();
140 finished_ = false;
141 return true;
142 }
143
144 /**
145 * @brief Format 1: which output a track plays into
146 * @param track Track index
147 * @param output Output index, or NO_OUTPUT for none
148 */
149 void set_track_output(uint8_t track, uint8_t output) {
150 if (track >= MAX_TRACKS) {
151 return;
152 }
153 track_output_[track] = output < Outputs ? output : NO_OUTPUT;
154 if (loaded_) {
155 scan();
156 }
157 }
158
159 /**
160 * @brief Format 0: which output a channel plays into
161 * @param channel MIDI channel, 0 to 15
162 * @param output Output index, or NO_OUTPUT for none
163 */
164 void set_channel_output(uint8_t channel, uint8_t output) {
165 if (channel >= CHANNELS) {
166 return;
167 }
168 channel_output_[channel] = output < Outputs ? output : NO_OUTPUT;
169 if (loaded_) {
170 scan();
171 }
172 }
173
174 /**
175 * @brief Send every event on an output on one channel
176 * @param output Output index
177 * @param channel MIDI channel, 0 to 15, or KEEP_CHANNEL to leave each event's channel
178 */
179 void set_output_channel(uint8_t output, uint8_t channel) {
180 if (output >= Outputs) {
181 return;
182 }
183 output_channel_[output] = channel < CHANNELS ? channel : KEEP_CHANNEL;
184 if (loaded_) {
185 scan();
186 }
187 }
188
189 /**
190 * @brief Mute an output: its sounding notes are released, and it sends nothing until unmuted
191 * @param output Output index
192 * @param on true to mute, false to unmute
193 */
194 void set_output_mute(uint8_t output, bool on) {
195 if (output >= Outputs || muted_[output] == on) {
196 return;
197 }
198 if (on) {
199 release_notes(output);
200 send_all_notes_off(output);
201 }
202 muted_[output] = on;
203 }
204 /** @brief True if the output is muted; false for an index out of range */
205 bool output_muted(uint8_t output) const { return output < Outputs && muted_[output]; }
206
207 /** @brief Loop on or off: at the end, play again from the top or stop */
208 void set_loop(bool on) { loop_ = on; }
209 /** @brief True if loop is on */
210 bool looping() const { return loop_; }
211
212 // Transport (standard MIDI)
213
214 /** Start: play from the top with every output reset. */
215 void start() {
216 if (!loaded_) {
217 return;
218 }
219 all_notes_off();
220 for (uint8_t i = 0; i < snapshot_count_; ++i) {
221 if (muted_[snapshot_[i].output]) {
222 continue;
223 }
224 emit_cc(snapshot_[i].output, snapshot_[i].channel, snapshot_[i].controller, snapshot_[i].value);
225 }
226 rewind();
227 pass_start_scaled_ = now_scaled_;
228 pass_ = 0;
229 finished_ = false;
230 playing_ = true;
231 }
232
233 /** Stop: hold the playhead, silence the outputs. */
234 void stop() {
235 if (!playing_) {
236 return;
237 }
238 playing_ = false;
239 all_notes_off();
240 }
241
242 /** Continue: play on from the playhead. Nothing to continue after the end. */
243 void resume() {
244 if (loaded_ && !finished_) {
245 playing_ = true;
246 }
247 }
248
249 /** @brief True while playing */
250 bool playing() const { return playing_; }
251 /** @brief True once play reached the end with loop off */
252 bool finished() const { return finished_; }
253 /** @brief True if the last load() took a file */
254 bool loaded() const { return loaded_; }
255
256 /** @brief Where the playhead is in the song, in microseconds from the top */
257 uint64_t position_us() const { return song_us_; }
258
259 /**
260 * @brief Let `elapsed_ticks` of the clock pass: emit every event that falls due
261 *
262 * Time counts while stopped too, so a resume picks up at the playhead
263 * without replaying the pause.
264 *
265 * @param elapsed_ticks Clock ticks since the last call
266 */
267 void advance(uint32_t elapsed_ticks) {
268 const uint64_t step = static_cast<uint64_t>(elapsed_ticks) * tick_scale_;
269 if (!loaded_ || !playing_) {
270 pass_start_scaled_ += step; // the song does not move while stopped
271 now_scaled_ += step;
272 return;
273 }
274 now_scaled_ += step;
275
276 for (;;) {
277 uint8_t best = NO_TRACK;
278 uint32_t best_tick = 0;
279 for (uint8_t t = 0; t < track_count_; ++t) {
280 const SmfEvent* ev = tracks_[t].peek();
281 if (ev != nullptr && (best == NO_TRACK || ev->tick < best_tick)) {
282 best = t;
283 best_tick = ev->tick;
284 }
285 }
286
287 if (best == NO_TRACK) { // every track has ended
288 if (!loop_ || song_us_ == 0) {
289 playing_ = false;
290 finished_ = true;
291 all_notes_off();
292 return;
293 }
294 all_notes_off();
295 pass_start_scaled_ += song_us_ * us_scale_;
296 rewind();
297 ++pass_;
298 continue;
299 }
300
301 const uint64_t numerator = static_cast<uint64_t>(best_tick - last_tick_) * tempo_us_ + tick_remainder_;
302 const uint64_t event_us = song_us_ + numerator / ticks_per_quarter_;
303 if (pass_start_scaled_ + event_us * us_scale_ > now_scaled_) {
304 return; // not due yet
305 }
306
307 song_us_ = event_us;
308 tick_remainder_ = numerator % ticks_per_quarter_;
309 last_tick_ = best_tick;
310
311 const SmfEvent ev = *tracks_[best].peek();
312 tracks_[best].pop();
313 if (ev.kind == SmfEvent::Kind::Tempo && ev.tempo_us > 0) {
314 tempo_us_ = ev.tempo_us;
315 } else if (ev.kind == SmfEvent::Kind::Channel) {
316 route(best, ev.midi);
317 }
318 }
319 }
320
321private:
322 static constexpr uint64_t MICROS_PER_SECOND = 1000000;
323 static constexpr uint8_t NO_TRACK = 0xFF;
324 static constexpr uint8_t NOTE_MASK = 0x7F;
325 static constexpr uint8_t NOTE_BITS = 32; /**< notes per word of the sounding set */
326 static constexpr uint8_t NOTE_WORDS = 128 / NOTE_BITS;
327
328 struct Controller {
329 uint8_t output;
330 uint8_t channel;
331 uint8_t controller;
332 uint8_t value;
333 };
334
335 void rewind() {
336 for (uint8_t t = 0; t < track_count_; ++t) {
337 tracks_[t].rewind();
338 }
339 tempo_us_ = DEFAULT_TEMPO_US;
340 song_us_ = 0;
341 last_tick_ = 0;
342 tick_remainder_ = 0;
343 }
344
345 /** The output an event plays into, and its channel after any rewrite. */
346 bool destination(uint8_t track, const MidiEvent& e, uint8_t& output, uint8_t& channel) const {
347 output = format_ == 0 ? channel_output_[e.channel & (CHANNELS - 1)] : track_output_[track];
348 if (output >= Outputs) {
349 return false;
350 }
351 channel = output_channel_[output] == KEEP_CHANNEL ? e.channel : output_channel_[output];
352 return true;
353 }
354
355 void route(uint8_t track, MidiEvent e) {
356 if (e.type == MessageType::ProgramChange && pass_ > 0) {
357 return; // setup, not song
358 }
359 uint8_t output = 0;
360 uint8_t channel = 0;
361 if (!destination(track, e, output, channel)) {
362 return;
363 }
364 if (muted_[output]) {
365 return;
366 }
367 e.channel = channel;
368 if (e.type == MessageType::NoteOn || e.type == MessageType::NoteOff) {
369 mark(output, channel, e.data1, e.type == MessageType::NoteOn && e.data2 > 0);
370 }
371 if (sink_ != nullptr) {
372 sink_(context_, output, e);
373 }
374 }
375
376 /** Record whether a note is sounding on an output's channel. */
377 void mark(uint8_t output, uint8_t channel, uint8_t note, bool on) {
378 const uint8_t n = note & NOTE_MASK;
379 uint32_t& word = sounding_[output][channel & (CHANNELS - 1)][n / NOTE_BITS];
380 const uint32_t bit = 1U << (n % NOTE_BITS);
381 word = on ? (word | bit) : (word & ~bit);
382 }
383
384 void emit_note_off(uint8_t output, uint8_t channel, uint8_t note) {
385 MidiEvent e;
386 e.type = MessageType::NoteOff;
387 e.channel = channel;
388 e.data1 = note;
389 e.data2 = 0;
390 if (sink_ != nullptr) {
391 sink_(context_, output, e);
392 }
393 }
394
395 void emit_cc(uint8_t output, uint8_t channel, uint8_t controller, uint8_t value) {
396 MidiEvent e;
397 e.type = MessageType::ControlChange;
398 e.channel = channel;
399 e.data1 = controller;
400 e.data2 = value;
401 if (sink_ != nullptr) {
402 sink_(context_, output, e);
403 }
404 }
405
406 /** A Note Off for each note sounding on an output. */
407 void release_notes(uint8_t o) {
408 for (uint8_t c = 0; c < CHANNELS; ++c) {
409 for (uint8_t w = 0; w < NOTE_WORDS; ++w) {
410 for (uint8_t b = 0; b < NOTE_BITS && sounding_[o][c][w] != 0; ++b) {
411 if (sounding_[o][c][w] & (1U << b)) {
412 sounding_[o][c][w] &= ~(1U << b);
413 emit_note_off(o, c, static_cast<uint8_t>(w * NOTE_BITS + b));
414 }
415 }
416 }
417 }
418 }
419
420 /** All Notes Off on each channel an output uses. */
421 void send_all_notes_off(uint8_t o) {
422 for (uint8_t c = 0; c < CHANNELS; ++c) {
423 if (used_channels_[o] & (1u << c)) {
424 emit_cc(o, c, ALL_NOTES_OFF, 0);
425 }
426 }
427 }
428
429 /** Silence: a Note Off for each sounding note, then All Notes Off on each channel an output uses. */
430 void all_notes_off() {
431 for (uint8_t o = 0; o < Outputs; ++o) {
432 release_notes(o);
433 }
434 for (uint8_t o = 0; o < Outputs; ++o) {
435 if (!muted_[o]) {
436 send_all_notes_off(o);
437 }
438 }
439 }
440
441 /** Which channels each output uses, and each controller's first value. */
442 void scan() {
443 for (uint8_t o = 0; o < Outputs; ++o) {
444 used_channels_[o] = 0;
445 }
446 snapshot_count_ = 0;
447 for (uint8_t t = 0; t < track_count_; ++t) {
448 SmfTrack cursor = tracks_[t];
449 cursor.rewind();
450 while (const SmfEvent* ev = cursor.peek()) {
451 uint8_t output = 0;
452 uint8_t channel = 0;
453 if (ev->kind == SmfEvent::Kind::Channel && destination(t, ev->midi, output, channel)) {
454 used_channels_[output] |= static_cast<uint16_t>(1u << channel);
455 if (ev->midi.type == MessageType::ControlChange) {
456 remember(output, channel, ev->midi);
457 }
458 }
459 cursor.pop();
460 }
461 }
462 }
463
464 void remember(uint8_t output, uint8_t channel, const MidiEvent& e) {
465 for (uint8_t i = 0; i < snapshot_count_; ++i) {
466 const Controller& c = snapshot_[i];
467 if (c.output == output && c.channel == channel && c.controller == e.data1) {
468 return;
469 }
470 }
471 if (snapshot_count_ < MAX_SNAPSHOT) {
472 snapshot_[snapshot_count_++] = Controller{output, channel, e.data1, e.data2};
473 }
474 }
475
476 Sink sink_;
477 void* context_;
478
479 SmfTrack tracks_[MAX_TRACKS];
480 uint8_t track_output_[MAX_TRACKS] = {};
481 uint8_t channel_output_[CHANNELS] = {};
482 uint8_t output_channel_[Outputs] = {};
483 uint16_t used_channels_[Outputs] = {};
484 bool muted_[Outputs] = {};
485 uint32_t sounding_[Outputs][CHANNELS][NOTE_WORDS] = {}; /**< notes on, per output and channel as sent */
486 Controller snapshot_[MAX_SNAPSHOT] = {};
487 uint8_t snapshot_count_ = 0;
488
489 uint16_t format_ = 0;
490 uint8_t track_count_ = 0;
491 uint16_t ticks_per_quarter_ = 1;
492 uint32_t us_scale_ = 1; /**< tick_rate / gcd(tick_rate, 10^6): microseconds -> scaled time */
493 uint32_t tick_scale_ = 1; /**< 10^6 / gcd(tick_rate, 10^6): clock ticks -> scaled time */
494
495 bool loaded_ = false;
496 bool playing_ = false;
497 bool finished_ = false;
498 bool loop_ = false;
499
500 uint32_t tempo_us_ = DEFAULT_TEMPO_US;
501 uint64_t song_us_ = 0; /**< time of the last event reached, from the top */
502 uint32_t last_tick_ = 0;
503 uint64_t tick_remainder_ = 0; /**< the part of a microsecond carried between segments */
504 uint64_t now_scaled_ = 0; /**< clock ticks elapsed x tick_scale_ */
505 uint64_t pass_start_scaled_ = 0; /**< where this pass of the song began, same units */
506 uint32_t pass_ = 0; /**< 0 on the first pass after a Start; loop wraps count up */
507};
508
509} // namespace sbl::midi
510
511#endif // SBL_PROTOCOL_MIDI_SEQUENCER_HPP_
Plays a Standard MIDI File to a set of outputs.
Definition sequencer.hpp:83
void(*)(void *context, uint8_t output, const MidiEvent &event) Sink
Receives each event the sequencer emits: the context pointer, the output index and the event.
Definition sequencer.hpp:97
bool loaded() const
True if the last load() took a file.
static constexpr uint8_t ALL_NOTES_OFF
Definition sequencer.hpp:94
bool finished() const
True once play reached the end with loop off.
void set_channel_output(uint8_t channel, uint8_t output)
Format 0: which output a channel plays into.
static constexpr uint8_t CHANNELS
Definition sequencer.hpp:89
static constexpr uint8_t MAX_TRACKS
Definition sequencer.hpp:88
uint64_t position_us() const
Where the playhead is in the song, in microseconds from the top.
static constexpr uint8_t NO_OUTPUT
Definition sequencer.hpp:90
bool load(const SmfReader &smf)
Take a parsed file and apply the default map. Stops playback.
void set_output_channel(uint8_t output, uint8_t channel)
Send every event on an output on one channel.
static constexpr uint8_t KEEP_CHANNEL
Definition sequencer.hpp:91
static constexpr uint8_t OUTPUTS
Definition sequencer.hpp:87
void set_loop(bool on)
Loop on or off: at the end, play again from the top or stop.
void set_track_output(uint8_t track, uint8_t output)
Format 1: which output a track plays into.
bool playing() const
True while playing.
void set_output_mute(uint8_t output, bool on)
Mute an output: its sounding notes are released, and it sends nothing until unmuted.
static constexpr uint32_t DEFAULT_TEMPO_US
Definition sequencer.hpp:93
Sequencer(uint32_t tick_rate, Sink sink, void *context)
Construct a stopped sequencer with no file loaded.
bool output_muted(uint8_t output) const
True if the output is muted; false for an index out of range.
static constexpr uint8_t MAX_SNAPSHOT
Definition sequencer.hpp:92
bool looping() const
True if loop is on.
void advance(uint32_t elapsed_ticks)
Let elapsed_ticks of the clock pass: emit every event that falls due.
Checks a Standard MIDI File header in memory and finds its track chunks.
uint8_t track_count() const
Track chunks found.
static constexpr uint8_t MAX_TRACKS
uint16_t format() const
The file's format, 0 or 1.
SmfError error() const
The result of the last parse()
SmfTrack track(uint8_t index) const
A fresh cursor at the start of a track.
uint16_t ticks_per_quarter() const
The header's division: ticks per quarter note.
A cursor over one track chunk.
void pop()
Consume the event peek() returned.
void rewind()
Return to the track's first event and clear error()
const SmfEvent * peek()
The next event, or nullptr when the track has ended.
MIDI parser, encoder, SMF and sequencer.
Definition drain.hpp:31
MIDI message types.
Standard MIDI File reader.