-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuidedTrack.sublime-workspace
More file actions
670 lines (670 loc) · 80.5 KB
/
GuidedTrack.sublime-workspace
File metadata and controls
670 lines (670 loc) · 80.5 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
{
"auto_complete":
{
"selected_items":
[
[
"heart",
"heartCanvas"
],
[
"We",
"Windowed"
],
[
"for",
"forward"
],
[
"Y",
"Ylessmean"
],
[
"FFT",
"FFTwindow"
],
[
"fre",
"frequency_subset"
],
[
"Buf",
"BufferFillTime"
],
[
"upate",
"updateMessages"
],
[
"get",
"getpulse"
],
[
"Bu",
"BufferFillTime"
],
[
"bu",
"bufferSize"
],
[
"Buff",
"bufferSize"
],
[
"pea",
"peak_idx"
],
[
"fr",
"frequency_subset"
],
[
"peak_",
"peak_idx"
],
[
"peak",
"peak_value"
],
[
"spect",
"spectrum_subset"
],
[
"spe",
"spectrum_subset"
],
[
"up",
"updateMessages"
],
[
"ul",
"updatePlot"
],
[
"sp",
"spectrum_subset"
],
[
"f",
"frequency_subset"
],
[
"upp",
"upper_idx"
],
[
"low",
"lowest_f"
],
[
"une",
"undefined"
],
[
"lower",
"lower_idx"
],
[
"ind",
"index_max"
],
[
"fun",
"function"
],
[
"o",
"oCanvas"
],
[
"oCa",
"oCanvasContext"
],
[
"eve",
"even_Y"
],
[
"ev",
"even_t"
],
[
"con",
"console"
],
[
"data",
"data"
],
[
"Grn",
"GrnAverage"
],
[
"char",
"chartCanvas"
],
[
"oCan",
"oChartCanvasCtx"
],
[
"b",
"bufferSize"
],
[
"oC",
"oChartCanvasCtx"
],
[
"Hea",
"HeadPos"
],
[
"head",
"head_pos"
],
[
"can",
"canvasOverlay"
],
[
"test",
"testOverlay"
],
[
"cana",
"canvasInput"
],
[
"Gr",
"GrnAverage"
],
[
"F",
"ForeHead_h"
],
[
"For",
"ForeHead_Y"
],
[
"Fore",
"ForeHead_X"
],
[
"Fo",
"ForeHead_w"
],
[
"ForeHead",
"ForeHead_h"
],
[
"fh",
"fh_u"
],
[
"subim",
"subimgY"
],
[
"su",
"subimgy"
],
[
"sub",
"subimgx"
],
[
"sum",
"subImage"
],
[
"testO",
"testOverlayContext"
],
[
"inp",
"inputContext"
]
]
},
"buffers":
[
{
"file": "index.html",
"settings":
{
"buffer_size": 6346,
"line_ending": "Windows"
}
},
{
"contents": "darkruby501.github.io\n=====================\nJavascript Photoplethysmogram Webcam Pulse Detector\n\n<Insert Copyright Info (Ruben Bloom, 2014 + others)>\n\nBased on https://github.com/thearn/webcam-pulse-detector\n\nUses: \n- https://github.com/auduno/headtrackr/\n- https://github.com/corbanbrook/dsp.js/\n- http://g.raphaeljs.com/\n- https://github.com/joewalnes/smoothie/\n\n\nTo-Do:\n- Debug operation in Mozilla Firefox.\n- Fix hardcoding of canvas sizes.\n- Potentially use only facedetection algorithm and no headtracking.\n- Use rotated head capture for forehead.\n- Refine FFT (windowing, etc.)\n- Apply smoothing to output? WMA?\n- Tidy variables.\n\n- Insert second plot for heart rate.\n- Set up way to record and export data.\n\nPotential Ways to Boost Accuracy:\n- Windowing on FFT\n- Filtering of Pulse Wave (band pass?).\n- Smoothing of Output (discard outliers)\n- Button to flush buffer\n- Automatically flush buffer when large movement detected\n- Green background!\n",
"file": "README.md",
"file_size": 907,
"file_write_time": 130558833499515997,
"settings":
{
"buffer_size": 954,
"line_ending": "Windows"
}
},
{
"contents": "/* \n * DSP.js - a comprehensive digital signal processing library for javascript\n * \n * Created by Corban Brook <corbanbrook@gmail.com> on 2010-01-01.\n * Copyright 2010 Corban Brook. All rights reserved.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////\n// CONSTANTS //\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * DSP is an object which contains general purpose utility functions and constants\n */\nvar DSP = {\n // Channels\n LEFT: 0,\n RIGHT: 1,\n MIX: 2,\n\n // Waveforms\n SINE: 1,\n TRIANGLE: 2,\n SAW: 3,\n SQUARE: 4,\n\n // Filters\n LOWPASS: 0,\n HIGHPASS: 1,\n BANDPASS: 2,\n NOTCH: 3,\n\n // Window functions\n BARTLETT: 1,\n BARTLETTHANN: 2,\n BLACKMAN: 3,\n COSINE: 4,\n GAUSS: 5,\n HAMMING: 6,\n HANN: 7,\n LANCZOS: 8,\n RECTANGULAR: 9,\n TRIANGULAR: 10,\n\n // Loop modes\n OFF: 0,\n FW: 1,\n BW: 2,\n FWBW: 3,\n\n // Math\n TWO_PI: 2*Math.PI\n};\n\n// Setup arrays for platforms which do not support byte arrays\nfunction setupTypedArray(name, fallback) {\n // check if TypedArray exists\n // typeof on Minefield and Chrome return function, typeof on Webkit returns object.\n if (typeof this[name] !== \"function\" && typeof this[name] !== \"object\") {\n // nope.. check if WebGLArray exists\n if (typeof this[fallback] === \"function\" && typeof this[fallback] !== \"object\") {\n this[name] = this[fallback];\n } else {\n // nope.. set as Native JS array\n this[name] = function(obj) {\n if (obj instanceof Array) {\n return obj;\n } else if (typeof obj === \"number\") {\n return new Array(obj);\n }\n };\n }\n }\n}\n\nsetupTypedArray(\"Float32Array\", \"WebGLFloatArray\");\nsetupTypedArray(\"Int32Array\", \"WebGLIntArray\");\nsetupTypedArray(\"Uint16Array\", \"WebGLUnsignedShortArray\");\nsetupTypedArray(\"Uint8Array\", \"WebGLUnsignedByteArray\");\n\n\n////////////////////////////////////////////////////////////////////////////////\n// DSP UTILITY FUNCTIONS //\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Inverts the phase of a signal\n *\n * @param {Array} buffer A sample buffer\n *\n * @returns The inverted sample buffer\n */\nDSP.invert = function(buffer) {\n for (var i = 0, len = buffer.length; i < len; i++) {\n buffer[i] *= -1;\n }\n\n return buffer;\n};\n\n/**\n * Converts split-stereo (dual mono) sample buffers into a stereo interleaved sample buffer\n *\n * @param {Array} left A sample buffer\n * @param {Array} right A sample buffer\n *\n * @returns The stereo interleaved buffer\n */\nDSP.interleave = function(left, right) {\n if (left.length !== right.length) {\n throw \"Can not interleave. Channel lengths differ.\";\n }\n \n var stereoInterleaved = new Float32Array(left.length * 2);\n \n for (var i = 0, len = left.length; i < len; i++) {\n stereoInterleaved[2*i] = left[i];\n stereoInterleaved[2*i+1] = right[i];\n }\n \n return stereoInterleaved;\n};\n\n/**\n * Converts a stereo-interleaved sample buffer into split-stereo (dual mono) sample buffers\n *\n * @param {Array} buffer A stereo-interleaved sample buffer\n *\n * @returns an Array containing left and right channels\n */\nDSP.deinterleave = (function() {\n var left, right, mix, deinterleaveChannel = []; \n\n deinterleaveChannel[DSP.MIX] = function(buffer) {\n for (var i = 0, len = buffer.length/2; i < len; i++) {\n mix[i] = (buffer[2*i] + buffer[2*i+1]) / 2;\n }\n return mix;\n };\n\n deinterleaveChannel[DSP.LEFT] = function(buffer) {\n for (var i = 0, len = buffer.length/2; i < len; i++) {\n left[i] = buffer[2*i];\n }\n return left;\n };\n\n deinterleaveChannel[DSP.RIGHT] = function(buffer) {\n for (var i = 0, len = buffer.length/2; i < len; i++) {\n right[i] = buffer[2*i+1];\n }\n return right;\n };\n\n return function(channel, buffer) { \n left = left || new Float32Array(buffer.length/2);\n right = right || new Float32Array(buffer.length/2);\n mix = mix || new Float32Array(buffer.length/2);\n\n if (buffer.length/2 !== left.length) {\n left = new Float32Array(buffer.length/2);\n right = new Float32Array(buffer.length/2);\n mix = new Float32Array(buffer.length/2);\n }\n\n return deinterleaveChannel[channel](buffer);\n };\n}());\n\n/**\n * Separates a channel from a stereo-interleaved sample buffer\n *\n * @param {Array} buffer A stereo-interleaved sample buffer\n * @param {Number} channel A channel constant (LEFT, RIGHT, MIX)\n *\n * @returns an Array containing a signal mono sample buffer\n */\nDSP.getChannel = DSP.deinterleave;\n\n/**\n * Helper method (for Reverb) to mix two (interleaved) samplebuffers. It's possible\n * to negate the second buffer while mixing and to perform a volume correction\n * on the final signal.\n *\n * @param {Array} sampleBuffer1 Array containing Float values or a Float32Array\n * @param {Array} sampleBuffer2 Array containing Float values or a Float32Array\n * @param {Boolean} negate When true inverts/flips the audio signal\n * @param {Number} volumeCorrection When you add multiple sample buffers, use this to tame your signal ;)\n *\n * @returns A new Float32Array interleaved buffer.\n */\nDSP.mixSampleBuffers = function(sampleBuffer1, sampleBuffer2, negate, volumeCorrection){\n var outputSamples = new Float32Array(sampleBuffer1);\n\n for(var i = 0; i<sampleBuffer1.length; i++){\n outputSamples[i] += (negate ? -sampleBuffer2[i] : sampleBuffer2[i]) / volumeCorrection;\n }\n \n return outputSamples;\n}; \n\n// Biquad filter types\nDSP.LPF = 0; // H(s) = 1 / (s^2 + s/Q + 1)\nDSP.HPF = 1; // H(s) = s^2 / (s^2 + s/Q + 1)\nDSP.BPF_CONSTANT_SKIRT = 2; // H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q)\nDSP.BPF_CONSTANT_PEAK = 3; // H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain)\nDSP.NOTCH = 4; // H(s) = (s^2 + 1) / (s^2 + s/Q + 1)\nDSP.APF = 5; // H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1)\nDSP.PEAKING_EQ = 6; // H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1)\nDSP.LOW_SHELF = 7; // H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1)\nDSP.HIGH_SHELF = 8; // H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)\n\n// Biquad filter parameter types\nDSP.Q = 1;\nDSP.BW = 2; // SHARED with BACKWARDS LOOP MODE\nDSP.S = 3;\n\n// Find RMS of signal\nDSP.RMS = function(buffer) {\n var total = 0;\n \n for (var i = 0, n = buffer.length; i < n; i++) {\n total += buffer[i] * buffer[i];\n }\n \n return Math.sqrt(total / n);\n};\n\n// Find Peak of signal\nDSP.Peak = function(buffer) {\n var peak = 0;\n \n for (var i = 0, n = buffer.length; i < n; i++) {\n peak = (Math.abs(buffer[i]) > peak) ? Math.abs(buffer[i]) : peak; \n }\n \n return peak;\n};\n\n// Fourier Transform Module used by DFT, FFT, RFFT\nfunction FourierTransform(bufferSize, sampleRate) {\n this.bufferSize = bufferSize;\n this.sampleRate = sampleRate;\n this.bandwidth = 2 / bufferSize * sampleRate / 2;\n\n this.spectrum = new Float32Array(bufferSize/2);\n this.real = new Float32Array(bufferSize);\n this.imag = new Float32Array(bufferSize);\n\n this.peakBand = 0;\n this.peak = 0;\n\n /**\n * Calculates the *middle* frequency of an FFT band.\n *\n * @param {Number} index The index of the FFT band.\n *\n * @returns The middle frequency in Hz.\n */\n this.getBandFrequency = function(index) {\n return this.bandwidth * index + this.bandwidth / 2;\n };\n\n this.calculateSpectrum = function() {\n var spectrum = this.spectrum,\n real = this.real,\n imag = this.imag,\n bSi = 2 / this.bufferSize,\n sqrt = Math.sqrt,\n rval, \n ival,\n mag;\n\n for (var i = 0, N = bufferSize/2; i < N; i++) {\n rval = real[i];\n ival = imag[i];\n mag = bSi * sqrt(rval * rval + ival * ival);\n\n if (mag > this.peak) {\n this.peakBand = i;\n this.peak = mag;\n }\n\n spectrum[i] = mag;\n }\n };\n}\n\n/**\n * DFT is a class for calculating the Discrete Fourier Transform of a signal.\n *\n * @param {Number} bufferSize The size of the sample buffer to be computed\n * @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)\n *\n * @constructor\n */\nfunction DFT(bufferSize, sampleRate) {\n FourierTransform.call(this, bufferSize, sampleRate);\n\n var N = bufferSize/2 * bufferSize;\n var TWO_PI = 2 * Math.PI;\n\n this.sinTable = new Float32Array(N);\n this.cosTable = new Float32Array(N);\n\n for (var i = 0; i < N; i++) {\n this.sinTable[i] = Math.sin(i * TWO_PI / bufferSize);\n this.cosTable[i] = Math.cos(i * TWO_PI / bufferSize);\n }\n}\n\n/**\n * Performs a forward transform on the sample buffer.\n * Converts a time domain signal to frequency domain spectra.\n *\n * @param {Array} buffer The sample buffer\n *\n * @returns The frequency spectrum array\n */\nDFT.prototype.forward = function(buffer) {\n var real = this.real, \n imag = this.imag,\n rval,\n ival;\n\n for (var k = 0; k < this.bufferSize/2; k++) {\n rval = 0.0;\n ival = 0.0;\n\n for (var n = 0; n < buffer.length; n++) {\n rval += this.cosTable[k*n] * buffer[n];\n ival += this.sinTable[k*n] * buffer[n];\n }\n\n real[k] = rval;\n imag[k] = ival;\n }\n\n return this.calculateSpectrum();\n};\n\n\n/**\n * FFT is a class for calculating the Discrete Fourier Transform of a signal\n * with the Fast Fourier Transform algorithm.\n *\n * @param {Number} bufferSize The size of the sample buffer to be computed. Must be power of 2\n * @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)\n *\n * @constructor\n */\nfunction FFT(bufferSize, sampleRate) {\n FourierTransform.call(this, bufferSize, sampleRate);\n \n this.reverseTable = new Uint32Array(bufferSize);\n\n var limit = 1;\n var bit = bufferSize >> 1;\n\n var i;\n\n while (limit < bufferSize) {\n for (i = 0; i < limit; i++) {\n this.reverseTable[i + limit] = this.reverseTable[i] + bit;\n }\n\n limit = limit << 1;\n bit = bit >> 1;\n }\n\n this.sinTable = new Float32Array(bufferSize);\n this.cosTable = new Float32Array(bufferSize);\n\n for (i = 0; i < bufferSize; i++) {\n this.sinTable[i] = Math.sin(-Math.PI/i);\n this.cosTable[i] = Math.cos(-Math.PI/i);\n }\n}\n\n/**\n * Performs a forward transform on the sample buffer.\n * Converts a time domain signal to frequency domain spectra.\n *\n * @param {Array} buffer The sample buffer. Buffer Length must be power of 2\n *\n * @returns The frequency spectrum array\n */\nFFT.prototype.forward = function(buffer) {\n // Locally scope variables for speed up\n var bufferSize = this.bufferSize,\n cosTable = this.cosTable,\n sinTable = this.sinTable,\n reverseTable = this.reverseTable,\n real = this.real,\n imag = this.imag,\n spectrum = this.spectrum;\n\n var k = Math.floor(Math.log(bufferSize) / Math.LN2);\n\n if (Math.pow(2, k) !== bufferSize) { throw \"Invalid buffer size, must be a power of 2.\"; }\n if (bufferSize !== buffer.length) { throw \"Supplied buffer is not the same size as defined FFT. FFT Size: \" + bufferSize + \" Buffer Size: \" + buffer.length; }\n\n var halfSize = 1,\n phaseShiftStepReal,\n phaseShiftStepImag,\n currentPhaseShiftReal,\n currentPhaseShiftImag,\n off,\n tr,\n ti,\n tmpReal,\n i;\n\n for (i = 0; i < bufferSize; i++) {\n real[i] = buffer[reverseTable[i]];\n imag[i] = 0;\n }\n\n while (halfSize < bufferSize) {\n //phaseShiftStepReal = Math.cos(-Math.PI/halfSize);\n //phaseShiftStepImag = Math.sin(-Math.PI/halfSize);\n phaseShiftStepReal = cosTable[halfSize];\n phaseShiftStepImag = sinTable[halfSize];\n \n currentPhaseShiftReal = 1;\n currentPhaseShiftImag = 0;\n\n for (var fftStep = 0; fftStep < halfSize; fftStep++) {\n i = fftStep;\n\n while (i < bufferSize) {\n off = i + halfSize;\n tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);\n ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);\n\n real[off] = real[i] - tr;\n imag[off] = imag[i] - ti;\n real[i] += tr;\n imag[i] += ti;\n\n i += halfSize << 1;\n }\n\n tmpReal = currentPhaseShiftReal;\n currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);\n currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);\n }\n\n halfSize = halfSize << 1;\n }\n\n return this.calculateSpectrum();\n};\n\nFFT.prototype.inverse = function(real, imag) {\n // Locally scope variables for speed up\n var bufferSize = this.bufferSize,\n cosTable = this.cosTable,\n sinTable = this.sinTable,\n reverseTable = this.reverseTable,\n spectrum = this.spectrum;\n \n real = real || this.real;\n imag = imag || this.imag;\n\n var halfSize = 1,\n phaseShiftStepReal,\n phaseShiftStepImag,\n currentPhaseShiftReal,\n currentPhaseShiftImag,\n off,\n tr,\n ti,\n tmpReal,\n i;\n\n for (i = 0; i < bufferSize; i++) {\n imag[i] *= -1;\n }\n\n var revReal = new Float32Array(bufferSize);\n var revImag = new Float32Array(bufferSize);\n \n for (i = 0; i < real.length; i++) {\n revReal[i] = real[reverseTable[i]];\n revImag[i] = imag[reverseTable[i]];\n }\n \n real = revReal;\n imag = revImag;\n\n while (halfSize < bufferSize) {\n phaseShiftStepReal = cosTable[halfSize];\n phaseShiftStepImag = sinTable[halfSize];\n currentPhaseShiftReal = 1;\n currentPhaseShiftImag = 0;\n\n for (var fftStep = 0; fftStep < halfSize; fftStep++) {\n i = fftStep;\n\n while (i < bufferSize) {\n off = i + halfSize;\n tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);\n ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);\n\n real[off] = real[i] - tr;\n imag[off] = imag[i] - ti;\n real[i] += tr;\n imag[i] += ti;\n\n i += halfSize << 1;\n }\n\n tmpReal = currentPhaseShiftReal;\n currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);\n currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);\n }\n\n halfSize = halfSize << 1;\n }\n\n var buffer = new Float32Array(bufferSize); // this should be reused instead\n for (i = 0; i < bufferSize; i++) {\n buffer[i] = real[i] / bufferSize;\n }\n\n return buffer;\n};\n\n/**\n * RFFT is a class for calculating the Discrete Fourier Transform of a signal\n * with the Fast Fourier Transform algorithm.\n *\n * This method currently only contains a forward transform but is highly optimized.\n *\n * @param {Number} bufferSize The size of the sample buffer to be computed. Must be power of 2\n * @param {Number} sampleRate The sampleRate of the buffer (eg. 44100)\n *\n * @constructor\n */\n\n// lookup tables don't really gain us any speed, but they do increase\n// cache footprint, so don't use them in here\n\n// also we don't use sepearate arrays for real/imaginary parts\n\n// this one a little more than twice as fast as the one in FFT\n// however I only did the forward transform\n\n// the rest of this was translated from C, see http://www.jjj.de/fxt/\n// this is the real split radix FFT\n\nfunction RFFT(bufferSize, sampleRate) {\n FourierTransform.call(this, bufferSize, sampleRate);\n\n this.trans = new Float32Array(bufferSize);\n\n this.reverseTable = new Uint32Array(bufferSize);\n\n // don't use a lookup table to do the permute, use this instead\n this.reverseBinPermute = function (dest, source) {\n var bufferSize = this.bufferSize, \n halfSize = bufferSize >>> 1, \n nm1 = bufferSize - 1, \n i = 1, r = 0, h;\n\n dest[0] = source[0];\n\n do {\n r += halfSize;\n dest[i] = source[r];\n dest[r] = source[i];\n \n i++;\n\n h = halfSize << 1;\n while (h = h >> 1, !((r ^= h) & h));\n\n if (r >= i) { \n dest[i] = source[r]; \n dest[r] = source[i];\n\n dest[nm1-i] = source[nm1-r]; \n dest[nm1-r] = source[nm1-i];\n }\n i++;\n } while (i < halfSize);\n dest[nm1] = source[nm1];\n };\n\n this.generateReverseTable = function () {\n var bufferSize = this.bufferSize, \n halfSize = bufferSize >>> 1, \n nm1 = bufferSize - 1, \n i = 1, r = 0, h;\n\n this.reverseTable[0] = 0;\n\n do {\n r += halfSize;\n \n this.reverseTable[i] = r;\n this.reverseTable[r] = i;\n\n i++;\n\n h = halfSize << 1;\n while (h = h >> 1, !((r ^= h) & h));\n\n if (r >= i) { \n this.reverseTable[i] = r;\n this.reverseTable[r] = i;\n\n this.reverseTable[nm1-i] = nm1-r;\n this.reverseTable[nm1-r] = nm1-i;\n }\n i++;\n } while (i < halfSize);\n\n this.reverseTable[nm1] = nm1;\n };\n\n this.generateReverseTable();\n}\n\n\n// Ordering of output:\n//\n// trans[0] = re[0] (==zero frequency, purely real)\n// trans[1] = re[1]\n// ...\n// trans[n/2-1] = re[n/2-1]\n// trans[n/2] = re[n/2] (==nyquist frequency, purely real)\n//\n// trans[n/2+1] = im[n/2-1]\n// trans[n/2+2] = im[n/2-2]\n// ...\n// trans[n-1] = im[1] \n\nRFFT.prototype.forward = function(buffer) {\n var n = this.bufferSize, \n spectrum = this.spectrum,\n x = this.trans, \n TWO_PI = 2*Math.PI,\n sqrt = Math.sqrt,\n i = n >>> 1,\n bSi = 2 / n,\n n2, n4, n8, nn, \n t1, t2, t3, t4, \n i1, i2, i3, i4, i5, i6, i7, i8, \n st1, cc1, ss1, cc3, ss3,\n e, \n a,\n rval, ival, mag; \n\n this.reverseBinPermute(x, buffer);\n\n /*\n var reverseTable = this.reverseTable;\n\n for (var k = 0, len = reverseTable.length; k < len; k++) {\n x[k] = buffer[reverseTable[k]];\n }\n */\n\n for (var ix = 0, id = 4; ix < n; id *= 4) {\n for (var i0 = ix; i0 < n; i0 += id) {\n //sumdiff(x[i0], x[i0+1]); // {a, b} <--| {a+b, a-b}\n st1 = x[i0] - x[i0+1];\n x[i0] += x[i0+1];\n x[i0+1] = st1;\n } \n ix = 2*(id-1);\n }\n\n n2 = 2;\n nn = n >>> 1;\n\n while((nn = nn >>> 1)) {\n ix = 0;\n n2 = n2 << 1;\n id = n2 << 1;\n n4 = n2 >>> 2;\n n8 = n2 >>> 3;\n do {\n if(n4 !== 1) {\n for(i0 = ix; i0 < n; i0 += id) {\n i1 = i0;\n i2 = i1 + n4;\n i3 = i2 + n4;\n i4 = i3 + n4;\n \n //diffsum3_r(x[i3], x[i4], t1); // {a, b, s} <--| {a, b-a, a+b}\n t1 = x[i3] + x[i4];\n x[i4] -= x[i3];\n //sumdiff3(x[i1], t1, x[i3]); // {a, b, d} <--| {a+b, b, a-b}\n x[i3] = x[i1] - t1; \n x[i1] += t1;\n \n i1 += n8;\n i2 += n8;\n i3 += n8;\n i4 += n8;\n \n //sumdiff(x[i3], x[i4], t1, t2); // {s, d} <--| {a+b, a-b}\n t1 = x[i3] + x[i4];\n t2 = x[i3] - x[i4];\n \n t1 = -t1 * Math.SQRT1_2;\n t2 *= Math.SQRT1_2;\n \n // sumdiff(t1, x[i2], x[i4], x[i3]); // {s, d} <--| {a+b, a-b}\n st1 = x[i2];\n x[i4] = t1 + st1; \n x[i3] = t1 - st1;\n \n //sumdiff3(x[i1], t2, x[i2]); // {a, b, d} <--| {a+b, b, a-b}\n x[i2] = x[i1] - t2;\n x[i1] += t2;\n }\n } else {\n for(i0 = ix; i0 < n; i0 += id) {\n i1 = i0;\n i2 = i1 + n4;\n i3 = i2 + n4;\n i4 = i3 + n4;\n \n //diffsum3_r(x[i3], x[i4], t1); // {a, b, s} <--| {a, b-a, a+b}\n t1 = x[i3] + x[i4]; \n x[i4] -= x[i3];\n \n //sumdiff3(x[i1], t1, x[i3]); // {a, b, d} <--| {a+b, b, a-b}\n x[i3] = x[i1] - t1; \n x[i1] += t1;\n }\n }\n \n ix = (id << 1) - n2;\n id = id << 2;\n } while (ix < n);\n \n e = TWO_PI / n2;\n\n for (var j = 1; j < n8; j++) {\n a = j * e;\n ss1 = Math.sin(a);\n cc1 = Math.cos(a);\n\n //ss3 = sin(3*a); cc3 = cos(3*a);\n cc3 = 4*cc1*(cc1*cc1-0.75);\n ss3 = 4*ss1*(0.75-ss1*ss1);\n \n ix = 0; id = n2 << 1;\n do {\n for (i0 = ix; i0 < n; i0 += id) {\n i1 = i0 + j;\n i2 = i1 + n4;\n i3 = i2 + n4;\n i4 = i3 + n4;\n \n i5 = i0 + n4 - j;\n i6 = i5 + n4;\n i7 = i6 + n4;\n i8 = i7 + n4;\n \n //cmult(c, s, x, y, &u, &v)\n //cmult(cc1, ss1, x[i7], x[i3], t2, t1); // {u,v} <--| {x*c-y*s, x*s+y*c}\n t2 = x[i7]*cc1 - x[i3]*ss1; \n t1 = x[i7]*ss1 + x[i3]*cc1;\n \n //cmult(cc3, ss3, x[i8], x[i4], t4, t3);\n t4 = x[i8]*cc3 - x[i4]*ss3; \n t3 = x[i8]*ss3 + x[i4]*cc3;\n \n //sumdiff(t2, t4); // {a, b} <--| {a+b, a-b}\n st1 = t2 - t4;\n t2 += t4;\n t4 = st1;\n \n //sumdiff(t2, x[i6], x[i8], x[i3]); // {s, d} <--| {a+b, a-b}\n //st1 = x[i6]; x[i8] = t2 + st1; x[i3] = t2 - st1;\n x[i8] = t2 + x[i6]; \n x[i3] = t2 - x[i6];\n \n //sumdiff_r(t1, t3); // {a, b} <--| {a+b, b-a}\n st1 = t3 - t1;\n t1 += t3;\n t3 = st1;\n \n //sumdiff(t3, x[i2], x[i4], x[i7]); // {s, d} <--| {a+b, a-b}\n //st1 = x[i2]; x[i4] = t3 + st1; x[i7] = t3 - st1;\n x[i4] = t3 + x[i2]; \n x[i7] = t3 - x[i2];\n \n //sumdiff3(x[i1], t1, x[i6]); // {a, b, d} <--| {a+b, b, a-b}\n x[i6] = x[i1] - t1; \n x[i1] += t1;\n \n //diffsum3_r(t4, x[i5], x[i2]); // {a, b, s} <--| {a, b-a, a+b}\n x[i2] = t4 + x[i5]; \n x[i5] -= t4;\n }\n \n ix = (id << 1) - n2;\n id = id << 2;\n \n } while (ix < n);\n }\n }\n\n while (--i) {\n rval = x[i];\n ival = x[n-i-1];\n mag = bSi * sqrt(rval * rval + ival * ival);\n\n if (mag > this.peak) {\n this.peakBand = i;\n this.peak = mag;\n }\n\n spectrum[i] = mag;\n }\n\n spectrum[0] = bSi * x[0];\n\n return spectrum;\n};\n\nfunction Sampler(file, bufferSize, sampleRate, playStart, playEnd, loopStart, loopEnd, loopMode) {\n this.file = file;\n this.bufferSize = bufferSize;\n this.sampleRate = sampleRate;\n this.playStart = playStart || 0; // 0%\n this.playEnd = playEnd || 1; // 100%\n this.loopStart = loopStart || 0;\n this.loopEnd = loopEnd || 1;\n this.loopMode = loopMode || DSP.OFF;\n this.loaded = false;\n this.samples = [];\n this.signal = new Float32Array(bufferSize);\n this.frameCount = 0;\n this.envelope = null;\n this.amplitude = 1;\n this.rootFrequency = 110; // A2 110\n this.frequency = 550;\n this.step = this.frequency / this.rootFrequency;\n this.duration = 0;\n this.samplesProcessed = 0;\n this.playhead = 0;\n \n var audio = /* new Audio();*/ document.createElement(\"AUDIO\");\n var self = this;\n \n this.loadSamples = function(event) {\n var buffer = DSP.getChannel(DSP.MIX, event.frameBuffer);\n for ( var i = 0; i < buffer.length; i++) {\n self.samples.push(buffer[i]);\n }\n };\n \n this.loadComplete = function() {\n // convert flexible js array into a fast typed array\n self.samples = new Float32Array(self.samples);\n self.loaded = true;\n };\n \n this.loadMetaData = function() {\n self.duration = audio.duration;\n };\n \n audio.addEventListener(\"MozAudioAvailable\", this.loadSamples, false);\n audio.addEventListener(\"loadedmetadata\", this.loadMetaData, false);\n audio.addEventListener(\"ended\", this.loadComplete, false);\n audio.muted = true;\n audio.src = file;\n audio.play();\n}\n\nSampler.prototype.applyEnvelope = function() {\n this.envelope.process(this.signal);\n return this.signal;\n};\n\nSampler.prototype.generate = function() {\n var frameOffset = this.frameCount * this.bufferSize;\n \n var loopWidth = this.playEnd * this.samples.length - this.playStart * this.samples.length;\n var playStartSamples = this.playStart * this.samples.length; // ie 0.5 -> 50% of the length\n var playEndSamples = this.playEnd * this.samples.length; // ie 0.5 -> 50% of the length\n var offset;\n\n for ( var i = 0; i < this.bufferSize; i++ ) {\n switch (this.loopMode) {\n case DSP.OFF:\n this.playhead = Math.round(this.samplesProcessed * this.step + playStartSamples);\n if (this.playhead < (this.playEnd * this.samples.length) ) {\n this.signal[i] = this.samples[this.playhead] * this.amplitude;\n } else {\n this.signal[i] = 0;\n }\n break;\n \n case DSP.FW:\n this.playhead = Math.round((this.samplesProcessed * this.step) % loopWidth + playStartSamples);\n if (this.playhead < (this.playEnd * this.samples.length) ) {\n this.signal[i] = this.samples[this.playhead] * this.amplitude;\n }\n break;\n \n case DSP.BW:\n this.playhead = playEndSamples - Math.round((this.samplesProcessed * this.step) % loopWidth);\n if (this.playhead < (this.playEnd * this.samples.length) ) {\n this.signal[i] = this.samples[this.playhead] * this.amplitude;\n }\n break;\n \n case DSP.FWBW:\n if ( Math.floor(this.samplesProcessed * this.step / loopWidth) % 2 === 0 ) {\n this.playhead = Math.round((this.samplesProcessed * this.step) % loopWidth + playStartSamples);\n } else {\n this.playhead = playEndSamples - Math.round((this.samplesProcessed * this.step) % loopWidth);\n } \n if (this.playhead < (this.playEnd * this.samples.length) ) {\n this.signal[i] = this.samples[this.playhead] * this.amplitude;\n }\n break;\n }\n this.samplesProcessed++;\n }\n\n this.frameCount++;\n\n return this.signal;\n};\n\nSampler.prototype.setFreq = function(frequency) {\n var totalProcessed = this.samplesProcessed * this.step;\n this.frequency = frequency;\n this.step = this.frequency / this.rootFrequency;\n this.samplesProcessed = Math.round(totalProcessed/this.step);\n};\n\nSampler.prototype.reset = function() {\n this.samplesProcessed = 0;\n this.playhead = 0;\n};\n\n/**\n * Oscillator class for generating and modifying signals\n *\n * @param {Number} type A waveform constant (eg. DSP.SINE)\n * @param {Number} frequency Initial frequency of the signal\n * @param {Number} amplitude Initial amplitude of the signal\n * @param {Number} bufferSize Size of the sample buffer to generate\n * @param {Number} sampleRate The sample rate of the signal\n *\n * @contructor\n */\nfunction Oscillator(type, frequency, amplitude, bufferSize, sampleRate) {\n this.frequency = frequency;\n this.amplitude = amplitude;\n this.bufferSize = bufferSize;\n this.sampleRate = sampleRate;\n //this.pulseWidth = pulseWidth;\n this.frameCount = 0;\n \n this.waveTableLength = 2048;\n\n this.cyclesPerSample = frequency / sampleRate;\n\n this.signal = new Float32Array(bufferSize);\n this.envelope = null;\n\n switch(parseInt(type, 10)) {\n case DSP.TRIANGLE:\n this.func = Oscillator.Triangle;\n break;\n\n case DSP.SAW:\n this.func = Oscillator.Saw;\n break;\n\n case DSP.SQUARE:\n this.func = Oscillator.Square;\n break;\n\n default:\n case DSP.SINE:\n this.func = Oscillator.Sine;\n break;\n }\n\n this.generateWaveTable = function() {\n Oscillator.waveTable[this.func] = new Float32Array(2048);\n var waveTableTime = this.waveTableLength / this.sampleRate;\n var waveTableHz = 1 / waveTableTime;\n\n for (var i = 0; i < this.waveTableLength; i++) {\n Oscillator.waveTable[this.func][i] = this.func(i * waveTableHz/this.sampleRate);\n }\n };\n\n if ( typeof Oscillator.waveTable === 'undefined' ) {\n Oscillator.waveTable = {};\n }\n\n if ( typeof Oscillator.waveTable[this.func] === 'undefined' ) {\n this.generateWaveTable();\n }\n \n this.waveTable = Oscillator.waveTable[this.func];\n}\n\n/**\n * Set the amplitude of the signal\n *\n * @param {Number} amplitude The amplitude of the signal (between 0 and 1)\n */\nOscillator.prototype.setAmp = function(amplitude) {\n if (amplitude >= 0 && amplitude <= 1) {\n this.amplitude = amplitude;\n } else {\n throw \"Amplitude out of range (0..1).\";\n }\n};\n \n/**\n * Set the frequency of the signal\n *\n * @param {Number} frequency The frequency of the signal\n */ \nOscillator.prototype.setFreq = function(frequency) {\n this.frequency = frequency;\n this.cyclesPerSample = frequency / this.sampleRate;\n};\n \n// Add an oscillator\nOscillator.prototype.add = function(oscillator) {\n for ( var i = 0; i < this.bufferSize; i++ ) {\n //this.signal[i] += oscillator.valueAt(i);\n this.signal[i] += oscillator.signal[i];\n }\n \n return this.signal;\n};\n \n// Add a signal to the current generated osc signal\nOscillator.prototype.addSignal = function(signal) {\n for ( var i = 0; i < signal.length; i++ ) {\n if ( i >= this.bufferSize ) {\n break;\n }\n this.signal[i] += signal[i];\n \n /*\n // Constrain amplitude\n if ( this.signal[i] > 1 ) {\n this.signal[i] = 1;\n } else if ( this.signal[i] < -1 ) {\n this.signal[i] = -1;\n }\n */\n }\n return this.signal;\n};\n \n// Add an envelope to the oscillator\nOscillator.prototype.addEnvelope = function(envelope) {\n this.envelope = envelope;\n};\n\nOscillator.prototype.applyEnvelope = function() {\n this.envelope.process(this.signal);\n};\n \nOscillator.prototype.valueAt = function(offset) {\n return this.waveTable[offset % this.waveTableLength];\n};\n \nOscillator.prototype.generate = function() {\n var frameOffset = this.frameCount * this.bufferSize;\n var step = this.waveTableLength * this.frequency / this.sampleRate;\n var offset;\n\n for ( var i = 0; i < this.bufferSize; i++ ) {\n //var step = (frameOffset + i) * this.cyclesPerSample % 1;\n //this.signal[i] = this.func(step) * this.amplitude;\n //this.signal[i] = this.valueAt(Math.round((frameOffset + i) * step)) * this.amplitude;\n offset = Math.round((frameOffset + i) * step);\n this.signal[i] = this.waveTable[offset % this.waveTableLength] * this.amplitude;\n }\n\n this.frameCount++;\n\n return this.signal;\n};\n\nOscillator.Sine = function(step) {\n return Math.sin(DSP.TWO_PI * step);\n};\n\nOscillator.Square = function(step) {\n return step < 0.5 ? 1 : -1;\n};\n\nOscillator.Saw = function(step) {\n return 2 * (step - Math.round(step));\n};\n\nOscillator.Triangle = function(step) {\n return 1 - 4 * Math.abs(Math.round(step) - step);\n};\n\nOscillator.Pulse = function(step) {\n // stub\n};\n \nfunction ADSR(attackLength, decayLength, sustainLevel, sustainLength, releaseLength, sampleRate) {\n this.sampleRate = sampleRate;\n // Length in seconds\n this.attackLength = attackLength;\n this.decayLength = decayLength;\n this.sustainLevel = sustainLevel;\n this.sustainLength = sustainLength;\n this.releaseLength = releaseLength;\n this.sampleRate = sampleRate;\n \n // Length in samples\n this.attackSamples = attackLength * sampleRate;\n this.decaySamples = decayLength * sampleRate;\n this.sustainSamples = sustainLength * sampleRate;\n this.releaseSamples = releaseLength * sampleRate;\n \n // Updates the envelope sample positions\n this.update = function() {\n this.attack = this.attackSamples;\n this.decay = this.attack + this.decaySamples;\n this.sustain = this.decay + this.sustainSamples;\n this.release = this.sustain + this.releaseSamples;\n };\n \n this.update();\n \n this.samplesProcessed = 0;\n}\n\nADSR.prototype.noteOn = function() {\n this.samplesProcessed = 0;\n this.sustainSamples = this.sustainLength * this.sampleRate;\n this.update();\n};\n\n// Send a note off when using a sustain of infinity to let the envelope enter the release phase\nADSR.prototype.noteOff = function() {\n this.sustainSamples = this.samplesProcessed - this.decaySamples;\n this.update();\n};\n\nADSR.prototype.processSample = function(sample) {\n var amplitude = 0;\n\n if ( this.samplesProcessed <= this.attack ) {\n amplitude = 0 + (1 - 0) * ((this.samplesProcessed - 0) / (this.attack - 0));\n } else if ( this.samplesProcessed > this.attack && this.samplesProcessed <= this.decay ) {\n amplitude = 1 + (this.sustainLevel - 1) * ((this.samplesProcessed - this.attack) / (this.decay - this.attack));\n } else if ( this.samplesProcessed > this.decay && this.samplesProcessed <= this.sustain ) {\n amplitude = this.sustainLevel;\n } else if ( this.samplesProcessed > this.sustain && this.samplesProcessed <= this.release ) {\n amplitude = this.sustainLevel + (0 - this.sustainLevel) * ((this.samplesProcessed - this.sustain) / (this.release - this.sustain));\n }\n \n return sample * amplitude;\n};\n\nADSR.prototype.value = function() {\n var amplitude = 0;\n\n if ( this.samplesProcessed <= this.attack ) {\n amplitude = 0 + (1 - 0) * ((this.samplesProcessed - 0) / (this.attack - 0));\n } else if ( this.samplesProcessed > this.attack && this.samplesProcessed <= this.decay ) {\n amplitude = 1 + (this.sustainLevel - 1) * ((this.samplesProcessed - this.attack) / (this.decay - this.attack));\n } else if ( this.samplesProcessed > this.decay && this.samplesProcessed <= this.sustain ) {\n amplitude = this.sustainLevel;\n } else if ( this.samplesProcessed > this.sustain && this.samplesProcessed <= this.release ) {\n amplitude = this.sustainLevel + (0 - this.sustainLevel) * ((this.samplesProcessed - this.sustain) / (this.release - this.sustain));\n }\n \n return amplitude;\n};\n \nADSR.prototype.process = function(buffer) {\n for ( var i = 0; i < buffer.length; i++ ) {\n buffer[i] *= this.value();\n\n this.samplesProcessed++;\n }\n \n return buffer;\n};\n \n \nADSR.prototype.isActive = function() {\n if ( this.samplesProcessed > this.release || this.samplesProcessed === -1 ) {\n return false;\n } else {\n return true;\n }\n};\n\nADSR.prototype.disable = function() {\n this.samplesProcessed = -1;\n};\n \nfunction IIRFilter(type, cutoff, resonance, sampleRate) {\n this.sampleRate = sampleRate;\n\n switch(type) {\n case DSP.LOWPASS:\n case DSP.LP12:\n this.func = new IIRFilter.LP12(cutoff, resonance, sampleRate);\n break;\n }\n}\n\nIIRFilter.prototype.__defineGetter__('cutoff',\n function() {\n return this.func.cutoff;\n }\n);\n\nIIRFilter.prototype.__defineGetter__('resonance',\n function() {\n return this.func.resonance;\n }\n);\n\nIIRFilter.prototype.set = function(cutoff, resonance) {\n this.func.calcCoeff(cutoff, resonance);\n};\n\nIIRFilter.prototype.process = function(buffer) {\n this.func.process(buffer);\n};\n\n// Add an envelope to the filter\nIIRFilter.prototype.addEnvelope = function(envelope) {\n if ( envelope instanceof ADSR ) {\n this.func.addEnvelope(envelope);\n } else {\n throw \"Not an envelope.\";\n }\n};\n\nIIRFilter.LP12 = function(cutoff, resonance, sampleRate) {\n this.sampleRate = sampleRate;\n this.vibraPos = 0;\n this.vibraSpeed = 0;\n this.envelope = false;\n \n this.calcCoeff = function(cutoff, resonance) {\n this.w = 2.0 * Math.PI * cutoff / this.sampleRate;\n this.q = 1.0 - this.w / (2.0 * (resonance + 0.5 / (1.0 + this.w)) + this.w - 2.0);\n this.r = this.q * this.q;\n this.c = this.r + 1.0 - 2.0 * Math.cos(this.w) * this.q;\n \n this.cutoff = cutoff;\n this.resonance = resonance;\n };\n\n this.calcCoeff(cutoff, resonance);\n\n this.process = function(buffer) {\n for ( var i = 0; i < buffer.length; i++ ) {\n this.vibraSpeed += (buffer[i] - this.vibraPos) * this.c;\n this.vibraPos += this.vibraSpeed;\n this.vibraSpeed *= this.r;\n \n /*\n var temp = this.vibraPos;\n \n if ( temp > 1.0 ) {\n temp = 1.0;\n } else if ( temp < -1.0 ) {\n temp = -1.0;\n } else if ( temp != temp ) {\n temp = 1;\n }\n \n buffer[i] = temp;\n */\n\n if (this.envelope) {\n buffer[i] = (buffer[i] * (1 - this.envelope.value())) + (this.vibraPos * this.envelope.value());\n this.envelope.samplesProcessed++;\n } else {\n buffer[i] = this.vibraPos;\n }\n }\n };\n}; \n\nIIRFilter.LP12.prototype.addEnvelope = function(envelope) {\n this.envelope = envelope;\n};\n\nfunction IIRFilter2(type, cutoff, resonance, sampleRate) {\n this.type = type;\n this.cutoff = cutoff;\n this.resonance = resonance;\n this.sampleRate = sampleRate;\n\n this.f = Float32Array(4);\n this.f[0] = 0.0; // lp\n this.f[1] = 0.0; // hp\n this.f[2] = 0.0; // bp\n this.f[3] = 0.0; // br \n \n this.calcCoeff = function(cutoff, resonance) {\n this.freq = 2 * Math.sin(Math.PI * Math.min(0.25, cutoff/(this.sampleRate*2))); \n this.damp = Math.min(2 * (1 - Math.pow(resonance, 0.25)), Math.min(2, 2/this.freq - this.freq * 0.5));\n };\n\n this.calcCoeff(cutoff, resonance);\n}\n\nIIRFilter2.prototype.process = function(buffer) {\n var input, output;\n var f = this.f;\n\n for ( var i = 0; i < buffer.length; i++ ) {\n input = buffer[i];\n\n // first pass\n f[3] = input - this.damp * f[2];\n f[0] = f[0] + this.freq * f[2];\n f[1] = f[3] - f[0];\n f[2] = this.freq * f[1] + f[2];\n output = 0.5 * f[this.type];\n\n // second pass\n f[3] = input - this.damp * f[2];\n f[0] = f[0] + this.freq * f[2];\n f[1] = f[3] - f[0];\n f[2] = this.freq * f[1] + f[2];\n output += 0.5 * f[this.type];\n\n if (this.envelope) {\n buffer[i] = (buffer[i] * (1 - this.envelope.value())) + (output * this.envelope.value());\n this.envelope.samplesProcessed++;\n } else {\n buffer[i] = output;\n }\n }\n};\n\nIIRFilter2.prototype.addEnvelope = function(envelope) {\n if ( envelope instanceof ADSR ) {\n this.envelope = envelope;\n } else {\n throw \"This is not an envelope.\";\n }\n};\n\nIIRFilter2.prototype.set = function(cutoff, resonance) {\n this.calcCoeff(cutoff, resonance);\n};\n\n\n\nfunction WindowFunction(type, alpha) {\n this.alpha = alpha;\n \n switch(type) {\n case DSP.BARTLETT:\n this.func = WindowFunction.Bartlett;\n break;\n \n case DSP.BARTLETTHANN:\n this.func = WindowFunction.BartlettHann;\n break;\n \n case DSP.BLACKMAN:\n this.func = WindowFunction.Blackman;\n this.alpha = this.alpha || 0.16;\n break;\n \n case DSP.COSINE:\n this.func = WindowFunction.Cosine;\n break;\n \n case DSP.GAUSS:\n this.func = WindowFunction.Gauss;\n this.alpha = this.alpha || 0.25;\n break;\n \n case DSP.HAMMING:\n this.func = WindowFunction.Hamming;\n break;\n \n case DSP.HANN:\n this.func = WindowFunction.Hann;\n break;\n \n case DSP.LANCZOS:\n this.func = WindowFunction.Lanczoz;\n break;\n \n case DSP.RECTANGULAR:\n this.func = WindowFunction.Rectangular;\n break;\n \n case DSP.TRIANGULAR:\n this.func = WindowFunction.Triangular;\n break;\n }\n}\n\nWindowFunction.prototype.process = function(buffer) {\n var length = buffer.length;\n for ( var i = 0; i < length; i++ ) {\n buffer[i] *= this.func(length, i, this.alpha);\n }\n return buffer;\n};\n\nWindowFunction.Bartlett = function(length, index) {\n return 2 / (length - 1) * ((length - 1) / 2 - Math.abs(index - (length - 1) / 2));\n};\n\nWindowFunction.BartlettHann = function(length, index) {\n return 0.62 - 0.48 * Math.abs(index / (length - 1) - 0.5) - 0.38 * Math.cos(DSP.TWO_PI * index / (length - 1));\n};\n\nWindowFunction.Blackman = function(length, index, alpha) {\n var a0 = (1 - alpha) / 2;\n var a1 = 0.5;\n var a2 = alpha / 2;\n\n return a0 - a1 * Math.cos(DSP.TWO_PI * index / (length - 1)) + a2 * Math.cos(4 * Math.PI * index / (length - 1));\n};\n\nWindowFunction.Cosine = function(length, index) {\n return Math.cos(Math.PI * index / (length - 1) - Math.PI / 2);\n};\n\nWindowFunction.Gauss = function(length, index, alpha) {\n return Math.pow(Math.E, -0.5 * Math.pow((index - (length - 1) / 2) / (alpha * (length - 1) / 2), 2));\n};\n\nWindowFunction.Hamming = function(length, index) {\n return 0.54 - 0.46 * Math.cos(DSP.TWO_PI * index / (length - 1));\n};\n\nWindowFunction.Hann = function(length, index) {\n return 0.5 * (1 - Math.cos(DSP.TWO_PI * index / (length - 1)));\n};\n\nWindowFunction.Lanczos = function(length, index) {\n var x = 2 * index / (length - 1) - 1;\n return Math.sin(Math.PI * x) / (Math.PI * x);\n};\n\nWindowFunction.Rectangular = function(length, index) {\n return 1;\n};\n\nWindowFunction.Triangular = function(length, index) {\n return 2 / length * (length / 2 - Math.abs(index - (length - 1) / 2));\n};\n\nfunction sinh (arg) {\n // Returns the hyperbolic sine of the number, defined as (exp(number) - exp(-number))/2 \n //\n // version: 1004.2314\n // discuss at: http://phpjs.org/functions/sinh // + original by: Onno Marsman\n // * example 1: sinh(-0.9834330348825909);\n // * returns 1: -1.1497971402636502\n return (Math.exp(arg) - Math.exp(-arg))/2;\n}\n\n/* \n * Biquad filter\n * \n * Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23.\n * Copyright 2010 Ricard Marxer. All rights reserved.\n *\n */\n// Implementation based on:\n// http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt\nfunction Biquad(type, sampleRate) {\n this.Fs = sampleRate;\n this.type = type; // type of the filter\n this.parameterType = DSP.Q; // type of the parameter\n\n this.x_1_l = 0;\n this.x_2_l = 0;\n this.y_1_l = 0;\n this.y_2_l = 0;\n\n this.x_1_r = 0;\n this.x_2_r = 0;\n this.y_1_r = 0;\n this.y_2_r = 0;\n\n this.b0 = 1;\n this.a0 = 1;\n\n this.b1 = 0;\n this.a1 = 0;\n\n this.b2 = 0;\n this.a2 = 0;\n\n this.b0a0 = this.b0 / this.a0;\n this.b1a0 = this.b1 / this.a0;\n this.b2a0 = this.b2 / this.a0;\n this.a1a0 = this.a1 / this.a0;\n this.a2a0 = this.a2 / this.a0;\n\n this.f0 = 3000; // \"wherever it's happenin', man.\" Center Frequency or\n // Corner Frequency, or shelf midpoint frequency, depending\n // on which filter type. The \"significant frequency\".\n\n this.dBgain = 12; // used only for peaking and shelving filters\n\n this.Q = 1; // the EE kind of definition, except for peakingEQ in which A*Q is\n // the classic EE Q. That adjustment in definition was made so that\n // a boost of N dB followed by a cut of N dB for identical Q and\n // f0/Fs results in a precisely flat unity gain filter or \"wire\".\n\n this.BW = -3; // the bandwidth in octaves (between -3 dB frequencies for BPF\n // and notch or between midpoint (dBgain/2) gain frequencies for\n // peaking EQ\n\n this.S = 1; // a \"shelf slope\" parameter (for shelving EQ only). When S = 1,\n // the shelf slope is as steep as it can be and remain monotonically\n // increasing or decreasing gain with frequency. The shelf slope, in\n // dB/octave, remains proportional to S for all other values for a\n // fixed f0/Fs and dBgain.\n\n this.coefficients = function() {\n var b = [this.b0, this.b1, this.b2];\n var a = [this.a0, this.a1, this.a2];\n return {b: b, a:a};\n };\n\n this.setFilterType = function(type) {\n this.type = type;\n this.recalculateCoefficients();\n };\n\n this.setSampleRate = function(rate) {\n this.Fs = rate;\n this.recalculateCoefficients();\n };\n\n this.setQ = function(q) {\n this.parameterType = DSP.Q;\n this.Q = Math.max(Math.min(q, 115.0), 0.001);\n this.recalculateCoefficients();\n };\n\n this.setBW = function(bw) {\n this.parameterType = DSP.BW;\n this.BW = bw;\n this.recalculateCoefficients();\n };\n\n this.setS = function(s) {\n this.parameterType = DSP.S;\n this.S = Math.max(Math.min(s, 5.0), 0.0001);\n this.recalculateCoefficients();\n };\n\n this.setF0 = function(freq) {\n this.f0 = freq;\n this.recalculateCoefficients();\n }; \n \n this.setDbGain = function(g) {\n this.dBgain = g;\n this.recalculateCoefficients();\n };\n\n this.recalculateCoefficients = function() {\n var A;\n if (type === DSP.PEAKING_EQ || type === DSP.LOW_SHELF || type === DSP.HIGH_SHELF ) {\n A = Math.pow(10, (this.dBgain/40)); // for peaking and shelving EQ filters only\n } else {\n A = Math.sqrt( Math.pow(10, (this.dBgain/20)) ); \n }\n\n var w0 = DSP.TWO_PI * this.f0 / this.Fs;\n\n var cosw0 = Math.cos(w0);\n var sinw0 = Math.sin(w0);\n\n var alpha = 0;\n \n switch (this.parameterType) {\n case DSP.Q:\n alpha = sinw0/(2*this.Q);\n break;\n \n case DSP.BW:\n alpha = sinw0 * sinh( Math.LN2/2 * this.BW * w0/sinw0 );\n break;\n\n case DSP.S:\n alpha = sinw0/2 * Math.sqrt( (A + 1/A)*(1/this.S - 1) + 2 );\n break;\n }\n\n /**\n FYI: The relationship between bandwidth and Q is\n 1/Q = 2*sinh(ln(2)/2*BW*w0/sin(w0)) (digital filter w BLT)\n or 1/Q = 2*sinh(ln(2)/2*BW) (analog filter prototype)\n\n The relationship between shelf slope and Q is\n 1/Q = sqrt((A + 1/A)*(1/S - 1) + 2)\n */\n\n var coeff;\n\n switch (this.type) {\n case DSP.LPF: // H(s) = 1 / (s^2 + s/Q + 1)\n this.b0 = (1 - cosw0)/2;\n this.b1 = 1 - cosw0;\n this.b2 = (1 - cosw0)/2;\n this.a0 = 1 + alpha;\n this.a1 = -2 * cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.HPF: // H(s) = s^2 / (s^2 + s/Q + 1)\n this.b0 = (1 + cosw0)/2;\n this.b1 = -(1 + cosw0);\n this.b2 = (1 + cosw0)/2;\n this.a0 = 1 + alpha;\n this.a1 = -2 * cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.BPF_CONSTANT_SKIRT: // H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q)\n this.b0 = sinw0/2;\n this.b1 = 0;\n this.b2 = -sinw0/2;\n this.a0 = 1 + alpha;\n this.a1 = -2*cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.BPF_CONSTANT_PEAK: // H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain)\n this.b0 = alpha;\n this.b1 = 0;\n this.b2 = -alpha;\n this.a0 = 1 + alpha;\n this.a1 = -2*cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.NOTCH: // H(s) = (s^2 + 1) / (s^2 + s/Q + 1)\n this.b0 = 1;\n this.b1 = -2*cosw0;\n this.b2 = 1;\n this.a0 = 1 + alpha;\n this.a1 = -2*cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.APF: // H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1)\n this.b0 = 1 - alpha;\n this.b1 = -2*cosw0;\n this.b2 = 1 + alpha;\n this.a0 = 1 + alpha;\n this.a1 = -2*cosw0;\n this.a2 = 1 - alpha;\n break;\n\n case DSP.PEAKING_EQ: // H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1)\n this.b0 = 1 + alpha*A;\n this.b1 = -2*cosw0;\n this.b2 = 1 - alpha*A;\n this.a0 = 1 + alpha/A;\n this.a1 = -2*cosw0;\n this.a2 = 1 - alpha/A;\n break;\n\n case DSP.LOW_SHELF: // H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1)\n coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/this.S - 1) + 2*A );\n this.b0 = A*((A+1) - (A-1)*cosw0 + coeff);\n this.b1 = 2*A*((A-1) - (A+1)*cosw0);\n this.b2 = A*((A+1) - (A-1)*cosw0 - coeff);\n this.a0 = (A+1) + (A-1)*cosw0 + coeff;\n this.a1 = -2*((A-1) + (A+1)*cosw0);\n this.a2 = (A+1) + (A-1)*cosw0 - coeff;\n break;\n\n case DSP.HIGH_SHELF: // H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)\n coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/this.S - 1) + 2*A );\n this.b0 = A*((A+1) + (A-1)*cosw0 + coeff);\n this.b1 = -2*A*((A-1) + (A+1)*cosw0);\n this.b2 = A*((A+1) + (A-1)*cosw0 - coeff);\n this.a0 = (A+1) - (A-1)*cosw0 + coeff;\n this.a1 = 2*((A-1) - (A+1)*cosw0);\n this.a2 = (A+1) - (A-1)*cosw0 - coeff;\n break;\n }\n \n this.b0a0 = this.b0/this.a0;\n this.b1a0 = this.b1/this.a0;\n this.b2a0 = this.b2/this.a0;\n this.a1a0 = this.a1/this.a0;\n this.a2a0 = this.a2/this.a0;\n };\n\n this.process = function(buffer) {\n //y[n] = (b0/a0)*x[n] + (b1/a0)*x[n-1] + (b2/a0)*x[n-2]\n // - (a1/a0)*y[n-1] - (a2/a0)*y[n-2]\n\n var len = buffer.length;\n var output = new Float32Array(len);\n\n for ( var i=0; i<buffer.length; i++ ) {\n output[i] = this.b0a0*buffer[i] + this.b1a0*this.x_1_l + this.b2a0*this.x_2_l - this.a1a0*this.y_1_l - this.a2a0*this.y_2_l;\n this.y_2_l = this.y_1_l;\n this.y_1_l = output[i];\n this.x_2_l = this.x_1_l;\n this.x_1_l = buffer[i];\n }\n\n return output;\n };\n\n this.processStereo = function(buffer) {\n //y[n] = (b0/a0)*x[n] + (b1/a0)*x[n-1] + (b2/a0)*x[n-2]\n // - (a1/a0)*y[n-1] - (a2/a0)*y[n-2]\n\n var len = buffer.length;\n var output = new Float32Array(len);\n \n for (var i = 0; i < len/2; i++) {\n output[2*i] = this.b0a0*buffer[2*i] + this.b1a0*this.x_1_l + this.b2a0*this.x_2_l - this.a1a0*this.y_1_l - this.a2a0*this.y_2_l;\n this.y_2_l = this.y_1_l;\n this.y_1_l = output[2*i];\n this.x_2_l = this.x_1_l;\n this.x_1_l = buffer[2*i];\n\n output[2*i+1] = this.b0a0*buffer[2*i+1] + this.b1a0*this.x_1_r + this.b2a0*this.x_2_r - this.a1a0*this.y_1_r - this.a2a0*this.y_2_r;\n this.y_2_r = this.y_1_r;\n this.y_1_r = output[2*i+1];\n this.x_2_r = this.x_1_r;\n this.x_1_r = buffer[2*i+1];\n }\n\n return output;\n };\n}\n\n/* \n * Magnitude to decibels\n * \n * Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23.\n * Copyright 2010 Ricard Marxer. All rights reserved.\n *\n * @buffer array of magnitudes to convert to decibels\n *\n * @returns the array in decibels\n *\n */\nDSP.mag2db = function(buffer) {\n var minDb = -120;\n var minMag = Math.pow(10.0, minDb / 20.0);\n\n var log = Math.log;\n var max = Math.max;\n \n var result = Float32Array(buffer.length);\n for (var i=0; i<buffer.length; i++) {\n result[i] = 20.0*log(max(buffer[i], minMag));\n }\n\n return result;\n};\n\n/* \n * Frequency response\n * \n * Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23.\n * Copyright 2010 Ricard Marxer. All rights reserved.\n *\n * Calculates the frequency response at the given points.\n *\n * @b b coefficients of the filter\n * @a a coefficients of the filter\n * @w w points (normally between -PI and PI) where to calculate the frequency response\n *\n * @returns the frequency response in magnitude\n *\n */\nDSP.freqz = function(b, a, w) {\n var i, j;\n\n if (!w) {\n w = Float32Array(200);\n for (i=0;i<w.length; i++) {\n w[i] = DSP.TWO_PI/w.length * i - Math.PI;\n }\n }\n\n var result = Float32Array(w.length);\n \n var sqrt = Math.sqrt;\n var cos = Math.cos;\n var sin = Math.sin;\n \n for (i=0; i<w.length; i++) {\n var numerator = {real:0.0, imag:0.0};\n for (j=0; j<b.length; j++) {\n numerator.real += b[j] * cos(-j*w[i]);\n numerator.imag += b[j] * sin(-j*w[i]);\n }\n\n var denominator = {real:0.0, imag:0.0};\n for (j=0; j<a.length; j++) {\n denominator.real += a[j] * cos(-j*w[i]);\n denominator.imag += a[j] * sin(-j*w[i]);\n }\n \n result[i] = sqrt(numerator.real*numerator.real + numerator.imag*numerator.imag) / sqrt(denominator.real*denominator.real + denominator.imag*denominator.imag);\n }\n\n return result;\n};\n\n/* \n * Graphical Equalizer\n *\n * Implementation of a graphic equalizer with a configurable bands-per-octave\n * and minimum and maximum frequencies\n * \n * Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23.\n * Copyright 2010 Ricard Marxer. All rights reserved.\n *\n */\nfunction GraphicalEq(sampleRate) {\n this.FS = sampleRate;\n this.minFreq = 40.0;\n this.maxFreq = 16000.0;\n\n this.bandsPerOctave = 1.0;\n\n this.filters = [];\n this.freqzs = [];\n\n this.calculateFreqzs = true;\n\n this.recalculateFilters = function() {\n var bandCount = Math.round(Math.log(this.maxFreq/this.minFreq) * this.bandsPerOctave/ Math.LN2);\n\n this.filters = [];\n for (var i=0; i<bandCount; i++) {\n var freq = this.minFreq*(Math.pow(2, i/this.bandsPerOctave));\n var newFilter = new Biquad(DSP.PEAKING_EQ, this.FS);\n newFilter.setDbGain(0);\n newFilter.setBW(1/this.bandsPerOctave);\n newFilter.setF0(freq);\n this.filters[i] = newFilter;\n this.recalculateFreqz(i);\n }\n };\n\n this.setMinimumFrequency = function(freq) {\n this.minFreq = freq;\n this.recalculateFilters();\n };\n\n this.setMaximumFrequency = function(freq) {\n this.maxFreq = freq;\n this.recalculateFilters();\n };\n\n this.setBandsPerOctave = function(bands) {\n this.bandsPerOctave = bands;\n this.recalculateFilters();\n };\n\n this.setBandGain = function(bandIndex, gain) {\n if (bandIndex < 0 || bandIndex > (this.filters.length-1)) {\n throw \"The band index of the graphical equalizer is out of bounds.\";\n }\n\n if (!gain) {\n throw \"A gain must be passed.\";\n }\n \n this.filters[bandIndex].setDbGain(gain);\n this.recalculateFreqz(bandIndex);\n };\n \n this.recalculateFreqz = function(bandIndex) {\n if (!this.calculateFreqzs) {\n return;\n }\n\n if (bandIndex < 0 || bandIndex > (this.filters.length-1)) {\n throw \"The band index of the graphical equalizer is out of bounds. \" + bandIndex + \" is out of [\" + 0 + \", \" + this.filters.length-1 + \"]\";\n }\n \n if (!this.w) {\n this.w = Float32Array(400);\n for (var i=0; i<this.w.length; i++) {\n this.w[i] = Math.PI/this.w.length * i;\n }\n }\n \n var b = [this.filters[bandIndex].b0, this.filters[bandIndex].b1, this.filters[bandIndex].b2];\n var a = [this.filters[bandIndex].a0, this.filters[bandIndex].a1, this.filters[bandIndex].a2];\n\n this.freqzs[bandIndex] = DSP.mag2db(DSP.freqz(b, a, this.w));\n };\n\n this.process = function(buffer) {\n var output = buffer;\n\n for (var i = 0; i < this.filters.length; i++) {\n output = this.filters[i].process(output);\n }\n\n return output;\n };\n\n this.processStereo = function(buffer) {\n var output = buffer;\n\n for (var i = 0; i < this.filters.length; i++) {\n output = this.filters[i].processStereo(output);\n }\n\n return output;\n };\n}\n\n/**\n * MultiDelay effect by Almer Thie (http://code.almeros.com).\n * Copyright 2010 Almer Thie. All rights reserved.\n * Example: http://code.almeros.com/code-examples/delay-firefox-audio-api/\n *\n * This is a delay that feeds it's own delayed signal back into its circular\n * buffer. Also known as a CombFilter.\n *\n * Compatible with interleaved stereo (or more channel) buffers and\n * non-interleaved mono buffers.\n *\n * @param {Number} maxDelayInSamplesSize Maximum possible delay in samples (size of circular buffer)\n * @param {Number} delayInSamples Initial delay in samples\n * @param {Number} masterVolume Initial master volume. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n * @param {Number} delayVolume Initial feedback delay volume. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n *\n * @constructor\n */\nfunction MultiDelay(maxDelayInSamplesSize, delayInSamples, masterVolume, delayVolume) {\n this.delayBufferSamples = new Float32Array(maxDelayInSamplesSize); // The maximum size of delay\n this.delayInputPointer = delayInSamples;\n this.delayOutputPointer = 0;\n \n this.delayInSamples = delayInSamples;\n this.masterVolume = masterVolume;\n this.delayVolume = delayVolume;\n}\n\n/**\n * Change the delay time in samples.\n *\n * @param {Number} delayInSamples Delay in samples\n */\nMultiDelay.prototype.setDelayInSamples = function (delayInSamples) {\n this.delayInSamples = delayInSamples;\n \n this.delayInputPointer = this.delayOutputPointer + delayInSamples;\n\n if (this.delayInputPointer >= this.delayBufferSamples.length-1) {\n this.delayInputPointer = this.delayInputPointer - this.delayBufferSamples.length; \n }\n};\n\n/**\n * Change the master volume.\n *\n * @param {Number} masterVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nMultiDelay.prototype.setMasterVolume = function(masterVolume) {\n this.masterVolume = masterVolume;\n};\n\n/**\n * Change the delay feedback volume.\n *\n * @param {Number} delayVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nMultiDelay.prototype.setDelayVolume = function(delayVolume) {\n this.delayVolume = delayVolume;\n};\n\n/**\n * Process a given interleaved or mono non-interleaved float value Array and adds the delayed audio.\n *\n * @param {Array} samples Array containing Float values or a Float32Array\n *\n * @returns A new Float32Array interleaved or mono non-interleaved as was fed to this function.\n */\nMultiDelay.prototype.process = function(samples) {\n // NB. Make a copy to put in the output samples to return.\n var outputSamples = new Float32Array(samples.length);\n\n for (var i=0; i<samples.length; i++) {\n // delayBufferSamples could contain initial NULL's, return silence in that case\n var delaySample = (this.delayBufferSamples[this.delayOutputPointer] === null ? 0.0 : this.delayBufferSamples[this.delayOutputPointer]);\n \n // Mix normal audio data with delayed audio\n var sample = (delaySample * this.delayVolume) + samples[i];\n \n // Add audio data with the delay in the delay buffer\n this.delayBufferSamples[this.delayInputPointer] = sample;\n \n // Return the audio with delay mix\n outputSamples[i] = sample * this.masterVolume;\n \n // Manage circulair delay buffer pointers\n this.delayInputPointer++;\n if (this.delayInputPointer >= this.delayBufferSamples.length-1) {\n this.delayInputPointer = 0;\n }\n \n this.delayOutputPointer++;\n if (this.delayOutputPointer >= this.delayBufferSamples.length-1) {\n this.delayOutputPointer = 0; \n } \n }\n \n return outputSamples;\n};\n\n/**\n * SingleDelay effect by Almer Thie (http://code.almeros.com).\n * Copyright 2010 Almer Thie. All rights reserved.\n * Example: See usage in Reverb class\n *\n * This is a delay that does NOT feeds it's own delayed signal back into its \n * circular buffer, neither does it return the original signal. Also known as\n * an AllPassFilter(?).\n *\n * Compatible with interleaved stereo (or more channel) buffers and\n * non-interleaved mono buffers.\n *\n * @param {Number} maxDelayInSamplesSize Maximum possible delay in samples (size of circular buffer)\n * @param {Number} delayInSamples Initial delay in samples\n * @param {Number} delayVolume Initial feedback delay volume. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n *\n * @constructor\n */\n\nfunction SingleDelay(maxDelayInSamplesSize, delayInSamples, delayVolume) {\n this.delayBufferSamples = new Float32Array(maxDelayInSamplesSize); // The maximum size of delay\n this.delayInputPointer = delayInSamples;\n this.delayOutputPointer = 0;\n \n this.delayInSamples = delayInSamples;\n this.delayVolume = delayVolume;\n}\n\n/**\n * Change the delay time in samples.\n *\n * @param {Number} delayInSamples Delay in samples\n */\nSingleDelay.prototype.setDelayInSamples = function(delayInSamples) {\n this.delayInSamples = delayInSamples;\n this.delayInputPointer = this.delayOutputPointer + delayInSamples;\n\n if (this.delayInputPointer >= this.delayBufferSamples.length-1) {\n this.delayInputPointer = this.delayInputPointer - this.delayBufferSamples.length; \n }\n};\n\n/**\n * Change the return signal volume.\n *\n * @param {Number} delayVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nSingleDelay.prototype.setDelayVolume = function(delayVolume) {\n this.delayVolume = delayVolume;\n};\n\n/**\n * Process a given interleaved or mono non-interleaved float value Array and\n * returns the delayed audio.\n *\n * @param {Array} samples Array containing Float values or a Float32Array\n *\n * @returns A new Float32Array interleaved or mono non-interleaved as was fed to this function.\n */\nSingleDelay.prototype.process = function(samples) {\n // NB. Make a copy to put in the output samples to return.\n var outputSamples = new Float32Array(samples.length);\n\n for (var i=0; i<samples.length; i++) {\n\n // Add audio data with the delay in the delay buffer\n this.delayBufferSamples[this.delayInputPointer] = samples[i];\n \n // delayBufferSamples could contain initial NULL's, return silence in that case\n var delaySample = this.delayBufferSamples[this.delayOutputPointer];\n\n // Return the audio with delay mix\n outputSamples[i] = delaySample * this.delayVolume;\n\n // Manage circulair delay buffer pointers\n this.delayInputPointer++;\n\n if (this.delayInputPointer >= this.delayBufferSamples.length-1) {\n this.delayInputPointer = 0;\n }\n \n this.delayOutputPointer++;\n\n if (this.delayOutputPointer >= this.delayBufferSamples.length-1) {\n this.delayOutputPointer = 0; \n } \n }\n \n return outputSamples;\n};\n\n/**\n * Reverb effect by Almer Thie (http://code.almeros.com).\n * Copyright 2010 Almer Thie. All rights reserved.\n * Example: http://code.almeros.com/code-examples/reverb-firefox-audio-api/\n *\n * This reverb consists of 6 SingleDelays, 6 MultiDelays and an IIRFilter2\n * for each of the two stereo channels.\n *\n * Compatible with interleaved stereo buffers only!\n *\n * @param {Number} maxDelayInSamplesSize Maximum possible delay in samples (size of circular buffers)\n * @param {Number} delayInSamples Initial delay in samples for internal (Single/Multi)delays\n * @param {Number} masterVolume Initial master volume. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n * @param {Number} mixVolume Initial reverb signal mix volume. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n * @param {Number} delayVolume Initial feedback delay volume for internal (Single/Multi)delays. Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n * @param {Number} dampFrequency Initial low pass filter frequency. 0 to 44100 (depending on your maximum sampling frequency)\n *\n * @constructor\n */\nfunction Reverb(maxDelayInSamplesSize, delayInSamples, masterVolume, mixVolume, delayVolume, dampFrequency) {\n this.delayInSamples = delayInSamples;\n this.masterVolume = masterVolume;\n this.mixVolume = mixVolume;\n this.delayVolume = delayVolume;\n this.dampFrequency = dampFrequency;\n \n this.NR_OF_MULTIDELAYS = 6;\n this.NR_OF_SINGLEDELAYS = 6;\n \n this.LOWPASSL = new IIRFilter2(DSP.LOWPASS, dampFrequency, 0, 44100);\n this.LOWPASSR = new IIRFilter2(DSP.LOWPASS, dampFrequency, 0, 44100);\n \n this.singleDelays = [];\n \n var i, delayMultiply;\n\n for (i = 0; i < this.NR_OF_SINGLEDELAYS; i++) {\n delayMultiply = 1.0 + (i/7.0); // 1.0, 1.1, 1.2...\n this.singleDelays[i] = new SingleDelay(maxDelayInSamplesSize, Math.round(this.delayInSamples * delayMultiply), this.delayVolume);\n }\n \n this.multiDelays = [];\n\n for (i = 0; i < this.NR_OF_MULTIDELAYS; i++) {\n delayMultiply = 1.0 + (i/10.0); // 1.0, 1.1, 1.2... \n this.multiDelays[i] = new MultiDelay(maxDelayInSamplesSize, Math.round(this.delayInSamples * delayMultiply), this.masterVolume, this.delayVolume);\n }\n}\n\n/**\n * Change the delay time in samples as a base for all delays.\n *\n * @param {Number} delayInSamples Delay in samples\n */\nReverb.prototype.setDelayInSamples = function (delayInSamples){\n this.delayInSamples = delayInSamples;\n\n var i, delayMultiply;\n \n for (i = 0; i < this.NR_OF_SINGLEDELAYS; i++) {\n delayMultiply = 1.0 + (i/7.0); // 1.0, 1.1, 1.2...\n this.singleDelays[i].setDelayInSamples( Math.round(this.delayInSamples * delayMultiply) );\n }\n \n for (i = 0; i < this.NR_OF_MULTIDELAYS; i++) {\n delayMultiply = 1.0 + (i/10.0); // 1.0, 1.1, 1.2...\n this.multiDelays[i].setDelayInSamples( Math.round(this.delayInSamples * delayMultiply) );\n }\n};\n\n/**\n * Change the master volume.\n *\n * @param {Number} masterVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nReverb.prototype.setMasterVolume = function (masterVolume){\n this.masterVolume = masterVolume;\n};\n\n/**\n * Change the reverb signal mix level.\n *\n * @param {Number} mixVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nReverb.prototype.setMixVolume = function (mixVolume){\n this.mixVolume = mixVolume;\n};\n\n/**\n * Change all delays feedback volume.\n *\n * @param {Number} delayVolume Float value: 0.0 (silence), 1.0 (normal), >1.0 (amplify)\n */\nReverb.prototype.setDelayVolume = function (delayVolume){\n this.delayVolume = delayVolume;\n \n var i;\n\n for (i = 0; i<this.NR_OF_SINGLEDELAYS; i++) {\n this.singleDelays[i].setDelayVolume(this.delayVolume);\n } \n \n for (i = 0; i<this.NR_OF_MULTIDELAYS; i++) {\n this.multiDelays[i].setDelayVolume(this.delayVolume);\n } \n};\n\n/**\n * Change the Low Pass filter frequency.\n *\n * @param {Number} dampFrequency low pass filter frequency. 0 to 44100 (depending on your maximum sampling frequency)\n */\nReverb.prototype.setDampFrequency = function (dampFrequency){\n this.dampFrequency = dampFrequency;\n \n this.LOWPASSL.set(dampFrequency, 0);\n this.LOWPASSR.set(dampFrequency, 0); \n};\n\n/**\n * Process a given interleaved float value Array and copies and adds the reverb signal.\n *\n * @param {Array} samples Array containing Float values or a Float32Array\n *\n * @returns A new Float32Array interleaved buffer.\n */\nReverb.prototype.process = function (interleavedSamples){ \n // NB. Make a copy to put in the output samples to return.\n var outputSamples = new Float32Array(interleavedSamples.length);\n \n // Perform low pass on the input samples to mimick damp\n var leftRightMix = DSP.deinterleave(interleavedSamples);\n this.LOWPASSL.process( leftRightMix[DSP.LEFT] );\n this.LOWPASSR.process( leftRightMix[DSP.RIGHT] ); \n var filteredSamples = DSP.interleave(leftRightMix[DSP.LEFT], leftRightMix[DSP.RIGHT]);\n\n var i;\n\n // Process MultiDelays in parallel\n for (i = 0; i<this.NR_OF_MULTIDELAYS; i++) {\n // Invert the signal of every even multiDelay\n outputSamples = DSP.mixSampleBuffers(outputSamples, this.multiDelays[i].process(filteredSamples), 2%i === 0, this.NR_OF_MULTIDELAYS);\n }\n \n // Process SingleDelays in series\n var singleDelaySamples = new Float32Array(outputSamples.length);\n for (i = 0; i<this.NR_OF_SINGLEDELAYS; i++) {\n // Invert the signal of every even singleDelay\n singleDelaySamples = DSP.mixSampleBuffers(singleDelaySamples, this.singleDelays[i].process(outputSamples), 2%i === 0, 1);\n }\n\n // Apply the volume of the reverb signal\n for (i = 0; i<singleDelaySamples.length; i++) {\n singleDelaySamples[i] *= this.mixVolume;\n }\n \n // Mix the original signal with the reverb signal\n outputSamples = DSP.mixSampleBuffers(singleDelaySamples, interleavedSamples, 0, 1);\n\n // Apply the master volume to the complete signal\n for (i = 0; i<outputSamples.length; i++) {\n outputSamples[i] *= this.masterVolume;\n }\n \n return outputSamples;\n};\n\n",
"file": "js/dsp.js",
"file_size": 69061,
"file_write_time": 130534183391391748,
"settings":
{
"buffer_size": 66759,
"line_ending": "Windows"
}
},
{
"file": "/C/Users/RMB/Drive/GuidedTrack/webcam-pulse-detector-no_openmdao/lib/processors_noopenmdao.py",
"settings":
{
"buffer_size": 8836,
"line_ending": "Unix"
}
}
],
"build_system": "",
"command_palette":
{
"height": 588.0,
"selected_items":
[
[
"in",
"Web Inspector"
],
[
"pak",
"Package Control: Install Package"
],
[
"web i",
"Web Inspector"
],
[
"install",
"Package Control: Install Package"
],
[
"Package Control: ",
"Package Control: List Packages"
],
[
"package",
"Package Control: List Packages"
]
],
"width": 624.0
},
"console":
{
"height": 175.0,
"history":
[
"1/0.040",
"1/.",
"1/(.1*.040)",
"import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)",
"where",
"dir",
"git clone git://github.com/sokolovstas/SublimeWebInspector.git -b ST3 Web\\ Inspector",
"cd",
"cd ..",
"install",
"import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)",
"Package Control: Install Package",
"Package Control",
"install",
"import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)"
]
},
"distraction_free":
{
"menu_visible": true,
"show_minimap": false,
"show_open_files": false,
"show_tabs": false,
"side_bar_visible": false,
"status_bar_visible": false
},
"file_history":
[
"/C/Users/RMB/Drive/GuidedTrack/darkruby501.github.io/js/g.line-min.js",
"/C/Users/RMB/Google Drive/GuidedTrack/GuidedTrackRMB/heart-rate/index.html",
"/C/Users/RMB/Drive/GuidedTrack/darkruby501.github.io/js/headtrackr.js",
"/C/Users/RMB/Google Drive/GuidedTrack/FaceTrackingHtml/facetracking.html",
"/C/Users/RMB/Drive/GuidedTrack/Server/darkruby501.github.io/darkruby501.github.io/js/pulsedetectr.js",
"/C/Users/RMB/Drive/GuidedTrack/Server/darkruby501.github.io/darkruby501.github.io/index.html",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/darkruby501.github.io/js/Chart.js",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/darkruby501.github.io/js/cbuffer.js",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/darkruby501.github.io/js/pulsedetectr.js",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/darkruby501.github.io/index.html",
"/C/Users/RMB/AppData/Roaming/Sublime Text 3/Packages/User/Preferences.sublime-settings",
"/C/Users/RMB/AppData/Roaming/Sublime Text 3/Packages/User/Default (Windows).sublime-keymap",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/index.html",
"/C/Users/RMB/Google Drive/GuidedTrack/canvas-video-effects/image-worker.js",
"/C/Users/RMB/Google Drive/GuidedTrack/canvas-video-effects/index.html",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/js/cbuffer.js",
"/C/Users/RMB/Documents/GitHub/cbuffer/test/index.html",
"/C/Users/RMB/AppData/Roaming/Sublime Text 3/Packages/Web Inspector 3/swi.sublime-settings",
"/C/Users/RMB/Google Drive/GuidedTrack/Server/image-worker.js",
"/C/Users/RMB/AppData/Roaming/Sublime Text 3/Packages/User/swi.sublime-settings",
"/C/Program Files/Sublime Text 3/Packages/Scala.sublime-package",
"/C/Program Files/Sublime Text 3/Packages/Pascal.sublime-package",
"/C/Users/RMB/AppData/Local/Google/Chrome/User Data/Default/Preferences",
"/C/Program Files/Sublime Text 3/Packages/Package Control.sublime-package",
"/C/Program Files/Sublime Text 3/Packages/Lisp.sublime-package",
"/C/Program Files/Sublime Text 3/Packages/R.sublime-package",
"/C/Program Files/Sublime Text 3/Packages/Batch File.sublime-package",
"/C/Program Files/Sublime Text 3/Packages/Rails.sublime-package"
],
"find":
{
"height": 50.0
},
"find_in_files":
{
"height": 0.0,
"where_history":
[
]
},
"find_state":
{
"case_sensitive": false,
"find_history":
[
"filter",
"window",
"windowfunction",
"dsp.hamming",
"lowest",
"highest",
"lowest",
"find",
"rfft",
"hamming",
"params.bufferSize",
"get_subface_means",
"get_subface_coord",
"480",
"640",
"100",
"320",
"240",
"320",
"currentDet",
"doVJDetection",
"CS",
"detectionInterval",
"updateP",
"oChartCanvas",
"240",
"320",
"240",
"320",
"<!",
"320",
"240",
"320",
"inputContext",
"debugOver",
"messagep",
"headtrackerMessage",
"faceObj",
"debugContext",
"canvasInput",
"gUMMessage",
"headtrackrStatus"
],
"highlight": true,
"in_selection": false,
"preserve_case": false,
"regex": false,
"replace_history":
[
"lower",
"upper",
"lower",
"fft",
"bufferSize",
"240",
"320",
"640",
"480",
"640",
"480",
"640",
"480",
"640",
"480",
"640",
"event",
"testOverlayContext"
],
"reverse": false,
"show_context": true,
"use_buffer2": true,
"whole_word": false,
"wrap": true
},
"groups":
[
{
"selected": 0,
"sheets":
[
{
"buffer": 0,
"file": "index.html",
"semi_transient": false,
"settings":
{
"buffer_size": 6346,
"regions":
{
},
"selection":
[
[
5086,
5086
]
],
"settings":
{
"syntax": "Packages/HTML/HTML.tmLanguage",
"translate_tabs_to_spaces": false
},
"translation.x": 0.0,
"translation.y": 2175.0,
"zoom_level": 1.0
},
"stack_index": 0,
"type": "text"
},
{
"buffer": 1,
"file": "README.md",
"semi_transient": false,
"settings":
{
"buffer_size": 954,
"regions":
{
},
"selection":
[
[
715,
715
]
],
"settings":
{
"syntax": "Packages/Markdown/Markdown.tmLanguage"
},
"translation.x": 0.0,
"translation.y": 0.0,
"zoom_level": 1.0
},
"stack_index": 1,
"type": "text"
},
{
"buffer": 2,
"file": "js/dsp.js",
"semi_transient": false,
"settings":
{
"buffer_size": 66759,
"regions":
{
},
"selection":
[
[
34047,
34053
]
],
"settings":
{
"syntax": "Packages/JavaScript/JavaScript.tmLanguage",
"tab_size": 2,
"translate_tabs_to_spaces": true
},
"translation.x": 0.0,
"translation.y": 12902.0,
"zoom_level": 1.0
},
"stack_index": 2,
"type": "text"
},
{
"buffer": 3,
"file": "/C/Users/RMB/Drive/GuidedTrack/webcam-pulse-detector-no_openmdao/lib/processors_noopenmdao.py",
"semi_transient": false,
"settings":
{
"buffer_size": 8836,
"regions":
{
},
"selection":
[
[
7672,
7672
]
],
"settings":
{
"syntax": "Packages/Python/Python.tmLanguage",
"tab_size": 4,
"translate_tabs_to_spaces": true
},
"translation.x": 0.0,
"translation.y": 2722.0,
"zoom_level": 1.0
},
"stack_index": 3,
"type": "text"
}
]
}
],
"incremental_find":
{
"height": 46.0
},
"input":
{
"height": 0.0
},
"layout":
{
"cells":
[
[
0,
0,
1,
1
]
],
"cols":
[
0.0,
1.0
],
"rows":
[
0.0,
1.0
]
},
"menu_visible": true,
"output.exec":
{
"height": 148.0
},
"output.find_results":
{
"height": 0.0
},
"project": "",
"replace":
{
"height": 94.0
},
"save_all_on_build": true,
"select_file":
{
"height": 0.0,
"selected_items":
[
],
"width": 0.0
},
"select_project":
{
"height": 0.0,
"selected_items":
[
],
"width": 0.0
},
"select_symbol":
{
"height": 0.0,
"selected_items":
[
],
"width": 0.0
},
"selected_group": 0,
"settings":
{
},
"show_minimap": true,
"show_open_files": false,
"show_tabs": true,
"side_bar_visible": true,
"side_bar_width": 401.0,
"status_bar_visible": true,
"template_settings":
{
}
}