forked from keijiro/smflite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSmfLite.cs
430 lines (355 loc) · 11.8 KB
/
SmfLite.cs
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//
// SmfLite.cs - A minimal toolkit for handling standard MIDI files (SMF) on Unity
//
// Copyright (C) 2013 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections.Generic;
namespace SmfLite
{
// An alias for internal use.
using DeltaEventPairList = System.Collections.Generic.List<SmfLite.MidiTrack.DeltaEventPair>;
//
// MIDI event
//
public class MidiEvent
{
#region Public members
public byte status;
public byte data1;
public byte data2;
public MidiEvent (byte status, byte data1, byte data2)
{
this.status = status;
this.data1 = data1;
this.data2 = data2;
}
public override string ToString ()
{
return "[" + status.ToString ("X") + "," + data1 + "," + data2 + "]";
}
#endregion
}
public class TempoEvent : MidiEvent
{
public readonly float Tempo;
public TempoEvent(byte[] bytes) : base(0xFF, 0x51, 0x03)
{
var micro = (bytes[0] << 16) + (bytes[1] << 8) + bytes[2];
Tempo = (60 * 1000 * 1000) / micro;
}
public override string ToString()
{
return "[Tempo " + Tempo + "]";
}
}
//
// MIDI track
//
// Stores only one track (usually a MIDI file contains one or more tracks).
//
public class MidiTrack
{
#region Internal data structure
// Data pair storing a delta-time value and an event.
public struct DeltaEventPair
{
public int delta;
public MidiEvent midiEvent;
public DeltaEventPair (int delta, MidiEvent midiEvent)
{
this.delta = delta;
this.midiEvent = midiEvent;
}
public override string ToString ()
{
return "(" + delta + ":" + midiEvent + ")";
}
}
#endregion
#region Public members
public MidiTrack ()
{
sequence = new List<DeltaEventPair> ();
}
// Returns an enumerator which enumerates the all delta-event pairs.
public List<DeltaEventPair>.Enumerator GetEnumerator ()
{
return sequence.GetEnumerator ();
}
public DeltaEventPair GetAtIndex (int index)
{
return sequence [index];
}
public override string ToString ()
{
var s = "";
foreach (var pair in sequence)
s += pair;
return s;
}
#endregion
#region Private and internal members
List<DeltaEventPair> sequence;
public void AddEvent (int delta, MidiEvent midiEvent)
{
sequence.Add (new DeltaEventPair (delta, midiEvent));
}
#endregion
}
//
// MIDI file container
//
public struct MidiFileContainer
{
#region Public members
// Division number == PPQN for this song.
public int division;
// Track list contained in this file.
public List<MidiTrack> tracks;
public MidiFileContainer (int division, List<MidiTrack> tracks)
{
this.division = division;
this.tracks = tracks;
}
public override string ToString ()
{
var temp = division.ToString () + ",";
foreach (var track in tracks) {
temp += track;
}
return temp;
}
#endregion
}
//
// Sequencer for MIDI tracks
//
// Works like an enumerator for MIDI events.
// Note that not only Advance() but also Start() can return MIDI events.
//
public class MidiTrackSequencer
{
#region Public members
public bool Playing {
get { return playing; }
}
// Constructor
// "ppqn" stands for Pulse Per Quater Note,
// which is usually provided with a MIDI header.
public MidiTrackSequencer (MidiTrack track, int ppqn, float bpm)
{
pulsePerSecond = bpm / 60.0f * ppqn;
enumerator = track.GetEnumerator ();
}
// Start the sequence.
// Returns a list of events at the beginning of the track.
public List<MidiEvent> Start (float startTime = 0.0f)
{
if (enumerator.MoveNext ()) {
pulseToNext = enumerator.Current.delta;
playing = true;
return Advance (startTime);
} else {
playing = false;
return null;
}
}
// Advance the song position.
// Returns a list of events between the current position and the next one.
public List<MidiEvent> Advance (float deltaTime)
{
if (!playing) {
return null;
}
pulseCounter += pulsePerSecond * deltaTime;
if (pulseCounter < pulseToNext) {
return null;
}
var messages = new List<MidiEvent> ();
while (pulseCounter >= pulseToNext) {
var pair = enumerator.Current;
messages.Add (pair.midiEvent);
if (!enumerator.MoveNext ()) {
playing = false;
break;
}
pulseCounter -= pulseToNext;
pulseToNext = enumerator.Current.delta;
}
return messages;
}
#endregion
#region Private members
DeltaEventPairList.Enumerator enumerator;
bool playing;
float pulsePerSecond;
float pulseToNext;
float pulseCounter;
#endregion
}
//
// MIDI file loader
//
// Loads an SMF and returns a file container object.
//
public static class MidiFileLoader
{
#region Public members
public static MidiFileContainer Load (byte[] data)
{
var tracks = new List<MidiTrack> ();
var reader = new MidiDataStreamReader (data);
// Chunk type.
if (new string (reader.ReadChars (4)) != "MThd") {
throw new System.FormatException ("Can't find header chunk.");
}
// Chunk length.
if (reader.ReadBEInt32 () != 6) {
throw new System.FormatException ("Length of header chunk must be 6.");
}
// Format (unused).
reader.Advance (2);
// Number of tracks.
var trackCount = reader.ReadBEInt16 ();
// Delta-time divisions.
var division = reader.ReadBEInt16 ();
if ((division & 0x8000) != 0) {
throw new System.FormatException ("SMPTE time code is not supported.");
}
// Read the tracks.
for (var trackIndex = 0; trackIndex < trackCount; trackIndex++) {
tracks.Add (ReadTrack (reader));
}
return new MidiFileContainer (division, tracks);
}
#endregion
#region Private members
static MidiTrack ReadTrack (MidiDataStreamReader reader)
{
var track = new MidiTrack ();
// Chunk type.
if (new string (reader.ReadChars (4)) != "MTrk") {
throw new System.FormatException ("Can't find track chunk.");
}
// Chunk length.
var chunkEnd = reader.ReadBEInt32 ();
chunkEnd += reader.Offset;
// Read delta-time and event pairs.
byte ev = 0;
while (reader.Offset < chunkEnd) {
// Delta time.
var delta = reader.ReadMultiByteValue ();
// Event type.
if ((reader.PeekByte () & 0x80) != 0) {
ev = reader.ReadByte ();
}
if (ev == 0xff)
{
// 0xff: Meta event (unused except tempo).
byte data1 = reader.ReadByte();
// tempo
if (data1 == 0x51)
{
reader.Advance(1);
track.AddEvent(delta, new TempoEvent(new[] { reader.ReadByte(), reader.ReadByte(), reader.ReadByte() }));
}
else
{
reader.Advance(reader.ReadMultiByteValue());
}
}
else if (ev == 0xf0)
{
// 0xf0: SysEx (unused).
while (reader.ReadByte() != 0xf7) {
}
} else {
// MIDI event
byte data1 = reader.ReadByte ();
byte data2 = ((ev & 0xe0) == 0xc0) ? (byte)0 : reader.ReadByte ();
track.AddEvent (delta, new MidiEvent (ev, data1, data2));
}
}
return track;
}
#endregion
}
//
// Binary data stream reader (for internal use)
//
class MidiDataStreamReader
{
byte[] data;
int offset;
public int Offset {
get { return offset; }
}
public MidiDataStreamReader (byte[] data)
{
this.data = data;
}
public void Advance (int length)
{
offset += length;
}
public byte PeekByte ()
{
return data [offset];
}
public byte ReadByte ()
{
return data [offset++];
}
public char[] ReadChars (int length)
{
var temp = new char[length];
for (var i = 0; i < length; i++) {
temp [i] = (char)ReadByte ();
}
return temp;
}
public int ReadBEInt32 ()
{
int b1 = ReadByte ();
int b2 = ReadByte ();
int b3 = ReadByte ();
int b4 = ReadByte ();
return b4 + (b3 << 8) + (b2 << 16) + (b1 << 24);
}
public int ReadBEInt16 ()
{
int b1 = ReadByte ();
int b2 = ReadByte ();
return b2 + (b1 << 8);
}
public int ReadMultiByteValue ()
{
int value = 0;
while (true) {
int b = ReadByte ();
value += b & 0x7f;
if (b < 0x80)
break;
value <<= 7;
}
return value;
}
}
}