-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmp3+midi-player.html
3206 lines (2970 loc) · 100 KB
/
mp3+midi-player.html
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html manifest="player.manifest">
<head>
<title>MP3 Player</title>
<link rel="icon" type="image/png" href="16.png">
</script>
<!-- MIDIFile: Repos folder must be in the same parent folder than the MIDIPlayer one -->
<script id="../../MIDIFile/dist/MIDIFile.js" type="text/javascript">
// MIDIEvents : Read and edit events from various sources (ArrayBuffer, Stream)
function MIDIEvents() {
throw new Error('MIDIEvents function not intended to be run.');
}
// Static constants
// Event types
MIDIEvents.EVENT_META = 0xFF;
MIDIEvents.EVENT_SYSEX = 0xF0;
MIDIEvents.EVENT_DIVSYSEX = 0xF7;
MIDIEvents.EVENT_MIDI = 0x8;
// Meta event types
MIDIEvents.EVENT_META_SEQUENCE_NUMBER = 0x00;
MIDIEvents.EVENT_META_TEXT = 0x01;
MIDIEvents.EVENT_META_COPYRIGHT_NOTICE = 0x02;
MIDIEvents.EVENT_META_TRACK_NAME = 0x03;
MIDIEvents.EVENT_META_INSTRUMENT_NAME = 0x04;
MIDIEvents.EVENT_META_LYRICS = 0x05;
MIDIEvents.EVENT_META_MARKER = 0x06;
MIDIEvents.EVENT_META_CUE_POINT = 0x07;
MIDIEvents.EVENT_META_MIDI_CHANNEL_PREFIX = 0x20;
MIDIEvents.EVENT_META_END_OF_TRACK = 0x2F;
MIDIEvents.EVENT_META_SET_TEMPO = 0x51;
MIDIEvents.EVENT_META_SMTPE_OFFSET = 0x54;
MIDIEvents.EVENT_META_TIME_SIGNATURE = 0x58;
MIDIEvents.EVENT_META_KEY_SIGNATURE = 0x59;
MIDIEvents.EVENT_META_SEQUENCER_SPECIFIC = 0x7F;
// MIDI event types
MIDIEvents.EVENT_MIDI_NOTE_OFF = 0x8;
MIDIEvents.EVENT_MIDI_NOTE_ON = 0x9;
MIDIEvents.EVENT_MIDI_NOTE_AFTERTOUCH = 0xA;
MIDIEvents.EVENT_MIDI_CONTROLLER = 0xB;
MIDIEvents.EVENT_MIDI_PROGRAM_CHANGE = 0xC;
MIDIEvents.EVENT_MIDI_CHANNEL_AFTERTOUCH = 0xD;
MIDIEvents.EVENT_MIDI_PITCH_BEND = 0xE;
// MIDI event sizes
MIDIEvents.MIDI_1PARAM_EVENTS = [
MIDIEvents.EVENT_MIDI_PROGRAM_CHANGE,
MIDIEvents.EVENT_MIDI_CHANNEL_AFTERTOUCH,
];
MIDIEvents.MIDI_2PARAMS_EVENTS = [
MIDIEvents.EVENT_MIDI_NOTE_OFF,
MIDIEvents.EVENT_MIDI_NOTE_ON,
MIDIEvents.EVENT_MIDI_NOTE_AFTERTOUCH,
MIDIEvents.EVENT_MIDI_CONTROLLER,
MIDIEvents.EVENT_MIDI_PITCH_BEND,
];
// Create an event stream parser
MIDIEvents.createParser = function midiEventsCreateParser(stream, startAt, strictMode) {
// Private vars
// Common vars
var eventTypeByte;
var event;
// MIDI events vars
var MIDIEventType;
var MIDIEventChannel;
var MIDIEventParam1;
// Wrap DataView into a data stream
if(stream instanceof DataView) {
stream = {
position: startAt || 0,
buffer: stream,
readUint8: function() {
return this.buffer.getUint8(this.position++);
},
readUint16: function() {
var v = this.buffer.getUint16(this.position);
this.position = this.position + 2;
return v;
},
readUint32: function() {
var v = this.buffer.getUint16(this.position);
this.position = this.position + 2;
return v;
},
readVarInt: function() {
var v = 0;
var i = 0;
var b;
while(4 > i++) {
b = this.readUint8();
if (b & 0x80) {
v += (b & 0x7f);
v <<= 7;
} else {
return v + b;
}
}
throw new Error('0x' + this.position.toString(16) + ':' +
' Variable integer length cannot exceed 4 bytes');
},
readBytes: function(length) {
var bytes = [];
for(; 0 < length; length--) {
bytes.push(this.readUint8());
}
return bytes;
},
pos: function() {
return '0x' + (this.buffer.byteOffset + this.position).toString(16);
},
end: function() {
return this.position === this.buffer.byteLength;
},
};
startAt = 0;
}
// Consume stream till not at start index
if(0 < startAt) {
while(startAt--) {
stream.readUint8();
}
}
// creating the parser object
return {
// Read the next event
next: function() {
// Check available datas
if(stream.end()) {
return null;
}
// Creating the event
event = {
// Memoize the event index
index: stream.pos(),
// Read the delta time
delta: stream.readVarInt(),
};
// Read the eventTypeByte
eventTypeByte = stream.readUint8();
if(0xF0 === (eventTypeByte & 0xF0)) {
// Meta events
if(eventTypeByte === MIDIEvents.EVENT_META) {
event.type = MIDIEvents.EVENT_META;
event.subtype = stream.readUint8();
event.length = stream.readVarInt();
switch(event.subtype) {
case MIDIEvents.EVENT_META_SEQUENCE_NUMBER:
if(strictMode && 2 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.msb = stream.readUint8();
event.lsb = stream.readUint8();
return event;
case MIDIEvents.EVENT_META_TEXT:
case MIDIEvents.EVENT_META_COPYRIGHT_NOTICE:
case MIDIEvents.EVENT_META_TRACK_NAME:
case MIDIEvents.EVENT_META_INSTRUMENT_NAME:
case MIDIEvents.EVENT_META_LYRICS:
case MIDIEvents.EVENT_META_MARKER:
case MIDIEvents.EVENT_META_CUE_POINT:
event.data = stream.readBytes(event.length);
return event;
case MIDIEvents.EVENT_META_MIDI_CHANNEL_PREFIX:
if(strictMode && 1 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.prefix = stream.readUint8();
return event;
case MIDIEvents.EVENT_META_END_OF_TRACK:
if(strictMode && 0 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
return event;
case MIDIEvents.EVENT_META_SET_TEMPO:
if(strictMode && 3 !== event.length) {
throw new Error(stream.pos() + ' Tempo meta event length must be 3.');
}
event.tempo = (
(stream.readUint8() << 16) +
(stream.readUint8() << 8) +
stream.readUint8()
);
event.tempoBPM = 60000000 / event.tempo;
return event;
case MIDIEvents.EVENT_META_SMTPE_OFFSET:
if(strictMode && 5 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.hour = stream.readUint8();
if(strictMode && 23 < event.hour) {
throw new Error(stream.pos() + ' SMTPE offset hour value must' +
' be part of 0-23.');
}
event.minutes = stream.readUint8();
if(strictMode && 59 < event.minutes) {
throw new Error(stream.pos() + ' SMTPE offset minutes value' +
' must be part of 0-59.');
}
event.seconds = stream.readUint8();
if(strictMode && 59 < event.seconds) {
throw new Error(stream.pos() + ' SMTPE offset seconds value' +
' must be part of 0-59.');
}
event.frames = stream.readUint8();
if(strictMode && 30 < event.frames) {
throw new Error(stream.pos() + ' SMTPE offset frames value must' +
' be part of 0-30.');
}
event.subframes = stream.readUint8();
if(strictMode && 99 < event.subframes) {
throw new Error(stream.pos() + ' SMTPE offset subframes value' +
' must be part of 0-99.');
}
return event;
case MIDIEvents.EVENT_META_KEY_SIGNATURE:
if(strictMode && 2 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.key = stream.readUint8();
if(strictMode && (-7 > event.key || 7 < event.key)) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.scale = stream.readUint8();
if(strictMode && 0 !== event.scale && 1 !== event.scale) {
throw new Error(stream.pos() + ' Key signature scale value must' +
' be 0 or 1.');
}
return event;
case MIDIEvents.EVENT_META_TIME_SIGNATURE:
if(strictMode && 4 !== event.length) {
throw new Error(stream.pos() + ' Bad metaevent length.');
}
event.data = stream.readBytes(event.length);
event.param1 = event.data[0];
event.param2 = event.data[1];
event.param3 = event.data[2];
event.param4 = event.data[3];
return event;
case MIDIEvents.EVENT_META_SEQUENCER_SPECIFIC:
event.data = stream.readBytes(event.length);
return event;
default:
if(strictMode) {
throw new Error(stream.pos() + ' Unknown meta event type ' +
'(' + event.subtype.toString(16) + ').');
}
event.data = stream.readBytes(event.length);
return event;
}
// System events
}
else if(eventTypeByte === MIDIEvents.EVENT_SYSEX || eventTypeByte === MIDIEvents.EVENT_DIVSYSEX) {
event.type = eventTypeByte;
event.length = stream.readVarInt();
event.data = stream.readBytes(event.length);
return event;
// Unknown event, assuming it's system like event
}
else {
if(strictMode) {
throw new Error(stream.pos() + ' Unknown event type ' +
eventTypeByte.toString(16) + ', Delta: ' + event.delta + '.');
}
event.type = eventTypeByte;
event.badsubtype = stream.readVarInt();
event.length = stream.readUint8();
event.data = stream.readBytes(event.length);
return event;
}
// MIDI eventsdestination[index++]
}
else {
// running status
if(0 === (eventTypeByte & 0x80)) {
if(!(MIDIEventType)) {
throw new Error(stream.pos() + ' Running status without previous event');
}
MIDIEventParam1 = eventTypeByte;
}
else {
MIDIEventType = eventTypeByte >> 4;
MIDIEventChannel = eventTypeByte & 0x0F;
MIDIEventParam1 = stream.readUint8();
}
event.type = MIDIEvents.EVENT_MIDI;
event.subtype = MIDIEventType;
event.channel = MIDIEventChannel;
event.param1 = MIDIEventParam1;
switch(MIDIEventType) {
case MIDIEvents.EVENT_MIDI_NOTE_OFF:
event.param2 = stream.readUint8();
return event;
case MIDIEvents.EVENT_MIDI_NOTE_ON:
event.param2 = stream.readUint8();
// If velocity is 0, it's a note off event in fact
if(!event.param2) {
event.subtype = MIDIEvents.EVENT_MIDI_NOTE_OFF;
event.param2 = 127; // Find a standard telling what to do here
}
return event;
case MIDIEvents.EVENT_MIDI_NOTE_AFTERTOUCH:
event.param2 = stream.readUint8();
return event;
case MIDIEvents.EVENT_MIDI_CONTROLLER:
event.param2 = stream.readUint8();
return event;
case MIDIEvents.EVENT_MIDI_PROGRAM_CHANGE:
return event;
case MIDIEvents.EVENT_MIDI_CHANNEL_AFTERTOUCH:
return event;
case MIDIEvents.EVENT_MIDI_PITCH_BEND:
event.param2 = stream.readUint8();
return event;
default:
if(strictMode) {
throw new Error(stream.pos() + ' Unknown MIDI event type ' +
'(' + MIDIEventType.toString(16) + ').');
}
return event;
}
}
},
};
};
// Return the buffer length needed to encode the given events
MIDIEvents.writeToTrack = function midiEventsWriteToTrack(events, destination, strictMode) {
var index = 0;
var i;
var j;
var k;
var l;
// Converting each event to binary MIDI datas
for(i = 0, j = events.length; i < j; i++) {
// Writing delta value
if(events[i].delta >>> 28) {
throw Error('Event #' + i + ': Maximum delta time value reached (' +
events[i].delta + '/134217728 max)');
}
if(events[i].delta >>> 21) {
destination[index++] = ((events[i].delta >>> 21) & 0x7F) | 0x80;
}
if(events[i].delta >>> 14) {
destination[index++] = ((events[i].delta >>> 14) & 0x7F) | 0x80;
}
if(events[i].delta >>> 7) {
destination[index++] = ((events[i].delta >>> 7) & 0x7F) | 0x80;
}
destination[index++] = (events[i].delta & 0x7F);
// MIDI Events encoding
if(events[i].type === MIDIEvents.EVENT_MIDI) {
// Adding the byte of subtype + channel
destination[index++] = (events[i].subtype << 4) + events[i].channel;
// Adding the byte of the first params
destination[index++] = events[i].param1;
// Adding a byte for the optionnal second param
if(-1 !== MIDIEvents.MIDI_2PARAMS_EVENTS.indexOf(events[i].subtype)) {
destination[index++] = events[i].param2;
}
// META / SYSEX events encoding
} else {
// Adding the event type byte
destination[index++] = events[i].type;
// Adding the META event subtype byte
if(events[i].type === MIDIEvents.EVENT_META) {
destination[index++] = events[i].subtype;
}
// Writing the event length bytes
if(events[i].length >>> 28) {
throw Error('Event #' + i + ': Maximum length reached (' +
events[i].length + '/134217728 max)');
}
if(events[i].length >>> 21) {
destination[index++] = ((events[i].length >>> 21) & 0x7F) | 0x80;
}
if(events[i].length >>> 14) {
destination[index++] = ((events[i].length >>> 14) & 0x7F) | 0x80;
}
if(events[i].length >>> 7) {
destination[index++] = ((events[i].length >>> 7) & 0x7F) | 0x80;
}
destination[index++] = (events[i].length & 0x7F);
if(events[i].type === MIDIEvents.EVENT_META) {
switch(events[i].subtype) {
case MIDIEvents.EVENT_META_SEQUENCE_NUMBER:
destination[index++] = events[i].msb;
destination[index++] = events[i].lsb;
break;
case MIDIEvents.EVENT_META_TEXT:
case MIDIEvents.EVENT_META_COPYRIGHT_NOTICE:
case MIDIEvents.EVENT_META_TRACK_NAME:
case MIDIEvents.EVENT_META_INSTRUMENT_NAME:
case MIDIEvents.EVENT_META_LYRICS:
case MIDIEvents.EVENT_META_MARKER:
case MIDIEvents.EVENT_META_CUE_POINT:
for(k = 0, l = events[i].length; k < l; k++) {
destination[index++] = events[i].data[k];
}
break;
case MIDIEvents.EVENT_META_MIDI_CHANNEL_PREFIX:
destination[index++] = events[i].prefix;
break;
case MIDIEvents.EVENT_META_END_OF_TRACK:
break;
case MIDIEvents.EVENT_META_SET_TEMPO:
destination[index++] = (events[i].tempo >> 16);
destination[index++] = (events[i].tempo >> 8) & 0xFF;
destination[index++] = events[i].tempo & 0xFF;
break;
case MIDIEvents.EVENT_META_SMTPE_OFFSET:
if(strictMode && 23 < events[i].hour) {
throw new Error('Event #' + i + ': SMTPE offset hour value must be' +
' part of 0-23.');
}
destination[index++] = events[i].hour;
if(strictMode && 59 < events[i].minutes) {
throw new Error('Event #' + i + ': SMTPE offset minutes value must' +
' be part of 0-59.');
}
destination[index++] = events[i].minutes;
if(strictMode && 59 < events[i].seconds) {
throw new Error('Event #' + i + ': SMTPE offset seconds value must' +
' be part of 0-59.');
}
destination[index++] = events[i].seconds;
if(strictMode && 30 < events[i].frames) {
throw new Error('Event #' + i + ': SMTPE offset frames amount must' +
' be part of 0-30.');
}
destination[index++] = events[i].frames;
if(strictMode && 99 < events[i].subframes) {
throw new Error('Event #' + i + ': SMTPE offset subframes amount' +
' must be part of 0-99.');
}
destination[index++] = events[i].subframes;
break;
case MIDIEvents.EVENT_META_KEY_SIGNATURE:
if('number' != typeof events[i].key || -7 > events[i].key ||
7 < events[i].scale) {
throw new Error('Event #' + i + ':The key signature key must be' +
' between -7 and 7');
}
if('number' !== typeof events[i].scale ||
0 > events[i].scale || 1 < events[i].scale) {
throw new Error('Event #' + i + ':' +
'The key signature scale must be 0 or 1');
}
destination[index++] = events[i].key;
destination[index++] = events[i].scale;
break;
// Not implemented
case MIDIEvents.EVENT_META_TIME_SIGNATURE:
case MIDIEvents.EVENT_META_SEQUENCER_SPECIFIC:
default:
for(k = 0, l = events[i].length; k < l; k++) {
destination[index++] = events[i].data[k];
}
break;
}
// Adding bytes corresponding to the sysex event datas
} else {
for(k = 0, l = events[i].length; k < l; k++) {
destination[index++] = events[i].data[k];
}
}
}
}
};
// Return the buffer length needed to encode the given events
MIDIEvents.getRequiredBufferLength = function(events) {
var bufferLength = 0;
var i = 0;
var j;
// Calculating the track size by adding events lengths
for(i = 0, j = events.length; i < j; i++) {
// Computing necessary bytes to encode the delta value
bufferLength +=
events[i].delta >>> 21 ? 4 :
events[i].delta >>> 14 ? 3 :
events[i].delta >>> 7 ? 2 : 1;
// MIDI Events have various fixed lengths
if(events[i].type === MIDIEvents.EVENT_MIDI) {
// Adding a byte for subtype + channel
bufferLength++;
// Adding a byte for the first params
bufferLength++;
// Adding a byte for the optionnal second param
if(-1 !== MIDIEvents.MIDI_2PARAMS_EVENTS.indexOf(events[i].subtype)) {
bufferLength++;
}
// META / SYSEX events lengths are self defined
} else {
// Adding a byte for the event type
bufferLength++;
// Adding a byte for META events subtype
if(events[i].type === MIDIEvents.EVENT_META) {
bufferLength++;
}
// Adding necessary bytes to encode the length
bufferLength +=
events[i].length >>> 21 ? 4 :
events[i].length >>> 14 ? 3 :
events[i].length >>> 7 ? 2 : 1;
// Adding bytes corresponding to the event length
bufferLength += events[i].length;
}
}
return bufferLength;
};
/*! http://mths.be/fromcodepoint v0.2.1 by @mathias */
if (!String.fromCodePoint) {
(function() {
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
var fromCodePoint = function(_) {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) != codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
if (defineProperty) {
defineProperty(String, 'fromCodePoint', {
'value': fromCodePoint,
'configurable': true,
'writable': true
});
} else {
String.fromCodePoint = fromCodePoint;
}
}());
}
/*! http://mths.be/codepointat v0.2.0 by @mathias */
if (!String.prototype.codePointAt) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var codePointAt = function(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
// `ToInteger`
var index = position ? Number(position) : 0;
if (index != index) { // better `isNaN`
index = 0;
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined;
}
// Get the first code unit
var first = string.charCodeAt(index);
var second;
if ( // check if its the start of a surrogate pair
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
};
if (defineProperty) {
defineProperty(String.prototype, 'codePointAt', {
'value': codePointAt,
'configurable': true,
'writable': true
});
} else {
String.prototype.codePointAt = codePointAt;
}
}());
}
// UTF8 : Manage UTF-8 strings in ArrayBuffers
var UTF8={
// non UTF8 encoding detection (cf README file for details)
'isNotUTF8': function(bytes, byteOffset, byteLength) {
try {
UTF8.getStringFromBytes(bytes, byteOffset, byteLength, true);
} catch(e) {
return true;
}
return false;
},
// UTF8 decoding functions
'getCharLength': function(theByte) {
// 4 bytes encoded char (mask 11110000)
if(0xF0 == (theByte&0xF0)) {
return 4;
// 3 bytes encoded char (mask 11100000)
} else if(0xE0 == (theByte&0xE0)) {
return 3;
// 2 bytes encoded char (mask 11000000)
} else if(0xC0 == (theByte&0xC0)) {
return 2;
// 1 bytes encoded char
} else if(theByte == (theByte&0x7F)) {
return 1;
}
return 0;
},
'getCharCode': function(bytes, byteOffset, charLength) {
var charCode = 0, mask = '';
byteOffset = byteOffset || 0;
// Retrieve charLength if not given
charLength = charLength || UTF8.getCharLength(bytes[byteOffset]);
if(charLength == 0) {
throw new Error(bytes[byteOffset].toString(2)+' is not a significative' +
' byte (offset:'+byteOffset+').');
}
// Return byte value if charlength is 1
if(1 === charLength) {
return bytes[byteOffset];
}
// Test UTF8 integrity
mask = '00000000'.slice(0, charLength) + 1 + '00000000'.slice(charLength + 1);
if(bytes[byteOffset]&(parseInt(mask, 2))) {
throw Error('Index ' + byteOffset + ': A ' + charLength + ' bytes' +
' encoded char' +' cannot encode the '+(charLength+1)+'th rank bit to 1.');
}
// Reading the first byte
mask='0000'.slice(0,charLength+1)+'11111111'.slice(charLength+1);
charCode+=(bytes[byteOffset]&parseInt(mask,2))<<((--charLength)*6);
// Reading the next bytes
while(charLength) {
if(0x80!==(bytes[byteOffset+1]&0x80)
||0x40===(bytes[byteOffset+1]&0x40)) {
throw Error('Index '+(byteOffset+1)+': Next bytes of encoded char'
+' must begin with a "10" bit sequence.');
}
charCode += ((bytes[++byteOffset]&0x3F) << ((--charLength) * 6));
}
return charCode;
},
'getStringFromBytes': function(bytes, byteOffset, byteLength, strict) {
var charLength, chars = [];
byteOffset = byteOffset|0;
byteLength=('number' === typeof byteLength ?
byteLength :
bytes.byteLength || bytes.length
);
for(; byteOffset < byteLength; byteOffset++) {
charLength = UTF8.getCharLength(bytes[byteOffset]);
if(byteOffset + charLength > byteLength) {
if(strict) {
throw Error('Index ' + byteOffset + ': Found a ' + charLength +
' bytes encoded char declaration but only ' +
(byteLength - byteOffset) +' bytes are available.');
}
} else {
chars.push(String.fromCodePoint(
UTF8.getCharCode(bytes, byteOffset, charLength, strict)
));
}
byteOffset += charLength - 1;
}
return chars.join('');
},
// UTF8 encoding functions
'getBytesForCharCode': function(charCode) {
if(charCode < 128) {
return 1;
} else if(charCode < 2048) {
return 2;
} else if(charCode < 65536) {
return 3;
} else if(charCode < 2097152) {
return 4;
}
throw new Error('CharCode '+charCode+' cannot be encoded with UTF8.');
},
'setBytesFromCharCode': function(charCode, bytes, byteOffset, neededBytes) {
charCode = charCode|0;
bytes = bytes || [];
byteOffset = byteOffset|0;
neededBytes = neededBytes || UTF8.getBytesForCharCode(charCode);
// Setting the charCode as it to bytes if the byte length is 1
if(1 == neededBytes) {
bytes[byteOffset] = charCode;
} else {
// Computing the first byte
bytes[byteOffset++] =
(parseInt('1111'.slice(0, neededBytes), 2) << 8 - neededBytes) +
(charCode >>> ((--neededBytes) * 6));
// Computing next bytes
for(;neededBytes>0;) {
bytes[byteOffset++] = ((charCode>>>((--neededBytes) * 6))&0x3F)|0x80;
}
}
return bytes;
},
'setBytesFromString': function(string, bytes, byteOffset, byteLength, strict) {
string = string || '';
bytes = bytes || [];
byteOffset = byteOffset|0;
byteLength = ('number' === typeof byteLength ?
byteLength :
bytes.byteLength||Infinity
);
for(var i = 0, j = string.length; i < j; i++) {
var neededBytes = UTF8.getBytesForCharCode(string[i].codePointAt(0));
if(strict && byteOffset + neededBytes > byteLength) {
throw new Error('Not enought bytes to encode the char "' + string[i] +
'" at the offset "' + byteOffset + '".');
}
UTF8.setBytesFromCharCode(string[i].codePointAt(0),
bytes, byteOffset, neededBytes, strict);
byteOffset += neededBytes;
}
return bytes;
}
};
// MIDIFile : Read (and soon edit) a MIDI file in a given ArrayBuffer
// Constructor
function MIDIFile(buffer, strictMode) {
var track;
var curIndex;
var i;
var j;
// If not buffer given, creating a new MIDI file
if(!buffer) {
// Creating the content
this.header = new MIDIFileHeader();
this.tracks = [new MIDIFileTrack()];
// if a buffer is provided, parsing him
} else {
if(!(buffer instanceof ArrayBuffer)) {
throw new Error('Invalid buffer received.');
}
// Minimum MIDI file size is a headerChunk size (14bytes)
// and an empty track (8+3bytes)
if(25 > buffer.byteLength) {
throw new Error('A buffer of a valid MIDI file must have, at least, a' +
' size of 25bytes.');
}
// Reading header
this.header = new MIDIFileHeader(buffer, strictMode);
this.tracks = [];
curIndex = MIDIFileHeader.HEADER_LENGTH;
// Reading tracks
for(i = 0, j = this.header.getTracksCount(); i < j; i++) {
// Testing the buffer length
if(strictMode && curIndex >= buffer.byteLength - 1) {
throw new Error('Couldn\'t find datas corresponding to the track #' + i + '.');
}
// Creating the track object
track = new MIDIFileTrack(buffer, curIndex, strictMode);
this.tracks.push(track);
// Updating index to the track end
curIndex += track.getTrackLength() + 8;
}
// Testing integrity : curIndex should be at the end of the buffer
if(strictMode && curIndex !== buffer.byteLength) {
throw new Error('It seems that the buffer contains too much datas.');
}
}
}
// Events reading helpers
MIDIFile.prototype.getEvents = function(type, subtype) {
var events;
var event;
var playTime = 0;
var filteredEvents = [];
var format = this.header.getFormat();
var tickResolution = this.header.getTickResolution();
var i;
var j;
var trackParsers;
var smallestDelta;
// Reading events
// if the read is sequential
if(1 !== format || 1 === this.tracks.length) {
for(i = 0, j = this.tracks.length; i < j; i++) {
// reset playtime if format is 2
playTime = (2 === format && playTime ? playTime : 0);
events = MIDIEvents.createParser(this.tracks[i].getTrackContent(), 0, false);
// loooping through events
event = events.next();
while(event) {
playTime += event.delta ? (event.delta * tickResolution) / 1000 : 0;
if(event.type === MIDIEvents.EVENT_META) {
// tempo change events
if(event.subtype === MIDIEvents.EVENT_META_SET_TEMPO) {
tickResolution = this.header.getTickResolution(event.tempo);
}
}
// push the asked events
if(((!type) || event.type === type) &&
((!subtype) || (event.subtype && event.subtype === type))) {
event.playTime = playTime;
filteredEvents.push(event);
}
event = events.next();
}
}
// the read is concurrent
} else {
trackParsers = [];
smallestDelta = -1;
// Creating parsers
for(i = 0, j = this.tracks.length; i < j; i++) {
trackParsers[i] = {};
trackParsers[i].parser = MIDIEvents.createParser(
this.tracks[i].getTrackContent(), 0, false);
trackParsers[i].curEvent = trackParsers[i].parser.next();
}
// Filling events
do {
smallestDelta = -1;
// finding the smallest event
for(i = 0, j = trackParsers.length; i < j; i++) {
if(trackParsers[i].curEvent) {
if(-1 === smallestDelta || trackParsers[i].curEvent.delta <
trackParsers[smallestDelta].curEvent.delta) {
smallestDelta = i;
}
}
}
if(-1 !== smallestDelta) {
// removing the delta of previous events
for(i = 0, j = trackParsers.length; i < j; i++) {
if(i !== smallestDelta && trackParsers[i].curEvent) {
trackParsers[i].curEvent.delta -= trackParsers[smallestDelta].curEvent.delta;
}
}
// filling values
event = trackParsers[smallestDelta].curEvent;
playTime += (event.delta ? (event.delta * tickResolution) / 1000 : 0);
if(event.type === MIDIEvents.EVENT_META) {
// tempo change events
if(event.subtype === MIDIEvents.EVENT_META_SET_TEMPO) {
tickResolution = this.header.getTickResolution(event.tempo);
}
}
// push midi events
if(((!type) || event.type === type) &&
((!subtype) || (event.subtype && event.subtype === type))) {
event.playTime = playTime;
event.track = smallestDelta;
filteredEvents.push(event);
}
// getting next event
trackParsers[smallestDelta].curEvent = trackParsers[smallestDelta].parser.next();
}
} while(-1 !== smallestDelta);
}
return filteredEvents;
};
MIDIFile.prototype.getMidiEvents = function() {
return this.getEvents(MIDIEvents.EVENT_MIDI);
};
MIDIFile.prototype.getLyrics = function() {
var events = this.getEvents(MIDIEvents.EVENT_META);
var texts = [];
var lyrics = [];
var event;
var i;
var j;
for(i = 0, j = events.length; i < j; i++) {
event = events[i];
// Lyrics
if(event.subtype === MIDIEvents.EVENT_META_LYRICS) {
lyrics.push(event);
// Texts
} else if(event.subtype === MIDIEvents.EVENT_META_TEXT) {
// Ignore special texts
if('@' === String.fromCharCode(event.data[0])) {
if('T' === String.fromCharCode(event.data[1])) {
// console.log('Title : ' + event.text.substring(2));
} else if('I' === String.fromCharCode(event.data[1])) {
// console.log('Info : ' + event.text.substring(2));
} else if('L' === String.fromCharCode(event.data[1])) {
// console.log('Lang : ' + event.text.substring(2));
}
// karaoke text follows, remove all previous text
} else if(0 === String.fromCharCode.apply(String, event.data).indexOf('words')) {
texts.length = 0;
// console.log('Word marker found');
// Karaoke texts
// If playtime is greater than 0
} else if(0 !== event.playTime) {
texts.push(event);
}
}
}
// Choosing the right lyrics
if(2 < lyrics.length) {
texts = lyrics;
} else if(!texts.length) {
texts = [];
}
// Convert texts and detect encoding
try {
texts.forEach(function(event) {
event.text = UTF8.getStringFromBytes(event.data, 0, event.length, true);
});
} catch (e) {
texts.forEach(function(event) {
event.text = event.data.map(function(c) {
return String.fromCharCode(c);
}).join('');
});
}
return texts;
};
// Basic events reading
MIDIFile.prototype.getTrackEvents = function(index) {
var event;
var events = [];
var parser;
if(index > this.tracks.length || 0 > index) {
throw Error('Invalid track index (' + index + ')');
}
parser = MIDIEvents.createParser(
this.tracks[index].getTrackContent(), 0, false
);
event = parser.next();
do {
events.push(event);
event = parser.next();
} while(event);
return events;
};
// Basic events writting
MIDIFile.prototype.setTrackEvents = function(index, events) {
var bufferLength;
var destination;