-
Notifications
You must be signed in to change notification settings - Fork 1
/
PopMidi.js
463 lines (408 loc) · 13.7 KB
/
PopMidi.js
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
Pop.Midi = {};
function Array_GetKey(TheArray,Value)
{
const Match = Object.keys(TheArray).find(k => TheArray[k] === Value);
return Match;
}
// http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html#BMA1_3
// value => name
Pop.Midi.GetNoteName = function(MidiNoteValue)
{
if (!Number.isInteger(MidiNoteValue))
throw `Pop.Midi.GetNoteName(${MidiNoteValue}) is expecting an integer from 0-127`;
const Note = MidiNoteValue % 12;
const Octave = Math.floor(MidiNoteValue/12);
// this produces a filename + url friendly note name C~_1 D_1 F~3 B5
const NoteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
//const OctaveNames = ['_1',0,1,2,3,4,5,6,7,8,9];
const OctaveNames = ['-2','-1',0,1,2,3,4,5,6,7,8];
if ( Note < 0 || Note >= NoteNames.length || Octave < 0 || Octave >= OctaveNames.length )
throw `Midi note value ${MidiNoteValue} out of range (Note=${Note} Octave=${Octave})`;
return NoteNames[Note]+OctaveNames[Octave];
}
Pop.Midi.GetNoteNames = function()
{
const Names = [];
for ( let i=127; i>=0; i-- )
Names.push(Pop.Midi.GetNoteName(i));
return Names;
}
const MidiControllerMessages = {};
MidiControllerMessages.BankSelect = 0;
MidiControllerMessages.ModulationWheel = 1;
MidiControllerMessages.BreathControl = 2;
MidiControllerMessages.FootController = 4;
MidiControllerMessages.PortamentoTime = 5;
MidiControllerMessages.DataEntry = 6;
MidiControllerMessages.ChannelVolume = 7;
MidiControllerMessages.Balance = 8;
MidiControllerMessages.Pan = 10;
MidiControllerMessages.ExpressionController = 11;
MidiControllerMessages.EffectControl1 = 12;
MidiControllerMessages.EffectControl2 = 13;
MidiControllerMessages.GeneralPurposeController1 = 16;
MidiControllerMessages.GeneralPurposeController2 = 17;
MidiControllerMessages.GeneralPurposeController3 = 18;
MidiControllerMessages.GeneralPurposeController4 = 19;
MidiControllerMessages.BankSelect2 = 32;
MidiControllerMessages.ModulationWheel2 = 33;
MidiControllerMessages.BreathControl2 = 34;
MidiControllerMessages.FootController2 = 36;
MidiControllerMessages.PortamentoTime2 = 37;
MidiControllerMessages.DataEntry2 = 38;
MidiControllerMessages.ChannelVolume2 = 39;
MidiControllerMessages.Balance2 = 40;
MidiControllerMessages.Pan2 = 42;
MidiControllerMessages.EffectControl1_2 = 44;
MidiControllerMessages.EffectControl2_2 = 45;
MidiControllerMessages.GeneralPurposeController1_2 = 48;
MidiControllerMessages.GeneralPurposeController2_2 = 49;
MidiControllerMessages.GeneralPurposeController3_2 = 50;
MidiControllerMessages.GeneralPurposeController4_2 = 51;
MidiControllerMessages.SoundController1 = 70;
MidiControllerMessages.SoundController2 = 71;
MidiControllerMessages.SoundController3 = 72;
MidiControllerMessages.SoundController4 = 73;
MidiControllerMessages.SoundController5 = 74;
MidiControllerMessages.SoundController6 = 75;
MidiControllerMessages.SoundController7 = 76;
MidiControllerMessages.SoundController8 = 77;
MidiControllerMessages.SoundController9 = 78;
MidiControllerMessages.SoundController10 = 79;
MidiControllerMessages.DataEntryPlus1 = 96;
MidiControllerMessages.DataEntryMinus1 = 97;
MidiControllerMessages.AllSoundOff = 120;
MidiControllerMessages.ResetAllControllers = 121;
MidiControllerMessages.LocalControlOnOff = 122;
MidiControllerMessages.AllNotesOff = 123;
const MetaEvents = {};
MetaEvents.EndOfTrack = 0x2f;
// http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html#BMA1_
// https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message
Pop.Midi.MidiEvents = {};
Pop.Midi.MidiEvents.Zero = 0b0000;
Pop.Midi.MidiEvents.Six = 0b0110;
Pop.Midi.MidiEvents.Three = 0b0011;
Pop.Midi.MidiEvents.NoteOff = 0b1000;
Pop.Midi.MidiEvents.NoteOn = 0b1001;
Pop.Midi.MidiEvents.PolyKeyPressure = 0b1010;
Pop.Midi.MidiEvents.ControlChange = 0b1011;
Pop.Midi.MidiEvents.ProgramChange = 0b1100;
Pop.Midi.MidiEvents.ChannelPressure = 0b1101;
Pop.Midi.MidiEvents.PitchBendChange = 0b1110;
Pop.Midi.MidiEvents.SystemMessage = 0b1111;
Pop.Midi.MidiEvents.GetName = function(Event)
{
const Name = Array_GetKey(Pop.Midi.MidiEvents,Event);
return Name;
}
function SliceString(Array,Start,Length)
{
const String8 = Array.slice(Start,Start + Length);
const StringString = String.fromCharCode(...String8);
return StringString;
}
function Slice32(Array,Start)
{
const Size8 = Array.slice(Start,Start + 4);
const Size8a = new Uint8Array(Size8.reverse());
const Size32 = new Uint32Array(Size8a.buffer)[0];
return Size32;
}
function Slice16(Array,Start)
{
const Size8 = Array.slice(Start,Start + 2);
const Size8a = new Uint8Array(Size8.reverse());
const Size16 = new Uint16Array(Size8a.buffer)[0];
return Size16;
}
Pop.Midi.Track = class
{
constructor(Filename)
{
this.Filename = Filename;
this.Notes = [];
}
GetLastNote(Note,Channel)
{
for (let i = this.Notes.length - 1;i >= 0;i--)
{
const NoteMeta = this.Notes[i];
if (NoteMeta.Channel != Channel)
continue;
if (NoteMeta.Note != Note)
continue;
return NoteMeta;
}
throw `"${this.Filename}" | No last note (${Note},${Channel}) found`;
}
PushNoteOn(Channel,TimeMs,Note,Velocity)
{
if (Velocity == 0)
return this.PushNoteOff(Channel,TimeMs,Note,Velocity);
const Meta = {};
Meta.Note = Pop.Midi.GetNoteName(Note);
Meta.Channel = Channel;
Meta.StartTimeMs = TimeMs;
Meta.EndTimeMs = null;
Meta.Velocity = Velocity;
// Pop.Debug(`"${this.Filename}" | Note on: ${JSON.stringify(Meta)}`);
this.Notes.push(Meta);
}
PushNoteOff(Channel,TimeMs,Note,Velocity)
{
Note = Pop.Midi.GetNoteName(Note);
// Pop.Debug(`"${this.Filename}" | Note off @${TimeMs}: ${Note} vel=${Velocity}`);
// get the last matching note and end it
const Meta = this.GetLastNote(Note,Channel);
Meta.EndTimeMs = TimeMs;
Meta.EndVelocity = Velocity;
const DurationMs = Math.round(Math.round(Meta.EndTimeMs - Meta.StartTimeMs) * 100) / 100 / 1000;
// Pop.Debug(`"${this.Filename}" | Note off: ${JSON.stringify({ ...Meta, DurationMs })}`);
}
GetDuration()
{
function GetNoteEnd(Note)
{
return (Note.EndTimeMs !== null) ? Note.EndTimeMs : Note.StartTimeMs;
}
const NoteEnds = this.Notes.map(GetNoteEnd);
const MaxTime = Math.max(...NoteEnds);
return MaxTime;
}
}
Pop.Midi.Parse = function (FileContents, Filename)
{
function BpmToTempo(Bpm)
{
// microsecs per 120bpm
const Mult = 500000 / 120;
return Bpm * Mult;
}
const Midi = {};
Midi.TicksToMs = null; // func
Midi.Tracks = null;
Midi.Format = null;
Midi.DurationMs = 0;
Midi.TempoMicroSecs = BpmToTempo(120); // 120bpm = default tempo
function Parse_MTrk(Data)
{
// add to next undefined track
const NextTrack = Midi.Tracks.indexOf(null);
const NewTrack = new Pop.Midi.Track(Filename);
Midi.Tracks[NextTrack] = NewTrack;
function GetLastNote(Note,Channel)
{
return NewTrack.GetLastNote(Note,Channel);
}
let DataPosition = 0;
function Peek8(Count=1)
{
const Extra = Count - 1;
if (DataPosition + Extra == Data.length)
//throw `Peek8 is last`;
return null;
if (DataPosition + Extra > Data.length)
throw RangeError("Track Data OOB")
const Value = (Extra == 0) ? Data[DataPosition] : Data.slice(DataPosition,DataPosition + Count);
return Value;
}
function Pop8()
{
const Value = Peek8();
DataPosition++;
return Value;
}
function Pop14()
{
const Lsb7 = Pop8() & 127;
const Msb7 = Pop8() & 127;
const Fourteen = (Msb7<<7) | (Lsb<<0);
return Fourteen;
}
function PopVariableLengthValue()
{
let Value = 0;
let LoopCount = 1000;
while (LoopCount-->0)
{
const v8 = Pop8();
const Continuation = v8 & 0x80;
const v7 = v8 & (~0x80);
//const Continuation = v8 & 0x01;
//const v7 = v8 & (~0x01);
Value <<= 7;
Value |= v7;
if (!Continuation)
break;
}
return Value;
}
function PopData(Length)
{
const Data = Peek8(Length);
DataPosition += Length;
return Data;
}
function PushPolyKeyPressure(Channel,TimeMs,Note,Velocity)
{
Note = Pop.Midi.GetNoteName(Note);
Pop.Debug(`PolyKeyPressure @${TimeMs}: ${Note} x${Velocity}`);
}
function PushControlChange(Channel,TimeMs,Control,Value)
{
Pop.Debug(`Control/Channel mode @${TimeMs} ${Control}=${Value}`);
}
function PushProgramChange(Channel,TimeMs,ProgramNumber)
{
Pop.Debug(`Program change @${TimeMs} ${ProgramNumber}`);
}
function PushChannelPressure(Channel,TimeMs,PressureValue)
{
Pop.Debug(`Channel pressure @${TimeMs} ${PressureValue}`);
}
function PushPitchBendChange(Channel,TimeMs,Change)
{
Pop.Debug(`Pitch bend @${TimeMs} ${Change}`);
}
function ParseMidiEvent(MidiEventAndChannel,TimeMs)
{
const MidiEvent = (MidiEventAndChannel & 0b11110000) >> 4;
const Channel = MidiEventAndChannel & 0b00001111;
const MidiEventName = Pop.Midi.MidiEvents.GetName(MidiEvent) || MidiEvent.toString(16);
const Next8 = Peek8();
//Pop.Debug(`Midi event: ${MidiEventName} Channel[${Channel}] Next=${Next8}`);
// http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html#BMA1_
switch(MidiEvent)
{
case Pop.Midi.MidiEvents.NoteOn: NewTrack.PushNoteOn(Channel,TimeMs,Pop8(),Pop8()); break;
case Pop.Midi.MidiEvents.NoteOff: NewTrack.PushNoteOff(Channel,TimeMs,Pop8(),Pop8()); break;
case Pop.Midi.MidiEvents.PolyKeyPressure: PushPolyKeyPressure(Channel,TimeMs,Pop8(),Pop8()); break;
case Pop.Midi.MidiEvents.ControlChange: PushControlChange(Channel,TimeMs,Pop8(),Pop8()); break;
case Pop.Midi.MidiEvents.ProgramChange: PushProgramChange(Channel,TimeMs,Pop8()); break;
case Pop.Midi.MidiEvents.ChannelPressure: PushChannelPressure(Channel,TimeMs,Pop8()); break;
case Pop.Midi.MidiEvents.PitchBendChange: PushPitchBendChange(Channel,TimeMs,Pop14()); break;
default:
// Pop.Debug(`Midi event: ${MidiEventName} Channel[${Channel}] Next=${Next8}`);
throw `Undhandled Midi event ${MidiEventName}`;
}
}
function ParseSystemEvent(Event)
{
const Length = PopVariableLengthValue();
Pop.Debug(`System event (${Event.toString(16)}) x${Length}`);
const EventData = PopData(Length);
}
function ParseMetaEvent()
{
const Event2 = Pop8();
if (Event2 == MetaEvents.EndOfTrack)
{
const Length0 = Pop8();
//const Length0 = 0;
// Pop.Debug(`EndOfTrack length=${Length0}==0`);
return;
}
const Length = PopVariableLengthValue();
// Pop.Debug(`Meta event #${Event2.toString(16)} x${Length}`);
const EventData = PopData(Length);
}
function ParseEvent(Event,TimeMs)
{
const SystemEvent = 0xf0;
const EscapeEvent = 0xf7;
const MetaEvent = 0xff;
switch (Event)
{
case SystemEvent:
case EscapeEvent:
return ParseSystemEvent(Event);
case MetaEvent:
return ParseMetaEvent();
default:
return ParseMidiEvent(Event,TimeMs);
}
}
// parse the data
let TimeTicks = 0;
while (Peek8()!==null)
{
//Pop.Debug(`Next= ${Peek8()}`);
const TicksSinceLast = PopVariableLengthValue();
TimeTicks += TicksSinceLast;
const TimeMs = Midi.TicksToMs(TimeTicks);
const Event = Pop8();
// Pop.Debug(`Event=${Event} Time=${TimeMs}(+${TicksSinceLast} ticks) DataPos ${DataPosition}/${Data.length}`);
ParseEvent(Event,TimeMs);
}
}
function Parse_Mthd(Data)
{
Midi.Format = Slice16(Data,0);
const TrackCount = Slice16(Data,2);
const TimeFormat16 = Slice16(Data,4);
Midi.Tracks = Array(TrackCount).fill(null);
const TimeFormatSmpte = (TimeFormat16>>15) != 0;
if ( !TimeFormatSmpte )
{
Midi.TicksToMs = function(Ticks)
{
const Tempo = Midi.TempoMicroSecs;
const TicksPerQuarter = TimeFormat16;
const MicroSecsPerQuarter = Tempo;
const MicroSecsPerTick = MicroSecsPerQuarter / TicksPerQuarter;
//const SecondsPerTick = MicroSecsPerTick / 1.000.000;
const MilliSecondsPerTick = MicroSecsPerTick / 1000;
const Ms = Ticks * MilliSecondsPerTick;
return Ms;
}
}
else
{
Midi.TicksToMs = function(Ticks)
{
const NegativeSmpte = (TimeFormat16 >> 7) & (127); // bits 8-14
const TicksPerFrame = TimeFormat16 & 127; // bits 0-7
throw `Todo: calculate Smpte time conversion ${TimeFormatSmpte} ${TimeFormat16} = ${NegativeSmpte} ${TicksPerFrame}`;
// negative SMPTE format ticks per frame
return Ticks;
}
}
// Pop.Debug(`Midi: ${JSON.stringify(Midi)}`);
}
function EnumAtom(Fourcc,Data)
{
// Pop.Debug(`Atom ${Fourcc} x${Data.length}; ${Data}`);
switch (Fourcc)
{
case 'MThd': return Parse_Mthd(Data);
case 'MTrk': return Parse_MTrk(Data);
}
throw `Unhandled Midi Atom ${Fourcc} x${Data.length}`;
}
function ParseAtom(Offset)
{
const Atom = {};
Atom.Fourcc = SliceString(FileContents,Offset + 0,4);
Atom.DataSize = Slice32(FileContents,Offset + 4);
Atom.DataOffset = 4 + 4;
Atom.AtomSize = Atom.DataOffset + Atom.DataSize;
return Atom;
}
for (let i = 0;i < FileContents.length;i += 0)
{
const Atom = ParseAtom(i);
const DataStart = i + Atom.DataOffset;
const DataEnd = DataStart + Atom.DataSize;
if (DataEnd > FileContents.length)
throw `Atom data ${DataStart}...${DataEnd} out of range (${FileContents.length})`;
const AtomData = FileContents.slice(DataStart,DataEnd);
EnumAtom( Atom.Fourcc, AtomData );
i += Atom.AtomSize;
}
// update duration
const TrackDurations = Midi.Tracks.map(t => t.GetDuration());
Midi.DurationMs = Math.max(...TrackDurations);
Midi.GetDurationMs = function () { return Math.floor(Midi.DurationMs); };
return Midi;
}