-
Notifications
You must be signed in to change notification settings - Fork 9
/
audioworklet.js
255 lines (221 loc) · 8.67 KB
/
audioworklet.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
// AudioWorklet polyfill
// Jari Kleimola 2017-20 ([email protected])
//
// loosely based on https://github.com/GoogleChromeLabs/houdini-samples/blob/master/animation-worklet/anim-worklet.js
// feature detection borrowed from Google's AudioWorklet demo page
//
AudioContext = window.AudioContext || window.webkitAudioContext;
(function(scope) {
"use strict";
// namespace to avoid global scope pollution
// disabling SABs for now
window.AWPF = window.AWPF || {}
AWPF.hasSAB = false; // window.SharedArrayBuffer !== undefined;
AWPF.origin = "";
// --------------------------------------------------------------------------
//
//
AWPF.PolyfillAudioWorklet = function() {
var imports = {};
var importedScripts = [];
function importOnWorker(src) {
if (!AWPF.worker.onmessage) AWPF.worker.onmessage = onmessage;
return new Promise(function(resolve, reject) {
if (importedScripts.indexOf(src) < 0) {
imports[src] = { resolve:resolve, reject:reject };
AWPF.worker.postMessage({ type:"import", url:src });
importedScripts.push(src);
}
else resolve();
});
}
var onmessage = function (e) {
var msg = e.data;
switch (msg.type) {
case "load":
var script = imports[msg.url];
if (script) {
if (!msg.error) script.resolve();
else script.reject(Error('Failed to load ' + msg.url));
delete imports[msg.url];
}
else console.log("throw: already registered");
// else throw new Error("InvalidStateError");
break;
case "register":
AWPF.descriptorMap[msg.name] = msg.descriptor;
break;
case "state":
var node = AWPF.workletNodes[msg.node];
if (node) {
if (msg.state == "running")
node.processor = msg.processor;
var event = new CustomEvent('statechange', { detail: msg.state });
node.onprocessorstatechange(event);
}
break;
case "process":
var node = AWPF.workletNodes[msg.node];
node.onRender(msg.buf);
break;
}
}
return { addModule:importOnWorker }
}
// --------------------------------------------------------------------------
//
//
AWPF.AudioWorkletNode = function (context, nodeName, options) {
if (AWPF.descriptorMap[nodeName] === undefined)
throw new Error("NotSupportedException");
// TODO step 9
this.id = AWPF.workletNodes.length;
AWPF.workletNodes.push(this);
var messageChannel = new MessageChannel();
this.port = messageChannel.port1;
// -- SPN min bufsize is 256, and it has max one input and max one output port
//
options = options || {}
options.buflenAWP = options.buflenAWP || 128;
options.buflenSPN = options.buflenSPN || AWPF.buflenSPN;
options.numberOfInputs = options.numberOfInputs || 0;
if (options.numberOfOutputs === undefined) options.numberOfOutputs = 1;
if (options.outputChannelCount === undefined) options.outputChannelCount = [1];
if (options.numberOfInputs) options.inputChannelCount = [2];
if (options.outputChannelCount.length != options.numberOfOutputs) throw new Error("InvalidArgumentException");
var nslices = (options.buflenSPN / options.buflenAWP) | 0;
var bytesPerBuffer = options.buflenAWP * nslices * 4;
function configurePort (type, options) {
var nports = (type == "input") ? options.numberOfInputs : options.numberOfOutputs;
if (nports > 0) {
var nchannels = 0;
var channelCount = (type == "input") ? options.inputChannelCount : options.outputChannelCount;
if (channelCount.length > 0) nchannels = channelCount[0];
if (nchannels <= 0) throw new Error("InvalidArgumentException");
var port = new Array(nchannels);
for (var c=0; c<nchannels; c++)
if (AWPF.hasSAB)
port[c] = new SharedArrayBuffer(bytesPerBuffer);
else {
port[c] = new Array(2);
for (var pingpong = 0; pingpong < 2; pingpong++) {
var ab = new ArrayBuffer(bytesPerBuffer);
port[c][pingpong] = new Float32Array(ab);
}
}
return port;
}
return null;
}
// -- io configuration is currently static
var audioIn = configurePort("input", options);
var audioOut = configurePort("output", options);
// -- create processor
this.processorState = "pending";
var args = { node:this.id, name:nodeName, options:options, hasSAB:AWPF.hasSAB }
args.audio = { input:audioIn, output:audioOut }
AWPF.worker.postMessage({ type:"createProcessor", args }, [messageChannel.port2])
this.onprocessorstatechange = function (e) {
this.processorState = e.detail;
if (!AWPF.hasSAB && this.processorState == "running")
render();
console.log("state:", e.detail);
}
// -- fix for blocked SABs -------------------------------------------------
if (!AWPF.hasSAB) {
var curbuf = 0;
var newBufferAvailable = false;
var self = this;
var render = function () {
var msg = { type:"process", processor:self.processor, time:context.currentTime, buf:[] };
if (audioIn) {
for (var c=0; c<audioIn.length; c++)
msg.buf.push(audioIn[c][curbuf].buffer);
}
for (var c=0; c<audioOut.length; c++)
msg.buf.push(audioOut[c][curbuf].buffer);
AWPF.worker.postMessage(msg, msg.buf);
curbuf = ((curbuf + 1) % 2) | 0;
newBufferAvailable = false;
}
this.onRender = function (buf) {
let c = 0;
if (audioIn) {
audioIn[0][curbuf ? 0:1] = new Float32Array(buf[c++]);
audioIn[1][curbuf ? 0:1] = new Float32Array(buf[c++]);
}
audioOut[0][curbuf ? 0:1] = new Float32Array(buf[c++]);
audioOut[1][curbuf ? 0:1] = new Float32Array(buf[c]);
newBufferAvailable = true;
}
}
// -- ScriptProcessorNode -------------------------------------------------
let ninChannels = options.inputChannelCount[0] || 0;
let noutChannels = options.outputChannelCount[0];
var spn = context.createScriptProcessor(options.buflenSPN, ninChannels, noutChannels);
this.input = spn;
this.connect = function (dst) {
spn.onaudioprocess = onprocess.bind(this);
spn.connect(dst)
}
this.disconnect = function () {
spn.onaudioprocess = null;
spn.disconnect();
}
if (AWPF.hasSAB) var outbuf = new Float32Array(audioOut[0]); // spn limitation
var onprocess = function (ape) {
if (this.processor === undefined) return;
var ibuff = ape.inputBuffer;
var obuff = ape.outputBuffer;
var outL = obuff.getChannelData(0);
if (AWPF.hasSAB) {
outL.set(outbuf);
var msg = { type:"process", processor:this.processor, time:context.currentTime };
AWPF.worker.postMessage(msg);
}
else {
if (audioIn) for (var c=0; c<audioIn.length; c++)
audioIn[c][curbuf].set(ibuff.getChannelData(c));
for (var c=0; c<audioOut.length; c++)
obuff.getChannelData(c).set(audioOut[c][curbuf]);
if (newBufferAvailable)
render();
}
}
}
// --------------------------------------------------------------------------
// -- borrowed from Google's AudioWorklet demo page
AWPF.AudioWorkletAvailable = function (actx) {
return actx.audioWorklet &&
actx.audioWorklet instanceof AudioWorklet &&
typeof actx.audioWorklet.addModule === 'function' &&
window.AudioWorkletNode;
}
AWPF.polyfill = function (scope, options) {
return new Promise( function (resolve) {
if (AWPF.AudioWorkletAvailable(scope))
resolve();
else {
options = options || {};
AWPF.buflenSPN = options.buflenSPN || 512;
AWPF.descriptorMap = {}; // node name to parameter descriptor map (should be in BAC)
AWPF.workletNodes = [];
AWPF.audioWorklet = AWPF.PolyfillAudioWorklet();
AWPF.context = scope;
if (!AWPF.AudioWorkletAvailable(scope))
scope.audioWorklet = AWPF.audioWorklet;
window.AudioWorkletNode = AWPF.AudioWorkletNode;
fetch(AWPF.origin + "audioworker.js").then(function (resp) {
resp.text().then(function (s) {
var u = window.URL.createObjectURL(new Blob([s]));
AWPF.worker = new Worker(u);
AWPF.worker.postMessage({ type:"init", sampleRate:scope.sampleRate, origin });
console.warn('Using Worker polyfill of AudioWorklet');
AWPF.isAudioWorkletPolyfilled = true;
resolve();
})
})
}
})
}
})();