-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvanalog.js
580 lines (473 loc) · 15.5 KB
/
vanalog.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
/*****************************************************************************
*
* This file is part of the MusicToy project. The project is
* distributed at:
* https://github.com/maximecb/MusicToy
*
* Copyright (c) 2012, Maxime Chevalier-Boisvert. All rights reserved.
*
* This software is licensed under the following license (Modified BSD
* License):
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
/**
@class Simple virtual analog synthesizer
@extends SynthNode
*/
function VAnalog(numOscs)
{
if (numOscs === undefined)
numOscs = 1;
this.name = 'vanalog';
/**
Array of oscillator parameters
*/
this.oscs = new Array(numOscs);
// Initialize the oscillator parameters
for (var i = 0; i < numOscs; ++i)
{
var osc = this.oscs[i] = {};
// Oscillator type
osc.type = 'sine';
// Duty cycle, for pulse wave
osc.duty = 0.5;
// Oscillator detuning, in cents
osc.detune = 0;
// ADSR amplitude envelope
osc.env = new ADSREnv(0.05, 0.05, 0.2, 0.1);
// Mixing volume
osc.volume = 1;
// Oscillator sync flag
osc.sync = false;
// Syncing oscillator detuning
osc.syncDetune = 0;
}
/**
Filter cutoff [0,1]
*/
this.cutoff = 1;
/**
Filter resonance [0,1]
*/
this.resonance = 0;
/**
Filter envelope
*/
this.filterEnv = new ADSREnv(0, 0, 1, Infinity);
/**
Filter envelope modulation amount
*/
this.filterEnvAmt = 1;
/**
Pitch envelope
*/
this.pitchEnv = new ADSREnv(0, 0, 1, Infinity);
/**
Pitch envelope amount
*/
this.pitchEnvAmt = 0;
/**
Active/on note array
*/
this.actNotes = [];
/**
Temporary oscillator buffer, for intermediate processing
*/
this.oscBuf = new Float64Array(SYNTH_BUF_SIZE);
/**
Temporary note buffer, for intermediate processing
*/
this.noteBuf = new Float64Array(SYNTH_BUF_SIZE);
// Sound output
new SynthOutput(this, 'output');
}
VAnalog.prototype = new SynthNode();
/**
Process an event
*/
VAnalog.prototype.processEvent = function (evt, time)
{
// Note-on event
if (evt instanceof NoteOnEvt)
{
// Get the note
var note = evt.note;
// Try to find the note among the active list
var noteState = undefined;
for (var i = 0; i < this.actNotes.length; ++i)
{
var state = this.actNotes[i];
if (state.note === note)
{
noteState = state;
break;
}
}
// If the note was not active before
if (noteState === undefined)
{
noteState = {};
// Note being played
noteState.note = note;
// Note velocity
noteState.vel = evt.vel;
// Time a note-on was received
noteState.onTime = time;
// Time a note-off was received
noteState.offTime = 0;
// Initialize the oscillator states
noteState.oscs = new Array(this.oscs.length);
for (var i = 0; i < this.oscs.length; ++i)
{
var oscState = {};
noteState.oscs[i] = oscState;
// Cycle position
oscState.cyclePos = 0;
// Sync cycle position
oscState.syncCyclePos = 0;
// Envelope amplitude at note-on and note-off time
oscState.onAmp = 0;
oscState.offAmp = 0;
}
// Initialize the filter state values
noteState.filterSt = new Array(8);
for (var i = 0; i < noteState.filterSt.length; ++i)
noteState.filterSt[i] = 0;
// Filter envelope value at note-on and note-off time
noteState.filterOnEnv = 0;
noteState.filterOffEnv = 0;
// Pitch envelope value at note-on and note-off time
noteState.pitchOnEnv = 0;
noteState.pitchOffEnv = 0;
// Add the note to the active list
this.actNotes.push(noteState);
}
// If the note was active before
else
{
// Store the oscillator amplitudes at note-on time
for (var i = 0; i < this.oscs.length; ++i)
{
var oscState = noteState.oscs[i];
oscState.onAmp = this.oscs[i].env.getValue(
time,
noteState.onTime,
noteState.offTime,
oscState.onAmp,
oscState.offAmp
);
//console.log('on amp: ' + oscState.onAmp);
}
// Filter envelope value at note-on time
noteState.filterOnEnv = this.filterEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.filterOnEnv,
noteState.filterOffEnv
);
// Pitch envelope value at note-on time
noteState.pitchOnEnv = this.pitchEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.pitchOnEnv,
noteState.pitchOffEnv
);
// Note velocity
noteState.vel = evt.vel;
// Set the on and off times
noteState.onTime = time;
noteState.offTime = 0;
}
//console.log('on time: ' + noteState.onTime);
}
// Note-off event
else if (evt instanceof NoteOffEvt)
{
// Get the note
var note = evt.note;
// Try to find the note among the active list
var noteState = undefined;
for (var i = 0; i < this.actNotes.length; ++i)
{
var state = this.actNotes[i];
if (state.note === note)
{
noteState = state;
break;
}
}
// If the note is active
if (noteState !== undefined)
{
// Store the oscillator amplitudes at note-off time
for (var i = 0; i < this.oscs.length; ++i)
{
var oscState = noteState.oscs[i];
oscState.offAmp = this.oscs[i].env.getValue(
time,
noteState.onTime,
noteState.offTime,
oscState.onAmp,
oscState.offAmp
);
}
// Filter envelope value at note-off time
noteState.filterOffEnv = this.filterEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.filterOnEnv,
noteState.filterOffEnv
);
// Pitch envelope value at note-off time
noteState.pitchOffEnv = this.pitchEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.pitchOnEnv,
noteState.pitchOffEnv
);
// Set the note-off time
noteState.offTime = time;
}
}
// All notes off event
else if (evt instanceof AllNotesOffEvt)
{
this.actNotes = [];
}
// By default, do nothing
}
/**
Update the outputs based on the inputs
*/
VAnalog.prototype.update = function (time, sampleRate)
{
// If there are no active notes, do nothing
if (this.actNotes.length === 0)
return;
// Get the output buffer
var outBuf = this.output.getBuffer(0);
// Initialize the output to 0
for (var i = 0; i < outBuf.length; ++i)
outBuf[i] = 0;
// Get the time at the end of the buffer
var endTime = time + ((outBuf.length - 1) / sampleRate);
// For each active note
for (var i = 0; i < this.actNotes.length; ++i)
{
var noteState = this.actNotes[i];
// Initialize the note buffer to 0
for (var smpIdx = 0; smpIdx < outBuf.length; ++smpIdx)
this.noteBuf[smpIdx] = 0;
// Maximum end amplitude value
var maxEndAmp = 0;
// For each oscillator
for (var oscNo = 0; oscNo < this.oscs.length; ++oscNo)
{
var oscParams = this.oscs[oscNo];
var oscState = noteState.oscs[oscNo];
// Generate the oscillator signal
this.genOsc(
time,
this.oscBuf,
oscParams,
oscState,
noteState,
sampleRate
);
// Compute the note volume
var noteVol = noteState.vel * oscParams.volume;
// Get the amplitude value at the start of the buffer
var ampStart = noteVol * oscParams.env.getValue(
time,
noteState.onTime,
noteState.offTime,
oscState.onAmp,
oscState.offAmp
);
// Get the envelope value at the end of the buffer
var ampEnd = noteVol * oscParams.env.getValue(
endTime,
noteState.onTime,
noteState.offTime,
oscState.onAmp,
oscState.offAmp
);
//console.log('start time: ' + time);
//console.log('start env: ' + envStart);
//console.log('end: ' + envEnd);
// Update the maximum end envelope value
maxEndAmp = Math.max(maxEndAmp, ampEnd);
// Modulate the output based on the amplitude envelope
for (var smpIdx = 0; smpIdx < outBuf.length; ++smpIdx)
{
var ratio = (smpIdx / (outBuf.length - 1));
this.oscBuf[smpIdx] *= ampStart + ratio * (ampEnd - ampStart);
}
// Accumulate the sample values in the note buffer
for (var smpIdx = 0; smpIdx < outBuf.length; ++smpIdx)
this.noteBuf[smpIdx] += this.oscBuf[smpIdx];
}
// Apply the filter to the temp buffer
this.applyFilter(time, noteState, this.noteBuf);
// Accumulate the sample values in the output buffer
for (var smpIdx = 0; smpIdx < outBuf.length; ++smpIdx)
outBuf[smpIdx] += this.noteBuf[smpIdx];
// If all envelopes have fallen to 0, remove the note from the active list
if (maxEndAmp === 0)
{
this.actNotes.splice(i, 1);
i--;
}
}
}
/**
Generate output for an oscillator and update its position
*/
VAnalog.prototype.genOsc = function (
time,
outBuf,
oscParams,
oscState,
noteState,
sampleRate
)
{
// Get the pitch envelope detuning value
var envDetune = this.pitchEnvAmt * this.pitchEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.pitchOnEnv,
noteState.pitchOffEnv
);
// Get the note
var note = noteState.note;
// Get the oscillator frequency
var freq = note.getFreq(oscParams.detune + envDetune);
// Get the initial cycle position
var cyclePos = oscState.cyclePos;
// Compute the cycle position change between samples
var deltaPos = freq / sampleRate;
// Get the sync oscillator frequency
var syncFreq = note.getFreq(oscParams.syncDetune);
// Get the initial sync cycle position
var syncCyclePos = oscState.syncCyclePos;
// Compute the cycle position change between samples
var syncDeltaPos = syncFreq / sampleRate;
// For each sample to be produced
for (var i = 0; i < outBuf.length; ++i)
{
// Switch on the oscillator type/waveform
switch (oscParams.type)
{
// Sine wave
case 'sine':
outBuf[i] = Math.sin(2 * Math.PI * cyclePos);
break;
// Triangle wave
case 'triangle':
if (cyclePos < 0.5)
outBuf[i] = (4 * cyclePos) - 1;
else
outBuf[i] = 1 - (4 * (cyclePos - 0.5));
break;
// Sawtooth wave
case 'sawtooth':
outBuf[i] = -1 + (2 * cyclePos);
break;
// Pulse wave
case 'pulse':
if (cyclePos < oscParams.duty)
outBuf[i] = -1;
else
outBuf[i] = 1;
break;
// Noise
case 'noise':
outBuf[i] = 1 - 2 * Math.random();
break;
default:
error('invalid waveform: ' + oscParams.type);
}
cyclePos += deltaPos;
if (cyclePos > 1)
cyclePos -= 1;
if (oscParams.sync === true)
{
syncCyclePos += syncDeltaPos;
if (syncCyclePos > 1)
{
syncCyclePos -= 1;
cyclePos = 0;
}
}
}
// Set the final cycle position
oscState.cyclePos = cyclePos;
// Set the final sync cycle position
oscState.syncCyclePos = syncCyclePos;
}
/**
Apply a filter to a buffer of samples
IIR, 2-pole, resonant Low Pass Filter (LPF)
*/
VAnalog.prototype.applyFilter = function (time, noteState, buffer)
{
assert (
this.cutoff >= 0 && this.cutoff <= 1,
'invalid filter cutoff'
);
assert (
this.resonance >= 0 && this.resonance <= 1,
'invalid filter resonance'
);
var filterEnvVal = this.filterEnv.getValue(
time,
noteState.onTime,
noteState.offTime,
noteState.filterOnEnv,
noteState.filterOffEnv
);
var filterEnvMag = (1 - this.cutoff) * this.filterEnvAmt;
var cutoff = this.cutoff + filterEnvMag * filterEnvVal;
var c = Math.pow(0.5, (1 - cutoff) / 0.125);
var r = Math.pow(0.5, (this.resonance + 0.125) / 0.125);
var mrc = 1 - r * c;
var v0 = noteState.filterSt[0];
var v1 = noteState.filterSt[1];
for (var i = 0; i < buffer.length; ++i)
{
v0 = (mrc * v0) - (c * v1) + (c * buffer[i]);
v1 = (mrc * v1) + (c * v0);
buffer[i] = v1;
}
noteState.filterSt[0] = v0;
noteState.filterSt[1] = v1;
}