-
Notifications
You must be signed in to change notification settings - Fork 0
/
MidiFile.cpp
3235 lines (2604 loc) · 77.7 KB
/
MidiFile.cpp
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
//
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Fri Nov 26 14:12:01 PST 1999
// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std;
// Filename: midifile/src/MidiFile.cpp
// Website: http://midifile.sapp.org
// Syntax: C++11
// vim: ts=3 noexpandtab
//
// Description: A class which can read/write Standard MIDI files.
// MIDI data is stored by track in an array. This
// class is used for example in the MidiPerform class.
//
#include "MidiFile.h"
#include "Binasc.h"
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <iterator>
#include <algorithm>
namespace smf {
//////////////////////////////
//
// MidiFile::MidiFile -- Constuctor.
//
MidiFile::MidiFile(void) {
m_events.resize(1);
for (int i=0; i<(int)m_events.size(); i++) {
m_events[i] = new MidiEventList;
}
}
MidiFile::MidiFile(const std::string& filename) {
m_events.resize(1);
for (int i=0; i<(int)m_events.size(); i++) {
m_events[i] = new MidiEventList;
}
read(filename);
}
MidiFile::MidiFile(std::istream& input) {
m_events.resize(1);
for (int i=0; i<(int)m_events.size(); i++) {
m_events[i] = new MidiEventList;
}
read(input);
}
MidiFile::MidiFile(const MidiFile& other) {
*this = other;
}
MidiFile::MidiFile(MidiFile&& other) {
*this = std::move(other);
}
//////////////////////////////
//
// MidiFile::~MidiFile -- Deconstructor.
//
MidiFile::~MidiFile() {
m_readFileName.clear();
clear();
if (m_events[0] != NULL) {
delete m_events[0];
m_events[0] = NULL;
}
m_events.resize(0);
m_rwstatus = false;
m_timemap.clear();
m_timemapvalid = 0;
}
//////////////////////////////
//
// MidiFile::operator= -- Copying another
//
MidiFile& MidiFile::operator=(const MidiFile& other) {
if (this == &other) {
return *this;
}
m_events.reserve(other.m_events.size());
auto it = other.m_events.begin();
std::generate_n(std::back_inserter(m_events), other.m_events.size(),
[&]()->MidiEventList* {
return new MidiEventList(**it++);
}
);
m_ticksPerQuarterNote = other.m_ticksPerQuarterNote;
m_theTrackState = other.m_theTrackState;
m_theTimeState = other.m_theTimeState;
m_readFileName = other.m_readFileName;
m_timemapvalid = other.m_timemapvalid;
m_timemap = other.m_timemap;
m_rwstatus = other.m_rwstatus;
if (other.m_linkedEventsQ) {
linkEventPairs();
}
return *this;
}
MidiFile& MidiFile::operator=(MidiFile&& other) {
m_events = std::move(other.m_events);
m_linkedEventsQ = other.m_linkedEventsQ;
other.m_linkedEventsQ = false;
other.m_events.clear();
other.m_events.emplace_back(new MidiEventList);
m_ticksPerQuarterNote = other.m_ticksPerQuarterNote;
m_theTrackState = other.m_theTrackState;
m_theTimeState = other.m_theTimeState;
m_readFileName = other.m_readFileName;
m_timemapvalid = other.m_timemapvalid;
m_timemap = other.m_timemap;
m_rwstatus = other.m_rwstatus;
return *this;
}
///////////////////////////////////////////////////////////////////////////
//
// reading/writing functions --
//
//////////////////////////////
//
// MidiFile::read -- Parse a Standard MIDI File or ASCII-encoded Standard MIDI
// File and store its contents in the object.
//
bool MidiFile::read(const std::string& filename) {
m_timemapvalid = 0;
setFilename(filename);
m_rwstatus = true;
std::fstream input;
input.open(filename.c_str(), std::ios::binary | std::ios::in);
if (!input.is_open()) {
m_rwstatus = false;
return m_rwstatus;
}
m_rwstatus = read(input);
return m_rwstatus;
}
//
// istream version of read().
//
bool MidiFile::read(std::istream& input) {
m_rwstatus = true;
if (input.peek() != 'M') {
// If the first byte in the input stream is not 'M', then presume that
// the MIDI file is in the binasc format which is an ASCII representation
// of the MIDI file. Convert the binasc content into binary content and
// then continue reading with this function.
std::stringstream binarydata;
Binasc binasc;
binasc.writeToBinary(binarydata, input);
binarydata.seekg(0, std::ios_base::beg);
if (binarydata.peek() != 'M') {
std::cout << "Bad MIDI data input" << std::endl;
m_rwstatus = false;
return m_rwstatus;
} else {
m_rwstatus = readSmf(binarydata);
return m_rwstatus;
}
} else {
m_rwstatus = readSmf(input);
return m_rwstatus;
}
}
//////////////////////////////
//
// MidiFile::readSmf -- Parse a Standard MIDI File and store its contents
// in the object.
//
bool MidiFile::readSmf(const std::string& filename) {
m_timemapvalid = 0;
setFilename(filename);
m_rwstatus = true;
std::fstream input;
input.open(filename.c_str(), std::ios::binary | std::ios::in);
if (!input.is_open()) {
m_rwstatus = false;
return m_rwstatus;
}
m_rwstatus = readSmf(input);
return m_rwstatus;
}
//////////////////////////////
//
// MidiFile::readSmf -- Parse a Standard MIDI File and store its contents in the object.
//
bool MidiFile::readSmf(std::istream& input) {
m_rwstatus = true;
std::string filename = getFilename();
int character;
// uchar buffer[123456] = {0};
ulong longdata;
ushort shortdata;
// Read the MIDI header (4 bytes of ID, 4 byte data size,
// anticipated 6 bytes of data.
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'M' at first byte, but found nothing." << std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'M') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'M' at first byte but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'T' at second byte, but found nothing." << std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'T') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'T' at second byte but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'h' at third byte, but found nothing." << std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'h') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'h' at third byte but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'd' at fourth byte, but found nothing." << std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'd') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'd' at fourth byte but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
// read header size (allow larger header size?)
longdata = readLittleEndian4Bytes(input);
if (longdata != 6) {
std::cout << "File " << filename
<< " is not a MIDI 1.0 Standard MIDI file." << std::endl;
std::cout << "The header size is " << longdata << " bytes." << std::endl;
m_rwstatus = false; return m_rwstatus;
}
// Header parameter #1: format type
int type;
shortdata = readLittleEndian2Bytes(input);
switch (shortdata) {
case 0:
type = 0;
break;
case 1:
type = 1;
break;
case 2:
// Type-2 MIDI files should probably be allowed as well,
// but I have never seen one in the wild to test with.
default:
std::cout << "Error: cannot handle a type-" << shortdata
<< " MIDI file" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
// Header parameter #2: track count
int tracks;
shortdata = readLittleEndian2Bytes(input);
if (type == 0 && shortdata != 1) {
std::cout << "Error: Type 0 MIDI file can only contain one track" << std::endl;
std::cout << "Instead track count is: " << shortdata << std::endl;
m_rwstatus = false; return m_rwstatus;
} else {
tracks = shortdata;
}
clear();
if (m_events[0] != NULL) {
delete m_events[0];
}
m_events.resize(tracks);
for (int z=0; z<tracks; z++) {
m_events[z] = new MidiEventList;
m_events[z]->reserve(10000); // Initialize with 10,000 event storage.
m_events[z]->clear();
}
// Header parameter #3: Ticks per quarter note
shortdata = readLittleEndian2Bytes(input);
if (shortdata >= 0x8000) {
int framespersecond = 255 - ((shortdata >> 8) & 0x00ff) + 1;
int subframes = shortdata & 0x00ff;
switch (framespersecond) {
case 25: framespersecond = 25; break;
case 24: framespersecond = 24; break;
case 29: framespersecond = 29; break; // really 29.97 for color television
case 30: framespersecond = 30; break;
default:
std::cout << "Warning: unknown FPS: " << framespersecond << std::endl;
std::cout << "Using non-standard FPS: " << framespersecond << std::endl;
}
m_ticksPerQuarterNote = framespersecond * subframes;
// std::cout << "SMPTE ticks: " << m_ticksPerQuarterNote << " ticks/sec" << std::endl;
// std::cout << "SMPTE frames per second: " << framespersecond << std::endl;
// std::cout << "SMPTE subframes per frame: " << subframes << std::endl;
} else {
m_ticksPerQuarterNote = shortdata;
}
//////////////////////////////////////////////////
//
// now read individual tracks:
//
uchar runningCommand;
MidiEvent event;
std::vector<uchar> bytes;
int xstatus;
for (int i=0; i<tracks; i++) {
runningCommand = 0;
// std::cout << "\nReading Track: " << i + 1 << flush;
// read track header...
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'M' at first byte in track, but found nothing."
<< std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'M') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'M' at first byte in track but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'T' at second byte in track, but found nothing."
<< std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'T') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'T' at second byte in track but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'r' at third byte in track, but found nothing."
<< std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'r') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'r' at third byte in track but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
character = input.get();
if (character == EOF) {
std::cout << "In file " << filename << ": unexpected end of file." << std::endl;
std::cout << "Expecting 'k' at fourth byte in track, but found nothing."
<< std::endl;
m_rwstatus = false; return m_rwstatus;
} else if (character != 'k') {
std::cout << "File " << filename << " is not a MIDI file" << std::endl;
std::cout << "Expecting 'k' at fourth byte in track but got '"
<< (char)character << "'" << std::endl;
m_rwstatus = false; return m_rwstatus;
}
// Now read track chunk size and throw it away because it is
// not really necessary since the track MUST end with an
// end of track meta event, and many MIDI files found in the wild
// do not correctly give the track size.
longdata = readLittleEndian4Bytes(input);
// Set the size of the track allocation so that it might
// approximately fit the data.
m_events[i]->reserve((int)longdata/2);
m_events[i]->clear();
// Read MIDI events in the track, which are pairs of VLV values
// and then the bytes for the MIDI message. Running status messags
// will be filled in with their implicit command byte.
// The timestamps are converted from delta ticks to absolute ticks,
// with the absticks variable accumulating the VLV tick values.
int absticks = 0;
while (!input.eof()) {
longdata = readVLValue(input);
absticks += longdata;
xstatus = extractMidiData(input, bytes, runningCommand);
if (xstatus == 0) {
m_rwstatus = false; return m_rwstatus;
}
event.setMessage(bytes);
event.tick = absticks;
event.track = i;
if (bytes[0] == 0xff && bytes[1] == 0x2f) {
// end-of-track message
// comment out the following line if you don't want to see the
// end of track message (which is always required, and will added
// automatically when a MIDI is written, so it is not necessary.
m_events[i]->push_back(event);
break;
}
m_events[i]->push_back(event);
}
}
m_theTimeState = TIME_STATE_ABSOLUTE;
// The original order of the MIDI events is marked with an enumeration which
// allows for reconstruction of the order when merging/splitting tracks to/from
// a type-0 configuration.
markSequence();
return m_rwstatus;
}
//////////////////////////////
//
// MidiFile::write -- write a standard MIDI file to a file or an output
// stream.
//
bool MidiFile::write(const std::string& filename) {
std::fstream output(filename.c_str(), std::ios::binary | std::ios::out);
if (!output.is_open()) {
std::cout << "Error: could not write: " << filename << std::endl;
return false;
}
m_rwstatus = write(output);
output.close();
return m_rwstatus;
}
//
// ostream version of MidiFile::write().
//
bool MidiFile::write(std::ostream& out) {
int oldTimeState = getTickState();
if (oldTimeState == TIME_STATE_ABSOLUTE) {
makeDeltaTicks();
}
// write the header of the Standard MIDI File
char ch;
// 1. The characters "MThd"
ch = 'M'; out << ch;
ch = 'T'; out << ch;
ch = 'h'; out << ch;
ch = 'd'; out << ch;
// 2. write the size of the header (always a "6" stored in unsigned long
// (4 bytes).
ulong longdata = 6;
writeBigEndianULong(out, longdata);
// 3. MIDI file format, type 0, 1, or 2
ushort shortdata;
shortdata = static_cast<ushort>(getNumTracks() == 1 ? 0 : 1);
writeBigEndianUShort(out,shortdata);
// 4. write out the number of tracks.
shortdata = static_cast<ushort>(getNumTracks());
writeBigEndianUShort(out, shortdata);
// 5. write out the number of ticks per quarternote. (avoiding SMTPE for now)
shortdata = static_cast<ushort>(getTicksPerQuarterNote());
writeBigEndianUShort(out, shortdata);
// now write each track.
std::vector<uchar> trackdata;
uchar endoftrack[4] = {0, 0xff, 0x2f, 0x00};
int i, j, k;
int size;
for (i=0; i<getNumTracks(); i++) {
trackdata.reserve(123456); // make the track data larger than
// expected data input
trackdata.clear();
for (j=0; j<(int)m_events[i]->size(); j++) {
if ((*m_events[i])[j].empty()) {
// Don't write empty m_events (probably a delete message).
continue;
}
if ((*m_events[i])[j].isEndOfTrack()) {
// Suppress end-of-track meta messages (one will be added
// automatically after all track data has been written).
continue;
}
writeVLValue((*m_events[i])[j].tick, trackdata);
if (((*m_events[i])[j].getCommandByte() == 0xf0) ||
((*m_events[i])[j].getCommandByte() == 0xf7)) {
// 0xf0 == Complete sysex message (0xf0 is part of the raw MIDI).
// 0xf7 == Raw byte message (0xf7 not part of the raw MIDI).
// Print the first byte of the message (0xf0 or 0xf7), then
// print a VLV length for the rest of the bytes in the message.
// In other words, when creating a 0xf0 or 0xf7 MIDI message,
// do not insert the VLV byte length yourself, as this code will
// do it for you automatically.
trackdata.push_back((*m_events[i])[j][0]); // 0xf0 or 0xf7;
writeVLValue(((int)(*m_events[i])[j].size())-1, trackdata);
for (k=1; k<(int)(*m_events[i])[j].size(); k++) {
trackdata.push_back((*m_events[i])[j][k]);
}
} else {
// non-sysex type of message, so just output the
// bytes of the message:
for (k=0; k<(int)(*m_events[i])[j].size(); k++) {
trackdata.push_back((*m_events[i])[j][k]);
}
}
}
size = (int)trackdata.size();
if ((size < 3) || !((trackdata[size-3] == 0xff)
&& (trackdata[size-2] == 0x2f))) {
trackdata.push_back(endoftrack[0]);
trackdata.push_back(endoftrack[1]);
trackdata.push_back(endoftrack[2]);
trackdata.push_back(endoftrack[3]);
}
// now ready to write to MIDI file.
// first write the track ID marker "MTrk":
ch = 'M'; out << ch;
ch = 'T'; out << ch;
ch = 'r'; out << ch;
ch = 'k'; out << ch;
// A. write the size of the MIDI data to follow:
longdata = (int)trackdata.size();
writeBigEndianULong(out, longdata);
// B. write the actual data
out.write((char*)trackdata.data(), trackdata.size());
}
if (oldTimeState == TIME_STATE_ABSOLUTE) {
makeAbsoluteTicks();
}
return true;
}
//////////////////////////////
//
// MidiFile::writeHex -- print the Standard MIDI file as a list of
// ASCII Hex bytes, formatted 25 to a line by default, and
// two digits for each hex byte code. If the input width is 0,
// then don't wrap lines.
//
// default value: width=25
//
bool MidiFile::writeHex(const std::string& filename, int width) {
std::fstream output(filename.c_str(), std::ios::out);
if (!output.is_open()) {
std::cout << "Error: could not write: " << filename << std::endl;
return false;
}
m_rwstatus = writeHex(output, width);
output.close();
return m_rwstatus;
}
//
// ostream version of MidiFile::writeHex().
//
bool MidiFile::writeHex(std::ostream& out, int width) {
std::stringstream tempstream;
MidiFile::write(tempstream);
int len = (int)tempstream.str().length();
int wordcount = 1;
int linewidth = width >= 0 ? width : 25;
for (int i=0; i<len; i++) {
int value = (unsigned char)tempstream.str()[i];
out << std::hex << std::setw(2) << std::setfill('0') << value;
if (linewidth) {
if (i < len - 1) {
out << ((wordcount % linewidth) ? ' ' : '\n');
}
wordcount++;
} else {
// print with no line breaks
if (i < len - 1) {
out << ' ';
}
}
}
if (linewidth) {
out << '\n';
}
return true;
}
//////////////////////////////
//
// MidiFile::writeBinasc -- write a standard MIDI file from data into
// the binasc format (ASCII version of the MIDI file).
//
bool MidiFile::writeBinasc(const std::string& filename) {
std::fstream output(filename.c_str(), std::ios::out);
if (!output.is_open()) {
std::cout << "Error: could not write: " << filename << std::endl;
return false;
}
m_rwstatus = writeBinasc(output);
output.close();
return m_rwstatus;
}
//
// ostream version of MidiFile::writeBinasc().
//
bool MidiFile::writeBinasc(std::ostream& output) {
std::stringstream binarydata;
m_rwstatus = write(binarydata);
if (m_rwstatus == false) {
return false;
}
Binasc binasc;
binasc.setMidiOn();
binarydata.seekg(0, std::ios_base::beg);
binasc.readFromBinary(output, binarydata);
return true;
}
//////////////////////////////
//
// MidiFile::writeBinascWithComents -- write a standard MIDI
// file from data into the binasc format (ASCII version
// of the MIDI file), including commentary about the MIDI messages.
//
bool MidiFile::writeBinascWithComments(const std::string& filename) {
std::fstream output(filename.c_str(), std::ios::out);
if (!output.is_open()) {
std::cout << "Error: could not write: " << filename << std::endl;
return 0;
}
m_rwstatus = writeBinascWithComments(output);
output.close();
return m_rwstatus;
}
//
// ostream version of MidiFile::writeBinascWithComments().
//
bool MidiFile::writeBinascWithComments(std::ostream& output) {
std::stringstream binarydata;
m_rwstatus = write(binarydata);
if (m_rwstatus == false) {
return false;
}
Binasc binasc;
binasc.setMidiOn();
binasc.setCommentsOn();
binarydata.seekg(0, std::ios_base::beg);
binasc.readFromBinary(output, binarydata);
return true;
}
//////////////////////////////
//
// MidiFile::status -- return the success flag from the last read or
// write (writeHex, writeBinasc).
//
bool MidiFile::status(void) const {
return m_rwstatus;
}
///////////////////////////////////////////////////////////////////////////
//
// track-related functions --
//
//////////////////////////////
//
// MidiFile::operator[] -- return the event list for the specified track.
//
MidiEventList& MidiFile::operator[](int aTrack) {
return *m_events[aTrack];
}
const MidiEventList& MidiFile::operator[](int aTrack) const {
return *m_events[aTrack];
}
//////////////////////////////
//
// MidiFile::getTrackCount -- return the number of tracks in
// the Midi File.
//
int MidiFile::getTrackCount(void) const {
return (int)m_events.size();
}
//
// Alias for getTrackCount()
//
int MidiFile::getNumTracks(void) const {
return getTrackCount();
}
//
// Alias for getTrackCount()
//
int MidiFile::size(void) const {
return getTrackCount();
}
//////////////////////////////
//
// MidiFile::removeEmpties -- Remove any MIDI message that
// contains no bytes.
//
void MidiFile::removeEmpties(void) {
for (int i=0; i<(int)m_events.size(); i++) {
m_events[i]->removeEmpties();
}
}
//////////////////////////////
//
// MidiFile::markSequence -- Assign a sequence serial number to
// every MidiEvent in every track in the MIDI file. This is
// useful if you want to preseve the order of MIDI messages in
// a track when they occur at the same tick time. Particularly
// for use with joinTracks() or sortTracks(). markSequence will
// be done automatically when a MIDI file is read, in case the
// ordering of m_events occuring at the same time is important.
// Use clearSequence() to use the default sorting behavior of
// sortTracks().
//
void MidiFile::markSequence(void) {
int sequence = 1;
for (int i=0; i<getTrackCount(); i++) {
sequence = operator[](i).markSequence(sequence);
}
}
//
// MidiFile::markSequence -- default value: sequence = 1.
//
void MidiFile::markSequence(int track, int sequence) {
if ((track >= 0) && (track < getTrackCount())) {
operator[](track).markSequence(sequence);
} else {
std::cout << "Warning: track " << track << " does not exist." << std::endl;
}
}
//////////////////////////////
//
// MidiFile::clearSequence -- Remove any seqence serial numbers from
// MidiEvents in the MidiFile. This will cause the default ordering by
// sortTracks() to be used, in which case the ordering of MidiEvents
// occurring at the same tick may switch their ordering.
//
void MidiFile::clearSequence(void) {
for (int i=0; i<getTrackCount(); i++) {
operator[](i).clearSequence();
}
}
void MidiFile::clearSequence(int track) {
if ((track >= 0) && (track < getTrackCount())) {
operator[](track).clearSequence();
} else {
std::cout << "Warning: track " << track << " does not exist." << std::endl;
}
}
//////////////////////////////
//
// MidiFile::joinTracks -- Interleave the data from all tracks,
// but keeping the identity of the tracks unique so that
// the function splitTracks can be called to split the
// tracks into separate units again. The style of the
// MidiFile when read from a file is with tracks split.
// The original track index is stored in the MidiEvent::track
// variable.
//
void MidiFile::joinTracks(void) {
if (getTrackState() == TRACK_STATE_JOINED) {
return;
}
if (getNumTracks() == 1) {
m_theTrackState = TRACK_STATE_JOINED;
return;
}
MidiEventList* joinedTrack;
joinedTrack = new MidiEventList;
int messagesum = 0;
int length = getNumTracks();
int i, j;
for (i=0; i<length; i++) {
messagesum += (*m_events[i]).size();
}
joinedTrack->reserve((int)(messagesum + 32 + messagesum * 0.1));
int oldTimeState = getTickState();
if (oldTimeState == TIME_STATE_DELTA) {
makeAbsoluteTicks();
}
for (i=0; i<length; i++) {
for (j=0; j<(int)m_events[i]->size(); j++) {
joinedTrack->push_back_no_copy(&(*m_events[i])[j]);
}
}
clear_no_deallocate();
delete m_events[0];
m_events.resize(0);
m_events.push_back(joinedTrack);
sortTracks();
if (oldTimeState == TIME_STATE_DELTA) {
makeDeltaTicks();
}
m_theTrackState = TRACK_STATE_JOINED;
}
//////////////////////////////
//
// MidiFile::splitTracks -- Take the joined tracks and split them
// back into their separate track identities.
//
void MidiFile::splitTracks(void) {
if (getTrackState() == TRACK_STATE_SPLIT) {
return;
}
int oldTimeState = getTickState();
if (oldTimeState == TIME_STATE_DELTA) {
makeAbsoluteTicks();
}
int maxTrack = 0;
int i;
int length = m_events[0]->size();
for (i=0; i<length; i++) {
if ((*m_events[0])[i].track > maxTrack) {
maxTrack = (*m_events[0])[i].track;
}
}
int trackCount = maxTrack + 1;
if (trackCount <= 1) {
return;
}
MidiEventList* olddata = m_events[0];
m_events[0] = NULL;
m_events.resize(trackCount);
for (i=0; i<trackCount; i++) {
m_events[i] = new MidiEventList;
}
for (i=0; i<length; i++) {
int trackValue = (*olddata)[i].track;
m_events[trackValue]->push_back_no_copy(&(*olddata)[i]);
}
olddata->detach();
delete olddata;
if (oldTimeState == TIME_STATE_DELTA) {
makeDeltaTicks();
}
m_theTrackState = TRACK_STATE_SPLIT;
}
//////////////////////////////
//
// MidiFile::splitTracksByChannel -- Take the joined tracks and split them
// back into their separate track identities.
//
void MidiFile::splitTracksByChannel(void) {
joinTracks();
if (getTrackState() == TRACK_STATE_SPLIT) {
return;
}
int oldTimeState = getTickState();