-
Notifications
You must be signed in to change notification settings - Fork 3
/
mc.php
1371 lines (1244 loc) · 43.3 KB
/
mc.php
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
<?php
/************************************************** **************************
Software: Midi Class
Version: 1.7.6
Date: 2010-02-19
Author: Valentin Schmidt
Contact: [email protected]
License: Freeware
You may use and modify this software as you wish.
Last Changes:
+ downloadMidFile: order of params swapped, so $file can be omitted to
directly start downloading file from memory without using a temp file
- some fixes by Michael Mlivoncic (MM):
+ PrCh added as shortened form (repetition)
+ exception-handling for PHP 5: raise exception on corrupt MIDI-files
+ download now sends gzip-Encoded (if supported by browser)
+ parser correctly reads field-length > 127 (several event types)
+ fixed problem with fopen ("rb")
+ PitchBend: correct values (writing back negative nums lead to corrupt files)
+ parser now accepts unknown meta-events
************************************************** **************************/
class Midi{
//Private properties
var $tracks; //array of tracks, where each track is array of message strings
var $timebase; //timebase = ticks per frame (quarter note)
var $tempo; //tempo as integer (0 for unknown)
var $tempoMsgNum; //position of tempo event in track 0
var $type;
/************************************************** **************************
* *
* Public methods *
* *
************************************************** **************************/
//---------------------------------------------------------------
// creates (or resets to) new empty MIDI song
//---------------------------------------------------------------
function open($timebase=480){
$this->tempo = 0;//125000 = 120 bpm
$this->timebase = $timebase;
$this->tracks = array();
}
//---------------------------------------------------------------
// sets tempo by replacing set tempo msg in track 0 (or adding new track 0)
//---------------------------------------------------------------
function setTempo($tempo){
$tempo = round($tempo);
if (isset($this->tempoMsgNum)) $this->tracks[0][$this->tempoMsgNum] = "0 Tempo $tempo";
else{
$tempoTrack = array('0 TimeSig 4/4 24 8',"0 Tempo $tempo",'0 Meta TrkEnd');
array_unshift($this->tracks, $tempoTrack);
$this->tempoMsgNum = 1;
}
$this->tempo = $tempo;
}
//---------------------------------------------------------------
// returns tempo (0 if not set)
//---------------------------------------------------------------
function getTempo(){
return $this->tempo;
}
//---------------------------------------------------------------
// sets tempo corresponding to given bpm
//---------------------------------------------------------------
function setBpm($bpm){
$tempo = round(60000000/$bpm);
$this->setTempo($tempo);
}
//---------------------------------------------------------------
// returns bpm corresponding to tempo
//---------------------------------------------------------------
function getBpm(){
return ($this->tempo!=0)?(int)(60000000/$this->tempo):0;
}
//---------------------------------------------------------------
// sets timebase
//---------------------------------------------------------------
function setTimebase($tb){
$this->timebase = $tb;
}
//---------------------------------------------------------------
// returns timebase
//---------------------------------------------------------------
function getTimebase(){
return $this->timebase;
}
//---------------------------------------------------------------
// adds new track, returns new track count
//---------------------------------------------------------------
function newTrack(){
array_push($this->tracks,array());
return count($this->tracks);
}
//---------------------------------------------------------------
// returns track $tn as array of msg strings
//---------------------------------------------------------------
function getTrack($tn){
return $this->tracks[$tn];
}
//---------------------------------------------------------------
// returns number of messages of track $tn
//---------------------------------------------------------------
function getMsgCount($tn){
return count($this->tracks[$tn]);
}
//---------------------------------------------------------------
// adds message to end of track $tn
//---------------------------------------------------------------
function addMsg($tn, $msgStr, $ttype=0){ //0:absolute, 1:delta
$track = $this->tracks[$tn];
if ($ttype==1){
$last = $this->_getTime($track[count($track)-1]);
$msg = explode(' ',$msgStr);
$dt = (int) $msg[0];
$msg[0] = $last + $dt;
$msgStr = implode(' ',$msg);
}
$track[] = $msgStr;
$this->tracks[$tn] = $track;
}
//---------------------------------------------------------------
// adds message at adequate position of track $n (slower than addMsg)
//---------------------------------------------------------------
function insertMsg($tn,$msgStr){
$time = $this->_getTime($msgStr);
$track = $this->tracks[$tn];
$mc = count($track);
for ($i=0;$i<$mc;$i++){
$t = $this->_getTime($track[$i]);
if ($t>=$time) break;
}
array_splice($this->tracks[$tn], $i, 0, $msgStr);
}
//---------------------------------------------------------------
// returns message number $mn of track $tn
//---------------------------------------------------------------
function getMsg($tn,$mn){
return $this->tracks[$tn][$mn];
}
//---------------------------------------------------------------
// deletes message number $mn of track $tn
//---------------------------------------------------------------
function deleteMsg($tn,$mn){
array_splice($this->tracks[$tn], $mn, 1);
}
//---------------------------------------------------------------
// deletes track $tn
//---------------------------------------------------------------
function deleteTrack($tn){
array_splice($this->tracks, $tn, 1);
return count($this->tracks);
}
//---------------------------------------------------------------
// returns number of tracks
//---------------------------------------------------------------
function getTrackCount(){
return count($this->tracks);
}
//---------------------------------------------------------------
// deletes all tracks except track $tn (and $track 0 which contains tempo info)
//---------------------------------------------------------------
function soloTrack($tn){
if ($tn==0) $this->tracks = array($this->tracks[0]);
else $this->tracks = array($this->tracks[0],$this->tracks[$tn]);
}
//---------------------------------------------------------------
// transposes song by $dn half tone steps
//---------------------------------------------------------------
function transpose($dn){
$tc = count($this->tracks);
for ($i=0;$i<$tc;$i++) $this->transposeTrack($i,$dn);
}
//---------------------------------------------------------------
// transposes track $tn by $dn half tone steps
//---------------------------------------------------------------
function transposeTrack($tn, $dn){
$track = $this->tracks[$tn];
$mc = count($track);
for ($i=0;$i<$mc;$i++){
$msg = explode(' ',$track[$i]);
if ($msg[1] == 'On' || $msg[1] == 'Off'){
eval("\$".$msg[3].';'); // $n
$n = max(0,min(127,$n+$dn));
$msg[3] = "n=$n";
$track[$i] = join(' ',$msg);
}
}
$this->tracks[$tn] = $track;
}
//---------------------------------------------------------------
// import whole MIDI song as text (mf2t-format)
//---------------------------------------------------------------
function importTxt($txt){
$txt = trim($txt);
// make unix text format
if (strpos($txt,"\r")!==false && strpos($txt,"<BR>")===false) // MAC
$txt = str_replace("\r","<BR>",$txt);
else // PC?
$txt = str_replace("\r",'',$txt);
$txt = $txt."<BR>";// makes things easier
$headerStr = strtok($txt,"<BR>");
$header = explode(' ',$headerStr); //"MFile $type $tc $timebase";
$this->type = $header[1];
$this->timebase = $header[3];
$this->tempo = 0;
$trackStrings = explode("MTrk<BR>",$txt);
array_shift($trackStrings);
$tracks = array();
foreach ($trackStrings as $trackStr){
$track = explode("<BR>",$trackStr);
array_pop($track);
array_pop($track);
if ($track[0]=="TimestampType=Delta"){//delta
array_shift($track);
$track = _delta2Absolute($track);
}
$tracks[] = $track;
}
$this->tracks = $tracks;
$this->_findTempo();
}
//---------------------------------------------------------------
// imports track as text (mf2t-format)
//---------------------------------------------------------------
function importTrackTxt($txt, $tn){
$txt = trim($txt);
// make unix text format
if (strpos($txt,"\r")!==false && strpos($txt,"<BR>")===false) // MAC
$txt = str_replace("\r","<BR>",$txt);
else // maybe PC, 0D 0A?
$txt = str_replace("\r",'',$txt);
$track = explode("<BR>",$txt);
if ($track[0]=='MTrk') array_shift($track);
if ($track[count($track)-1]=='TrkEnd') array_pop($track);
if ($track[0]=="TimestampType=Delta"){//delta
array_shift($track);
$track = _delta2Absolute($track);
}
$tn = isset($tn)?$tn:count($this.tracks);
$this->tracks[$tn] = $track;
if ($tn==0) $this->_findTempo();
}
//---------------------------------------------------------------
// returns MIDI song as text
//---------------------------------------------------------------
function getTxt($ttype=0){ //0:absolute, 1:delta
$timebase = $this->timebase;
$tracks = $this->tracks;
$tc = count($tracks);
$type = ($tc>1)?1:0;
$str = "HEAD $tc $timebase<BR>";
for ($i=0;$i<$tc;$i++) $str .= $this->getTrackTxt($i,$ttype);
return $str;
}
//---------------------------------------------------------------
// returns track as text
//---------------------------------------------------------------
function getTrackTxt($tn,$ttype=0){ //0:absolute, 1:delta
$track = $this->tracks[$tn];
$str = "MTrk<BR>";
if ($ttype==1) {//time as delta
$str .= "TimestampType=Delta<BR>";
$last = 0;
foreach ($track as $msgStr){
$msg = explode (' ', $msgStr);
$t = (int) $msg[0];
$msg[0] = $t - $last;
$str .= implode(' ',$msg)."<BR>";
$last = $t;
}
}else foreach ($track as $msg) $str .= $msg."<BR>";
$str .= "TrkEnd<BR>";
return $str;
}
//---------------------------------------------------------------
// returns MIDI XML representation (v0.9, http://www.musicxml.org/dtds/midixml.dtd)
//---------------------------------------------------------------
function getXml($ttype=0){ //0:absolute, 1:delta
$tracks = $this->tracks;
$tc = count($tracks);
$type = ($tc>1)?1:0;
$timebase = $this->timebase;
$xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<!DOCTYPE MIDIFile PUBLIC
\"-//Recordare//DTD MusicXML 0.9 MIDI//EN\"
\"http://www.musicxml.org/dtds/midixml.dtd\">
<MIDIFile>
<Format>$type</Format>
<TrackCount>$tc</TrackCount>
<TicksPerBeat>$timebase</TicksPerBeat>
<TimestampType>".($ttype==1?'Delta':'Absolute')."</TimestampType><BR>";
for ($i=0;$i<$tc;$i++){
$xml .= "<Track Number=\"$i\"><BR>";
$track = $tracks[$i];
$mc = count($track);
$last = 0;
for ($j=0;$j<$mc;$j++){
$msg = explode(' ',$track[$j]);
$t = (int) $msg[0];
if ($ttype==1){//delta
$dt = $t - $last;
$last = $t;
}
$xml .= " <Event><BR>";
$xml .= ($ttype==1)?" <Delta>$dt</Delta><BR>":" <Absolute>$t</Absolute><BR>";
$xml .= ' ';
switch($msg[1]){
case 'PrCh':
eval("\$".$msg[2].';'); // $ch
eval("\$".$msg[3].';'); // $p
$xml .= "<ProgramChange Channel=\"$ch\" Number=\"$p\"/><BR>";
break;
case 'On':
case 'Off':
eval("\$".$msg[2].';'); // $ch
eval("\$".$msg[3].';'); // $n
eval("\$".$msg[4].';'); // $v
$xml .= "<Note{$msg[1]} Channel=\"$ch\" Note=\"$n\" Velocity=\"$v\"/><BR>";
break;
case 'PoPr':
eval("\$".$msg[2].';'); // $ch
eval("\$".$msg[3].';'); // $n
eval("\$".$msg[4].';'); // $v
$xml .= "<PolyKeyPressure Channel=\"$ch\" Note=\"$n\" Pressure=\"$v\"/><BR>";
break;
case 'Par':
eval("\$".$msg[2].';'); // ch
eval("\$".$msg[3].';'); // c
eval("\$".$msg[4].';'); // v
$xml .= "<ControlChange Channel=\"$ch\" Control=\"$c\" Value=\"$v\"/><BR>";
break;
case 'ChPr':
eval("\$".$msg[2].';'); // ch
eval("\$".$msg[3].';'); // v
$xml .= "<ChannelKeyPressure Channel=\"$ch\" Pressure=\"$v\"/><BR>";
break;
case 'Pb':
eval("\$".$msg[2].';'); // ch
eval("\$".$msg[3].';'); // v
$xml .= "<PitchBendChange Channel=\"$ch\" Value=\"$v\"/><BR>";
break;
case 'Seqnr':
$xml .= "<SequenceNumber Value=\"{$msg[2]}\"/><BR>";
break;
case 'Meta':
$txttypes = array('Text','Copyright','TrkName','InstrName','Ly ric','Marker','Cue');
$mtype = $msg[2];
$pos = array_search($mtype, $txttypes);
if ($pos !== FALSE){
$tags = array('TextEvent','CopyrightNotice','TrackName','I nstrumentName','Lyric','Marker','CuePoint');
$tag = $tags[$pos];
$line = $track[$j];
$start = strpos($line,'"')+1;
$end = strrpos($line,'"');
$txt = substr($line,$start,$end-$start);
$xml .= "<$tag>".htmlspecialchars($txt)."</$tag><BR>";
}else{
if ($mtype == 'TrkEnd')
$xml .= "<EndOfTrack/><BR>";
elseif ($mtype == '0x20' || $mtype == '0x21') // ChannelPrefix ???
$xml .= "<MIDIChannelPrefix Value=\"{$msg[3]}\"/><BR>";
}
break;
case 'Tempo':
$xml .= "<SetTempo Value=\"{$msg[2]}\"/><BR>";
break;
case 'SMPTE':
$xml .= "<SMPTEOffset TimeCodeType=\"1\" Hour=\"{$msg[2]}\" Minute=\"{$msg[3]}\" Second=\"{$msg[4]}\" Frame=\"{$msg[5]}\" FractionalFrame=\"{$msg[6]}\"/><BR>"; //TimeCodeType???
break;
case 'TimeSig': // LogDenum???
$ts = explode('/',$msg[2]);
$xml .= "<TimeSignature Numerator=\"{$ts[0]}\" LogDenominator=\"".log($ts[1])/log(2)."\" MIDIClocksPerMetronomeClick=\"{$msg[3]}\" ThirtySecondsPer24Clocks=\"{$msg[4]}\"/><BR>";
break;
case 'KeySig':
$mode = ($msg[3]=='major')?0:1;
$xml .= "<KeySignature Fifths=\"{$msg[2]}\" Mode=\"$mode\"/><BR>"; // ???
break;
case 'SeqSpec':
$line = $track[$j];
$start = strpos($line,'SeqSpec')+8;
$data = substr($line,$start);
$xml .= "<SequencerSpecific>$data</SequencerSpecific><BR>";
break;
case 'SysEx':
$str = '';
for ($k=3;$k<count($msg);$k++) $str .= $msg[$k].' ';
$str = trim(strtoupper($str));
$xml .= "<SystemExclusive>$str</SystemExclusive><BR>";
break;
/* TODO:
<AllSoundOff Channel="9"/>
<ResetAllControllers Channel="9"/>
<LocalControl Channel="9" Value="on"/>
<AllNotesOff Channel="9"/>
<OmniOff Channel="9"/>
<OmniOn Channel="9"/>
<MonoMode Channel="9" Value="5"/>
<PolyMode Channel="9"/>
*/
default:
_err('unknown event: '.$msg[1]);
exit();
}
$xml .= " </Event><BR>";
}
$xml .= "</Track><BR>";
}
$xml .= "</MIDIFile>";
return $xml;
}
//---------------------------------------------------------------
// import MIDI XML representation
// (so far only a subset of http://www.musicxml.org/dtds/midixml.dtd (v0.8), see documentation)
//---------------------------------------------------------------
function importXml($xmlStr){
$this->evt = array();
$this->atr = array();
$this->dat = '';
$this->open();
$this->xml_parser = xml_parser_create("ISO-8859-1");
xml_set_object($this->xml_parser, $this);
xml_set_element_handler($this->xml_parser, "_startElement", "_endElement");
xml_set_character_data_handler($this->xml_parser,"_chData");
if (!xml_parse($this->xml_parser, $xmlStr, TRUE))
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->xml_parser)),xml_get_current_line_number($this->xml_parser)));
xml_parser_free($this->xml_parser);
}
//---------------------------------------------------------------
// imports Standard MIDI File (typ 0 or 1) (and RMID)
// (if optional parameter $tn set, only track $tn is imported)
//---------------------------------------------------------------
function importMid($smf_path){
$SMF = fopen($smf_path, "rb"); // Standard MIDI File, type 0 or 1.
if (!isset($song)) $song = '';
while(!feof($SMF))
{
$song .= fread($SMF,1024);
}
fclose($SMF);
if (strpos($song,'MThd')>0) $song = substr($song,strpos($song,'MThd'));//get rid of RMID header
$header = substr($song,0,14);
if (substr($header,0,8)!="MThd\0\0\0\6") _err('wrong MIDI-header');
$type = ord($header[9]);
if ($type>1) _err('only SMF Typ 0 and 1 supported');
//$trackCnt = ord($header[10])*256 + ord($header[11]); //ignore
$timebase = ord($header[12])*256 + ord($header[13]);
$this->type = $type;
$this->timebase = $timebase;
$this->tempo = 0; // maybe (hopefully!) overwritten by _parseTrack
$trackStrings = explode('MTrk',$song);
array_shift($trackStrings);
$tracks = array();
$tsc = count($trackStrings);
if (func_num_args()>1){
$tn = func_get_arg(1);
if ($tn>=$tsc) _err('SMF has less tracks than $tn');
$tracks[] = $this->_parseTrack($trackStrings[$tn],$tn);
} else
for ($i=0;$i<$tsc;$i++) $tracks[] = $this->_parseTrack($trackStrings[$i],$i);
$this->tracks = $tracks;
}
//---------------------------------------------------------------
// returns binary MIDI string
//---------------------------------------------------------------
function getMid(){
$tracks = $this->tracks;
$tc = count($tracks);
$type = ($tc > 1)?1:0;
$midStr = "MThd\0\0\0\6\0".chr($type)._getBytes($tc,2)._getBytes($this->timebase,2);
for ($i=0;$i<$tc;$i++){
$track = $tracks[$i];
$mc = count($track);
$time = 0;
$midStr .= "MTrk";
$trackStart = strlen($midStr);
$last = '';
for ($j=0;$j<$mc;$j++){
$line = $track[$j];
$t = $this->_getTime($line);
$dt = $t - $time;
// A: IGNORE EVENTS WITH INCORRECT TIMESTAMP
if ($dt<0) continue;
// B: THROW ERROR
#if ($dt<0) _err('incorrect timestamp!');
$time = $t;
$midStr .= _writeVarLen($dt);
// repetition, same event, same channel, omit first byte (smaller file size)
$str = $this->_getMsgStr($line);
$start = ord($str[0]);
if ($start>=0x80 && $start<=0xEF && $start==$last) $str = substr($str, 1);
$last = $start;
$midStr .= $str;
}
$trackLen = strlen($midStr) - $trackStart;
$midStr = substr($midStr,0,$trackStart)._getBytes($trackLen, 4).substr($midStr,$trackStart);
}
return $midStr;
}
//---------------------------------------------------------------
// saves MIDI song as Standard MIDI File
//---------------------------------------------------------------
function saveMidFile($mid_path, $chmod=false){
if (count($this->tracks)<1) _err('MIDI song has no tracks');
$SMF = fopen($mid_path, "wb"); // SMF
fwrite($SMF,$this->getMid());
fclose($SMF);
if ($chmod!==false) @chmod($mid_path, $chmod);
}
//---------------------------------------------------------------
// embeds Standard MIDI File (according to template)
//---------------------------------------------------------------
function playMidFile($file,$visible=true,$autostart=true,$loop=true,$player='default'){
include('player/'.$player.'.tpl.php');
}
//---------------------------------------------------------------
// starts download of Standard MIDI File, either from memory or from the server's filesystem
// ATTENTION: order of params swapped, so $file can be omitted to directly start download
//---------------------------------------------------------------
function downloadMidFile($output, $file=false){
ob_start("ob_gzhandler"); // for compressed output...
//$mime_type = 'audio/midi';
$mime_type = 'application/octetstream'; // force download
header('Content-Type: '.$mime_type);
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename="'.$output.'"');
header('Pragma: no-cache');
if ($file){
$d=fopen($file,"rb");
fpassthru($d);
@fclose($d);
}else
echo $this->getMid();
exit();
}
//************************************************** *************
// PUBLIC UTILITIES
//************************************************** *************
//---------------------------------------------------------------
// returns list of standard instrument names
//---------------------------------------------------------------
function getInstrumentList(){
return array('Piano','Bright Piano','Electric Grand','Honky Tonk Piano','Electric Piano 1','Electric Piano 2','Harpsichord','Clavinet','Celesta','Glockenspie l','Music Box','Vibraphone','Marimba','Xylophone','Tubular Bell','Dulcimer','Hammond Organ','Perc Organ','Rock Organ','Church Organ','Reed Organ','Accordion','Harmonica','Tango Accordion','Nylon Str Guitar','Steel String Guitar','Jazz Electric Gtr','Clean Guitar','Muted Guitar','Overdrive Guitar','Distortion Guitar','Guitar Harmonics','Acoustic Bass','Fingered Bass','Picked Bass','Fretless Bass','Slap Bass 1','Slap Bass 2','Syn Bass 1','Syn Bass 2','Violin','Viola','Cello','Contrabass','Tremolo Strings','Pizzicato Strings','Orchestral Harp','Timpani','Ensemble Strings','Slow Strings','Synth Strings 1','Synth Strings 2','Choir Aahs','Voice Oohs','Syn Choir','Orchestra Hit','Trumpet','Trombone','Tuba','Muted Trumpet','French Horn','Brass Ensemble','Syn Brass 1','Syn Brass 2','Soprano Sax','Alto Sax','Tenor Sax','Baritone Sax','Oboe','English Horn','Bassoon','Clarinet','Piccolo','Flute','Reco rder','Pan Flute','Bottle Blow','Shakuhachi','Whistle','Ocarina','Syn Square Wave','Syn Saw Wave','Syn Calliope','Syn Chiff','Syn Charang','Syn Voice','Syn Fifths Saw','Syn Brass and Lead','Fantasia','Warm Pad','Polysynth','Space Vox','Bowed Glass','Metal Pad','Halo Pad','Sweep Pad','Ice Rain','Soundtrack','Crystal','Atmosphere','Brightn ess','Goblins','Echo Drops','Sci Fi','Sitar','Banjo','Shamisen','Koto','Kalimba','B ag Pipe','Fiddle','Shanai','Tinkle Bell','Agogo','Steel Drums','Woodblock','Taiko Drum','Melodic Tom','Syn Drum','Reverse Cymbal','Guitar Fret Noise','Breath Noise','Seashore','Bird','Telephone','Helicopter', 'Applause','Gunshot');
}
//---------------------------------------------------------------
// returns list of drumset instrument names
//---------------------------------------------------------------
function getDrumset(){
return array(
35=>'Acoustic Bass Drum',
36=>'Bass Drum 1',
37=>'Side Stick',
38=>'Acoustic Snare',
39=>'Hand Clap',
40=>'Electric Snare',
41=>'Low Floor Tom',
42=>'Closed Hi-Hat',
43=>'High Floor Tom',
44=>'Pedal Hi-Hat',
45=>'Low Tom',
46=>'Open Hi-Hat',
47=>'Low Mid Tom',
48=>'High Mid Tom',
49=>'Crash Cymbal 1',
50=>'High Tom',
51=>'Ride Cymbal 1',
52=>'Chinese Cymbal',
53=>'Ride Bell',
54=>'Tambourine',
55=>'Splash Cymbal',
56=>'Cowbell',
57=>'Crash Cymbal 2',
58=>'Vibraslap',
59=>'Ride Cymbal 2',
60=>'High Bongo',
61=>'Low Bongo',
62=>'Mute High Conga',
63=>'Open High Conga',
64=>'Low Conga',
65=>'High Timbale',
66=>'Low Timbale',
//35..66
67=>'High Agogo',
68=>'Low Agogo',
69=>'Cabase',
70=>'Maracas',
71=>'Short Whistle',
72=>'Long Whistle',
73=>'Short Guiro',
74=>'Long Guiro',
75=>'Claves',
76=>'High Wood Block',
77=>'Low Wood Block',
78=>'Mute Cuica',
79=>'Open Cuica',
80=>'Mute Triangle',
81=>'Open Triangle');
}
//---------------------------------------------------------------
// returns list of standard drum kit names
//---------------------------------------------------------------
function getDrumkitList(){
return array(
1 => 'Dry',
9 => 'Room',
19 => 'Power',
25 => 'Electronic',
33 => 'Jazz',
41 => 'Brush',
57 => 'SFX',
128 => 'Default'
);
}
//---------------------------------------------------------------
// returns list of note names
//---------------------------------------------------------------
function getNoteList(){
//note 69 (A6) = A440
//note 60 (C6) = Middle C
return array(
//Do Re Mi Fa So La Ti
'C0', 'Cs0', 'D0', 'Ds0', 'E0', 'F0', 'Fs0', 'G0', 'Gs0', 'A0', 'As0', 'B0',
'C1', 'Cs1', 'D1', 'Ds1', 'E1', 'F1', 'Fs1', 'G1', 'Gs1', 'A1', 'As1', 'B1',
'C2', 'Cs2', 'D2', 'Ds2', 'E2', 'F2', 'Fs2', 'G2', 'Gs2', 'A2', 'As2', 'B2',
'C3', 'Cs3', 'D3', 'Ds3', 'E3', 'F3', 'Fs3', 'G3', 'Gs3', 'A3', 'As3', 'B3',
'C4', 'Cs4', 'D4', 'Ds4', 'E4', 'F4', 'Fs4', 'G4', 'Gs4', 'A4', 'As4', 'B4',
'C5', 'Cs5', 'D5', 'Ds5', 'E5', 'F5', 'Fs5', 'G5', 'Gs5', 'A5', 'As5', 'B5',
'C6', 'Cs6', 'D6', 'Ds6', 'E6', 'F6', 'Fs6', 'G6', 'Gs6', 'A6', 'As6', 'B6',
'C7', 'Cs7', 'D7', 'Ds7', 'E7', 'F7', 'Fs7', 'G7', 'Gs7', 'A7', 'As7', 'B7',
'C8', 'Cs8', 'D8', 'Ds8', 'E8', 'F8', 'Fs8', 'G8', 'Gs8', 'A8', 'As8', 'B8',
'C9', 'Cs9', 'D9', 'Ds9', 'E9', 'F9', 'Fs9', 'G9', 'Gs9', 'A9', 'As9', 'B9',
'C10','Cs10','D10','Ds10','E10','F10','Fs10','G10' );
}
/************************************************** **************************
* *
* Private methods *
* *
************************************************** **************************/
//---------------------------------------------------------------
// returns time code of message string
//---------------------------------------------------------------
function _getTime($msgStr){
return (int) strtok($msgStr,' ');
}
//---------------------------------------------------------------
// returns binary code for message string
//---------------------------------------------------------------
function _getMsgStr($line){
$msg = explode(' ',$line);
switch($msg[1]){
case 'PrCh': // 0x0C
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // prog
return chr(0xC0+$ch-1).chr($p);
break;
case 'On': // 0x09
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // note
eval("\$".$msg[4].';'); // vel
return chr(0x90+$ch-1).chr($n).chr($v);
break;
case 'Off': // 0x08
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // note
eval("\$".$msg[4].';'); // vel
return chr(0x80+$ch-1).chr($n).chr($v);
break;
case 'PoPr': // 0x0A = PolyPressure
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // note
eval("\$".$msg[4].';'); // val
return chr(0xA0+$ch-1).chr($n).chr($v);
break;
case 'Par': // 0x0B = ControllerChange
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // controller
eval("\$".$msg[4].';'); // val
return chr(0xB0+$ch-1).chr($c).chr($v);
break;
case 'ChPr': // 0x0D = ChannelPressure
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // val
return chr(0xD0+$ch-1).chr($v);
break;
case 'Pb': // 0x0E = PitchBend
eval("\$".$msg[2].';'); // chan
eval("\$".$msg[3].';'); // val (2 Bytes!)
$a = $v & 0x7f; // Bits 0..6
$b = ($v >> 7) & 0x7f; // Bits 7..13
return chr(0xE0+$ch-1).chr($a).chr($b);
break;
// META EVENTS
case 'Seqnr': // 0x00 = sequence_number
$num = chr($msg[2]);
if ($msg[2]>255) _err("code broken around Seqnr event");
return "\xFF\x00\x02\x00$num";
break;
case 'Meta':
$type = $msg[2];
switch ($type){
case 'Text': //0x01: // Meta Text
case 'Copyright': //0x02: // Meta Copyright
case 'TrkName': //0x03: // Meta TrackName ???SeqName???
case 'InstrName': //0x04: // Meta InstrumentName
case 'Lyric': //0x05: // Meta Lyrics
case 'Marker': //0x06: // Meta Marker
case 'Cue': //0x07: // Meta Cue
$texttypes = array('Text','Copyright','TrkName','InstrName','Ly ric','Marker','Cue');
$byte = chr(array_search($type,$texttypes)+1);
$start = strpos($line,'"')+1;
$end = strrpos($line,'"');
$txt = substr($line,$start,$end-$start);
// MM: Todo: Len could also be more than one Byte (variable length; see. "Sequence/Track name specification)
$len = chr(strlen($txt));
if ($len>127) _err("code broken (write varLen-Meta)");
return "\xFF$byte$len$txt";
break;
case 'TrkEnd': //0x2F
return "\xFF\x2F\x00";
break;
case '0x20': // 0x20 = ChannelPrefix
$v = chr($msg[3]);
return "\xFF\x20\x01$v";
break;
case '0x21': // 0x21 = ChannelPrefixOrPort
$v = chr($msg[3]);
return "\xFF\x21\x01$v";
break;
default:
_err("unknown meta event: $type");
exit();
}
break;
case 'Tempo': // 0x51
$tempo = _getBytes((int)$msg[2],3);
return "\xFF\x51\x03$tempo";
break;
case 'SMPTE': // 0x54 = SMPTE offset
$h = chr($msg[2]);
$m = chr($msg[3]);
$s = chr($msg[4]);
$f = chr($msg[5]);
$fh = chr($msg[6]);
return "\xFF\x54\x05$h$m$s$f$fh";
break;
case 'TimeSig': // 0x58
$zt = explode('/',$msg[2]);
$z = chr($zt[0]);
$t = chr(log($zt[1])/log(2));
$mc = chr($msg[3]);
$c = chr($msg[4]);
return "\xFF\x58\x04$z$t$mc$c";
break;
case 'KeySig': // 0x59
$vz = chr($msg[2]);
$g = chr(($msg[3]=='major')?0:1);
return "\xFF\x59\x02$vz$g";
break;
case 'SeqSpec': // 0x7F = Sequencer specific data (Bs: 0 SeqSpec 00 00 41)
$cnt = count($msg)-2;
$data = '';
for ($i=0;$i<$cnt;$i++)
$data.=_hex2bin($msg[$i+2]);
// MM: ToDo: Len >127 has to be variable length-encoded !!!
$len = chr(strlen($data));
if ($len>127) _err('code broken (write varLen-Meta)');
return "\xFF\x7F$len$data";
break;
case 'SysEx': // 0xF0 = SysEx
$start = strpos($line,'f0');
$end = strrpos($line,'f7');
$data = substr($line,$start+3,$end-$start-1);
$data = _hex2bin(str_replace(' ','',$data));
$len = chr(strlen($data));
return "\xF0$len".$data;
break;
default:
@_err('unknown event: '.$msg[1]);
exit();
}
}
//---------------------------------------------------------------
// converts binary track string to track (list of msg strings)
//---------------------------------------------------------------
function _parseTrack($binStr, $tn){
//$trackLen2 = ((( (( (ord($binStr[0]) << 8) | ord($binStr[1]))<<8) | ord($binStr[2]) ) << 8 ) | ord($binStr[3]) );
//$trackLen2 += 4;
$trackLen = strlen($binStr);
// MM: ToDo: Warn if trackLen and trackLen2 are different!!!
// if ($trackLen != $trackLen2) { echo "Warning: TrackLength is corrupt ($trackLen != $trackLen2)! <BR>"; }
$p=4;
$time = 0;
$track = array();
while ($p<$trackLen){
// timedelta
$dt = _readVarLen($binStr,$p);
$time += $dt;
$byte = ord($binStr[$p]);
$high = $byte >> 4;
$low = $byte - $high*16;
switch($high){
case 0x0C: //PrCh = ProgramChange
$chan = $low+1;
$prog = ord($binStr[$p+1]);
$last = 'PrCh';
$track[] = "$time PrCh ch=$chan p=$prog";
$p+=2;
break;
case 0x09: //On
$chan = $low+1;
$note = ord($binStr[$p+1]);
$vel = ord($binStr[$p+2]);
$last = 'On';
$track[] = "$time On ch=$chan n=$note v=$vel";
$p+=3;
break;
case 0x08: //Off
$chan = $low+1;
$note = ord($binStr[$p+1]);
$vel = ord($binStr[$p+2]);
$last = 'Off';
$track[] = "$time Off ch=$chan n=$note v=$vel";
$p+=3;
break;
case 0x0A: //PoPr = PolyPressure
$chan = $low+1;
$note = ord($binStr[$p+1]);
$val = ord($binStr[$p+2]);
$last = 'PoPr';
$track[] = "$time PoPr ch=$chan n=$note v=$val";
$p+=3;
break;
case 0x0B: //Par = ControllerChange
$chan = $low+1;
$c = ord($binStr[$p+1]);
$val = ord($binStr[$p+2]);
$last = 'Par';
$track[] = "$time Par ch=$chan c=$c v=$val";
$p+=3;
break;
case 0x0D: //ChPr = ChannelPressure
$chan = $low+1;
$val = ord($binStr[$p+1]);
$last = 'ChPr';
$track[] = "$time ChPr ch=$chan v=$val";
$p+=2;
break;
case 0x0E: //Pb = PitchBend
$chan = $low+1;
$val = (ord($binStr[$p+1]) & 0x7F) | (((ord($binStr[$p+2])) & 0x7F) << 7);
$last = 'Pb';
$track[] = "$time Pb ch=$chan v=$val";
$p+=3;
break;
default:
switch($byte){
case 0xFF: // Meta
$meta = ord($binStr[$p+1]);
switch ($meta){
case 0x00: // sequence_number
$tmp = ord($binStr[$p+2]);
if ($tmp==0x00) { $num = $tn; $p+=3;}
else { $num= 1; $p+=5; }
$track[] = "$time Seqnr $num";
break;
case 0x01: // Meta Text
case 0x02: // Meta Copyright
case 0x03: // Meta TrackName ???sequence_name???
case 0x04: // Meta InstrumentName
case 0x05: // Meta Lyrics
case 0x06: // Meta Marker
case 0x07: // Meta Cue
$texttypes = array('Text','Copyright','TrkName','InstrName','Ly ric','Marker','Cue');
$type = $texttypes[$meta-1];
$p +=2;
$len = _readVarLen($binStr, $p);
if (($len+$p) > $trackLen) _err("Meta $type has corrupt variable length field ($len) [track: $tn dt: $dt]");
$txt = substr($binStr, $p,$len);
$p+=$len;
break;
case 0x20: // ChannelPrefix
if (ord($binStr[$p+2])==0){
$p+=3;
}else{
$chan = ord($binStr[$p+3]);
if ($chan<10) $chan = '0'.$chan;//???
$last = 'MetaChannelPrefix';
$p+=4;
}
break;
case 0x21: // ChannelPrefixOrPort
$chan = ord($binStr[$p+3]);
if ($chan<10) $chan = '0'.$chan;//???
$p+=4;
break;
case 0x2F: // Meta TrkEnd
return $track;//ignore rest
break;
case 0x51: // Tempo
$tempo = ord($binStr[$p+3])*256*256 + ord($binStr[$p+4])*256 + ord($binStr[$p+5]);
if ($tn==0 && $time==0) {
$this->tempo = $tempo;// ???
$this->tempoMsgNum = count($track) - 1;
}
$p+=6;
break;
case 0x54: // SMPTE offset
$len = ord($binStr[$p+2]); # should be: 0x05 => $p+=8;
$h = $len>0 ? ord($binStr[$p+3]) : 0;
$m = $len>1 ? ord($binStr[$p+4]) : 0;
$s = $len>2 ? ord($binStr[$p+5]) : 0;
$f = $len>3 ? ord($binStr[$p+6]) : 0;
$fh = $len>4 ? ord($binStr[$p+7]) : 0;