-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlayer.pde
705 lines (565 loc) · 22.5 KB
/
Player.pde
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
import javax.sound.midi.*;
import uk.co.kernite.VGM.*;
import java.util.LinkedHashMap;
class Player {
final int LENGTH_THRESHOLD = 90000000;
final int TEMPO_LIMIT = 1000;
final String DEFAULT_STOPPED_MSG = "Drag and drop a file to play...";
final String DEFAULT_EMPTY_MSGS = "• no messages •";
VGMPlayer vgm_player;
boolean new_engine = false;
Sequencer seq;
Sequence mid;
javax.sound.midi.Synthesizer alt_syn;
MidiFileFormat metadata;
PlayerDisplay disp;
VGMPlayerDisplay vgm_disp;
int midi_resolution;
int meta_channel_prefix = 0;
int meta_curr_track = 0;
int num_tracks = 0;
ChannelOsc[] channels;
long prev_position;
String curr_filename = DEFAULT_STOPPED_MSG;
String sf_filename = "Default";
String vgm_emu_type = "";
int curr_rpn = 0;
int curr_bank = 0;
int mid_rootnote = 0; // C
int mid_scale = 0; // major
int playing_state = -1; // -1 no loaded, 0 paused, 1 playing
boolean system_synth = false;
boolean vgm_mode = false;
float vu_anim_val = 0.0;
boolean vu_anim_returning = false;
float osc_synth_volume_mult = 1.0;
boolean locked_vis_redraw = false;
// values to be read by the display...
String history_text_messages = ""; // keeping track of every text (meta) msg gotten
String last_text_message = DEFAULT_EMPTY_MSGS;
float last_freqDetune = 0.0;
float last_noteDetune = 0.0;
String custom_info_msg = "";
HashMap<String, String> metadata_map;
long epoch_at_begin = 0;
Player() {
channels = new ChannelOsc[16];
metadata_map = new LinkedHashMap();
create_visualizer(true);
create_display(0, 318);
set_seq_synth(prefs.getBoolean("remember", true) ? prefs.getBoolean("remember synth", true) : true);
if (win_plist == null) {
seq.setLoopCount(-1);
disp.b_loop.set_pressed(true);
}
else {
seq.setLoopCount(0);
disp.b_loop.set_pressed(false);
}
if (system_synth) load_soundfont(new File(prefs.get("sf path", "")), false);
vgm_player = new VGMPlayer(44100);
vgm_player.setVolume(0.5);
vgm_disp = new VGMPlayerDisplay(vgm_player);
}
void create_display(int x, int y) {
PlayerDisplay d;
d = new PlayerDisplay(x, y, this);
this.disp = d;
}
void create_visualizer() {
create_visualizer(false);
}
void create_visualizer(boolean also_osc_objects) {
locked_vis_redraw = true;
for (int i = 0; i < 16; i++) {
if (also_osc_objects) {
channels[i] = new ChannelOsc(-1);
if (i == 9) channels[i] = new ChannelOsc(4);
}
channels[i].create_display(i, channel_disp_type);
if (also_osc_objects) channels[i].disp.redraw(); // draw meters at value 0
else if (playing_state == -1) {
vu_anim_val = 0.0;
vu_anim_returning = false;
}
}
locked_vis_redraw = false;
}
protected String bytes_to_text(byte[] arr) {
String text = "";
for (byte b : arr) {
if (b >= 0) text += Character.toString((char) b);
else text += "×";
}
return text.trim().replace("\n", "");
}
protected void set_params_from_sysex(byte[] arr) {
int man_id = arr[0];
if (man_id < 0) return;
String s = metadata_map.getOrDefault("Manufacturer ID", "");
switch(man_id) {
case 67: // Yamh, XG
if (s.contains("XG")) break;
metadata_map.put("Manufacturer ID", s + "XG ");
break;
case 65: // Rold, GS
if (s.contains("GS")) break;
metadata_map.put("Manufacturer ID", metadata_map.getOrDefault("Manufacturer ID", "") + "GS ");
break;
default: // check if GM or GM2
if (arr[2] == 9 && !s.contains("GM"))
metadata_map.put("Manufacturer ID",
metadata_map.getOrDefault("Manufacturer ID", "") +
(arr[3] == 1 ? "GM " : arr[3] == 3 ? "GM2 " : ""));
break;
}
}
protected void set_rpn_param_val(int chan, float value) {
switch (curr_rpn) {
case 0:
channels[chan].curr_bend_range = value;
break;
default:
break;
}
}
protected void add_rpn_param_val(int chan, float value, boolean negative) {
int mult = (negative ? -1 : 1);
switch (curr_rpn) {
case 0:
channels[chan].curr_bend_range += value * mult;
break;
default:
break;
}
}
String play_file(String filename) {
return play_file(filename, false);
}
String play_file(String filename, boolean keep_paused) {
if (filename.toLowerCase().endsWith("wav")) {
play_wav(filename);
return "";
}
else if (vgm_extensions.contains(filename.toLowerCase().substring(filename.lastIndexOf(".")+1))) {
return play_vgm(filename);
}
File file = new File(filename);
if (system_synth && prefs.getBoolean("autoload sf", true)) try_match_soundfont(filename);
try {
mid = MidiSystem.getSequence(file);
prep_javax_midi(false);
num_tracks = mid.getTracks().length;
set_playing_state(-1);
seq.setSequence(mid);
if (seq.getTempoInBPM() >= TEMPO_LIMIT) throw new InvalidMidiDataException();
midi_resolution = mid.getResolution();
curr_filename = filename;
setTicks(0);
epoch_at_begin = java.time.Instant.now().getEpochSecond();
set_playing_state(keep_paused ? 0 : 1);
vgm_player.stop();
}
catch(InvalidMidiDataException imde) {
return "Invalid MIDI data!";
}
catch(IOException ioe) {
return "I/O Exception!";
}
catch (Exception e) {}
vgm_mode = false;
metadata_map.put("Song tempo", Integer.toString(floor(seq.getTempoInBPM())) + " BPM");
return "";
}
String play_vgm(String filename) {
try {
vgm_player.stop();
vgm_player.loadFile(filename);
vgm_player.startTrack(0, 60);
vgm_emu_type = vgm_player.getEmuName();
}
catch (Exception e) {
return "Impossible";
}
vgm_mode = true;
set_playing_state(-1);
curr_filename = filename;
return "";
}
void play_wav(String filename) {
// no
set_playing_state(-1);
File file = new File(filename);
load_soundfont(file);
//prep_javax_midi();
try {
event_listener.send(new ShortMessage(128, 0, 48, 127), 0);
event_listener.send(new ShortMessage(192, 0, 0, 0), 0);
event_listener.send(new ShortMessage(144, 0, 48, 127), 0);
}
catch (InvalidMidiDataException imde) {
println("imde on wav");
}
}
boolean is_song_long() {
return seq.getMicrosecondLength() > LENGTH_THRESHOLD;
}
Sequence prep_javax_midi(boolean right_now) {
try {
int n = mid == null ? 16 : mid.getTracks().length;
float vol = win_labs == null ? 0x2f : map(win_labs.k_volume.value, 0.0, 2.0, 0x00, 0x4f);
for (int i = 0; i < n; i++) {
// msgs: remove reverb, soften volume
if (mid != null) {
mid.getTracks()[i].add(new MidiEvent(new ShortMessage(176, i, 91, 0), 0));
mid.getTracks()[i].add(new MidiEvent(new SysexMessage(
new byte[] {(byte)0xf0, 0x7f, 0x7f, 0x04, 0x01, 0x00, (byte)vol, (byte)0xf7}, 8)
, 0));
}
if (right_now) {
event_listener.send(new ShortMessage(176, i, 91, 1), 0);
event_listener.send(new SysexMessage(
new byte[] {(byte)0xf0, 0x7f, 0x7f, 0x04, 0x01, 0x00, (byte)vol, (byte)0xf7}, 8)
, 0);
}
}
}
catch (InvalidMidiDataException imde) {
println("can't adjust system synth (imde)");
}
return mid;
}
void reload_curr_file(boolean from_looppoint) {
if (from_looppoint)
setTicks(seq.getLoopStartPoint());
else {
setTicks(0);
epoch_at_begin = java.time.Instant.now().getEpochSecond();
clear_meta_msgs();
}
}
void try_match_soundfont(String mid_filename) {
mid_filename = mid_filename.replaceFirst("[.][^.]+$", "");
File f = new File(mid_filename + ".dls");
if (!f.exists() || f.isDirectory()) {
f = new File(mid_filename + ".sf2");
}
if (f.exists() && !f.isDirectory()) {
load_soundfont(f);
}
else return;
}
String load_soundfont(File file) {
return load_soundfont(file, true);
}
String load_soundfont(File file, boolean switch_mode) {
try {
Soundbank sf = MidiSystem.getSoundbank(file);
if (switch_mode) set_seq_synth(true);
alt_syn.loadAllInstruments(sf);
sf_filename = check_and_shrink_string(file.getName().replaceFirst("[.][^.]+$", ""), 16);
metadata_map.put("SF Name", sf.getName());
metadata_map.put("SF Description", sf.getDescription());
metadata_map.put("SF Vendor", sf.getVendor());
}
catch (InvalidMidiDataException imd) {
return "Invalid SF data!";
}
catch (IOException ioe) {
return "I/O Error!";
}
return "";
}
void set_seq_synth(boolean is_system) {
int playing_state_before = playing_state;
String prev_filename = curr_filename;
int prev_ticks = seq == null ? 0 : int(seq.getTickPosition());
long[] prev_looppoints = null;
if (seq != null) prev_looppoints = new long[] {seq.getLoopStartPoint(), seq.getLoopEndPoint()};
set_playing_state(-1);
try {
if (seq != null) seq.close();
seq = MidiSystem.getSequencer(false);
seq.open();
seq.setLoopCount(disp.b_loop.pressed ? -1 : 0);
seq.addMetaEventListener(meta_listener);
Transmitter transmitter = seq.getTransmitter();
if (is_system) {
if (alt_syn == null) {
alt_syn = MidiSystem.getSynthesizer();
alt_syn.open();
}
}
transmitter.setReceiver(event_listener);
system_synth = is_system;
new Sound(PARENT).volume(is_system ? 0 : OVERALL_VOL);
}
catch (MidiUnavailableException mue) {
println("Midi device unavailable!");
}
if (playing_state_before >= 0) {
prep_javax_midi(true);
play_file(prev_filename, playing_state_before == 0);
seq.setLoopStartPoint(prev_looppoints[0]);
seq.setLoopEndPoint(prev_looppoints[1]);
setTicks(prev_ticks);
if (playing_state_before == 0) set_playing_state(0); // keep paused if it was
}
}
void reset_looppoints() {
seq.setLoopEndPoint(-1);
seq.setLoopStartPoint(0);
}
void set_all_freqDetune(float freq_detune) {
last_freqDetune = freq_detune;
for (ChannelOsc c : channels) {
c.set_all_oscs_freqDetune(freq_detune);
}
}
void set_all_noteDetune(float note_detune) {
last_noteDetune = note_detune;
for (ChannelOsc c : channels) {
c.set_all_oscs_noteDetune(note_detune);
}
}
void set_all_osc_types(float osc_type) {
for (ChannelOsc c : channels) {
c.set_osc_type(osc_type);
}
}
void vu_anim_step() {
if (locked_vis_redraw) return;
for (ChannelOsc c : channels) {
c.disp.meter_vu_lerped = vu_anim_val;
c.disp.redraw();
}
if (!vu_anim_returning && vu_anim_val <= 0.99) vu_anim_val = 1 - (1 - vu_anim_val) * 0.76;
else vu_anim_returning = true;
if (vu_anim_returning) vu_anim_val *= 0.9;
}
void setTicks(long ticks) {
seq.setTickPosition(ticks);
meta_curr_track = 1;
}
void set_playing_state(int how) {
if (seq == null || how == playing_state) return;
if (win_labs != null)
win_labs.k_pitchbend.value = win_labs.k_pitchbend.neutral_value;
how = constrain(how, -1, 1);
switch (how) {
case -1:
seq.stop();
shut_up_all();
reset_all_params();
break;
case 0:
seq.stop();
shut_up_all();
break;
case 1:
seq.start();
seq.setTempoFactor(win_labs == null ? 1 : win_labs.k_player_speed.value);
break;
}
playing_state = how;
request_media_buttons_refresh();
}
void shut_up_all() {
for (ChannelOsc c : channels) c.shut_up();
}
void reset_all_params() {
for (ChannelOsc c : channels) c.reset_params();
setTicks(0);
clear_meta_msgs();
clear_metadata_map_keep_sf();
curr_rpn = 0;
curr_bank = 0;
mid_rootnote = 0;
mid_scale = 0;
curr_filename = DEFAULT_STOPPED_MSG;
epoch_at_begin = 0;
reset_looppoints();
}
void clear_meta_msgs() {
last_text_message = DEFAULT_EMPTY_MSGS;
history_text_messages = "";
if (dialog_meta_msgs != null) dialog_meta_msgs.setLargeMessage("");
}
void clear_metadata_map_keep_sf() {
String n = metadata_map.get("SF Name");
String d = metadata_map.get("SF Description");
String v = metadata_map.get("SF Vendor");
metadata_map.clear();
metadata_map.put("SF Name", n);
metadata_map.put("SF Description", d);
metadata_map.put("SF Vendor", v);
}
void set_channel_muted(boolean how, int chan) {
channels[chan].set_muted(how);
if (alt_syn != null) alt_syn.getChannels()[chan].setMute(how);
}
void set_channel_solo(boolean how, int chan) {
if (how) {
for (ChannelOsc c : channels) {
if (c.id == chan) set_channel_muted(false, c.id);
else set_channel_muted(true, c.id);
}
}
else {
for (ChannelOsc c : channels) {
set_channel_muted(!c.silenced, c.id);
}
}
}
String[][] get_metadata_table() {
if (metadata_map == null) return null;
int size = metadata_map.size() - (system_synth ? 0 : 3);
String[][] t = new String[size][2];
int i = 0;
for (Entry e : metadata_map.entrySet()) {
if (e.getValue() == null ||((String) e.getValue()).equals("")) continue;
if (!system_synth && (((String) e.getKey()).contains("SF"))) continue;
t[i] = new String[] {(String) e.getKey(), (String) e.getValue()};
i++;
}
return t;
}
void check_chan_disp_buttons(int mButton) {
for (ChannelOsc c : channels) c.disp.check_buttons(mButton);
}
void redraw() {
if (locked_vis_redraw) return;
for (ChannelOsc c : channels) {
c.redraw_playing();
}
this.disp.redraw(true);
if (vgm_mode) this.vgm_disp.redraw();
}
Receiver event_listener = new Receiver() {
void send(MidiMessage msg, long timeStamp) {
if (system_synth) {
try {
alt_syn.getReceiver().send(msg, timeStamp);
}
catch (MidiUnavailableException mue) { println("mue on system synth"); }
}
if (msg instanceof ShortMessage) {
ShortMessage event = (ShortMessage) msg;
int chan = event.getChannel();
int comm = event.getCommand();
int data1 = event.getData1();
int data2 = event.getData2();
if (comm == ShortMessage.NOTE_ON && data2 > 0) {
channels[chan].play_note(data1, data2);
}
else if (comm == ShortMessage.NOTE_OFF || (comm == ShortMessage.NOTE_ON && data2 <= 0)) {
channels[chan].stop_note(data1);
}
else if (comm == ShortMessage.PROGRAM_CHANGE) {
if (chan == 9) {
channels[chan].set_osc_type(4);
}
else {
channels[chan].set_osc_type(prog_osc_relationship[data1]);
}
channels[chan].midi_program = data1;
}
else if (comm == ShortMessage.PITCH_BEND) {
channels[chan].set_bend(data1, data2);
}
else if (comm == ShortMessage.CONTROL_CHANGE) {
switch (data1) {
case 0: // bank select
curr_bank = data2;
break;
case 7:
channels[chan].set_volume(data2); // chan vol
break;
case 10: // chan pan
channels[chan].set_pan(data2);
break;
case 11: // chan expression
channels[chan].set_expression(data2);
break;
case 100:
curr_rpn = data2; // rpn set
break;
case 98:
curr_rpn = data2;
break;
case 6:
set_rpn_param_val(chan, data2); // data entry
break;
case 64: // hold pedal
channels[chan].set_hold(data2);
break;
case 66: // sostenuto pedal
channels[chan].set_sostenuto(data2);
break;
case 67: // soft pedal
channels[chan].set_soft(data2);
break;
case 96:
add_rpn_param_val(chan, data2, false); // data increment
break;
case 97:
add_rpn_param_val(chan, data2, true); // data decrement
break;
default:
break;
}
}
}
else if (msg instanceof SysexMessage) {
set_params_from_sysex(((SysexMessage)msg).getData());
}
}
void close() {}
};
MetaEventListener meta_listener = new MetaEventListener() {
void meta(MetaMessage msg) {
int type = msg.getType();
byte[] data = msg.getData();
if (type == 32) { // Channel prefix
meta_channel_prefix = (int) data[0];
}
else if (type == 2) { // Copyright
metadata_map.put("Copyright", bytes_to_text(data));
}
else if (type == 3) { // Track name
metadata_map.put(
num_tracks == 1 ? "Sequence title" :
"Track " + meta_curr_track + " name",
bytes_to_text(data));
meta_curr_track++;
}
else if (type == 4) { // Instrument name
metadata_map.put("Ch. " + (meta_channel_prefix+1) + "'s instrument", bytes_to_text(data));
}
else if (type == 1 || type == 5 || type == 6 || type == 7) { // Lyrics or text
String text = bytes_to_text(data);
if (type == 6 || type == 7) text = "• " + text + " •";
if (!text.equals("")) {
last_text_message = text;
history_text_messages += text + "\n";
dialog_meta_msgs.addToLargeMessage(text);
}
}
else if (type == 88) { // Time signature
metadata_map.put("Time signature", data[0] + "/" + (int)pow(2, data[1]));
}
else if (type == 89) { // Key signature
mid_scale = data[data.length - 1];
if (mid_scale == 0) mid_rootnote = major_rootnotes[data[0] + 7];
else if (mid_scale == 1) mid_rootnote = minor_rootnotes[data[0] + 7];
metadata_map.put("Key signature", NOTE_NAMES[mid_rootnote] + " " + (mid_scale == 0 ? "major" : "minor"));
return;
}
else if (type == 47) { // End
set_playing_state(-1);
if (win_plist != null && win_plist.active) win_plist.set_current_item(win_plist.current_item + 1);
return;
}
}
};
}