-
Notifications
You must be signed in to change notification settings - Fork 128
/
midi.d
1273 lines (1074 loc) · 29.8 KB
/
midi.d
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
/**
This file is a port of some old C code I had for reading and writing .mid files. Not much docs, but viewing the source may be helpful.
I'll eventually refactor it into something more D-like
History:
Written in C in August 2008
Minimally ported to D in September 2017
Updated May 2020 with significant changes.
*/
module arsd.midi;
/+
So the midi ticks are defined in terms of per quarter note so that's good stuff.
If you're reading live though you have milliseconds, and probably want to round them
off a little to fit the beat.
+/
import core.time;
version(NewMidiDemo)
void main(string[] args) {
auto f = new MidiFile();
import std.file;
//f.loadFromBytes(cast(ubyte[]) read("test.mid"));
f.loadFromBytes(cast(ubyte[]) read(args[1]));
import arsd.simpleaudio;
import core.thread;
auto o = MidiOutput(0);
setSigIntHandler();
scope(exit) {
o.silenceAllNotes();
o.reset();
restoreSigIntHandler();
}
import std.stdio : writeln;
foreach(item; f.playbackStream) {
if(interrupted) return;
Thread.sleep(item.wait);
if(!item.event.isMeta)
o.writeMidiMessage(item.event.status, item.event.data1, item.event.data2);
else
writeln(item);
}
return;
auto t = new MidiTrack();
auto t2 = new MidiTrack();
f.tracks ~= t;
f.tracks ~= t2;
t.events ~= MidiEvent(0, 0x90, C, 127);
t.events ~= MidiEvent(256, 0x90, C, 0);
t.events ~= MidiEvent(256, 0x90, D, 127);
t.events ~= MidiEvent(256, 0x90, D, 0);
t.events ~= MidiEvent(256, 0x90, E, 127);
t.events ~= MidiEvent(256, 0x90, E, 0);
t.events ~= MidiEvent(256, 0x90, F, 127);
t.events ~= MidiEvent(0, 0xff, 0x05, 0 /* unused */, ['h', 'a', 'm']);
t.events ~= MidiEvent(256, 0x90, F, 0);
t2.events ~= MidiEvent(0, (MIDI_EVENT_PROGRAM_CHANGE << 4) | 0x01, 68);
t2.events ~= MidiEvent(128, 0x91, E, 127);
t2.events ~= MidiEvent(0, 0xff, 0x05, 0 /* unused */, ['a', 'd', 'r']);
t2.events ~= MidiEvent(1024, 0x91, E, 0);
write("test.mid", f.toBytes());
}
@safe:
class MidiFile {
///
ubyte[] toBytes() {
MidiWriteBuffer buf;
buf.write("MThd");
buf.write4(6);
buf.write2(format);
buf.write2(cast(ushort) tracks.length);
buf.write2(timing);
foreach(track; tracks) {
auto data = track.toBytes();
buf.write("MTrk");
buf.write4(cast(int) data.length);
buf.write(data);
}
return buf.bytes;
}
///
void loadFromBytes(ubyte[] bytes) {
// FIXME: actually read the riff header to skip properly
if(bytes.length && bytes[0] == 'R')
bytes = bytes[0x14 .. $];
MidiReadBuffer buf = MidiReadBuffer(bytes);
if(buf.readChars(4) != "MThd")
throw new Exception("not midi");
if(buf.read4() != 6)
throw new Exception("idk what this even is");
this.format = buf.read2();
this.tracks = new MidiTrack[](buf.read2());
this.timing = buf.read2();
foreach(ref track; tracks) {
track = new MidiTrack();
track.loadFromBuffer(buf);
}
}
// when I read, I plan to cut the end of track marker off.
// 0 == combined into one track
// 1 == multiple tracks
// 2 == multiple one-track patterns
ushort format = 1;
// FIXME
ushort timing = 0x80; // 128 ticks per quarter note
MidiTrack[] tracks;
/++
Returns a forward range for playback. Each item is a command, which
is like the midi event but with some more annotations and control methods.
Modifying this MidiFile object or any of its children during playback
may cause trouble.
Note that you do not need to handle any meta events, it keeps the
tempo internally, but you can look at it if you like.
+/
const(PlayStreamEvent)[] playbackStream() {
PlayStreamEvent[] stream;
size_t size;
foreach(track; tracks)
size += track.events.length;
stream.reserve(size);
Duration position;
static struct NoteOnInfo {
PlayStreamEvent* event;
int turnedOnTicks;
Duration turnedOnPosition;
}
NoteOnInfo[] noteOnInfo = new NoteOnInfo[](128 * 16);
scope(exit) noteOnInfo = null;
static struct LastNoteInfo {
PlayStreamEvent*[6] event; // in case there's a chord
int eventCount;
int turnedOnTicks;
}
LastNoteInfo[/*16*/] lastNoteInfo = new LastNoteInfo[](16); // it doesn't allow the static array cuz of @safe and i don't wanna deal with that so just doing this, nbd alloc anyway
void recordOff(scope NoteOnInfo* noi, int midiClockPosition) {
noi.event.noteOnDuration = position - noi.turnedOnPosition;
noi.event = null;
}
// FIXME: what about rests?
foreach(item; flattenedTrackStream) {
position += item.wait;
stream ~= item;
if(item.event.event == MIDI_EVENT_NOTE_ON) {
if(item.event.data2 == 0)
goto off;
auto ptr = &stream[$-1];
auto noi = ¬eOnInfo[(item.event.channel & 0x0f) * 128 + (item.event.data1 & 0x7f)];
if(noi.event) {
recordOff(noi, item.midiClockPosition);
}
noi.event = ptr;
noi.turnedOnTicks = item.midiClockPosition;
noi.turnedOnPosition = position;
auto lni = &lastNoteInfo[(item.event.channel & 0x0f)];
if(lni.eventCount) {
if(item.midiClockPosition == lni.turnedOnTicks) {
if(lni.eventCount == lni.event.length)
goto maxedOut;
lni.event[lni.eventCount++] = ptr;
} else {
maxedOut:
foreach(ref e; lni.event[0 .. lni.eventCount])
e.midiTicksToNextNoteOnChannel = item.midiClockPosition - lni.turnedOnTicks;
goto frist;
}
} else {
frist:
lni.event[0] = ptr;
lni.eventCount = 1;
lni.turnedOnTicks = item.midiClockPosition;
}
} else if(item.event.event == MIDI_EVENT_NOTE_OFF) {
off:
auto noi = ¬eOnInfo[(item.event.channel & 0x0f) * 128 + (item.event.data1 & 0x7f)];
if(noi.event) {
recordOff(noi, item.midiClockPosition);
}
}
}
return stream;
}
/++
Returns a forward range for playback or analysis that flattens the midi
tracks into a single stream. Each item is a command, which
is like the midi event but with some more annotations and control methods.
Modifying this MidiFile object or any of its children during iteration
may cause trouble.
Note that you do not need to handle any meta events, it keeps the
tempo internally, but you can look at it if you like.
+/
FlattenedTrackStream flattenedTrackStream() {
return FlattenedTrackStream(this);
}
}
static struct PlayStreamEvent {
/// This is how long you wait until triggering this event.
/// Note it may be zero.
Duration wait;
/// And this is the midi event message.
MidiEvent event;
string toString() const {
return event.toString();
}
/// informational. May be null if the stream didn't come from a file or tracks.
MidiFile file;
/// ditto
MidiTrack track;
/++
Gives the position ot the global midi clock for this event. The `event.deltaTime`
is in units of the midi clock, but the actual event has the clock per-track whereas
this value is global, meaning it might not be the sum of event.deltaTime to this point.
(It should add up if you only sum ones with the same [track] though.
The midi clock is used in conjunction with the [MidiFile.timing] and current tempo
state to determine a real time wait value, which you can find in the [wait] member.
This position is probably less useful than the running sum of [wait]s, but is provided
just in case it is useful to you.
+/
int midiClockPosition;
/++
The duration between this non-zero velocity note on and its associated note off.
Will be zero if this isn't actually a note on, the input stream was not seekable (e.g.
a real time recording), or if a note off was not found ahead in the stream.
It is basically how long the pianist held down the key.
Be aware that that the note on to note off is not necessarily associated with the
note you'd see on sheet music. It is more about the time the sound actually rings,
but it may not exactly be that either due to the time it takes for the note to
fade out.
+/
Duration noteOnDuration;
/++
This is the count of midi clock ticks after this non-zero velocity note on event (if
it is not one of those, this value will be zero) and the next note that will be sounded
on its same channel.
While rests may throw this off, this number is the most help in this struct for determining
the note length you'd put on sheet music. Divide it by [MidiFile.timing] to get the number
of midi quarter notes, which is directly correlated to the musical beat.
Will be zero if this isn't actually a note on, the input stream was not seekable (e.g.
a real time recording where the next note hasn't been struck yet), or if a note off was
not found ahead in the stream.
+/
int midiTicksToNextNoteOnChannel;
// when recording and working in milliseconds we prolly want to round off to the nearest 64th note, or even less fine grained at user command todeal with bad musicians (i.e. me) being off beat
}
static immutable(PlayStreamEvent)[] longWait = [{wait: 1.weeks, event: {status: 0xff, data1: 0x01, meta: null}}];
struct FlattenedTrackStream {
FlattenedTrackStream save() {
auto copy = this;
copy.trackPositions = this.trackPositions.dup;
return copy;
}
MidiFile file;
this(MidiFile file) {
this.file = file;
this.trackPositions.length = file.tracks.length;
foreach(idx, ref tp; this.trackPositions) {
tp.remaining = file.tracks[idx].events[];
tp.track = file.tracks[idx];
}
this.currentTrack = -1;
this.tempo = 500000; // microseconds per quarter note
popFront();
}
//@nogc:
int midiClock;
void popFront() {
done = true;
for(auto c = currentTrack + 1; c < trackPositions.length; c++) {
auto tp = trackPositions[c];
if(tp.remaining.length && tp.remaining[0].deltaTime == tp.clock) {
auto f = tp.remaining[0];
trackPositions[c].remaining = tp.remaining[1 .. $];
trackPositions[c].clock = 0;
if(tp.remaining.length == 0 || tp.remaining[0].deltaTime > 0) {
currentTrack += 1;
}
pending = PlayStreamEvent(0.seconds, f, file, tp.track, midiClock);
processPending();
done = false;
return;
}
}
// if nothing happened there, time to advance the clock
int minWait = int.max;
int minWaitTrack = -1;
foreach(idx, track; trackPositions) {
if(track.remaining.length) {
auto dt = track.remaining[0].deltaTime - track.clock;
if(dt < minWait) {
minWait = dt;
minWaitTrack = cast(int) idx;
}
}
}
if(minWaitTrack == -1) {
done = true;
return;
}
foreach(ref tp; trackPositions) {
tp.clock += minWait;
}
done = false;
// file.timing, if high bit clear, is ticks per quarter note
// if high bit set... idk it is different.
//
// then the temp is microseconds per quarter note.
auto time = (cast(long) minWait * tempo / file.timing).usecs;
midiClock += minWait;
pending = PlayStreamEvent(time, trackPositions[minWaitTrack].remaining[0], file, trackPositions[minWaitTrack].track, midiClock);
processPending();
trackPositions[minWaitTrack].remaining = trackPositions[minWaitTrack].remaining[1 .. $];
trackPositions[minWaitTrack].clock = 0;
currentTrack = minWaitTrack;
return;
}
private struct TrackPosition {
MidiEvent[] remaining;
int clock;
MidiTrack track;
}
private TrackPosition[] trackPositions;
private int currentTrack;
private void processPending() {
if(pending.event.status == 0xff && pending.event.data1 == MetaEvent.Tempo) {
this.tempo = 0;
foreach(i; pending.event.meta) {
this.tempo <<= 8;
this.tempo |= i;
}
}
}
@property
PlayStreamEvent front() {
return pending;
}
private uint tempo;
private PlayStreamEvent pending;
private bool done;
@property
bool empty() {
return done;
}
}
class MidiTrack {
ubyte[] toBytes() {
MidiWriteBuffer buf;
foreach(event; events)
event.writeToBuffer(buf);
MidiEvent end;
end.status = 0xff;
end.data1 = 0x2f;
end.meta = null;
end.writeToBuffer(buf);
return buf.bytes;
}
void loadFromBuffer(ref MidiReadBuffer buf) {
if(buf.readChars(4) != "MTrk")
throw new Exception("wtf no track header");
auto trackLength = buf.read4();
auto begin = buf.bytes.length;
ubyte runningStatus;
while(buf.bytes.length) {
MidiEvent newEvent = MidiEvent.fromBuffer(buf, runningStatus);
if(newEvent.isMeta && newEvent.data1 == MetaEvent.Name)
name_ = cast(string) newEvent.meta.idup;
if(newEvent.status == 0xff && newEvent.data1 == MetaEvent.EndOfTrack) {
break;
}
events ~= newEvent;
}
//assert(begin - trackLength == buf.bytes.length);
}
/++
All the midi events found in the track.
+/
MidiEvent[] events;
/++
The name of the track, as found from metadata at load time.
This may change to scan events to see updates without the cache in the future.
+/
@property string name() {
return name_;
}
private string name_;
/++
This field is not used or stored in a midi file; it is just
a place to store some state in your player.
I use it to keep flags like if the track is currently enabled.
+/
int customPlayerInfo;
override string toString() const {
string s;
foreach(event; events)
s ~= event.toString ~ "\n";
return s;
}
}
enum MetaEvent {
SequenceNumber = 0,
// these take a text param
Text = 1,
Copyright = 2,
Name = 3,
Instrument = 4,
Lyric = 5,
Marker = 6,
CuePoint = 7,
PatchName = 8,
DeviceName = 9,
// no param
EndOfTrack = 0x2f,
// different ones
Tempo = 0x51, // 3 bytes form big-endian micro-seconds per quarter note. 120 BPM default.
SMPTEOffset = 0x54, // 5 bytes. I don't get this one....
TimeSignature = 0x58, // 4 bytes: numerator, denominator, clocks per click, 32nd notes per quarter note. (8 == quarter note gets the beat)
KeySignature = 0x59, // 2 bytes: first byte is signed offset from C in semitones, second byte is 0 for major, 1 for minor
// arbitrary length custom param
Proprietary = 0x7f,
}
struct MidiEvent {
int deltaTime;
ubyte status;
ubyte data1; // if meta, this is the identifier
//union {
//struct {
ubyte data2;
//}
const(ubyte)[] meta; // iff status == 0xff
//}
invariant () {
assert(status & 0x80);
assert(!(data1 & 0x80));
assert(!(data2 & 0x80));
assert(status == 0xff || meta is null);
}
/// Convenience factories for various meta-events
static MidiEvent Text(string t) { return MidiEvent(0, 0xff, MetaEvent.Text, 0, cast(const(ubyte)[]) t); }
/// ditto
static MidiEvent Copyright(string t) { return MidiEvent(0, 0xff, MetaEvent.Copyright, 0, cast(const(ubyte)[]) t); }
/// ditto
static MidiEvent Name(string t) { return MidiEvent(0, 0xff, MetaEvent.Name, 0, cast(const(ubyte)[]) t); }
/// ditto
static MidiEvent Lyric(string t) { return MidiEvent(0, 0xff, MetaEvent.Lyric, 0, cast(const(ubyte)[]) t); }
/// ditto
static MidiEvent Marker(string t) { return MidiEvent(0, 0xff, MetaEvent.Marker, 0, cast(const(ubyte)[]) t); }
/// ditto
static MidiEvent CuePoint(string t) { return MidiEvent(0, 0xff, MetaEvent.CuePoint, 0, cast(const(ubyte)[]) t); }
/++
Conveneince factories for normal events. These just put your given values into the event as raw data so you're responsible to know what they do.
History:
Added January 2, 2022 (dub v10.5)
+/
static MidiEvent NoteOn(int channel, int note, int velocity) { return MidiEvent(0, (MIDI_EVENT_NOTE_ON << 4) | (channel & 0x0f), note & 0x7f, velocity & 0x7f); }
/// ditto
static MidiEvent NoteOff(int channel, int note, int velocity) { return MidiEvent(0, (MIDI_EVENT_NOTE_OFF << 4) | (channel & 0x0f), note & 0x7f, velocity & 0x7f); }
/+
// FIXME: this is actually a relatively complicated one i should fix, it combines bits... 8192 == 0.
// This is a bit of a magical function, it takes a signed bend between 0 and 81
static MidiEvent PitchBend(int channel, int bend) {
return MidiEvent(0, (MIDI_EVENT_PITCH_BEND << 4) | (channel & 0x0f), bend & 0x7f, bend & 0x7f);
}
+/
// this overload ok, it is what the thing actually tells. coarse == 64 means we're at neutral.
/// ditto
static MidiEvent PitchBend(int channel, int fine, int coarse) { return MidiEvent(0, (MIDI_EVENT_PITCH_BEND << 4) | (channel & 0x0f), fine & 0x7f, coarse & 0x7f); }
/// ditto
static MidiEvent NoteAftertouch(int channel, int note, int velocity) { return MidiEvent(0, (MIDI_EVENT_NOTE_AFTERTOUCH << 4) | (channel & 0x0f), note & 0x7f, velocity & 0x7f); }
// FIXME the different controllers do have standard IDs we could look up in an enum... and many of them have coarse/fine things you can send as two messages.
/// ditto
static MidiEvent Controller(int channel, int controller, int value) { return MidiEvent(0, (MIDI_EVENT_CONTROLLER << 4) | (channel & 0x0f), controller & 0x7f, value & 0x7f); }
// the two byte ones
/// ditto
static MidiEvent ProgramChange(int channel, int program) { return MidiEvent(0, (MIDI_EVENT_PROGRAM_CHANGE << 4) | (channel & 0x0f), program & 0x7f); }
/// ditto
static MidiEvent ChannelAftertouch(int channel, int param) { return MidiEvent(0, (MIDI_EVENT_CHANNEL_AFTERTOUCH << 4) | (channel & 0x0f), param & 0x7f); }
///
bool isMeta() const {
return status == 0xff;
}
///
ubyte event() const {
return status >> 4;
}
///
ubyte channel() const {
return status & 0x0f;
}
///
string toString() const {
static string tos(int a) {
char[16] buffer;
auto bufferPos = buffer.length;
do {
buffer[--bufferPos] = a % 10 + '0';
a /= 10;
} while(a);
return buffer[bufferPos .. $].idup;
}
static string toh(ubyte b) {
char[2] buffer;
buffer[0] = (b >> 4) & 0x0f;
if(buffer[0] < 10)
buffer[0] += '0';
else
buffer[0] += 'A' - 10;
buffer[1] = b & 0x0f;
if(buffer[1] < 10)
buffer[1] += '0';
else
buffer[1] += 'A' - 10;
return buffer.idup;
}
string s;
s ~= tos(deltaTime);
s ~= ": ";
s ~= toh(status);
s ~= " ";
s ~= toh(data1);
s ~= " ";
if(isMeta) {
switch(data1) {
case MetaEvent.Text:
case MetaEvent.Copyright:
case MetaEvent.Name:
case MetaEvent.Instrument:
case MetaEvent.Lyric:
case MetaEvent.Marker:
case MetaEvent.CuePoint:
case MetaEvent.PatchName:
case MetaEvent.DeviceName:
s ~= cast(const(char)[]) meta;
break;
case MetaEvent.TimeSignature:
ubyte numerator = meta[0];
ubyte denominator = meta[1];
ubyte clocksPerClick = meta[2];
ubyte notesPerQuarter = meta[3]; // 32nd notes / Q so 8 = quarter note gets the beat
s ~= tos(numerator);
s ~= "/";
s ~= tos(denominator);
s ~= " ";
s ~= tos(clocksPerClick);
s ~= " ";
s ~= tos(notesPerQuarter);
break;
case MetaEvent.KeySignature:
byte offset = meta[0];
ubyte minor = meta[1];
if(offset < 0) {
s ~= "-";
s ~= tos(-cast(int) offset);
} else {
s ~= tos(offset);
}
s ~= minor ? " minor" : " major";
break;
// case MetaEvent.Tempo:
// could process this but idk if it needs to be shown
// break;
case MetaEvent.Proprietary:
foreach(m; meta) {
s ~= toh(m);
s ~= " ";
}
break;
default:
s ~= cast(const(char)[]) meta;
}
} else {
s ~= toh(data2);
s ~= " ";
s ~= tos(channel);
s ~= " ";
switch(event) {
case MIDI_EVENT_NOTE_OFF: s ~= "NOTE_OFF"; break;
case MIDI_EVENT_NOTE_ON: s ~= data2 ? "NOTE_ON" : "NOTE_ON_ZERO"; break;
case MIDI_EVENT_NOTE_AFTERTOUCH: s ~= "NOTE_AFTERTOUCH"; break;
case MIDI_EVENT_CONTROLLER: s ~= "CONTROLLER"; break;
case MIDI_EVENT_PROGRAM_CHANGE: s ~= "PROGRAM_CHANGE"; break;
case MIDI_EVENT_CHANNEL_AFTERTOUCH: s ~= "CHANNEL_AFTERTOUCH"; break;
case MIDI_EVENT_PITCH_BEND: s ~= "PITCH_BEND"; break;
default:
}
}
return s;
}
static MidiEvent fromBuffer(ref MidiReadBuffer buf, ref ubyte runningStatus) {
MidiEvent event;
start_over:
event.deltaTime = buf.readv();
auto nb = buf.read1();
if(nb == 0xff) {
// meta...
event.status = 0xff;
event.data1 = buf.read1(); // the type
int len = buf.readv();
auto meta = new ubyte[](len);
foreach(idx; 0 .. len)
meta[idx] = buf.read1();
event.meta = meta;
} else if(nb >= 0xf0) {
// FIXME I'm just skipping this entirely but there might be value in here
nb = buf.read1();
while(nb < 0xf0)
nb = buf.read1();
goto start_over;
} else if(nb & 0b1000_0000) {
event.status = nb;
runningStatus = nb;
event.data1 = buf.read1();
if(event.event != MIDI_EVENT_CHANNEL_AFTERTOUCH &&
event.event != MIDI_EVENT_PROGRAM_CHANGE)
{
event.data2 = buf.read1();
}
} else {
event.status = runningStatus;
event.data1 = nb;
if(event.event != MIDI_EVENT_CHANNEL_AFTERTOUCH &&
event.event != MIDI_EVENT_PROGRAM_CHANGE)
{
event.data2 = buf.read1();
}
}
return event;
}
void writeToBuffer(ref MidiWriteBuffer buf) const {
buf.writev(deltaTime);
buf.write1(status);
// FIXME: what about other sysex stuff?
if(meta) {
buf.write1(data1);
buf.writev(cast(int) meta.length);
buf.write(meta);
} else {
buf.write1(data1);
if(event != MIDI_EVENT_CHANNEL_AFTERTOUCH &&
event != MIDI_EVENT_PROGRAM_CHANGE)
{
buf.write1(data2);
}
}
}
}
struct MidiReadBuffer {
ubyte[] bytes;
char[] readChars(int len) {
auto c = bytes[0 .. len];
bytes = bytes[len .. $];
return cast(char[]) c;
}
ubyte[] readBytes(int len) {
auto c = bytes[0 .. len];
bytes = bytes[len .. $];
return c;
}
int read4() {
int i;
foreach(a; 0 .. 4) {
i <<= 8;
i |= bytes[0];
bytes = bytes[1 .. $];
}
return i;
}
ushort read2() {
ushort i;
foreach(a; 0 .. 2) {
i <<= 8;
i |= bytes[0];
bytes = bytes[1 .. $];
}
return i;
}
ubyte read1() {
auto b = bytes[0];
bytes = bytes[1 .. $];
return b;
}
int readv() {
int value = read1();
ubyte c;
if(value & 0x80) {
value &= 0x7f;
do
value = (value << 7) | ((c = read1) & 0x7f);
while(c & 0x80);
}
return value;
}
}
struct MidiWriteBuffer {
ubyte[] bytes;
void write(const char[] a) {
bytes ~= a;
}
void write(const ubyte[] a) {
bytes ~= a;
}
void write4(int v) {
// big endian
bytes ~= (v >> 24) & 0xff;
bytes ~= (v >> 16) & 0xff;
bytes ~= (v >> 8) & 0xff;
bytes ~= v & 0xff;
}
void write2(ushort v) {
// big endian
bytes ~= v >> 8;
bytes ~= v & 0xff;
}
void write1(ubyte v) {
bytes ~= v;
}
void writev(int v) {
// variable
uint buffer = v & 0x7f;
while((v >>= 7)) {
buffer <<= 8;
buffer |= ((v & 0x7f) | 0x80);
}
while(true) {
bytes ~= buffer & 0xff;
if(buffer & 0x80)
buffer >>= 8;
else
break;
}
}
}
import core.stdc.stdio;
import core.stdc.stdlib;
int freq(int note){
import std.math;
float r = note - 69;
r /= 12;
r = pow(2, r);
r*= 440;
return cast(int) r;
}
enum A = 69; // 440 hz per midi spec
enum As = 70;
enum B = 71;
enum C = 72; // middle C + 1 octave
enum Cs = 73;
enum D = 74;
enum Ds = 75;
enum E = 76;
enum F = 77;
enum Fs = 78;
enum G = 79;
enum Gs = 80;
immutable string[] noteNames = [ // just do note % 12 to index this
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
];
enum MIDI_EVENT_NOTE_OFF = 0x08;
enum MIDI_EVENT_NOTE_ON = 0x09;
enum MIDI_EVENT_NOTE_AFTERTOUCH = 0x0a;
enum MIDI_EVENT_CONTROLLER = 0x0b;
enum MIDI_EVENT_PROGRAM_CHANGE = 0x0c;// only one param
enum MIDI_EVENT_CHANNEL_AFTERTOUCH = 0x0d;// only one param
enum MIDI_EVENT_PITCH_BEND = 0x0e;
/+
35 Acoustic Bass Drum 59 Ride Cymbal 2
36 Bass Drum 1 60 Hi Bongo
37 Side Stick 61 Low Bongo
38 Acoustic Snare 62 Mute Hi Conga
39 Hand Clap 63 Open Hi Conga
40 Electric Snare 64 Low Conga
41 Low Floor Tom 65 High Timbale
42 Closed Hi-Hat 66 Low Timbale
43 High Floor Tom 67 High Agogo
44 Pedal Hi-Hat 68 Low Agogo
45 Low Tom 69 Cabasa
46 Open Hi-Hat 70 Maracas
47 Low-Mid Tom 71 Short Whistle
48 Hi-Mid Tom 72 Long Whistle
49 Crash Cymbal 1 73 Short Guiro
50 High Tom 74 Long Guiro
51 Ride Cymbal 1 75 Claves
52 Chinese Cymbal 76 Hi Wood Block
53 Ride Bell 77 Low Wood Block
54 Tambourine 78 Mute Cuica
55 Splash Cymbal 79 Open Cuica
56 Cowbell 80 Mute Triangle
57 Crash Cymbal 2 81 Open Triangle
58 Vibraslap
+/
static immutable string[] instrumentNames = [
"", // 0 is nothing
// Piano:
"Acoustic Grand Piano",
"Bright Acoustic Piano",
"Electric Grand Piano",
"Honky-tonk Piano",
"Electric Piano 1",
"Electric Piano 2",
"Harpsichord",
"Clavinet",
// Chromatic Percussion:
"Celesta",
"Glockenspiel",
"Music Box",
"Vibraphone",
"Marimba",
"Xylophone",
"Tubular Bells",
"Dulcimer",
// Organ:
"Drawbar Organ",
"Percussive Organ",
"Rock Organ",
"Church Organ",
"Reed Organ",
"Accordion",
"Harmonica",
"Tango Accordion",
// Guitar:
"Acoustic Guitar (nylon)",
"Acoustic Guitar (steel)",
"Electric Guitar (jazz)",
"Electric Guitar (clean)",
"Electric Guitar (muted)",
"Overdriven Guitar",
"Distortion Guitar",
"Guitar harmonics",
// Bass:
"Acoustic Bass",
"Electric Bass (finger)",
"Electric Bass (pick)",