-
Notifications
You must be signed in to change notification settings - Fork 7
/
midi.oc
271 lines (235 loc) · 8.9 KB
/
midi.oc
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
import std::vector::Vector
import std::buffer::{ Buffer, BytesReader }
import std::fs
import std::logging::{ log }
import std::math
struct Note {
start: f64
duration: f64
key: u8
velocity: u8
}
struct Track {
name: str
notes: &Vector<Note>
}
def Track::free(&this) {
.name.free()
.notes.free()
}
struct MidiFile {
tracks: &Vector<Track>
min_note_time: f64
max_note_time: f64
}
def MidiFile::free(&this) {
for track in .tracks.iter() {
track.free()
}
.tracks.free()
}
struct Parser {
ticks: u64
time: f64
division: u64
tempo: u32 // microseconds per beat
min_note_time: f64
max_note_time: f64
}
def Parser::ticks_to_seconds(&this, ticks: u64): f64 {
return (ticks as f64 / .division as f64) * (.tempo as f64 / 1000000.0)
}
struct KeyState {
time: f64
velocity: u8
}
def Parser::parse_track(&this, io: &BytesReader): Track {
// Reset the time and ticks for each track
.ticks = 0
.time = 0.0
.tempo = 500000
let header = io.read_bytes_sv(4)
assert header == "MTrk", "Invalid track header"
let length = io.read_u32()
log(Debug, f"(MIDI) Track length: {length}")
let data = io.read_bytes_sv(length)
let notes = Vector<Note>::new()
let name = f"Unnamed Track" // Allocate
let prev_status = 0u8
let tio = data.reader()
let keystate: [KeyState; 128]
while not tio.is_empty() {
let delta_ticks = read_var_length(&tio) as u64
.ticks += delta_ticks
let delta_time = .ticks_to_seconds(delta_ticks as u64)
.time += delta_time
let status = tio.read_u8()
if status & 0x80 == 0 {
// Running status
status = prev_status
tio.index--
} else {
prev_status = status
}
match status & 0xF0 {
0xc0 => { // Program change
let channel = status & 0x0F
let program = tio.read_u8()
log(Debug, f"(MIDI) Program change: channel={channel}, program={program}")
}
0xb0 => { // Control change
let channel = status & 0x0F
let control = tio.read_u8()
let value = tio.read_u8()
log(Debug, f"(MIDI) Control change: channel={channel}, control={control}, value={value}")
}
0x90 => { // Note on
let channel = status & 0x0F
let note = tio.read_u8()
let velocity = tio.read_u8()
log(Debug, f"(MIDI) Note on: channel={channel}, note={note}, velocity={velocity}, time={.time}, ticks={.ticks}")
// Special case for note-off
if velocity == 0 {
let ks = keystate[note]
let duration = .time - ks.time
notes.push(Note(ks.time, duration, note, ks.velocity))
.max_note_time = .max_note_time.max(.time)
// Normal note on event
} else {
keystate[note] = KeyState(.time, velocity)
.min_note_time = .min_note_time.min(.time)
}
}
0x80 => { // Note off
let channel = status & 0x0F
let note = tio.read_u8()
let velocity = tio.read_u8()
log(Debug, f"(MIDI) Note off: channel={channel}, note={note}, velocity={velocity}")
let ks = keystate[note]
let duration = .time - ks.time
notes.push(Note(ks.time, duration, note, ks.velocity))
.max_note_time = .max_note_time.max(.time)
}
0xd0 => { // Channel pressure
let channel = status & 0x0F
let pressure = tio.read_u8()
log(Debug, f"(MIDI) Channel pressure: channel={channel}, pressure={pressure}")
}
0xe0 => { // Pitch bend
let channel = status & 0x0F
let lsb = tio.read_u8()
let msb = tio.read_u8()
let value = (msb as u16 << 7) | lsb as u16
log(Debug, f"(MIDI) Pitch bend: channel={channel}, value={value}")
}
else => match status {
0xff => { // Meta event
let meta_type = tio.read_u8()
log(Debug, f"(MIDI) Meta event, type: {meta_type:02x}")
match meta_type {
0x00 => { tio.read_bytes_sv(2) } // Sequence number
0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 |
0x09 | 0x0a | 0x0b | 0x0c | 0x0d | 0x0e | 0x0f => { // Text event
let length = read_var_length(&tio)
let text = tio.read_bytes_sv(length)
log(Debug, f"(MIDI) Text: {text}")
if meta_type == 0x03 {
name.free()
name = text.copy_data_to_cstr()
}
}
0x20 => { tio.read_bytes_sv(2) } // Channel prefix
0x21 => { tio.read_bytes_sv(2) } // Port
0x2f => { tio.read_bytes_sv(1) } // End of track
0x7f => { // Sequencer specific
let length = read_var_length(&tio)
let data = tio.read_bytes_sv(length)
log(Debug, f"(MIDI) Sequencer specific: {data}")
}
0x51 => { // Tempo
assert tio.read_u8() == 0x03
let tempo = tio.read_u16() as u32 << 8 | tio.read_u8() as u32 // 24-bit tempo
log(Debug, f"(MIDI) Tempo: {tempo}")
.tempo = tempo
}
0x54 => { // SMPTE offset
assert tio.read_u8() == 0x05
let hr = tio.read_u8()
let mn = tio.read_u8()
let se = tio.read_u8()
let fr = tio.read_u8()
let ff = tio.read_u8()
log(Debug, f"(MIDI) SMPTE offset: {hr}:{mn}:{se}:{fr}:{ff}")
}
0x58 => { // Time signature
assert tio.read_u8() == 0x04
let num = tio.read_u8()
let den = tio.read_u8()
let clocks = tio.read_u8()
let notes = tio.read_u8()
log(Debug, f"(MIDI) Time signature: {num}/{den as u32}, clocks={clocks}, notes={notes}")
}
0x59 => { // Key signature
assert tio.read_u8() == 0x02
let sf = tio.read_i8()
let mi = tio.read_u8()
log(Debug, f"(MIDI) Key signature: sf={sf}, mi={mi}")
}
else => {
log(Error, f"(MIDI) Unknown meta type: {meta_type:02x}")
std::exit(1)
}
}
}
else => {
log(Error, f"(MIDI) Unknown Status: {status:02x}")
std::exit(1)
}
}
}
}
return Track(name, notes)
}
def Parser::parse_midi(&this, io: &BytesReader): MidiFile {
let header = io.read_bytes_sv(4)
assert header == "MThd", "Invalid header"
let length = io.read_u32()
let format = io.read_u16()
let num_tracks = io.read_u16()
log(Debug, f"(MIDI) Number of tracks: {num_tracks}, length: {length}, format: {format}")
let division = io.read_u16()
assert division & 0x8000 == 0, "SMPTE time division not supported"
.division = division as u64
log(Debug, f"(MIDI) Division: PPQ")
log(Debug, f"(MIDI) Division: (14-0): {division}")
let tracks = Vector<Track>::new()
while not io.is_empty() {
let track = .parse_track(io)
if track.notes.size == 0 {
track.name.free()
track.notes.free()
} else {
tracks.push(track)
}
}
return MidiFile(tracks, .min_note_time, .max_note_time)
}
def read_var_length(io: &BytesReader): u32 {
let res = 0
while true {
let byte = io.read_u8()
res = (res << 7) | (byte & 0x7F) as u32
if byte & 0x80 == 0 {
break
}
}
return res
}
def parse_file(filename: str): MidiFile {
let data = fs::read_file(filename)
let io = data.reader()
let parser: Parser
let midi = parser.parse_midi(&io)
data.free()
return midi
}