-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmidi2agb.cpp
More file actions
2044 lines (1925 loc) · 84.3 KB
/
midi2agb.cpp
File metadata and controls
2044 lines (1925 loc) · 84.3 KB
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
#include <string>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <unordered_map>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstdarg>
#include <cmath>
#include <cassert>
#include <cstring>
#include <filesystem>
#include "cppmidi/cppmidi.h"
static void dbg(const char *msg, ...);
static void die(const char *msg, ...);
static void err(const char *msg, ...);
static void usage() {
err("midi2agb, version %s\n", GIT_VERSION);
err("\n");
err("Usage: midi2agb [options] <input.mid> [<output.s>]\n\n");
err("Options:\n");
err("-s <sym> | symbol name for song header (default: file name)\n");
err("-m <mvl> | master volume 0..128 (default: 128)\n");
err("-g <vgr> | voicegroup symbol name (default: voicegroup000)\n");
err("-p <pri> | song priority 0..127 (default: 0)\n");
err("-r <rev> | song reverb 0..127 (default: 0)\n");
err("-n | apply natural volume scale\n");
err("-v | output debug information\n");
err("--modt <val> | global modulation type 0..2\n");
err("--modsc <val> | global modulation scale 0.0 - 16.0\n");
err("--lfos <val> | global modulation speed 0..127\n");
err(" | (val * 24 / 256) oscillations per beat\n");
err("--lfodl <val> | global modulation delay 0..127 ticks\n");
exit(1);
}
static void fix_str(std::string& str) {
// replaces all characters that are not alphanumerical
for (size_t i = 0; i < str.size(); i++) {
if (str[i] >= 'a' && str[i] <= 'z')
continue;
if (str[i] >= 'A' && str[i] <= 'Z')
continue;
if (str[i] >= '0' && str[i] <= '9' && i > 0)
continue;
str[i] = '_';
}
}
static std::string arg_sym;
static uint8_t arg_mvl = 128;
static std::string arg_vgr;
static uint8_t arg_pri = 0;
static uint8_t arg_rev = 0;
static bool arg_natural = false;
// conditional global event options
static uint8_t arg_modt = 0;
static bool arg_modt_global = false;
static uint8_t arg_lfos = 0;
static bool arg_lfos_global = false;
static uint8_t arg_lfodl = 0;
static bool arg_lfodl_global = false;
static float arg_mod_scale = 1.0f;
static std::filesystem::path arg_input_file;
static bool arg_input_file_read = false;
static std::filesystem::path arg_output_file;
static bool arg_output_file_read = false;
// misc arguments
static bool arg_debug_output = false;
//
static cppmidi::midi_file mf;
static void midi_read_infile_arguments();
static void midi_remove_empty_tracks();
static void midi_apply_filters();
static void midi_apply_loop_and_state_reset();
static void midi_remove_redundant_events();
static void midi_to_agb();
static void agb_optimize();
static void write_agb();
int main(int argc, char *argv[]) {
if (argc == 1)
usage();
auto start = std::chrono::high_resolution_clock::now();
try {
// argument parsing
for (int i = 1; i < argc; i++) {
std::string st(argv[i]);
if (!st.compare("-s")) {
if (++i >= argc)
die("-s: missing parameter\n");
arg_sym = argv[i];
fix_str(arg_sym);
} else if (!st.compare("-m")) {
if (++i >= argc)
die("-m: missing parameter\n");
int mvl = std::stoi(argv[i]);
if (mvl < 0 || mvl > 128)
die("-m: parameter %d out of range\n", mvl);
arg_mvl = static_cast<uint8_t>(mvl);
} else if (!st.compare("-g")) {
if (++i >= argc)
die("-g missing parameter\n");
arg_vgr = argv[i];
fix_str(arg_vgr);
} else if (!st.compare("-p")) {
if (++i >= argc)
die("-p: missing parameter\n");
int prio = std::stoi(argv[i]);
if (prio < 0 || prio > 127)
die("-p: parameter %d out of range\n", prio);
arg_pri = static_cast<uint8_t>(prio);
} else if (!st.compare("-r")) {
if (++i >= argc)
die("-r: missing parameter\n");
int rev = std::stoi(argv[i]);
if (rev < 0 || rev > 127)
die("-r: parameter %d out of range\n", rev);
arg_rev = static_cast<uint8_t>(rev);
} else if (!st.compare("-n")) {
arg_natural = true;
} else if (!st.compare("-v")) {
arg_debug_output = true;
} else if (!st.compare("--modt")) {
if (++i >= argc)
die("--modt: missing parameter\n");
int modt = std::stoi(argv[i]);
if (modt < 0 || modt > 2)
die("--modt: parameter %d out of range\n", modt);
arg_modt = static_cast<uint8_t>(modt);
arg_modt_global = true;
} else if (!st.compare("--modsc")) {
if (++i >= argc)
die("--modsc: missing parameter\n");
float modscale = std::stof(std::string(argv[i]));
if (modscale < 0.0f || modscale > 16.0f)
die("--modscale: parameter %f out of range\n", modscale);
arg_mod_scale = modscale;
} else if (!st.compare("--lfos")) {
if (++i >= argc)
die("--lfos: missing parameter\n");
int lfos = std::stoi(argv[i]);
if (lfos < 0 || lfos > 127)
die("--lfos: parameter %d out of range\n", lfos);
arg_lfos = static_cast<uint8_t>(lfos);
arg_lfos_global = true;
} else if (!st.compare("--lfodl")) {
if (++i >= argc)
die("--lfodl: missing parameter\n");
int lfodl = std::stoi(argv[i]);
if (lfodl < 0 || lfodl > 127)
die("--lfodl: parameter %d out of range\n", lfodl);
arg_lfodl = static_cast<uint8_t>(lfodl);
arg_lfodl_global = true;
} else if (!st.compare(0, 2, "-V")) {
int mvl = std::stoi(st.substr(2));
if (mvl < 0 || mvl > 128)
die("-V: parameter %d out of range\n", mvl);
arg_mvl = static_cast<uint8_t>(mvl);
} else if (!st.compare(0, 2, "-G")) {
arg_vgr = std::string("voicegroup") + st.substr(2);
fix_str(arg_vgr);
} else if (!st.compare(0, 2, "-P")) {
int prio = std::stoi(st.substr(2));
if (prio < 0 || prio > 127)
die("-P: parameter %d out of range\n", prio);
arg_pri = static_cast<uint8_t>(prio);
} else if (!st.compare(0, 2, "-R")) {
int rev = std::stoi(argv[i]);
if (rev < 0 || rev > 127)
die("-R: parameter %d out of range\n", rev);
arg_rev = static_cast<uint8_t>(rev);
} else if (!st.compare(0, 2, "-L")) {
arg_sym = st.substr(2);
fix_str(arg_sym);
} else {
if (!st.compare("--")) {
if (++i >= argc)
die("--: missing file name\n");
}
if (!arg_input_file_read) {
arg_input_file = argv[i];
if (arg_input_file.empty())
die("empty input file name\n");
arg_input_file_read = true;
} else if (!arg_output_file_read) {
arg_output_file = argv[i];
if (arg_output_file.empty())
die("empty output file name\n");
arg_output_file_read = true;
} else {
die("Too many files specified\n");
}
}
}
// check arguments
if (!arg_input_file_read) {
die("No input file specified\n");
}
if (!arg_output_file_read) {
// create output file name if none is provided
arg_output_file = arg_input_file;
arg_output_file.replace_extension("s");
arg_output_file_read = true;
}
if (arg_sym.size() == 0) {
// .string() can technically be omitted, but MinGW still wants it :/
arg_sym = arg_output_file.filename().replace_extension("").string();
fix_str(arg_sym);
}
if (arg_vgr.size() == 0) {
arg_vgr = "voicegroup000";
}
// load midi file
mf.load_from_file(arg_input_file);
// 24 clocks per quarter note is pretty much the standard for GBA
mf.convert_time_division(24);
midi_read_infile_arguments();
midi_remove_empty_tracks();
midi_apply_filters();
midi_apply_loop_and_state_reset();
midi_remove_redundant_events();
midi_to_agb();
agb_optimize();
write_agb();
} catch (const cppmidi::xcept& ex) {
fprintf(stderr, "cppmidi lib error:\n%s\n", ex.what());
return 1;
} catch (const std::exception& ex) {
fprintf(stderr, "std lib error:\n%s\n", ex.what());
return 1;
}
auto end = std::chrono::high_resolution_clock::now();
dbg("took %ld us\n",
std::chrono::duration_cast<std::chrono::microseconds>(end - start).count());
}
static const uint8_t MIDI_CC_EX_BENDR = 20;
static const uint8_t MIDI_CC_EX_LFOS = 21;
static const uint8_t MIDI_CC_EX_MODT = 22;
static const uint8_t MIDI_CC_EX_TUNE = 24;
static const uint8_t MIDI_CC_EX_LFODL = 26;
static const uint8_t MIDI_CC_EX_LOOP = 30;
static const uint8_t MIDI_CC_EX_PRIO = 33;
static const uint8_t EX_LOOP_START = 100;
static const uint8_t EX_LOOP_END = 101;
struct agb_ev {
enum class ty {
WAIT, LOOP_START, LOOP_END, PRIO, TEMPO, KEYSH, VOICE, VOL, PAN,
BEND, BENDR, LFOS, LFODL, MOD, MODT, TUNE, XCMD, EOT, TIE, NOTE,
} type;
agb_ev(ty type) : type(type) {}
union {
uint32_t wait;
uint8_t prio;
uint8_t tempo;
int8_t keysh;
uint8_t voice;
uint8_t vol;
int8_t pan;
int8_t bend;
uint8_t bendr;
uint8_t lfos;
uint8_t lfodl;
uint8_t mod;
uint8_t modt;
int8_t tune;
struct { uint8_t type; uint8_t par; } xcmd;
struct { uint8_t key; } eot;
struct { uint8_t key; uint8_t vel; } tie;
struct { uint8_t len; uint8_t key; uint8_t vel; } note;
};
size_t size() const {
switch (type) {
case ty::WAIT: return 1;
case ty::LOOP_START: return 0;
case ty::LOOP_END: return 5;
case ty::PRIO: return 2;
case ty::TEMPO: return 2;
case ty::KEYSH: return 2;
case ty::VOICE: return 2;
case ty::VOL: return 2;
case ty::PAN: return 2;
case ty::BEND: return 2;
case ty::BENDR: return 2;
case ty::LFOS: return 2;
case ty::LFODL: return 2;
case ty::MOD: return 2;
case ty::MODT: return 2;
case ty::TUNE: return 2;
case ty::XCMD: return 3;
case ty::EOT: return 2;
case ty::TIE: return 3;
case ty::NOTE: return 4;
default: throw std::runtime_error("agb_ev::size() error");
}
}
bool operator==(const agb_ev& rhs) const {
if (type != rhs.type)
return false;
switch (type) {
case ty::WAIT: return wait == rhs.wait;
case ty::LOOP_START: return true;
case ty::LOOP_END: return true;
case ty::PRIO: return prio == rhs.prio;
case ty::TEMPO: return tempo == rhs.tempo;
case ty::KEYSH: return keysh == rhs.keysh;
case ty::VOICE: return voice == rhs.voice;
case ty::VOL: return vol == rhs.vol;
case ty::PAN: return pan == rhs.pan;
case ty::BEND: return bend == rhs.bend;
case ty::BENDR: return bendr == rhs.bendr;
case ty::LFOS: return lfos == rhs.lfos;
case ty::LFODL: return lfodl == rhs.lfodl;
case ty::MOD: return mod == rhs.mod;
case ty::MODT: return modt == rhs.modt;
case ty::TUNE: return tune == rhs.tune;
case ty::XCMD: return xcmd.type == rhs.xcmd.type && xcmd.par == rhs.xcmd.par;
case ty::EOT: return eot.key == rhs.eot.key;
case ty::TIE: return tie.key == rhs.tie.key && tie.vel == rhs.tie.vel;
case ty::NOTE: return note.len == rhs.note.len && note.key == rhs.note.key && note.vel == rhs.note.vel;
default: throw std::runtime_error("agb_ev::operator== error");
}
}
bool operator!=(const agb_ev& rhs) const {
return !operator==(rhs);
}
size_t hash() const {
switch (type) {
case ty::WAIT:
return wait ^ 0xd5697712;
case ty::LOOP_START:
case ty::LOOP_END:
return static_cast<size_t>(type);
case ty::PRIO:
case ty::TEMPO:
case ty::KEYSH:
case ty::VOICE:
case ty::VOL:
case ty::PAN:
case ty::BEND:
case ty::BENDR:
case ty::LFOS:
case ty::LFODL:
case ty::MOD:
case ty::MODT:
case ty::TUNE:
case ty::EOT:
return prio ^ static_cast<size_t>(type);
case ty::XCMD:
case ty::TIE:
return static_cast<size_t>(xcmd.type) ^
static_cast<size_t>(xcmd.par << 1) ^ 0x709124be;
case ty::NOTE:
return note.len ^ static_cast<size_t>(note.key << 1) ^
static_cast<size_t>(note.vel << 2) ^ 0x41698a8e;
default:
throw std::runtime_error("hash error");
}
}
};
struct agb_bar {
agb_bar() : is_referenced(false), does_reference(false) {}
std::vector<agb_ev> events;
bool operator==(const agb_bar& rhs) const {
if (events.size() != rhs.events.size())
return false;
for (size_t i = 0; i < events.size(); i++) {
if (events[i] != rhs.events[i])
return false;
}
return true;
}
bool operator!=(const agb_bar& rhs) const {
return !operator==(rhs);
}
size_t hash() const {
size_t hs = 0x1;
for (const agb_ev& ev : events) {
size_t h = ev.hash();
hs *= h;
hs ^= h;
}
return hs;
}
size_t size() const {
size_t s = 0;
for (const agb_ev& ev : events) {
s += ev.size();
}
return s;
}
bool is_referenced;
bool does_reference;
};
struct agb_bar_ref_hasher {
typedef std::reference_wrapper<agb_bar> rw_agb_bar;
size_t operator()(const rw_agb_bar& x) const {
return x.get().hash();
}
bool operator()(const rw_agb_bar& a,const rw_agb_bar& b) const {
return a.get() == b.get();
}
};
struct agb_track {
std::vector<agb_bar> bars;
};
struct agb_song {
std::vector<agb_track> tracks;
};
agb_song as;
static inline bool ev_tick_cmp(
const std::unique_ptr<cppmidi::midi_event>& a,
const std::unique_ptr<cppmidi::midi_event>& b) {
return a->ticks < b->ticks;
}
static int trk_get_channel_num(const cppmidi::midi_track& trk) {
using namespace cppmidi;
int channel = -1;
for (const std::unique_ptr<midi_event>& ev : trk.midi_events) {
const message_midi_event *mev = dynamic_cast<const message_midi_event*>(&*ev);
if (mev) {
channel = mev->channel();
break;
}
}
return channel;
}
template<class T, int ctrl = -1>
static bool find_next_event_at_tick_index(const cppmidi::midi_track& mtrk,
const size_t start_event, size_t& next_event) {
size_t next_index = start_event + 1;
while (1) {
if (next_index >= mtrk.midi_events.size())
return false;
if (mtrk[next_index]->ticks > mtrk[start_event]->ticks)
return false;
if (typeid(*mtrk[next_index]) == typeid(T)) {
if (ctrl != -1) {
const cppmidi::controller_message_midi_event& cev =
static_cast<const cppmidi::controller_message_midi_event&>(
*mtrk[next_index]);
if (cev.get_controller() == ctrl) {
next_event = next_index;
return true;
}
} else {
next_event = next_index;
return true;
}
}
next_index += 1;
}
}
const uint8_t MIDI_NOTE_PARSE_INIT = 0x0;
const uint8_t MIDI_NOTE_PARSE_SHORT = 0x1;
const uint8_t MIDI_NOTE_PARSE_TIE = 0x2;
static void midi_read_infile_arguments() {
using namespace cppmidi;
/*
* Special Events (use Marker/Text/Cuepoint):
* - "[": loop start for all tracks
* - "]": loop end for all tracks
* - "modt=%d": set's modulation type at position
* - "tune=%d": set's tuning (+-1 key, range -64 to +63)
* - "lfos=%d": set's lfo speed
* - "lfos_global=%d": ^ globally
* - "lfodl=%d": set's lfo delay
* - "lfodl_global=%d": ^ globally
* - "modscale_global=%f": scales modulation by factor %f
* - "modt_global=%d": set's modulation type for whole song
*/
bool found_start = false, found_end = false;
uint32_t loop_start = 0, loop_end = 0;
uint8_t lsb_rpn = 0, msb_rpn = 0;
uint32_t last_event = 0;
std::vector<bool> volume_init(mf.midi_tracks.size(), false);
// parse meta events
for (size_t itrk = 0; itrk < mf.midi_tracks.size(); itrk++) {
midi_track& mtrk = mf[itrk];
for (size_t ievt = 0; ievt < mtrk.midi_events.size(); ievt++) {
midi_event& ev = *mtrk[ievt];
last_event = std::max(ev.ticks, last_event);
std::string ev_text;
if (typeid(ev) == typeid(marker_meta_midi_event)) {
// marker
const marker_meta_midi_event& mev =
static_cast<const marker_meta_midi_event&>(ev);
ev_text = mev.get_text();
} else if (typeid(ev) == typeid(text_meta_midi_event)) {
// text
const text_meta_midi_event& tev =
static_cast<const text_meta_midi_event&>(ev);
ev_text = tev.get_text();
} else if (typeid(ev) == typeid(cuepoint_meta_midi_event)) {
// cuepoint
const cuepoint_meta_midi_event& cev =
static_cast<const cuepoint_meta_midi_event&>(ev);
ev_text = cev.get_text();
} else if (typeid(ev) == typeid(controller_message_midi_event)) {
const controller_message_midi_event& cev =
static_cast<const controller_message_midi_event&>(ev);
if (cev.get_controller() == MIDI_CC_LSB_RPN) {
lsb_rpn = cev.get_value();
} else if (cev.get_controller() == MIDI_CC_MSB_RPN) {
msb_rpn = cev.get_value();
} else if (cev.get_controller() == MIDI_CC_MSB_DATA_ENTRY &&
msb_rpn == 0 && lsb_rpn == 0) {
// found a bend range command
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
cev.ticks, cev.channel(),
MIDI_CC_EX_BENDR, cev.get_value());
} else if (cev.get_controller() == MIDI_CC_MSB_VOLUME) {
volume_init[itrk] = true;
}
continue;
} else if (typeid(ev) == typeid(noteoff_message_midi_event)) {
// for correct midi note parsing the velocity in the noteoff
// command get's used for marking, reset to intial 0
noteoff_message_midi_event& noteoff_ev =
static_cast<noteoff_message_midi_event&>(ev);
noteoff_ev.set_velocity(MIDI_NOTE_PARSE_INIT);
continue;
} else {
continue;
}
// found an event with a possibly valid text
if (!ev_text.compare("[") || !ev_text.compare("loopStart")) {
found_start = true;
loop_start = ev.ticks;
} else if (!ev_text.compare("]") || !ev_text.compare("loopEnd")) {
found_end = true;
loop_end = ev.ticks;
} else if (!strncmp(ev_text.c_str(), "modt=", 5)) {
int modt = std::stoi(ev_text.substr(5));
modt = std::clamp(modt, 0, 2);
int channel = trk_get_channel_num(mtrk);
if (channel >= 0) {
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
ev.ticks, channel, MIDI_CC_EX_MODT,
static_cast<uint8_t>(modt));
}
} else if (!strncmp(ev_text.c_str(), "modt_global=", 12)) {
arg_modt_global = true;
int modt = std::stoi(ev_text.substr(12));
modt = std::clamp(modt, 0, 2);
arg_modt = static_cast<uint8_t>(modt);
} else if (!strncmp(ev_text.c_str(), "tune=", 5)) {
int tune = std::stoi(ev_text.substr(5));
tune = std::clamp(tune, -64, 63);
int channel = trk_get_channel_num(mtrk);
if (channel >= 0) {
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
ev.ticks, channel, MIDI_CC_EX_TUNE,
static_cast<uint8_t>(tune));
}
} else if (!strncmp(ev_text.c_str(), "lfos=", 5)) {
int lfos = std::stoi(ev_text.substr(5));
lfos = std::clamp(lfos, 0, 127);
int channel = trk_get_channel_num(mtrk);
if (channel >= 0) {
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
ev.ticks, channel, MIDI_CC_EX_LFOS,
static_cast<uint8_t>(lfos));
}
} else if (!strncmp(ev_text.c_str(), "lfos_global=", 12)) {
arg_lfos_global = true;
int lfos = std::stoi(ev_text.substr(12));
lfos = std::clamp(lfos, 0, 127);
arg_lfos = static_cast<uint8_t>(lfos);
} else if (!strncmp(ev_text.c_str(), "lfodl=", 6)) {
int lfodl = std::stoi(ev_text.substr(6));
lfodl = std::clamp(lfodl, 0, 127);
int channel = trk_get_channel_num(mtrk);
if (channel >= 0) {
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
ev.ticks, channel, MIDI_CC_EX_LFODL,
static_cast<uint8_t>(lfodl));
}
} else if (!strncmp(ev_text.c_str(), "lfodl_global=", 13)) {
arg_lfodl_global = true;
int lfodl = std::stoi(ev_text.substr(13));
lfodl = std::clamp(lfodl, 0, 127);
arg_lfodl = static_cast<uint8_t>(lfodl);
} else if (!strncmp(ev_text.c_str(), "prio=", 5)) {
int prio = std::stoi(ev_text.substr(5));
prio = std::clamp(prio, 0, 127);
int channel = trk_get_channel_num(mtrk);
if (channel >= 0) {
mtrk[ievt] = std::make_unique<controller_message_midi_event>(
ev.ticks, channel, MIDI_CC_EX_PRIO,
static_cast<uint8_t>(prio));
}
} else if (!strncmp(ev_text.c_str(), "modscale_global=", 16)) {
arg_mod_scale = std::stof(ev_text.substr(16));
arg_mod_scale = std::clamp(arg_mod_scale, 0.0f, 16.0f);
// the actual scale get's applied in a seperate filter
} else if (!strncmp(ev_text.c_str(), "sym=", 4)) {
arg_sym = ev_text.substr(4);
fix_str(arg_sym);
} else if (!strncmp(ev_text.c_str(), "mvl=", 4)) {
int mvl = std::stoi(ev_text.substr(4));
if (mvl < 0 || mvl > 128)
die("infile \"mvl=%d\" out of range\n", mvl);
arg_mvl = static_cast<uint8_t>(mvl);
} else if (!strncmp(ev_text.c_str(), "vgr=", 4)) {
arg_vgr = ev_text.substr(4);
fix_str(arg_vgr);
} else if (!strncmp(ev_text.c_str(), "pri=", 4)) {
int prio = std::stoi(ev_text.substr(4));
if (prio < 0 || prio > 127)
die("infile \"pri=%d\" out of range\n", prio);
arg_pri = static_cast<uint8_t>(prio);
} else if (!strncmp(ev_text.c_str(), "rev=", 4)) {
int rev = std::stoi(ev_text.substr(4));
if (rev < 0 || rev > 127)
die("infile \"rev=%d\" out of range\n", rev);
arg_rev = static_cast<uint8_t>(rev);
} else if (!strncmp(ev_text.c_str(), "nat=", 4)) {
int nat = std::stoi(ev_text.substr(4));
if (nat < 0 || nat > 1)
die("infile \"nat=%d\" out of range\n", nat);
if (nat == 1)
arg_natural = true;
else
arg_natural = false;
}
} // end event loop
} // end track loop
// insert loop and global events
for (size_t itrk = 0; itrk < mf.midi_tracks.size(); itrk++) {
midi_track& mtrk = mf[itrk];
int chn = trk_get_channel_num(mtrk);
// chn mustn't be negative because track with no message events
// have been sorted out previously
if (chn < 0)
continue;
if (found_start) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
loop_start, static_cast<uint8_t>(chn),
MIDI_CC_EX_LOOP, EX_LOOP_START));
auto loop_start_event_pos = std::lower_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(loop_start_event_pos, std::move(cev));
}
if (found_end) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
loop_end, static_cast<uint8_t>(chn),
MIDI_CC_EX_LOOP, EX_LOOP_END));
auto loop_end_event_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(loop_end_event_pos, std::move(cev));
}
if (arg_modt_global) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
0, static_cast<uint8_t>(chn),
MIDI_CC_EX_MODT, arg_modt));
auto insert_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(insert_pos, std::move(cev));
}
if (arg_lfos_global) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
0, static_cast<uint8_t>(chn),
MIDI_CC_EX_LFOS, arg_lfos));
auto insert_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(insert_pos, std::move(cev));
}
if (arg_lfodl_global) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
0, static_cast<uint8_t>(chn),
MIDI_CC_EX_LFODL, arg_lfodl));
auto insert_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(insert_pos, std::move(cev));
}
if (!volume_init[itrk]) {
std::unique_ptr<midi_event> cev(new controller_message_midi_event(
0, static_cast<uint8_t>(chn),
MIDI_CC_MSB_VOLUME, 127));
auto insert_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
cev, ev_tick_cmp);
mtrk.midi_events.insert(insert_pos, std::move(cev));
}
std::unique_ptr<midi_event> dev(new dummy_midi_event(last_event));
auto insert_pos = std::upper_bound(
mtrk.midi_events.begin(),
mtrk.midi_events.end(),
dev, ev_tick_cmp);
mtrk.midi_events.insert(insert_pos, std::move(dev));
}
}
static void midi_remove_empty_tracks() {
using namespace cppmidi;
midi_track tempo_track;
midi_track timesignature_track;
// seperate tempo events
for (midi_track& mtrk : mf.midi_tracks) {
for (size_t ievt = 0; ievt < mtrk.midi_events.size(); ievt++) {
if (typeid(*mtrk[ievt]) == typeid(tempo_meta_midi_event)) {
uint32_t tick = mtrk[ievt]->ticks;
tempo_track.midi_events.emplace_back(std::move(mtrk[ievt]));
mtrk[ievt] = std::make_unique<dummy_midi_event>(tick);
} else if (typeid(*mtrk[ievt]) == typeid(timesignature_meta_midi_event)) {
uint32_t tick = mtrk[ievt]->ticks;
timesignature_track.midi_events.emplace_back(std::move(mtrk[ievt]));
mtrk[ievt] = std::make_unique<dummy_midi_event>(tick);
}
}
}
tempo_track.sort_events();
timesignature_track.sort_events();
// remove tracks without notes
for (size_t itrk = 0; itrk < mf.midi_tracks.size(); itrk++) {
// set false if a note event was found
bool del = true;
for (const std::unique_ptr<midi_event>& ev : mf[itrk].midi_events) {
if (typeid(*ev) == typeid(noteon_message_midi_event)) {
del = false;
break;
}
}
if (del) {
dbg("deleting meta only track: %d\n", itrk);
mf.midi_tracks.erase(mf.midi_tracks.begin() +
static_cast<long>(itrk--));
}
}
if (mf.midi_tracks.size() == 0)
return;
// remove surplus time signature events
for (size_t ievt = 0; ievt < timesignature_track.midi_events.size(); ievt++) {
size_t dummy;
if (find_next_event_at_tick_index<timesignature_meta_midi_event>(
timesignature_track, ievt, dummy)) {
timesignature_track.midi_events.erase(timesignature_track.midi_events.begin() +
static_cast<long>(ievt--));
}
}
// all empty tracks deleted, now reinsert tempo events to first track
size_t insert_begin = 0;
for (std::unique_ptr<midi_event>& tev : tempo_track.midi_events) {
// locate position for insertion
auto position = std::lower_bound(
mf[0].midi_events.begin() + insert_begin,
mf[0].midi_events.end(),
tev, ev_tick_cmp);
// do not allow events to be inserted before the previous ones
insert_begin = position - mf[0].midi_events.begin() + 1;
mf[0].midi_events.insert(position, std::move(tev));
}
// same for time signatures
insert_begin = 0;
for (std::unique_ptr<midi_event>& tev : timesignature_track.midi_events) {
// locate position for insertion
auto position = std::lower_bound(
mf[0].midi_events.begin() + insert_begin,
mf[0].midi_events.end(),
tev, ev_tick_cmp);
// do not allow events to be inserted before the previous ones
insert_begin = position - mf[0].midi_events.begin() + 1;
mf[0].midi_events.insert(position, std::move(tev));
}
// done
}
/*
* midi_apply_filters() :
*
* Volume / Velocity:
* The GBA engine will multiply the sample's waveform by the volume values.
* Since this will do a linear scale and not a natural scale, this function
* applies the scale beforehand. Also, expression and volume are combined
* to volume only.
*
* Modulation Scale:
* The scale of modulation intensity isn't really standardized.
* Therefore an option to globally scale the modulation is offerred.
*/
static void midi_apply_filters() {
using namespace cppmidi;
auto vol_scale = [&](uint8_t vol, uint8_t expr) {
double x = vol * expr * arg_mvl;
if (arg_natural) {
x /= 127.0 * 127.0 * 128.0;
x = pow(x, 10.0 / 6.0);
x *= 127.0;
x = std::round(x);
} else {
x /= 127.0 * 128.0;
x = std::round(x);
}
return static_cast<uint8_t>(std::clamp(static_cast<int>(x), 0, 127));
};
auto vel_scale = [&](uint8_t vel) {
double x = vel;
if (arg_natural) {
x /= 127.0;
x = pow(x, 10.0 / 6.0);
x *= 127.0;
x = std::round(x);
}
// clamp to lower 1 because midi velocity 0 is a note off
return static_cast<uint8_t>(std::clamp(static_cast<int>(x), 1, 127));
};
for (midi_track& mtrk : mf.midi_tracks) {
uint8_t volume = 100;
uint8_t expression = 127;
for (size_t ievt = 0; ievt < mtrk.midi_events.size(); ievt++) {
midi_event& ev = *mtrk[ievt];
if (typeid(ev) == typeid(controller_message_midi_event)) {
controller_message_midi_event& ctrl_ev =
static_cast<controller_message_midi_event&>(ev);
if (ctrl_ev.get_controller() == MIDI_CC_MSB_VOLUME) {
volume = ctrl_ev.get_value();
ctrl_ev.set_value(vol_scale(volume, expression));
} else if (ctrl_ev.get_controller() == MIDI_CC_MSB_EXPRESSION) {
expression = ctrl_ev.get_value();
ctrl_ev.set_controller(MIDI_CC_MSB_VOLUME);
ctrl_ev.set_value(vol_scale(volume, expression));
} else if (ctrl_ev.get_controller() == MIDI_CC_MSB_MOD) {
float scaled_mod = ctrl_ev.get_value() * arg_mod_scale;
scaled_mod = std::roundf(scaled_mod);
ctrl_ev.set_value(static_cast<uint8_t>(std::clamp(scaled_mod, 0.0f, 127.0f)));
}
}
else if (typeid(ev) == typeid(noteon_message_midi_event)) {
noteon_message_midi_event& note_ev =
static_cast<noteon_message_midi_event&>(ev);
note_ev.set_velocity(vel_scale(note_ev.get_velocity()));
}
}
}
}
static void midi_apply_loop_and_state_reset() {
using namespace cppmidi;
for (midi_track& mtrk : mf.midi_tracks) {
uint32_t tempo = 500000; // 120 bpm
bool tempo_init = false;
uint8_t voice = 0;
uint8_t vol = 100;
uint8_t pan = 0x40;
int16_t bend = 0;
uint8_t bendr = 2;
uint8_t mod = 0;
uint8_t modt = 0;
uint8_t tune = 0x40;
uint8_t prio = 0;
// FIXME add memacc and pseudo echo for completeness
// omitted for now because nobody would be using it
uint32_t loop_start_tick = 0xFFFFFFFF;
for (size_t itrk = 0; itrk < mtrk.midi_events.size(); itrk++) {
midi_event& ev = *mtrk[itrk];
if (typeid(ev) == typeid(tempo_meta_midi_event)) {
tempo_meta_midi_event& tev = static_cast<tempo_meta_midi_event&>(ev);
if (ev.ticks <= loop_start_tick) {
tempo = tev.get_us_per_beat();
tempo_init = true;
}
} else if (typeid(ev) == typeid(program_message_midi_event)) {
program_message_midi_event& pev = static_cast<program_message_midi_event&>(ev);
if (ev.ticks <= loop_start_tick)
voice = pev.get_program();
} else if (typeid(ev) == typeid(pitchbend_message_midi_event)) {
pitchbend_message_midi_event& pev = static_cast<pitchbend_message_midi_event&>(ev);
if (ev.ticks <= loop_start_tick)
bend = pev.get_pitch();
} else if (typeid(ev) == typeid(controller_message_midi_event)) {
controller_message_midi_event& cev = static_cast<controller_message_midi_event&>(ev);
uint8_t ctrl = cev.get_controller();
switch (ctrl) {
case MIDI_CC_MSB_VOLUME:
if (ev.ticks <= loop_start_tick)
vol = cev.get_value();
break;
case MIDI_CC_MSB_PAN:
if (ev.ticks <= loop_start_tick)
pan = cev.get_value();
break;
case MIDI_CC_EX_BENDR:
if (ev.ticks <= loop_start_tick)
bendr = cev.get_value();
break;
case MIDI_CC_MSB_MOD:
if (ev.ticks <= loop_start_tick)
mod = cev.get_value();
break;
case MIDI_CC_EX_MODT:
if (ev.ticks <= loop_start_tick)
modt = cev.get_value();
break;
case MIDI_CC_EX_TUNE:
if (ev.ticks <= loop_start_tick)
tune = cev.get_value();
break;
case MIDI_CC_EX_PRIO:
if (ev.ticks <= loop_start_tick)
prio = cev.get_value();
break;
case MIDI_CC_EX_LOOP:
if (cev.get_value() == EX_LOOP_START) {
// loop start
loop_start_tick = ev.ticks;
} else if (cev.get_value() == EX_LOOP_END &&
ev.ticks > loop_start_tick) {
// loop end insert events for start state
std::vector<std::unique_ptr<midi_event>> ptrs;
if (tempo_init) {
ptrs.emplace_back(new tempo_meta_midi_event(
ev.ticks, tempo));
}
ptrs.emplace_back(new program_message_midi_event(
ev.ticks, cev.channel(),
voice));
ptrs.emplace_back(new controller_message_midi_event(
ev.ticks, cev.channel(),
MIDI_CC_MSB_VOLUME, vol));
ptrs.emplace_back(new controller_message_midi_event(
ev.ticks, cev.channel(),
MIDI_CC_MSB_PAN, pan));
ptrs.emplace_back(new pitchbend_message_midi_event(
ev.ticks, cev.channel(), bend));
ptrs.emplace_back(new controller_message_midi_event(
ev.ticks, cev.channel(),
MIDI_CC_EX_BENDR, bendr));
ptrs.emplace_back(new controller_message_midi_event(
ev.ticks, cev.channel(),