forked from jummbus/jummbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsynth.ts
More file actions
11117 lines (9897 loc) · 631 KB
/
synth.ts
File metadata and controls
11117 lines (9897 loc) · 631 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
// Copyright (c) 2012-2022 John Nesky and contributing authors, distributed under the MIT license, see accompanying the LICENSE.md file.
import { Dictionary, DictionaryArray, FilterType, SustainType, EnvelopeType, InstrumentType, EffectType, EnvelopeComputeIndex, Transition, Unison, Chord, Vibrato, Envelope, AutomationTarget, Config, getDrumWave, drawNoiseSpectrum, getArpeggioPitchIndex, performIntegralOld, getPulseWidthRatio, effectsIncludeTransition, effectsIncludeChord, effectsIncludePitchShift, effectsIncludeDetune, effectsIncludeVibrato, effectsIncludeNoteFilter, effectsIncludeDistortion, effectsIncludeBitcrusher, effectsIncludePanning, effectsIncludeChorus, effectsIncludeEcho, effectsIncludeReverb, OperatorWave } from "./SynthConfig";
import { EditorConfig } from "../editor/EditorConfig";
import { scaleElementsByFactor, inverseRealFourierTransform } from "./FFT";
import { Deque } from "./Deque";
import { FilterCoefficients, FrequencyResponse, DynamicBiquadFilter, warpInfinityToNyquist } from "./filtering";
declare global {
interface Window {
AudioContext: any;
webkitAudioContext: any;
}
}
const epsilon: number = (1.0e-24); // For detecting and avoiding float denormals, which have poor performance.
// For performance debugging:
//let samplesAccumulated: number = 0;
//let samplePerformance: number = 0;
export function clamp(min: number, max: number, val: number): number {
max = max - 1;
if (val <= max) {
if (val >= min) return val;
else return min;
} else {
return max;
}
}
function validateRange(min: number, max: number, val: number): number {
if (min <= val && val <= max) return val;
throw new Error(`Value ${val} not in range [${min}, ${max}]`);
}
const enum CharCode {
SPACE = 32,
HASH = 35,
PERCENT = 37,
AMPERSAND = 38,
PLUS = 43,
DASH = 45,
DOT = 46,
NUM_0 = 48,
NUM_1 = 49,
NUM_2 = 50,
NUM_3 = 51,
NUM_4 = 52,
NUM_5 = 53,
NUM_6 = 54,
NUM_7 = 55,
NUM_8 = 56,
NUM_9 = 57,
EQUALS = 61,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
UNDERSCORE = 95,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
LEFT_CURLY_BRACE = 123,
RIGHT_CURLY_BRACE = 125,
}
const enum SongTagCode {
beatCount = CharCode.a, // added in BeepBox URL version 2
bars = CharCode.b, // added in BeepBox URL version 2
vibrato = CharCode.c, // added in BeepBox URL version 2, DEPRECATED
fadeInOut = CharCode.d, // added in BeepBox URL version 3 for transition, switched to fadeInOut in 9
loopEnd = CharCode.e, // added in BeepBox URL version 2
eqFilter = CharCode.f, // added in BeepBox URL version 3
barCount = CharCode.g, // added in BeepBox URL version 3
unison = CharCode.h, // added in BeepBox URL version 2
instrumentCount = CharCode.i, // added in BeepBox URL version 3
patternCount = CharCode.j, // added in BeepBox URL version 3
key = CharCode.k, // added in BeepBox URL version 2
loopStart = CharCode.l, // added in BeepBox URL version 2
reverb = CharCode.m, // added in BeepBox URL version 5, DEPRECATED
channelCount = CharCode.n, // added in BeepBox URL version 6
channelOctave = CharCode.o, // added in BeepBox URL version 3
patterns = CharCode.p, // added in BeepBox URL version 2
effects = CharCode.q, // added in BeepBox URL version 7
rhythm = CharCode.r, // added in BeepBox URL version 2
scale = CharCode.s, // added in BeepBox URL version 2
tempo = CharCode.t, // added in BeepBox URL version 2
preset = CharCode.u, // added in BeepBox URL version 7
volume = CharCode.v, // added in BeepBox URL version 2
wave = CharCode.w, // added in BeepBox URL version 2
supersaw = CharCode.x, // added in BeepBox URL version 9
filterResonance = CharCode.y, // added in BeepBox URL version 7, DEPRECATED
drumsetEnvelopes = CharCode.z, // added in BeepBox URL version 7 for filter envelopes, still used for drumset envelopes
algorithm = CharCode.A, // added in BeepBox URL version 6
feedbackAmplitude = CharCode.B, // added in BeepBox URL version 6
chord = CharCode.C, // added in BeepBox URL version 7, DEPRECATED
detune = CharCode.D, // added in JummBox URL version 3(?) for detune, DEPRECATED
envelopes = CharCode.E, // added in BeepBox URL version 6 for FM operator envelopes, repurposed in 9 for general envelopes.
feedbackType = CharCode.F, // added in BeepBox URL version 6
arpeggioSpeed = CharCode.G, // added in JummBox URL version 3 for arpeggioSpeed, DEPRECATED
harmonics = CharCode.H, // added in BeepBox URL version 7
stringSustain = CharCode.I, // added in BeepBox URL version 9
// = CharCode.J,
// = CharCode.K,
pan = CharCode.L, // added between 8 and 9, DEPRECATED
customChipWave = CharCode.M, // added in JummBox URL version 1(?) for customChipWave
songTitle = CharCode.N, // added in JummBox URL version 1(?) for songTitle
limiterSettings = CharCode.O, // added in JummBox URL version 3(?) for limiterSettings
operatorAmplitudes = CharCode.P, // added in BeepBox URL version 6
operatorFrequencies = CharCode.Q, // added in BeepBox URL version 6
operatorWaves = CharCode.R, // added in JummBox URL version 4 for operatorWaves
spectrum = CharCode.S, // added in BeepBox URL version 7
startInstrument = CharCode.T, // added in BeepBox URL version 6
channelNames = CharCode.U, // added in JummBox URL version 4(?) for channelNames
feedbackEnvelope = CharCode.V, // added in BeepBox URL version 6, DEPRECATED
pulseWidth = CharCode.W, // added in BeepBox URL version 7
aliases = CharCode.X, // added in JummBox URL version 4 for aliases, DEPRECATED
// = CharCode.Y,
// = CharCode.Z,
// = CharCode.NUM_0,
// = CharCode.NUM_1,
// = CharCode.NUM_2,
// = CharCode.NUM_3,
// = CharCode.NUM_4,
// = CharCode.NUM_5,
// = CharCode.NUM_6,
// = CharCode.NUM_7,
// = CharCode.NUM_8,
// = CharCode.NUM_9,
// = CharCode.DASH,
// = CharCode.UNDERSCORE,
}
const base64IntToCharCode: ReadonlyArray<number> = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 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, 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, 45, 95];
const base64CharCodeToInt: ReadonlyArray<number> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 62, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 63, 0, 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, 0, 0, 0, 0, 0]; // 62 could be represented by either "-" or "." for historical reasons. New songs should use "-".
class BitFieldReader {
private _bits: number[] = [];
private _readIndex: number = 0;
constructor(source: string, startIndex: number, stopIndex: number) {
for (let i: number = startIndex; i < stopIndex; i++) {
const value: number = base64CharCodeToInt[source.charCodeAt(i)];
this._bits.push((value >> 5) & 0x1);
this._bits.push((value >> 4) & 0x1);
this._bits.push((value >> 3) & 0x1);
this._bits.push((value >> 2) & 0x1);
this._bits.push((value >> 1) & 0x1);
this._bits.push(value & 0x1);
}
}
public read(bitCount: number): number {
let result: number = 0;
while (bitCount > 0) {
result = result << 1;
result += this._bits[this._readIndex++];
bitCount--;
}
return result;
}
public readLongTail(minValue: number, minBits: number): number {
let result: number = minValue;
let numBits: number = minBits;
while (this._bits[this._readIndex++]) {
result += 1 << numBits;
numBits++;
}
while (numBits > 0) {
numBits--;
if (this._bits[this._readIndex++]) {
result += 1 << numBits;
}
}
return result;
}
public readPartDuration(): number {
return this.readLongTail(1, 3);
}
public readLegacyPartDuration(): number {
return this.readLongTail(1, 2);
}
public readPinCount(): number {
return this.readLongTail(1, 0);
}
public readPitchInterval(): number {
if (this.read(1)) {
return -this.readLongTail(1, 3);
} else {
return this.readLongTail(1, 3);
}
}
}
class BitFieldWriter {
private _index: number = 0;
private _bits: number[] = [];
public clear() {
this._index = 0;
}
public write(bitCount: number, value: number): void {
bitCount--;
while (bitCount >= 0) {
this._bits[this._index++] = (value >>> bitCount) & 1;
bitCount--;
}
}
public writeLongTail(minValue: number, minBits: number, value: number): void {
if (value < minValue) throw new Error("value out of bounds");
value -= minValue;
let numBits: number = minBits;
while (value >= (1 << numBits)) {
this._bits[this._index++] = 1;
value -= 1 << numBits;
numBits++;
}
this._bits[this._index++] = 0;
while (numBits > 0) {
numBits--;
this._bits[this._index++] = (value >>> numBits) & 1;
}
}
public writePartDuration(value: number): void {
this.writeLongTail(1, 3, value);
}
public writePinCount(value: number): void {
this.writeLongTail(1, 0, value);
}
public writePitchInterval(value: number): void {
if (value < 0) {
this.write(1, 1); // sign
this.writeLongTail(1, 3, -value);
} else {
this.write(1, 0); // sign
this.writeLongTail(1, 3, value);
}
}
public concat(other: BitFieldWriter): void {
for (let i: number = 0; i < other._index; i++) {
this._bits[this._index++] = other._bits[i];
}
}
public encodeBase64(buffer: number[]): number[] {
for (let i: number = 0; i < this._index; i += 6) {
const value: number = (this._bits[i] << 5) | (this._bits[i + 1] << 4) | (this._bits[i + 2] << 3) | (this._bits[i + 3] << 2) | (this._bits[i + 4] << 1) | this._bits[i + 5];
buffer.push(base64IntToCharCode[value]);
}
return buffer;
}
public lengthBase64(): number {
return Math.ceil(this._index / 6);
}
}
export interface NotePin {
interval: number;
time: number;
size: number;
}
export function makeNotePin(interval: number, time: number, size: number): NotePin {
return { interval: interval, time: time, size: size };
}
export class Note {
public pitches: number[];
public pins: NotePin[];
public start: number;
public end: number;
public continuesLastPattern: boolean;
public constructor(pitch: number, start: number, end: number, size: number, fadeout: boolean = false) {
this.pitches = [pitch];
this.pins = [makeNotePin(0, 0, size), makeNotePin(0, end - start, fadeout ? 0 : size)];
this.start = start;
this.end = end;
this.continuesLastPattern = false;
}
public pickMainInterval(): number {
let longestFlatIntervalDuration: number = 0;
let mainInterval: number = 0;
for (let pinIndex: number = 1; pinIndex < this.pins.length; pinIndex++) {
const pinA: NotePin = this.pins[pinIndex - 1];
const pinB: NotePin = this.pins[pinIndex];
if (pinA.interval == pinB.interval) {
const duration: number = pinB.time - pinA.time;
if (longestFlatIntervalDuration < duration) {
longestFlatIntervalDuration = duration;
mainInterval = pinA.interval;
}
}
}
if (longestFlatIntervalDuration == 0) {
let loudestSize: number = 0;
for (let pinIndex: number = 0; pinIndex < this.pins.length; pinIndex++) {
const pin: NotePin = this.pins[pinIndex];
if (loudestSize < pin.size) {
loudestSize = pin.size;
mainInterval = pin.interval;
}
}
}
return mainInterval;
}
public clone(): Note {
const newNote: Note = new Note(-1, this.start, this.end, 3);
newNote.pitches = this.pitches.concat();
newNote.pins = [];
for (const pin of this.pins) {
newNote.pins.push(makeNotePin(pin.interval, pin.time, pin.size));
}
newNote.continuesLastPattern = this.continuesLastPattern;
return newNote;
}
public getEndPinIndex(part: number): number {
let endPinIndex: number;
for (endPinIndex = 1; endPinIndex < this.pins.length - 1; endPinIndex++) {
if (this.pins[endPinIndex].time + this.start > part) break;
}
return endPinIndex;
}
}
export class Pattern {
public notes: Note[] = [];
public readonly instruments: number[] = [0];
public cloneNotes(): Note[] {
const result: Note[] = [];
for (const note of this.notes) {
result.push(note.clone());
}
return result;
}
public reset(): void {
this.notes.length = 0;
this.instruments[0] = 0;
this.instruments.length = 1;
}
public toJsonObject(song: Song, channel: Channel, isModChannel: boolean): any {
const noteArray: Object[] = [];
for (const note of this.notes) {
// Only one ins per pattern is enforced in mod channels.
let instrument: Instrument = channel.instruments[this.instruments[0]];
let mod: number = Math.max(0, Config.modCount - note.pitches[0] - 1);
let volumeCap: number = song.getVolumeCapForSetting(isModChannel, instrument.modulators[mod], instrument.modFilterTypes[mod]);
const pointArray: Object[] = [];
for (const pin of note.pins) {
let useVol: number = isModChannel ? Math.round(pin.size) : Math.round(pin.size * 100 / volumeCap);
pointArray.push({
"tick": (pin.time + note.start) * Config.rhythms[song.rhythm].stepsPerBeat / Config.partsPerBeat,
"pitchBend": pin.interval,
"volume": useVol,
"forMod": isModChannel,
});
}
const noteObject: any = {
"pitches": note.pitches,
"points": pointArray,
};
if (note.start == 0) {
noteObject["continuesLastPattern"] = note.continuesLastPattern;
}
noteArray.push(noteObject);
}
const patternObject: any = { "notes": noteArray };
if (song.patternInstruments) {
patternObject["instruments"] = this.instruments.map(i => i + 1);
}
return patternObject;
}
public fromJsonObject(patternObject: any, song: Song, channel: Channel, importedPartsPerBeat: number, isNoiseChannel: boolean, isModChannel: boolean): void {
if (song.patternInstruments) {
if (Array.isArray(patternObject["instruments"])) {
const instruments: any[] = patternObject["instruments"];
const instrumentCount: number = clamp(Config.instrumentCountMin, song.getMaxInstrumentsPerPatternForChannel(channel) + 1, instruments.length);
for (let j: number = 0; j < instrumentCount; j++) {
this.instruments[j] = clamp(0, channel.instruments.length, (instruments[j] | 0) - 1);
}
this.instruments.length = instrumentCount;
} else {
this.instruments[0] = clamp(0, channel.instruments.length, (patternObject["instrument"] | 0) - 1);
this.instruments.length = 1;
}
}
if (patternObject["notes"] && patternObject["notes"].length > 0) {
const maxNoteCount: number = Math.min(song.beatsPerBar * Config.partsPerBeat * (isModChannel ? Config.modCount : 1), patternObject["notes"].length >>> 0);
// TODO: Consider supporting notes specified in any timing order, sorting them and truncating as necessary.
//let tickClock: number = 0;
for (let j: number = 0; j < patternObject["notes"].length; j++) {
if (j >= maxNoteCount) break;
const noteObject = patternObject["notes"][j];
if (!noteObject || !noteObject["pitches"] || !(noteObject["pitches"].length >= 1) || !noteObject["points"] || !(noteObject["points"].length >= 2)) {
continue;
}
const note: Note = new Note(0, 0, 0, 0);
note.pitches = [];
note.pins = [];
for (let k: number = 0; k < noteObject["pitches"].length; k++) {
const pitch: number = noteObject["pitches"][k] | 0;
if (note.pitches.indexOf(pitch) != -1) continue;
note.pitches.push(pitch);
if (note.pitches.length >= Config.maxChordSize) break;
}
if (note.pitches.length < 1) continue;
//let noteClock: number = tickClock;
let startInterval: number = 0;
for (let k: number = 0; k < noteObject["points"].length; k++) {
const pointObject: any = noteObject["points"][k];
if (pointObject == undefined || pointObject["tick"] == undefined) continue;
const interval: number = (pointObject["pitchBend"] == undefined) ? 0 : (pointObject["pitchBend"] | 0);
const time: number = Math.round((+pointObject["tick"]) * Config.partsPerBeat / importedPartsPerBeat);
let instrument: Instrument = channel.instruments[this.instruments[0]];
let mod: number = Math.max(0, Config.modCount - note.pitches[0] - 1);
// Only one instrument per pattern allowed in mod channels.
let volumeCap: number = song.getVolumeCapForSetting(isModChannel, instrument.modulators[mod], instrument.modFilterTypes[mod]);
// The strange volume formula used for notes is not needed for mods. Some rounding errors were possible.
// A "forMod" signifier was added to new JSON export to detect when the higher precision export was used in a file.
let size: number;
if (pointObject["volume"] == undefined) {
size = volumeCap;
} else if (pointObject["forMod"] == undefined) {
size = Math.max(0, Math.min(volumeCap, Math.round((pointObject["volume"] | 0) * volumeCap / 100)));
}
else {
size = ((pointObject["forMod"] | 0) > 0) ? Math.round(pointObject["volume"] | 0) : Math.max(0, Math.min(volumeCap, Math.round((pointObject["volume"] | 0) * volumeCap / 100)));
}
if (time > song.beatsPerBar * Config.partsPerBeat) continue;
if (note.pins.length == 0) {
//if (time < noteClock) continue;
note.start = time;
startInterval = interval;
} else {
//if (time <= noteClock) continue;
}
//noteClock = time;
note.pins.push(makeNotePin(interval - startInterval, time - note.start, size));
}
if (note.pins.length < 2) continue;
note.end = note.pins[note.pins.length - 1].time + note.start;
const maxPitch: number = isNoiseChannel ? Config.drumCount - 1 : Config.maxPitch;
let lowestPitch: number = maxPitch;
let highestPitch: number = 0;
for (let k: number = 0; k < note.pitches.length; k++) {
note.pitches[k] += startInterval;
if (note.pitches[k] < 0 || note.pitches[k] > maxPitch) {
note.pitches.splice(k, 1);
k--;
}
if (note.pitches[k] < lowestPitch) lowestPitch = note.pitches[k];
if (note.pitches[k] > highestPitch) highestPitch = note.pitches[k];
}
if (note.pitches.length < 1) continue;
for (let k: number = 0; k < note.pins.length; k++) {
const pin: NotePin = note.pins[k];
if (pin.interval + lowestPitch < 0) pin.interval = -lowestPitch;
if (pin.interval + highestPitch > maxPitch) pin.interval = maxPitch - highestPitch;
if (k >= 2) {
if (pin.interval == note.pins[k - 1].interval &&
pin.interval == note.pins[k - 2].interval &&
pin.size == note.pins[k - 1].size &&
pin.size == note.pins[k - 2].size) {
note.pins.splice(k - 1, 1);
k--;
}
}
}
if (note.start == 0) {
note.continuesLastPattern = (noteObject["continuesLastPattern"] === true);
} else {
note.continuesLastPattern = false;
}
this.notes.push(note);
}
}
}
}
export class Operator {
public frequency: number = 0;
public amplitude: number = 0;
public waveform: number = 0;
public pulseWidth: number = 0.5;
constructor(index: number) {
this.reset(index);
}
public reset(index: number): void {
this.frequency = 0;
this.amplitude = (index <= 1) ? Config.operatorAmplitudeMax : 0;
this.waveform = 0;
this.pulseWidth = 5;
}
public copy(other: Operator): void {
this.frequency = other.frequency;
this.amplitude = other.amplitude;
this.waveform = other.waveform;
this.pulseWidth = other.pulseWidth;
}
}
export class SpectrumWave {
public spectrum: number[] = [];
public hash: number = -1;
constructor(isNoiseChannel: boolean) {
this.reset(isNoiseChannel);
}
public reset(isNoiseChannel: boolean): void {
for (let i: number = 0; i < Config.spectrumControlPoints; i++) {
if (isNoiseChannel) {
this.spectrum[i] = Math.round(Config.spectrumMax * (1 / Math.sqrt(1 + i / 3)));
} else {
const isHarmonic: boolean = i == 0 || i == 7 || i == 11 || i == 14 || i == 16 || i == 18 || i == 21 || i == 23 || i >= 25;
this.spectrum[i] = isHarmonic ? Math.max(0, Math.round(Config.spectrumMax * (1 - i / 30))) : 0;
}
}
this.markCustomWaveDirty();
}
public markCustomWaveDirty(): void {
const hashMult: number = Synth.fittingPowerOfTwo(Config.spectrumMax + 2) - 1;
let hash: number = 0;
for (const point of this.spectrum) hash = ((hash * hashMult) + point) >>> 0;
this.hash = hash;
}
}
class SpectrumWaveState {
public wave: Float32Array | null = null;
private _hash: number = -1;
public getCustomWave(settings: SpectrumWave, lowestOctave: number): Float32Array {
if (this._hash == settings.hash) return this.wave!;
this._hash = settings.hash;
const waveLength: number = Config.spectrumNoiseLength;
if (this.wave == null || this.wave.length != waveLength + 1) {
this.wave = new Float32Array(waveLength + 1);
}
const wave: Float32Array = this.wave;
for (let i: number = 0; i < waveLength; i++) {
wave[i] = 0;
}
const highestOctave: number = 14;
const falloffRatio: number = 0.25;
// Nudge the 2/7 and 4/7 control points so that they form harmonic intervals.
const pitchTweak: number[] = [0, 1 / 7, Math.log2(5 / 4), 3 / 7, Math.log2(3 / 2), 5 / 7, 6 / 7];
function controlPointToOctave(point: number): number {
return lowestOctave + Math.floor(point / Config.spectrumControlPointsPerOctave) + pitchTweak[(point + Config.spectrumControlPointsPerOctave) % Config.spectrumControlPointsPerOctave];
}
let combinedAmplitude: number = 1;
for (let i: number = 0; i < Config.spectrumControlPoints + 1; i++) {
const value1: number = (i <= 0) ? 0 : settings.spectrum[i - 1];
const value2: number = (i >= Config.spectrumControlPoints) ? settings.spectrum[Config.spectrumControlPoints - 1] : settings.spectrum[i];
const octave1: number = controlPointToOctave(i - 1);
let octave2: number = controlPointToOctave(i);
if (i >= Config.spectrumControlPoints) octave2 = highestOctave + (octave2 - highestOctave) * falloffRatio;
if (value1 == 0 && value2 == 0) continue;
combinedAmplitude += 0.02 * drawNoiseSpectrum(wave, waveLength, octave1, octave2, value1 / Config.spectrumMax, value2 / Config.spectrumMax, -0.5);
}
if (settings.spectrum[Config.spectrumControlPoints - 1] > 0) {
combinedAmplitude += 0.02 * drawNoiseSpectrum(wave, waveLength, highestOctave + (controlPointToOctave(Config.spectrumControlPoints) - highestOctave) * falloffRatio, highestOctave, settings.spectrum[Config.spectrumControlPoints - 1] / Config.spectrumMax, 0, -0.5);
}
inverseRealFourierTransform(wave, waveLength);
scaleElementsByFactor(wave, 5.0 / (Math.sqrt(waveLength) * Math.pow(combinedAmplitude, 0.75)));
// Duplicate the first sample at the end for easier wrap-around interpolation.
wave[waveLength] = wave[0];
return wave;
}
}
export class HarmonicsWave {
public harmonics: number[] = [];
public hash: number = -1;
constructor() {
this.reset();
}
public reset(): void {
for (let i: number = 0; i < Config.harmonicsControlPoints; i++) {
this.harmonics[i] = 0;
}
this.harmonics[0] = Config.harmonicsMax;
this.harmonics[3] = Config.harmonicsMax;
this.harmonics[6] = Config.harmonicsMax;
this.markCustomWaveDirty();
}
public markCustomWaveDirty(): void {
const hashMult: number = Synth.fittingPowerOfTwo(Config.harmonicsMax + 2) - 1;
let hash: number = 0;
for (const point of this.harmonics) hash = ((hash * hashMult) + point) >>> 0;
this.hash = hash;
}
}
class HarmonicsWaveState {
public wave: Float32Array | null = null;
private _hash: number = -1;
private _generatedForType: InstrumentType;
public getCustomWave(settings: HarmonicsWave, instrumentType: InstrumentType): Float32Array {
if (this._hash == settings.hash && this._generatedForType == instrumentType) return this.wave!;
this._hash = settings.hash;
this._generatedForType = instrumentType;
const harmonicsRendered: number = (instrumentType == InstrumentType.pickedString) ? Config.harmonicsRenderedForPickedString : Config.harmonicsRendered;
const waveLength: number = Config.harmonicsWavelength;
const retroWave: Float32Array = getDrumWave(0, null, null);
if (this.wave == null || this.wave.length != waveLength + 1) {
this.wave = new Float32Array(waveLength + 1);
}
const wave: Float32Array = this.wave;
for (let i: number = 0; i < waveLength; i++) {
wave[i] = 0;
}
const overallSlope: number = -0.25;
let combinedControlPointAmplitude: number = 1;
for (let harmonicIndex: number = 0; harmonicIndex < harmonicsRendered; harmonicIndex++) {
const harmonicFreq: number = harmonicIndex + 1;
let controlValue: number = harmonicIndex < Config.harmonicsControlPoints ? settings.harmonics[harmonicIndex] : settings.harmonics[Config.harmonicsControlPoints - 1];
if (harmonicIndex >= Config.harmonicsControlPoints) {
controlValue *= 1 - (harmonicIndex - Config.harmonicsControlPoints) / (harmonicsRendered - Config.harmonicsControlPoints);
}
const normalizedValue: number = controlValue / Config.harmonicsMax;
let amplitude: number = Math.pow(2, controlValue - Config.harmonicsMax + 1) * Math.sqrt(normalizedValue);
if (harmonicIndex < Config.harmonicsControlPoints) {
combinedControlPointAmplitude += amplitude;
}
amplitude *= Math.pow(harmonicFreq, overallSlope);
// Multiply all the sine wave amplitudes by 1 or -1 based on the LFSR
// retro wave (effectively random) to avoid egregiously tall spikes.
amplitude *= retroWave[harmonicIndex + 589];
wave[waveLength - harmonicFreq] = amplitude;
}
inverseRealFourierTransform(wave, waveLength);
// Limit the maximum wave amplitude.
const mult: number = 1 / Math.pow(combinedControlPointAmplitude, 0.7);
for (let i: number = 0; i < wave.length; i++) wave[i] *= mult;
performIntegralOld(wave);
// The first sample should be zero, and we'll duplicate it at the end for easier interpolation.
wave[waveLength] = wave[0];
return wave;
}
}
export class FilterControlPoint {
public freq: number = 0;
public gain: number = Config.filterGainCenter;
public type: FilterType = FilterType.peak;
public set(freqSetting: number, gainSetting: number): void {
this.freq = freqSetting;
this.gain = gainSetting;
}
public getHz(): number {
return FilterControlPoint.getHzFromSettingValue(this.freq);
}
public static getHzFromSettingValue(value: number): number {
return Config.filterFreqReferenceHz * Math.pow(2.0, (value - Config.filterFreqReferenceSetting) * Config.filterFreqStep);
}
public static getSettingValueFromHz(hz: number): number {
return Math.log2(hz / Config.filterFreqReferenceHz) / Config.filterFreqStep + Config.filterFreqReferenceSetting;
}
public static getRoundedSettingValueFromHz(hz: number): number {
return Math.max(0, Math.min(Config.filterFreqRange - 1, Math.round(FilterControlPoint.getSettingValueFromHz(hz))));
}
public getLinearGain(peakMult: number = 1.0): number {
const power: number = (this.gain - Config.filterGainCenter) * Config.filterGainStep;
const neutral: number = (this.type == FilterType.peak) ? 0.0 : -0.5;
const interpolatedPower: number = neutral + (power - neutral) * peakMult;
return Math.pow(2.0, interpolatedPower);
}
public static getRoundedSettingValueFromLinearGain(linearGain: number): number {
return Math.max(0, Math.min(Config.filterGainRange - 1, Math.round(Math.log2(linearGain) / Config.filterGainStep + Config.filterGainCenter)));
}
public toCoefficients(filter: FilterCoefficients, sampleRate: number, freqMult: number = 1.0, peakMult: number = 1.0): void {
const cornerRadiansPerSample: number = 2.0 * Math.PI * Math.max(Config.filterFreqMinHz, Math.min(Config.filterFreqMaxHz, freqMult * this.getHz())) / sampleRate;
const linearGain: number = this.getLinearGain(peakMult);
switch (this.type) {
case FilterType.lowPass:
filter.lowPass2ndOrderButterworth(cornerRadiansPerSample, linearGain);
break;
case FilterType.highPass:
filter.highPass2ndOrderButterworth(cornerRadiansPerSample, linearGain);
break;
case FilterType.peak:
filter.peak2ndOrder(cornerRadiansPerSample, linearGain, 1.0);
break;
default:
throw new Error();
}
}
public getVolumeCompensationMult(): number {
const octave: number = (this.freq - Config.filterFreqReferenceSetting) * Config.filterFreqStep;
const gainPow: number = (this.gain - Config.filterGainCenter) * Config.filterGainStep;
switch (this.type) {
case FilterType.lowPass:
const freqRelativeTo8khz: number = Math.pow(2.0, octave) * Config.filterFreqReferenceHz / 8000.0;
// Reverse the frequency warping from importing legacy simplified filters to imitate how the legacy filter cutoff setting affected volume.
const warpedFreq: number = (Math.sqrt(1.0 + 4.0 * freqRelativeTo8khz) - 1.0) / 2.0;
const warpedOctave: number = Math.log2(warpedFreq);
return Math.pow(0.5, 0.2 * Math.max(0.0, gainPow + 1.0) + Math.min(0.0, Math.max(-3.0, 0.595 * warpedOctave + 0.35 * Math.min(0.0, gainPow + 1.0))));
case FilterType.highPass:
return Math.pow(0.5, 0.125 * Math.max(0.0, gainPow + 1.0) + Math.min(0.0, 0.3 * (-octave - Math.log2(Config.filterFreqReferenceHz / 125.0)) + 0.2 * Math.min(0.0, gainPow + 1.0)));
case FilterType.peak:
const distanceFromCenter: number = octave + Math.log2(Config.filterFreqReferenceHz / 2000.0);
const freqLoudness: number = Math.pow(1.0 / (1.0 + Math.pow(distanceFromCenter / 3.0, 2.0)), 2.0);
return Math.pow(0.5, 0.125 * Math.max(0.0, gainPow) + 0.1 * freqLoudness * Math.min(0.0, gainPow));
default:
throw new Error();
}
}
}
export class FilterSettings {
public readonly controlPoints: FilterControlPoint[] = [];
public controlPointCount: number = 0;
constructor() {
this.reset();
}
reset(): void {
this.controlPointCount = 0;
}
addPoint(type: FilterType, freqSetting: number, gainSetting: number): void {
let controlPoint: FilterControlPoint;
if (this.controlPoints.length <= this.controlPointCount) {
controlPoint = new FilterControlPoint();
this.controlPoints[this.controlPointCount] = controlPoint;
} else {
controlPoint = this.controlPoints[this.controlPointCount];
}
this.controlPointCount++;
controlPoint.type = type;
controlPoint.set(freqSetting, gainSetting);
}
public toJsonObject(): Object {
const filterArray: any[] = [];
for (let i: number = 0; i < this.controlPointCount; i++) {
const point: FilterControlPoint = this.controlPoints[i];
filterArray.push({
"type": Config.filterTypeNames[point.type],
"cutoffHz": Math.round(point.getHz() * 100) / 100,
"linearGain": Math.round(point.getLinearGain() * 10000) / 10000,
});
}
return filterArray;
}
public fromJsonObject(filterObject: any): void {
this.controlPoints.length = 0;
if (filterObject) {
for (const pointObject of filterObject) {
const point: FilterControlPoint = new FilterControlPoint();
point.type = Config.filterTypeNames.indexOf(pointObject["type"]);
if (<any>point.type == -1) point.type = FilterType.peak;
if (pointObject["cutoffHz"] != undefined) {
point.freq = FilterControlPoint.getRoundedSettingValueFromHz(pointObject["cutoffHz"]);
} else {
point.freq = 0;
}
if (pointObject["linearGain"] != undefined) {
point.gain = FilterControlPoint.getRoundedSettingValueFromLinearGain(pointObject["linearGain"]);
} else {
point.gain = Config.filterGainCenter;
}
this.controlPoints.push(point);
}
}
this.controlPointCount = this.controlPoints.length;
}
// Returns true if all filter control points match in number and type (but not freq/gain)
public static filtersCanMorph(filterA: FilterSettings, filterB: FilterSettings): boolean {
if (filterA.controlPointCount != filterB.controlPointCount)
return false;
for (let i: number = 0; i < filterA.controlPointCount; i++) {
if (filterA.controlPoints[i].type != filterB.controlPoints[i].type)
return false;
}
return true;
}
// Interpolate two FilterSettings, where pos=0 is filterA and pos=1 is filterB
public static lerpFilters(filterA: FilterSettings, filterB: FilterSettings, pos: number): FilterSettings {
let lerpedFilter: FilterSettings = new FilterSettings();
// One setting or another is null, return the other.
if (filterA == null) {
return filterA;
}
if (filterB == null) {
return filterB;
}
pos = Math.max(0, Math.min(1, pos));
// Filter control points match in number and type
if (this.filtersCanMorph(filterA, filterB)) {
for (let i: number = 0; i < filterA.controlPointCount; i++) {
lerpedFilter.controlPoints[i] = new FilterControlPoint();
lerpedFilter.controlPoints[i].type = filterA.controlPoints[i].type;
lerpedFilter.controlPoints[i].freq = filterA.controlPoints[i].freq + (filterB.controlPoints[i].freq - filterA.controlPoints[i].freq) * pos;
lerpedFilter.controlPoints[i].gain = filterA.controlPoints[i].gain + (filterB.controlPoints[i].gain - filterA.controlPoints[i].gain) * pos;
}
lerpedFilter.controlPointCount = filterA.controlPointCount;
return lerpedFilter;
}
else {
// Not allowing morph of unmatching filters for now. It's a hornet's nest of problems, and I had it implemented and mostly working and it didn't sound very interesting since the shape becomes "mushy" in between
return (pos >= 1) ? filterB : filterA;
}
}
public convertLegacySettings(legacyCutoffSetting: number, legacyResonanceSetting: number, legacyEnv: Envelope): void {
this.reset();
const legacyFilterCutoffMaxHz: number = 8000; // This was carefully calculated to correspond to no change in response when filtering at 48000 samples per second... when using the legacy simplified low-pass filter.
const legacyFilterMax: number = 0.95;
const legacyFilterMaxRadians: number = Math.asin(legacyFilterMax / 2.0) * 2.0;
const legacyFilterMaxResonance: number = 0.95;
const legacyFilterCutoffRange: number = 11;
const legacyFilterResonanceRange: number = 8;
const resonant: boolean = (legacyResonanceSetting > 1);
const firstOrder: boolean = (legacyResonanceSetting == 0);
const cutoffAtMax: boolean = (legacyCutoffSetting == legacyFilterCutoffRange - 1);
const envDecays: boolean = (legacyEnv.type == EnvelopeType.flare || legacyEnv.type == EnvelopeType.twang || legacyEnv.type == EnvelopeType.decay || legacyEnv.type == EnvelopeType.noteSize);
const standardSampleRate: number = 48000;
const legacyHz: number = legacyFilterCutoffMaxHz * Math.pow(2.0, (legacyCutoffSetting - (legacyFilterCutoffRange - 1)) * 0.5);
const legacyRadians: number = Math.min(legacyFilterMaxRadians, 2 * Math.PI * legacyHz / standardSampleRate);
if (legacyEnv.type == EnvelopeType.none && !resonant && cutoffAtMax) {
// The response is flat and there's no envelopes, so don't even bother adding any control points.
} else if (firstOrder) {
// In general, a 1st order lowpass can be approximated by a 2nd order lowpass
// with a cutoff ~4 octaves higher (*16) and a gain of 1/16.
// However, BeepBox's original lowpass filters behaved oddly as they
// approach the nyquist frequency, so I've devised this curved conversion
// to guess at a perceptually appropriate new cutoff frequency and gain.
const extraOctaves: number = 3.5;
const targetRadians: number = legacyRadians * Math.pow(2.0, extraOctaves);
const curvedRadians: number = targetRadians / (1.0 + targetRadians / Math.PI);
const curvedHz: number = standardSampleRate * curvedRadians / (2.0 * Math.PI)
const freqSetting: number = FilterControlPoint.getRoundedSettingValueFromHz(curvedHz);
const finalHz: number = FilterControlPoint.getHzFromSettingValue(freqSetting);
const finalRadians: number = 2.0 * Math.PI * finalHz / standardSampleRate;
const legacyFilter: FilterCoefficients = new FilterCoefficients();
legacyFilter.lowPass1stOrderSimplified(legacyRadians);
const response: FrequencyResponse = new FrequencyResponse();
response.analyze(legacyFilter, finalRadians);
const legacyFilterGainAtNewRadians: number = response.magnitude();
let logGain: number = Math.log2(legacyFilterGainAtNewRadians);
// Bias slightly toward 2^(-extraOctaves):
logGain = -extraOctaves + (logGain + extraOctaves) * 0.82;
// Decaying envelopes move the cutoff frequency back into an area where the best approximation of the first order slope requires a lower gain setting.
if (envDecays) logGain = Math.min(logGain, -1.0);
const convertedGain: number = Math.pow(2.0, logGain);
const gainSetting: number = FilterControlPoint.getRoundedSettingValueFromLinearGain(convertedGain);
this.addPoint(FilterType.lowPass, freqSetting, gainSetting);
} else {
const intendedGain: number = 0.5 / (1.0 - legacyFilterMaxResonance * Math.sqrt(Math.max(0.0, legacyResonanceSetting - 1.0) / (legacyFilterResonanceRange - 2.0)));
const invertedGain: number = 0.5 / intendedGain;
const maxRadians: number = 2.0 * Math.PI * legacyFilterCutoffMaxHz / standardSampleRate;
const freqRatio: number = legacyRadians / maxRadians;
const targetRadians: number = legacyRadians * (freqRatio * Math.pow(invertedGain, 0.9) + 1.0);
const curvedRadians: number = legacyRadians + (targetRadians - legacyRadians) * invertedGain;
let curvedHz: number;
if (envDecays) {
curvedHz = standardSampleRate * Math.min(curvedRadians, legacyRadians * Math.pow(2, 0.25)) / (2.0 * Math.PI);
} else {
curvedHz = standardSampleRate * curvedRadians / (2.0 * Math.PI);
}