-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
438 lines (418 loc) · 11 KB
/
index.html
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
<!DOCTYPE html>
<html style="height: 100vh">
<head>
<title>supercoil</title>
</head>
<body style="margin: 0; padding: 0; height: 100%; width: 100%; display: flex">
<textarea
id="code"
spellcheck="false"
style="
width: 100%;
font-size: 24px;
color: white;
background: indigo;
border: 0;
outline: none;
padding: 10px;
"
></textarea>
<button
style="position: fixed; right: 0; bottom: 0; font-size: 30px"
id="playButton"
>
play
</button>
<button
style="
display: none;
position: fixed;
right: 0;
bottom: 0;
font-size: 30px;
"
id="stopButton"
>
stop
</button>
<script>
// audio init
console.log(
`Welcome to supercoil, a minimal audio graph livecoding editor..
Click into the page and press ctrl enter to evaluate the code!
Read https://github.com/felixroos/supercoil to find out more!
`
);
let ac;
document.addEventListener("click", function initAudio() {
ac = new AudioContext();
ac.resume();
document.removeEventListener("click", initAudio);
});
async function getSimpleDynamicWorklet(ac, code) {
const name = `simple-custom-${Date.now()}`;
const workletCode = `
class Node {
constructor(type, ins) {
this.type = type;
let maxExpansions = 1;
this.ins = ins.map(input => {
input = this.parseInput(input);
if(input.type === 'poly') {
maxExpansions = Math.max(maxExpansions, input.ins.length);
}
return input;
});
// multichannel expansion
if(maxExpansions > 1) {
this.type = 'poly';
this.ins = Array(maxExpansions).fill(0).map((_,i) => {
const clone = new this.constructor(type, []);
clone.ins = ins.map(input => {
input = clone.parseInput(input);
if(input.type === 'poly') {
return input.ins[i % input.ins.length];
}
return input;
});
return clone;
});
}
}
parseInput(input) {
if(typeof input === 'function') {
input = input(this); // lambda feedback
}
if(Array.isArray(input)) {
input = new Node('poly', input); // interpret Arrays as poly nodes
}
return input;
}
}
let register = (type, nodeClass = Node) => {
Node.prototype[type] = function (...args) {
return new nodeClass(type, [this, ...args]);
};
return (...args) => new nodeClass(type, args);
};
function topoSort(graph) {
const sorted = [];
const visited = new Set();
function dfs(node) {
if (!(node instanceof Node) || visited.has(node)) {
return; // constant values or already visited nodes
}
visited.add(node);
for (let i in node.ins) {
dfs(node.ins[i]);
}
sorted.push(node);
}
dfs(graph);
return sorted;
}
Node.prototype.compile = function() {
let nodes = topoSort(this);
const getRegister = (input) => ["number","string"].includes(typeof input) ? input : \`r[\${nodes.indexOf(input)}]\`;
let lines = [];
for(let id in nodes) {
const args = nodes[id].ins.map(getRegister).join(",");
lines.push(\`r[\${id}] = nodes[\${id}].update(\${args}); // \${nodes[id].type}\`);
}
let channels;
if(this.type === 'poly') {
channels = [this.ins[0], this.ins[1]];
} else {
channels = [this, this]
}
channels = channels.map(getRegister)
lines.push(\`o[0] = \${channels[0]}; // out 0\`);
lines.push(\`o[1] = \${channels[1]}; // out 1\`);
const code = lines.join(\`\\n\`);
console.log(code);
let update = new Function("nodes", "time", "r", "o", code);
let r = new Array(nodes.length).fill(0);
let tick = (t, o) => update(nodes, t, r, o);
return tick;
}
let dsp;
Node.prototype.out = function() {
dsp = this.compile()
}
const SAMPLE_RATE = sampleRate;
const ISR = 1 / SAMPLE_RATE;
const pulse = register(
"pulse",
class extends Node {
phase = 0;
update(freq, duty = 0.5) {
this.phase = ISR * freq;
let cyclePos = this.phase % 1;
return cyclePos < duty ? 1 : -1;
}
}
);
const sine = register(
"sine",
class extends Node {
phase = 0;
update = (freq) => Math.sin((this.phase = 2 * Math.PI * freq * ISR));
}
);
const add = register(
"add",
class extends Node {
update = (a, b) => a b;
}
);
const mul = register(
"mul",
class extends Node {
update = (a, b) => a * b;
}
);
const dust = register(
"dust",
class extends Node {
update = (density) => (Math.random() < density * ISR ? Math.random() : 0);
}
);
const range = register(
"range",
class extends Node {
update(input, min, max) {
const uni = (input 1) * 0.5;
return uni * (max - min) min;
}
}
);
const impulse = register(
"impulse",
class extends Node {
phase = 1;
update(freq) {
this.phase = ISR * freq;
let v = this.phase >= 1 ? 1 : 0;
this.phase = this.phase % 1;
return v;
}
}
);
const lpf = register(
"lpf",
class extends Node {
s0 = 0;
s1 = 0;
update(s, cutoff, resonance = 0) {
// Out of bound values can produce NaNs
cutoff = Math.min(cutoff, 1);
resonance = Math.max(resonance, 0);
var c = Math.pow(0.5, (1 - cutoff) / 0.125);
var r = Math.pow(0.5, (resonance 0.125) / 0.125);
var mrc = 1 - r * c;
var v0 = this.s0;
var v1 = this.s1;
// Apply the filter to the sample
v0 = mrc * v0 - c * v1 c * s;
v1 = mrc * v1 c * v0;
s = v1;
this.s0 = v0;
this.s1 = v1;
return s;
}
}
);
function lerp(x, y0, y1) {
if (x >= 1) return y1;
return y0 x * (y1 - y0);
}
const adsr = register(
"adsr",
class extends Node {
state = "off";
startTime = 0;
startVal = 0;
constructor(type, ins) {
ins.unshift("time");
super(type, ins);
}
update(curTime, gate, attack, decay, susVal, release) {
switch (this.state) {
case "off": {
if (gate > 0) {
this.state = "attack";
this.startTime = curTime;
this.startVal = 0;
}
return 0;
}
case "attack": {
let time = curTime - this.startTime;
if (time > attack) {
this.state = "decay";
this.startTime = curTime;
return 1;
}
return lerp(time / attack, this.startVal, 1);
}
case "decay": {
let time = curTime - this.startTime;
let curVal = lerp(time / decay, 1, susVal);
if (gate <= 0) {
this.state = "release";
this.startTime = curTime;
this.startVal = curVal;
return curVal;
}
if (time > decay) {
this.state = "sustain";
this.startTime = curTime;
return susVal;
}
return curVal;
}
case "sustain": {
if (gate <= 0) {
this.state = "release";
this.startTime = curTime;
this.startVal = susVal;
}
return susVal;
}
case "release": {
let time = curTime - this.startTime;
if (time > release) {
this.state = "off";
return 0;
}
let curVal = lerp(time / release, this.startVal, 0);
if (gate > 0) {
this.state = "attack";
this.startTime = curTime;
this.startVal = curVal;
}
return curVal;
}
}
throw "invalid envelope state";
}
}
);
export class Delay extends Node {
writeIdx = 0;
readIdx = 0;
constructor(type, ins) {
super(type, ins);
const MAX_DELAY_TIME = 10;
this.buffer = new Float32Array(MAX_DELAY_TIME * SAMPLE_RATE);
this.buffer.fill(0);
}
write(s, delayTime) {
this.writeIdx = (this.writeIdx 1) % this.buffer.length;
this.buffer[this.writeIdx] = s;
// Calculate how far in the past to read
let numSamples = Math.min(
Math.floor(SAMPLE_RATE * delayTime),
this.buffer.length - 1
);
this.readIdx = this.writeIdx - numSamples;
// If past the start of the buffer, wrap around
if (this.readIdx < 0) this.readIdx = this.buffer.length;
}
update(input, delayTime) {
this.write(input, delayTime);
return this.buffer[this.readIdx];
}
}
const delay = register("delay", Delay)
const saw = register("saw", class extends Node {
phase = 0
update = (freq) => {
this.phase = ISR * freq;
return (this.phase % 1) * 2 - 1;
}
})
// end of lib
${code};
class MyProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.t = 0;
this.stopped = false;
this.o = [0, 0];
this.port.onmessage = (e) => {
if(e.data==='stop') {
this.stopped = true;
}
};
}
process(inputs, outputs, parameters) {
const output = outputs[0];
const outChannel0 = output[0];
const outChannel1 = output[1];
for (let i = 0; i < outChannel0.length; i ) {
dsp(this.t / ${ac.sampleRate}, this.o);
outChannel0[i] = this.o[0];
outChannel1[i] = this.o[1];
this.t ;
}
return !this.stopped;
}
}
registerProcessor('${name}', MyProcessor);
`;
const base64String = btoa(workletCode);
const dataURL = `data:text/javascript;base64,${base64String}`;
await ac.audioWorklet.addModule(dataURL);
const node = new AudioWorkletNode(ac, name, {
outputChannelCount: [2],
});
const stop = () => node.port.postMessage("stop");
return { node, stop };
}
// control
let worklet;
const stop = async () => {
worklet?.stop();
worklet?.node?.disconnect();
stopButton.style.display = "none";
playButton.style.display = "block";
};
const update = async (code) => {
ac = ac || new AudioContext();
await ac.resume();
stop();
worklet = await getSimpleDynamicWorklet(ac, code);
worklet.node.connect(ac.destination);
window.location.hash = "#" btoa(code);
stopButton.style.display = "block";
playButton.style.display = "none";
};
// ui
const input = document.getElementById("code");
const playButton = document.getElementById("playButton");
const stopButton = document.getElementById("stopButton");
let urlCode = window.location.hash.slice(1);
if (urlCode) {
urlCode = atob(urlCode);
console.log("loaded code from url!");
}
const initialCode =
urlCode ||
`saw(55).lpf(sine(.5).range(.4,.8))
.mul(impulse(4).adsr(.1,.1,.1,.1))
.out()`;
input.value = initialCode;
input.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.altKey) && e.key === "Enter") {
update(input.value);
} else if ((e.ctrlKey || e.altKey) && e.code === "Period") {
stop();
e.preventDefault();
}
});
playButton.addEventListener("click", () => update(input.value));
stopButton.addEventListener("click", () => stop());
</script>
</body>
</html>