-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsp.js
2300 lines (1879 loc) · 65.1 KB
/
dsp.js
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
/*
* DSP.js - a comprehensive digital signal processing library for javascript
*
* Created by Corban Brook <[email protected]> on 2010-01-01.
* Copyright 2010 Corban Brook. All rights reserved.
*
*/
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS //
////////////////////////////////////////////////////////////////////////////////
/**
* DSP is an object which contains general purpose utility functions and constants
*/
var DSP = {
// Channels
LEFT: 0,
RIGHT: 1,
MIX: 2,
// Waveforms
SINE: 1,
TRIANGLE: 2,
SAW: 3,
SQUARE: 4,
// Filters
LOWPASS: 0,
HIGHPASS: 1,
BANDPASS: 2,
NOTCH: 3,
// Window functions
BARTLETT: 1,
BARTLETTHANN: 2,
BLACKMAN: 3,
COSINE: 4,
GAUSS: 5,
HAMMING: 6,
HANN: 7,
LANCZOS: 8,
RECTANGULAR: 9,
TRIANGULAR: 10,
// Loop modes
OFF: 0,
FW: 1,
BW: 2,
FWBW: 3,
// Math
TWO_PI: 2*Math.PI
};
// Setup arrays for platforms which do not support byte arrays
function setupTypedArray(name, fallback) {
// check if TypedArray exists
// typeof on Minefield and Chrome return function, typeof on Webkit returns object.
if (typeof this[name] !== "function" && typeof this[name] !== "object") {
// nope.. check if WebGLArray exists
if (typeof this[fallback] === "function" && typeof this[fallback] !== "object") {
this[name] = this[fallback];
} else {
// nope.. set as Native JS array
this[name] = function(obj) {
if (obj instanceof Array) {
return obj;
} else if (typeof obj === "number") {
return new Array(obj);
}
};
}
}
}
setupTypedArray("Float32Array", "WebGLFloatArray");
setupTypedArray("Int32Array", "WebGLIntArray");
setupTypedArray("Uint16Array", "WebGLUnsignedShortArray");
setupTypedArray("Uint8Array", "WebGLUnsignedByteArray");
////////////////////////////////////////////////////////////////////////////////
// DSP UTILITY FUNCTIONS //
////////////////////////////////////////////////////////////////////////////////
/**
* Inverts the phase of a signal
*
* @param {Array} buffer A sample buffer
*
* @returns The inverted sample buffer
*/
DSP.invert = function(buffer) {
for (var i = 0, len = buffer.length; i < len; i++) {
buffer[i] *= -1;
}
return buffer;
};
/**
* Converts split-stereo (dual mono) sample buffers into a stereo interleaved sample buffer
*
* @param {Array} left A sample buffer
* @param {Array} right A sample buffer
*
* @returns The stereo interleaved buffer
*/
DSP.interleave = function(left, right) {
if (left.length !== right.length) {
throw "Can not interleave. Channel lengths differ.";
}
var stereoInterleaved = new Float32Array(left.length * 2);
for (var i = 0, len = left.length; i < len; i++) {
stereoInterleaved[2*i] = left[i];
stereoInterleaved[2*i+1] = right[i];
}
return stereoInterleaved;
};
/**
* Converts a stereo-interleaved sample buffer into split-stereo (dual mono) sample buffers
*
* @param {Array} buffer A stereo-interleaved sample buffer
*
* @returns an Array containing left and right channels
*/
DSP.deinterleave = (function() {
var left, right, mix, deinterleaveChannel = [];
deinterleaveChannel[DSP.MIX] = function(buffer) {
for (var i = 0, len = buffer.length/2; i < len; i++) {
mix[i] = (buffer[2*i] + buffer[2*i+1]) / 2;
}
return mix;
};
deinterleaveChannel[DSP.LEFT] = function(buffer) {
for (var i = 0, len = buffer.length/2; i < len; i++) {
left[i] = buffer[2*i];
}
return left;
};
deinterleaveChannel[DSP.RIGHT] = function(buffer) {
for (var i = 0, len = buffer.length/2; i < len; i++) {
right[i] = buffer[2*i+1];
}
return right;
};
return function(channel, buffer) {
left = left || new Float32Array(buffer.length/2);
right = right || new Float32Array(buffer.length/2);
mix = mix || new Float32Array(buffer.length/2);
if (buffer.length/2 !== left.length) {
left = new Float32Array(buffer.length/2);
right = new Float32Array(buffer.length/2);
mix = new Float32Array(buffer.length/2);
}
return deinterleaveChannel[channel](buffer);
};
}());
/**
* Separates a channel from a stereo-interleaved sample buffer
*
* @param {Array} buffer A stereo-interleaved sample buffer
* @param {Number} channel A channel constant (LEFT, RIGHT, MIX)
*
* @returns an Array containing a signal mono sample buffer
*/
DSP.getChannel = DSP.deinterleave;
/**
* Helper method (for Reverb) to mix two (interleaved) samplebuffers. It's possible
* to negate the second buffer while mixing and to perform a volume correction
* on the final signal.
*
* @param {Array} sampleBuffer1 Array containing Float values or a Float32Array
* @param {Array} sampleBuffer2 Array containing Float values or a Float32Array
* @param {Boolean} negate When true inverts/flips the audio signal
* @param {Number} volumeCorrection When you add multiple sample buffers, use this to tame your signal ;)
*
* @returns A new Float32Array interleaved buffer.
*/
DSP.mixSampleBuffers = function(sampleBuffer1, sampleBuffer2, negate, volumeCorrection){
var outputSamples = new Float32Array(sampleBuffer1);
for(var i = 0; i<sampleBuffer1.length; i++){
outputSamples[i] += (negate ? -sampleBuffer2[i] : sampleBuffer2[i]) / volumeCorrection;
}
return outputSamples;
};
// Biquad filter types
DSP.LPF = 0; // H(s) = 1 / (s^2 + s/Q + 1)
DSP.HPF = 1; // H(s) = s^2 / (s^2 + s/Q + 1)
DSP.BPF_CONSTANT_SKIRT = 2; // H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q)
DSP.BPF_CONSTANT_PEAK = 3; // H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain)
DSP.NOTCH = 4; // H(s) = (s^2 + 1) / (s^2 + s/Q + 1)
DSP.APF = 5; // H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1)
DSP.PEAKING_EQ = 6; // H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1)
DSP.LOW_SHELF = 7; // H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1)
DSP.HIGH_SHELF = 8; // H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)
// Biquad filter parameter types
DSP.Q = 1;
DSP.BW = 2; // SHARED with BACKWARDS LOOP MODE
DSP.S = 3;
// Find RMS of signal
DSP.RMS = function(buffer) {
var total = 0;
for (var i = 0, n = buffer.length; i < n; i++) {
total += buffer[i] * buffer[i];
}
return Math.sqrt(total / n);
};
// Find Peak of signal
DSP.Peak = function(buffer) {
var peak = 0;
for (var i = 0, n = buffer.length; i < n; i++) {
peak = (Math.abs(buffer[i]) > peak) ? Math.abs(buffer[i]) : peak;
}
return peak;
};
// Fourier Transform Module used by DFT, FFT, RFT
function FourierTransform(bufferSize, sampleRate) {
this.bufferSize = bufferSize;
this.sampleRate = sampleRate;
this.bandwidth = 2 / bufferSize * sampleRate / 2;
this.spectrum = new Float32Array(bufferSize/2);
this.real = new Float32Array(bufferSize);
this.imag = new Float32Array(bufferSize);
this.peakBand = 0;
this.peak = 0;
/**
* Calculates the *middle* frequency of an FFT band.
*
* @param {Number} index The index of the FFT band.
*
* @returns The middle frequency in Hz.
*/
this.getBandFrequency = function(index) {
return this.bandwidth * index + this.bandwidth / 2;
};
this.calculateSpectrum = function() {
var spectrum = this.spectrum,
real = this.real,
imag = this.imag,
bSi = 2 / this.bufferSize,
sqrt = Math.sqrt,
rval,
ival,
mag;
for (var i = 0, N = bufferSize/2; i < N; i++) {
rval = real[i];
ival = imag[i];
mag = bSi * sqrt(rval * rval + ival * ival);
if (mag > this.peak) {
this.peakBand = i;
this.peak = mag;
}
spectrum[i] = mag;
}
};
}
/**
* DFT is a class for calculating the Discrete Fourier Transform of a signal.
*
* @param {Number} bufferSize The size of the sample buffer to be computed
* @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)
*
* @constructor
*/
function DFT(bufferSize, sampleRate) {
FourierTransform.call(this, bufferSize, sampleRate);
var N = bufferSize/2 * bufferSize;
var TWO_PI = 2 * Math.PI;
this.sinTable = new Float32Array(N);
this.cosTable = new Float32Array(N);
for (var i = 0; i < N; i++) {
this.sinTable[i] = Math.sin(i * TWO_PI / bufferSize);
this.cosTable[i] = Math.cos(i * TWO_PI / bufferSize);
}
}
/**
* Performs a forward tranform on the sample buffer.
* Converts a time domain signal to frequency domain spectra.
*
* @param {Array} buffer The sample buffer
*
* @returns The frequency spectrum array
*/
DFT.prototype.forward = function(buffer) {
var real = this.real,
imag = this.imag,
rval,
ival;
for (var k = 0; k < this.bufferSize/2; k++) {
rval = 0.0;
ival = 0.0;
for (var n = 0; n < buffer.length; n++) {
rval += this.cosTable[k*n] * buffer[n];
ival += this.sinTable[k*n] * buffer[n];
}
real[k] = rval;
imag[k] = ival;
}
return this.calculateSpectrum();
};
/**
* FFT is a class for calculating the Discrete Fourier Transform of a signal
* with the Fast Fourier Transform algorithm.
*
* @param {Number} bufferSize The size of the sample buffer to be computed. Must be power of 2
* @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)
*
* @constructor
*/
function FFT(bufferSize, sampleRate) {
FourierTransform.call(this, bufferSize, sampleRate);
this.reverseTable = new Uint32Array(bufferSize);
var limit = 1;
var bit = bufferSize >> 1;
var i;
while (limit < bufferSize) {
for (i = 0; i < limit; i++) {
this.reverseTable[i + limit] = this.reverseTable[i] + bit;
}
limit = limit << 1;
bit = bit >> 1;
}
this.sinTable = new Float32Array(bufferSize);
this.cosTable = new Float32Array(bufferSize);
for (i = 0; i < bufferSize; i++) {
this.sinTable[i] = Math.sin(-Math.PI/i);
this.cosTable[i] = Math.cos(-Math.PI/i);
}
}
/**
* Performs a forward tranform on the sample buffer.
* Converts a time domain signal to frequency domain spectra.
*
* @param {Array} buffer The sample buffer. Buffer Length must be power of 2
*
* @returns The frequency spectrum array
*/
FFT.prototype.forward = function(buffer) {
// Locally scope variables for speed up
var bufferSize = this.bufferSize,
cosTable = this.cosTable,
sinTable = this.sinTable,
reverseTable = this.reverseTable,
real = this.real,
imag = this.imag,
spectrum = this.spectrum;
var k = Math.floor(Math.log(bufferSize) / Math.LN2);
if (Math.pow(2, k) !== bufferSize) { throw "Invalid buffer size, must be a power of 2."; }
if (bufferSize !== buffer.length) { throw "Supplied buffer is not the same size as defined FFT. FFT Size: " + bufferSize + " Buffer Size: " + buffer.length; }
var halfSize = 1,
phaseShiftStepReal,
phaseShiftStepImag,
currentPhaseShiftReal,
currentPhaseShiftImag,
off,
tr,
ti,
tmpReal,
i;
for (i = 0; i < bufferSize; i++) {
real[i] = buffer[reverseTable[i]];
imag[i] = 0;
}
while (halfSize < bufferSize) {
//phaseShiftStepReal = Math.cos(-Math.PI/halfSize);
//phaseShiftStepImag = Math.sin(-Math.PI/halfSize);
phaseShiftStepReal = cosTable[halfSize];
phaseShiftStepImag = sinTable[halfSize];
currentPhaseShiftReal = 1;
currentPhaseShiftImag = 0;
for (var fftStep = 0; fftStep < halfSize; fftStep++) {
i = fftStep;
while (i < bufferSize) {
off = i + halfSize;
tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);
ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);
real[off] = real[i] - tr;
imag[off] = imag[i] - ti;
real[i] += tr;
imag[i] += ti;
i += halfSize << 1;
}
tmpReal = currentPhaseShiftReal;
currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);
currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);
}
halfSize = halfSize << 1;
}
return this.calculateSpectrum();
};
FFT.prototype.inverse = function(real, imag) {
// Locally scope variables for speed up
var bufferSize = this.bufferSize,
cosTable = this.cosTable,
sinTable = this.sinTable,
reverseTable = this.reverseTable,
spectrum = this.spectrum;
real = real || this.real;
imag = imag || this.imag;
var halfSize = 1,
phaseShiftStepReal,
phaseShiftStepImag,
currentPhaseShiftReal,
currentPhaseShiftImag,
off,
tr,
ti,
tmpReal,
i;
for (i = 0; i < bufferSize; i++) {
imag[i] *= -1;
}
var revReal = new Float32Array(bufferSize);
var revImag = new Float32Array(bufferSize);
for (i = 0; i < real.length; i++) {
revReal[i] = real[reverseTable[i]];
revImag[i] = imag[reverseTable[i]];
}
real = revReal;
imag = revImag;
while (halfSize < bufferSize) {
phaseShiftStepReal = cosTable[halfSize];
phaseShiftStepImag = sinTable[halfSize];
currentPhaseShiftReal = 1;
currentPhaseShiftImag = 0;
for (var fftStep = 0; fftStep < halfSize; fftStep++) {
i = fftStep;
while (i < bufferSize) {
off = i + halfSize;
tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);
ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);
real[off] = real[i] - tr;
imag[off] = imag[i] - ti;
real[i] += tr;
imag[i] += ti;
i += halfSize << 1;
}
tmpReal = currentPhaseShiftReal;
currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);
currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);
}
halfSize = halfSize << 1;
}
var buffer = new Float32Array(bufferSize); // this should be reused instead
for (i = 0; i < bufferSize; i++) {
buffer[i] = real[i] / bufferSize;
}
return buffer;
};
/**
* RFFT is a class for calculating the Discrete Fourier Transform of a signal
* with the Fast Fourier Transform algorithm.
*
* This method currently only contains a forward transform but is highly optimized.
*
* @param {Number} bufferSize The size of the sample buffer to be computed. Must be power of 2
* @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)
*
* @constructor
*/
// lookup tables don't really gain us any speed, but they do increase
// cache footprint, so don't use them in here
// also we don't use sepearate arrays for real/imaginary parts
// this one a little more than twice as fast as the one in FFT
// however I only did the forward transform
// the rest of this was translated from C, see http://www.jjj.de/fxt/
// this is the real split radix FFT
function RFFT(bufferSize, sampleRate) {
FourierTransform.call(this, bufferSize, sampleRate);
this.trans = new Float32Array(bufferSize);
this.reverseTable = new Uint32Array(bufferSize);
// don't use a lookup table to do the permute, use this instead
this.reverseBinPermute = function (dest, source) {
var bufferSize = this.bufferSize,
halfSize = bufferSize >>> 1,
nm1 = bufferSize - 1,
i = 1, r = 0, h;
dest[0] = source[0];
do {
r += halfSize;
dest[i] = source[r];
dest[r] = source[i];
i++;
h = halfSize << 1;
while (h = h >> 1, !((r ^= h) & h));
if (r >= i) {
dest[i] = source[r];
dest[r] = source[i];
dest[nm1-i] = source[nm1-r];
dest[nm1-r] = source[nm1-i];
}
i++;
} while (i < halfSize);
dest[nm1] = source[nm1];
};
this.generateReverseTable = function () {
var bufferSize = this.bufferSize,
halfSize = bufferSize >>> 1,
nm1 = bufferSize - 1,
i = 1, r = 0, h;
this.reverseTable[0] = 0;
do {
r += halfSize;
this.reverseTable[i] = r;
this.reverseTable[r] = i;
i++;
h = halfSize << 1;
while (h = h >> 1, !((r ^= h) & h));
if (r >= i) {
this.reverseTable[i] = r;
this.reverseTable[r] = i;
this.reverseTable[nm1-i] = nm1-r;
this.reverseTable[nm1-r] = nm1-i;
}
i++;
} while (i < halfSize);
this.reverseTable[nm1] = nm1;
};
this.generateReverseTable();
}
// Ordering of output:
//
// trans[0] = re[0] (==zero frequency, purely real)
// trans[1] = re[1]
// ...
// trans[n/2-1] = re[n/2-1]
// trans[n/2] = re[n/2] (==nyquist frequency, purely real)
//
// trans[n/2+1] = im[n/2-1]
// trans[n/2+2] = im[n/2-2]
// ...
// trans[n-1] = im[1]
RFFT.prototype.forward = function(buffer) {
var n = this.bufferSize,
spectrum = this.spectrum,
x = this.trans,
TWO_PI = 2*Math.PI,
sqrt = Math.sqrt,
i = n >>> 1,
bSi = 2 / n,
n2, n4, n8, nn,
t1, t2, t3, t4,
i1, i2, i3, i4, i5, i6, i7, i8,
st1, cc1, ss1, cc3, ss3,
e,
a,
rval, ival, mag;
this.reverseBinPermute(x, buffer);
/*
var reverseTable = this.reverseTable;
for (var k = 0, len = reverseTable.length; k < len; k++) {
x[k] = buffer[reverseTable[k]];
}
*/
for (var ix = 0, id = 4; ix < n; id *= 4) {
for (var i0 = ix; i0 < n; i0 += id) {
//sumdiff(x[i0], x[i0+1]); // {a, b} <--| {a+b, a-b}
st1 = x[i0] - x[i0+1];
x[i0] += x[i0+1];
x[i0+1] = st1;
}
ix = 2*(id-1);
}
n2 = 2;
nn = n >>> 1;
while((nn = nn >>> 1)) {
ix = 0;
n2 = n2 << 1;
id = n2 << 1;
n4 = n2 >>> 2;
n8 = n2 >>> 3;
do {
if(n4 !== 1) {
for(i0 = ix; i0 < n; i0 += id) {
i1 = i0;
i2 = i1 + n4;
i3 = i2 + n4;
i4 = i3 + n4;
//diffsum3_r(x[i3], x[i4], t1); // {a, b, s} <--| {a, b-a, a+b}
t1 = x[i3] + x[i4];
x[i4] -= x[i3];
//sumdiff3(x[i1], t1, x[i3]); // {a, b, d} <--| {a+b, b, a-b}
x[i3] = x[i1] - t1;
x[i1] += t1;
i1 += n8;
i2 += n8;
i3 += n8;
i4 += n8;
//sumdiff(x[i3], x[i4], t1, t2); // {s, d} <--| {a+b, a-b}
t1 = x[i3] + x[i4];
t2 = x[i3] - x[i4];
t1 = -t1 * Math.SQRT1_2;
t2 *= Math.SQRT1_2;
// sumdiff(t1, x[i2], x[i4], x[i3]); // {s, d} <--| {a+b, a-b}
st1 = x[i2];
x[i4] = t1 + st1;
x[i3] = t1 - st1;
//sumdiff3(x[i1], t2, x[i2]); // {a, b, d} <--| {a+b, b, a-b}
x[i2] = x[i1] - t2;
x[i1] += t2;
}
} else {
for(i0 = ix; i0 < n; i0 += id) {
i1 = i0;
i2 = i1 + n4;
i3 = i2 + n4;
i4 = i3 + n4;
//diffsum3_r(x[i3], x[i4], t1); // {a, b, s} <--| {a, b-a, a+b}
t1 = x[i3] + x[i4];
x[i4] -= x[i3];
//sumdiff3(x[i1], t1, x[i3]); // {a, b, d} <--| {a+b, b, a-b}
x[i3] = x[i1] - t1;
x[i1] += t1;
}
}
ix = (id << 1) - n2;
id = id << 2;
} while (ix < n);
e = TWO_PI / n2;
for (var j = 1; j < n8; j++) {
a = j * e;
ss1 = Math.sin(a);
cc1 = Math.cos(a);
//ss3 = sin(3*a); cc3 = cos(3*a);
cc3 = 4*cc1*(cc1*cc1-0.75);
ss3 = 4*ss1*(0.75-ss1*ss1);
ix = 0; id = n2 << 1;
do {
for (i0 = ix; i0 < n; i0 += id) {
i1 = i0 + j;
i2 = i1 + n4;
i3 = i2 + n4;
i4 = i3 + n4;
i5 = i0 + n4 - j;
i6 = i5 + n4;
i7 = i6 + n4;
i8 = i7 + n4;
//cmult(c, s, x, y, &u, &v)
//cmult(cc1, ss1, x[i7], x[i3], t2, t1); // {u,v} <--| {x*c-y*s, x*s+y*c}
t2 = x[i7]*cc1 - x[i3]*ss1;
t1 = x[i7]*ss1 + x[i3]*cc1;
//cmult(cc3, ss3, x[i8], x[i4], t4, t3);
t4 = x[i8]*cc3 - x[i4]*ss3;
t3 = x[i8]*ss3 + x[i4]*cc3;
//sumdiff(t2, t4); // {a, b} <--| {a+b, a-b}
st1 = t2 - t4;
t2 += t4;
t4 = st1;
//sumdiff(t2, x[i6], x[i8], x[i3]); // {s, d} <--| {a+b, a-b}
//st1 = x[i6]; x[i8] = t2 + st1; x[i3] = t2 - st1;
x[i8] = t2 + x[i6];
x[i3] = t2 - x[i6];
//sumdiff_r(t1, t3); // {a, b} <--| {a+b, b-a}
st1 = t3 - t1;
t1 += t3;
t3 = st1;
//sumdiff(t3, x[i2], x[i4], x[i7]); // {s, d} <--| {a+b, a-b}
//st1 = x[i2]; x[i4] = t3 + st1; x[i7] = t3 - st1;
x[i4] = t3 + x[i2];
x[i7] = t3 - x[i2];
//sumdiff3(x[i1], t1, x[i6]); // {a, b, d} <--| {a+b, b, a-b}
x[i6] = x[i1] - t1;
x[i1] += t1;
//diffsum3_r(t4, x[i5], x[i2]); // {a, b, s} <--| {a, b-a, a+b}
x[i2] = t4 + x[i5];
x[i5] -= t4;
}
ix = (id << 1) - n2;
id = id << 2;
} while (ix < n);
}
}
while (--i) {
rval = x[i];
ival = x[n-i-1];
mag = bSi * sqrt(rval * rval + ival * ival);
if (mag > this.peak) {
this.peakBand = i;
this.peak = mag;
}
spectrum[i] = mag;
}
spectrum[0] = bSi * x[0];
return spectrum;
};
function Sampler(file, bufferSize, sampleRate, playStart, playEnd, loopStart, loopEnd, loopMode) {
this.file = file;
this.bufferSize = bufferSize;
this.sampleRate = sampleRate;
this.playStart = playStart || 0; // 0%
this.playEnd = playEnd || 1; // 100%
this.loopStart = loopStart || 0;
this.loopEnd = loopEnd || 1;
this.loopMode = loopMode || DSP.OFF;
this.loaded = false;
this.samples = [];
this.signal = new Float32Array(bufferSize);
this.frameCount = 0;
this.envelope = null;
this.amplitude = 1;
this.rootFrequency = 110; // A2 110
this.frequency = 550;
this.step = this.frequency / this.rootFrequency;
this.duration = 0;
this.samplesProcessed = 0;
this.playhead = 0;
var audio = /* new Audio();*/ document.createElement("AUDIO");
var self = this;
this.loadSamples = function(event) {
var buffer = DSP.getChannel(DSP.MIX, event.frameBuffer);
for ( var i = 0; i < buffer.length; i++) {
self.samples.push(buffer[i]);
}
};
this.loadComplete = function() {
// convert flexible js array into a fast typed array
self.samples = new Float32Array(self.samples);
self.loaded = true;
};
this.loadMetaData = function() {
self.duration = audio.duration;
};
audio.addEventListener("MozAudioAvailable", this.loadSamples, false);
audio.addEventListener("loadedmetadata", this.loadMetaData, false);
audio.addEventListener("ended", this.loadComplete, false);
audio.muted = true;
audio.src = file;
audio.play();
}
Sampler.prototype.applyEnvelope = function() {
this.envelope.process(this.signal);
return this.signal;
};
Sampler.prototype.generate = function() {
var frameOffset = this.frameCount * this.bufferSize;
var loopWidth = this.playEnd * this.samples.length - this.playStart * this.samples.length;
var playStartSamples = this.playStart * this.samples.length; // ie 0.5 -> 50% of the length
var playEndSamples = this.playEnd * this.samples.length; // ie 0.5 -> 50% of the length
var offset;
for ( var i = 0; i < this.bufferSize; i++ ) {
switch (this.loopMode) {
case DSP.OFF:
this.playhead = Math.round(this.samplesProcessed * this.step + playStartSamples);
if (this.playhead < (this.playEnd * this.samples.length) ) {
this.signal[i] = this.samples[this.playhead] * this.amplitude;
} else {
this.signal[i] = 0;
}
break;
case DSP.FW:
this.playhead = Math.round((this.samplesProcessed * this.step) % loopWidth + playStartSamples);
if (this.playhead < (this.playEnd * this.samples.length) ) {
this.signal[i] = this.samples[this.playhead] * this.amplitude;
}
break;
case DSP.BW:
this.playhead = playEndSamples - Math.round((this.samplesProcessed * this.step) % loopWidth);
if (this.playhead < (this.playEnd * this.samples.length) ) {
this.signal[i] = this.samples[this.playhead] * this.amplitude;
}
break;
case DSP.FWBW:
if ( Math.floor(this.samplesProcessed * this.step / loopWidth) % 2 === 0 ) {
this.playhead = Math.round((this.samplesProcessed * this.step) % loopWidth + playStartSamples);
} else {
this.playhead = playEndSamples - Math.round((this.samplesProcessed * this.step) % loopWidth);
}
if (this.playhead < (this.playEnd * this.samples.length) ) {
this.signal[i] = this.samples[this.playhead] * this.amplitude;
}
break;
}
this.samplesProcessed++;
}
this.frameCount++;
return this.signal;
};
Sampler.prototype.setFreq = function(frequency) {
this.frequency = frequency;
this.step = this.frequency / this.rootFrequency;
};
Sampler.prototype.reset = function() {
this.samplesProcessed = 0;
this.playhead = 0;
};
/**
* Oscillator class for generating and modifying signals
*
* @param {Number} type A waveform constant (eg. DSP.SINE)
* @param {Number} frequency Initial frequency of the signal
* @param {Number} amplitude Initial amplitude of the signal
* @param {Number} bufferSize Size of the sample buffer to generate
* @param {Number} sampleRate The sample rate of the signal
*
* @contructor
*/
function Oscillator(type, frequency, amplitude, bufferSize, sampleRate) {
this.frequency = frequency;
this.amplitude = amplitude;
this.bufferSize = bufferSize;
this.sampleRate = sampleRate;
//this.pulseWidth = pulseWidth;
this.frameCount = 0;
this.waveTableLength = 2048;
this.cyclesPerSample = frequency / sampleRate;
this.signal = new Float32Array(bufferSize);
this.envelope = null;
switch(parseInt(type, 10)) {
case DSP.TRIANGLE:
this.func = Oscillator.Triangle;
break;
case DSP.SAW:
this.func = Oscillator.Saw;
break;
case DSP.SQUARE:
this.func = Oscillator.Square;
break;
default:
case DSP.SINE:
this.func = Oscillator.Sine;
break;
}
this.generateWaveTable = function() {
Oscillator.waveTable[this.func] = new Float32Array(2048);
var waveTableTime = this.waveTableLength / this.sampleRate;
var waveTableHz = 1 / waveTableTime;
for (var i = 0; i < this.waveTableLength; i++) {
Oscillator.waveTable[this.func][i] = this.func(i * waveTableHz/this.sampleRate);
}
};