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
smf_reader.hpp
Go to the documentation of this file.
1/**
2 * @file smf_reader.hpp
3 * @brief Standard MIDI File reader
4 */
5
6#ifndef SBL_PROTOCOL_MIDI_SMF_READER_HPP_
7#define SBL_PROTOCOL_MIDI_SMF_READER_HPP_
8
9#include <cstddef>
10#include <cstdint>
11
13
14namespace sbl::midi {
15
16/** @brief Result of SmfReader::parse() */
17enum class SmfError : uint8_t {
18 None, /**< the header and every track were found */
19 NotSmf, /**< no MThd header chunk at the start */
20 BadHeader, /**< header too short, zero division, or format 0 with more than one track */
21 UnsupportedFormat, /**< format 2 */
22 SmpteDivision, /**< division in SMPTE frames rather than ticks per quarter note */
23 TooManyTracks, /**< more tracks than SmfReader::MAX_TRACKS */
24 Truncated, /**< a chunk runs past the end of the data, or tracks are missing */
25};
26
27/** One event from a track, with its absolute tick. */
28struct SmfEvent {
29 /** @brief Which of the fields below the event carries */
30 enum class Kind : uint8_t { Channel, Tempo, TimeSignature, TrackName, EndOfTrack };
31
32 Kind kind = Kind::EndOfTrack; /**< what the event is */
33 uint32_t tick = 0; /**< ticks from the start of the track */
34 MidiEvent midi{}; /**< Channel */
35 uint32_t tempo_us = 0; /**< Tempo: microseconds per quarter note */
36 uint8_t numerator = 0; /**< TimeSignature */
37 uint8_t denominator_power = 0; /**< TimeSignature: the denominator is 2^power */
38 const uint8_t* text = nullptr; /**< TrackName: points into the file, not terminated */
39 uint32_t text_length = 0; /**< TrackName: length of text in bytes */
40};
41
42/**
43 * @brief A cursor over one track chunk
44 *
45 * peek() decodes the next event without consuming it; pop() consumes it. A
46 * malformed event ends the track and sets error(). The file's bytes must
47 * outlive the cursor.
48 */
49class SmfTrack {
50public:
51 /** @brief An empty cursor: peek() returns nullptr */
52 SmfTrack() = default;
53
54 /**
55 * @brief A cursor at the start of a track chunk's body
56 * @param data First byte after the MTrk chunk header
57 * @param length Body length in bytes
58 */
59 SmfTrack(const uint8_t* data, uint32_t length) : data_(data), length_(length) { rewind(); }
60
61 /** @brief Return to the track's first event and clear error() */
62 void rewind() {
63 pos_ = 0;
64 tick_ = 0;
65 running_status_ = 0;
66 has_pending_ = false;
67 error_ = false;
68 done_ = (data_ == nullptr);
69 }
70
71 /** @brief The next event, or nullptr when the track has ended */
72 const SmfEvent* peek() {
73 if (!has_pending_ && !done_) {
74 has_pending_ = decode(pending_);
75 }
76 return has_pending_ ? &pending_ : nullptr;
77 }
78
79 /** @brief Consume the event peek() returned */
80 void pop() { has_pending_ = false; }
81
82 /** @brief True once the track has ended and its last event was popped */
83 bool done() const { return done_ && !has_pending_; }
84 /** @brief True if a malformed event ended the track */
85 bool error() const { return error_; }
86
87private:
88 static constexpr uint8_t STATUS_BIT = 0x80;
89 static constexpr uint8_t META = 0xFF;
90 static constexpr uint8_t SYSEX = 0xF0;
91 static constexpr uint8_t SYSEX_ESCAPE = 0xF7;
92 static constexpr uint8_t SYSTEM_FIRST = 0xF0;
93 static constexpr uint8_t META_TRACK_NAME = 0x03;
94 static constexpr uint8_t META_END_OF_TRACK = 0x2F;
95 static constexpr uint8_t META_TEMPO = 0x51;
96 static constexpr uint8_t META_TIME_SIGNATURE = 0x58;
97 static constexpr uint32_t TEMPO_LENGTH = 3;
98 static constexpr uint32_t TIME_SIGNATURE_LENGTH = 2; /**< nn dd; the clock bytes are not used */
99 static constexpr uint8_t VLQ_MAX_BYTES = 4;
100 static constexpr uint8_t VLQ_MORE = 0x80;
101 static constexpr uint8_t VLQ_BITS = 0x7F;
102 static constexpr uint8_t VLQ_SHIFT = 7;
103 static constexpr uint8_t STATUS_KIND_MASK = 0xF0;
104 static constexpr uint8_t CHANNEL_MASK = 0x0F;
105 static constexpr uint8_t PROGRAM_CHANGE = 0xC0;
106 static constexpr uint8_t CHANNEL_PRESSURE = 0xD0;
107
108 bool fail() {
109 error_ = true;
110 done_ = true;
111 return false;
112 }
113
114 bool read_vlq(uint32_t& out) {
115 out = 0;
116 for (uint8_t i = 0; i < VLQ_MAX_BYTES; ++i) {
117 if (pos_ >= length_) {
118 return false;
119 }
120 const uint8_t b = data_[pos_++];
121 out = (out << VLQ_SHIFT) | (b & VLQ_BITS);
122 if ((b & VLQ_MORE) == 0) {
123 return true;
124 }
125 }
126 return false; // longer than four bytes: not a valid delta or length
127 }
128
129 /** Decode the next event a player cares about; skip the rest. */
130 bool decode(SmfEvent& ev) {
131 while (pos_ < length_) {
132 uint32_t delta = 0;
133 if (!read_vlq(delta)) {
134 return fail();
135 }
136 tick_ += delta;
137 if (pos_ >= length_) {
138 return fail();
139 }
140 const uint8_t lead = data_[pos_];
141
142 if (lead == META) {
143 if (pos_ + 2 > length_) {
144 return fail();
145 }
146 const uint8_t type = data_[pos_ + 1];
147 pos_ += 2;
148 uint32_t len = 0;
149 if (!read_vlq(len) || pos_ + len > length_) {
150 return fail();
151 }
152 const uint32_t body = pos_;
153 pos_ += len;
154 running_status_ = 0; // meta events cancel running status
155
156 ev = SmfEvent{};
157 ev.tick = tick_;
158 switch (type) {
159 case META_END_OF_TRACK:
160 ev.kind = SmfEvent::Kind::EndOfTrack;
161 done_ = true;
162 return true;
163 case META_TEMPO:
164 if (len < TEMPO_LENGTH) {
165 return fail();
166 }
167 ev.kind = SmfEvent::Kind::Tempo;
168 ev.tempo_us = (static_cast<uint32_t>(data_[body]) << 16) |
169 (static_cast<uint32_t>(data_[body + 1]) << 8) | data_[body + 2];
170 return true;
171 case META_TIME_SIGNATURE:
172 if (len < TIME_SIGNATURE_LENGTH) {
173 return fail();
174 }
175 ev.kind = SmfEvent::Kind::TimeSignature;
176 ev.numerator = data_[body];
177 ev.denominator_power = data_[body + 1];
178 return true;
179 case META_TRACK_NAME:
180 ev.kind = SmfEvent::Kind::TrackName;
181 ev.text = data_ + body;
182 ev.text_length = len;
183 return true;
184 default: continue; // a meta event a player doesn't need
185 }
186 }
187
188 if (lead == SYSEX || lead == SYSEX_ESCAPE) {
189 ++pos_;
190 uint32_t len = 0;
191 if (!read_vlq(len) || pos_ + len > length_) {
192 return fail();
193 }
194 pos_ += len;
195 running_status_ = 0; // SysEx cancels running status too
196 continue;
197 }
198
199 uint8_t status = running_status_;
200 if (lead & STATUS_BIT) {
201 if (lead >= SYSTEM_FIRST) {
202 return fail(); // no other system messages in a track
203 }
204 status = lead;
205 running_status_ = lead;
206 ++pos_;
207 } else if (status == 0) {
208 return fail(); // data with no status in effect
209 }
210
211 const uint8_t kind = status & STATUS_KIND_MASK;
212 const uint8_t data_bytes = (kind == PROGRAM_CHANGE || kind == CHANNEL_PRESSURE) ? 1 : 2;
213 if (pos_ + data_bytes > length_) {
214 return fail();
215 }
216
217 ev = SmfEvent{};
218 ev.kind = SmfEvent::Kind::Channel;
219 ev.tick = tick_;
220 ev.midi.type = static_cast<MessageType>(kind);
221 ev.midi.channel = status & CHANNEL_MASK;
222 ev.midi.data1 = data_[pos_];
223 ev.midi.data2 = data_bytes == 2 ? data_[pos_ + 1] : 0;
224 pos_ += data_bytes;
225 return true;
226 }
227 done_ = true; // ran out without End of Track: accept the end
228 return false;
229 }
230
231 const uint8_t* data_ = nullptr;
232 uint32_t length_ = 0;
233 uint32_t pos_ = 0;
234 uint32_t tick_ = 0;
235 uint8_t running_status_ = 0;
236 bool has_pending_ = false;
237 bool done_ = true;
238 bool error_ = false;
239 SmfEvent pending_{};
240};
241
242/**
243 * @brief Checks a Standard MIDI File header in memory and finds its track chunks
244 *
245 * Reads a Standard MIDI File already in memory: no filesystem, no allocation,
246 * nothing copied. The reader checks the header and finds the track chunks;
247 * an SmfTrack walks one track's events in order, one at a time.
248 *
249 * What it understands (Standard MIDI Files 1.0):
250 * - formats 0 and 1 (format 2 is refused)
251 * - ticks-per-quarter-note division (SMPTE division is refused)
252 * - variable-length delta times
253 * - running status, which carries across delta times and is cancelled by
254 * SysEx and meta events
255 * - the meta events a player needs: Set Tempo, Time Signature, Track Name
256 * and End of Track; other meta events and SysEx are skipped
257 * - chunks that are not MTrk, which are skipped
258 *
259 * Usage:
260 * @code
261 * sbl::midi::SmfReader smf;
262 * if (smf.parse(bytes, size) != sbl::midi::SmfError::None) { ... }
263 * sbl::midi::SmfTrack track = smf.track(1);
264 * while (const sbl::midi::SmfEvent* ev = track.peek()) { ...; track.pop(); }
265 * @endcode
266 */
268public:
269 static constexpr uint8_t MAX_TRACKS = 16; /**< track chunks the reader records */
270
271 /**
272 * @brief Check the header and find the tracks
273 * @param data File bytes; they must outlive the reader and its tracks
274 * @param size File length in bytes
275 * @return SmfError::None, or why the file was refused
276 */
277 SmfError parse(const uint8_t* data, size_t size) {
278 *this = SmfReader{};
279 if (data == nullptr || size < CHUNK_HEADER || !id_is(data, "MThd")) {
280 return fail(SmfError::NotSmf);
281 }
282 const uint32_t header_length = be32(data + ID_LENGTH);
283 if (header_length < HEADER_BODY || size < CHUNK_HEADER + header_length) {
284 return fail(SmfError::BadHeader);
285 }
286
287 const uint16_t format = be16(data + CHUNK_HEADER);
288 const uint16_t tracks = be16(data + CHUNK_HEADER + 2);
289 const uint16_t division = be16(data + CHUNK_HEADER + 4);
290 if (division & SMPTE_DIVISION_BIT) {
291 return fail(SmfError::SmpteDivision);
292 }
293 if (division == 0) {
294 return fail(SmfError::BadHeader);
295 }
296 if (format > 1) {
297 return fail(SmfError::UnsupportedFormat);
298 }
299 if (format == 0 && tracks != 1) {
300 return fail(SmfError::BadHeader);
301 }
302 if (tracks > MAX_TRACKS) {
303 return fail(SmfError::TooManyTracks);
304 }
305
306 size_t pos = CHUNK_HEADER + header_length;
307 uint8_t found = 0;
308 while (found < tracks) {
309 if (pos + CHUNK_HEADER > size) {
310 return fail(SmfError::Truncated);
311 }
312 const uint32_t length = be32(data + pos + ID_LENGTH);
313 if (pos + CHUNK_HEADER + length > size) {
314 return fail(SmfError::Truncated);
315 }
316 if (id_is(data + pos, "MTrk")) {
317 track_data_[found] = data + pos + CHUNK_HEADER;
318 track_length_[found] = length;
319 ++found;
320 } // any other chunk: skipped, as the spec asks
321 pos += CHUNK_HEADER + length;
322 }
323
324 format_ = format;
325 track_count_ = found;
326 ticks_per_quarter_ = division;
327 return SmfError::None;
328 }
329
330 /** @brief The result of the last parse() */
331 SmfError error() const { return error_; }
332 /** @brief The file's format, 0 or 1 */
333 uint16_t format() const { return format_; }
334 /** @brief Track chunks found */
335 uint8_t track_count() const { return track_count_; }
336 /** @brief The header's division: ticks per quarter note */
337 uint16_t ticks_per_quarter() const { return ticks_per_quarter_; }
338
339 /**
340 * @brief A fresh cursor at the start of a track
341 * @param index Track number, 0 to track_count() - 1
342 * @return The cursor, or an empty one if index is out of range
343 */
344 SmfTrack track(uint8_t index) const {
345 if (index >= track_count_) {
346 return SmfTrack{};
347 }
348 return SmfTrack{track_data_[index], track_length_[index]};
349 }
350
351private:
352 static constexpr size_t ID_LENGTH = 4;
353 static constexpr size_t CHUNK_HEADER = 8; /**< id + 32-bit length */
354 static constexpr uint32_t HEADER_BODY = 6; /**< format, ntrks, division */
355 static constexpr uint16_t SMPTE_DIVISION_BIT = 0x8000;
356
357 static bool id_is(const uint8_t* p, const char* id) {
358 for (size_t i = 0; i < ID_LENGTH; ++i) {
359 if (p[i] != static_cast<uint8_t>(id[i])) {
360 return false;
361 }
362 }
363 return true;
364 }
365 static uint16_t be16(const uint8_t* p) { return static_cast<uint16_t>((p[0] << 8) | p[1]); }
366 static uint32_t be32(const uint8_t* p) {
367 return (static_cast<uint32_t>(p[0]) << 24) | (static_cast<uint32_t>(p[1]) << 16) |
368 (static_cast<uint32_t>(p[2]) << 8) | p[3];
369 }
370
371 SmfError fail(SmfError e) {
372 error_ = e;
373 return e;
374 }
375
376 const uint8_t* track_data_[MAX_TRACKS] = {};
377 uint32_t track_length_[MAX_TRACKS] = {};
378 SmfError error_ = SmfError::None;
379 uint16_t format_ = 0;
380 uint8_t track_count_ = 0;
381 uint16_t ticks_per_quarter_ = 0;
382};
383
384} // namespace sbl::midi
385
386#endif // SBL_PROTOCOL_MIDI_SMF_READER_HPP_
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
SmfError parse(const uint8_t *data, size_t size)
Check the header and find the 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.
SmfTrack()=default
An empty cursor: peek() returns nullptr.
bool error() const
True if a malformed event ended the track.
void rewind()
Return to the track's first event and clear error()
SmfTrack(const uint8_t *data, uint32_t length)
A cursor at the start of a track chunk's body.
bool done() const
True once the track has ended and its last event was popped.
const SmfEvent * peek()
The next event, or nullptr when the track has ended.
MIDI parser, encoder, SMF and sequencer.
Definition drain.hpp:31
SmfError
Result of SmfReader::parse()
MIDI message types.
const uint8_t * text
Kind
Which of the fields below the event carries.