@libreaudio/la-call 0.2.0-rc.1 → 0.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -59,9 +59,27 @@ about 3.7 MB, which barely compresses, so long-lived caching is what helps).
59
59
  ```
60
60
  - **Hosting the files yourself:** copy `node_modules/@libreaudio/la-call/dist/*.{wasm,js}`
61
61
  to a static folder and pass `createWasmProcessor(ctx, { assetBaseUrl: '/static/la-call/' })`.
62
- - **Server:** send `.wasm` as `Content-Type: application/wasm` so it compiles while downloading.
63
- - **Content-Security-Policy:** `script-src` needs `'wasm-unsafe-eval'`. On Android, where a
64
- ScriptProcessorNode is used instead of a worklet, it also needs `'unsafe-eval'`.
62
+ - **Server:** enable gzip or brotli for `.wasm` (saves about 0.9 MB); many servers do not compress
63
+ `application/wasm` by default.
64
+ - **Content-Security-Policy:** `script-src` needs `'wasm-unsafe-eval'`. The ScriptProcessorNode
65
+ fallback (see below) also needs `'unsafe-eval'`.
66
+
67
+ ## ScriptProcessorNode fallback
68
+
69
+ The processor runs in an AudioWorklet on every browser that supports it, Android included.
70
+ Where AudioWorklet is missing (old browsers, pages not served over HTTPS) it falls back to a
71
+ ScriptProcessorNode, which runs on the main thread and adds about two buffers of delay.
72
+ For very weak devices the fallback can also be forced:
73
+
74
+ ```js
75
+ createWasmProcessor(ctx, { useScriptProcessor: true, scriptProcessorBufferSize: 2048 });
76
+ ```
77
+
78
+ | buffer | added delay at 48 kHz |
79
+ |---|---|
80
+ | 1024 | ~43 ms |
81
+ | 2048 | ~85 ms |
82
+ | 4096 (default) | ~170 ms |
65
83
 
66
84
  ## Changes in 0.2.0
67
85
 
@@ -70,6 +88,11 @@ about 3.7 MB, which barely compresses, so long-lived caching is what helps).
70
88
  - `setParameter(name, value)`, `setEnabled()` and `destroy()` on the returned node.
71
89
  Parameters are no longer set by posting `{ symbol }` messages to `node.port`.
72
90
  - Fixed the fallback for browsers without wasm SIMD.
91
+ - Android uses the AudioWorklet too, instead of always using a ScriptProcessorNode
92
+ (about 170 ms less delay). `useScriptProcessor` and `scriptProcessorBufferSize` force and
93
+ tune the fallback.
94
+ - The wasm is downloaded and compiled once. Chrome used to download it twice and compile it
95
+ twice, because it cannot hand a compiled module to an AudioWorklet.
73
96
 
74
97
  ## License
75
98
 
package/dist/index.d.ts CHANGED
@@ -28,8 +28,16 @@ export interface WasmProcessorProperties extends LoadOptions {
28
28
  intensity?: number;
29
29
  /** initial parameter values, keyed by symbol */
30
30
  parameters?: Record<string, number>;
31
- /** use a ScriptProcessorNode instead of an AudioWorkletNode (default: on Android only) */
31
+ /**
32
+ * use a ScriptProcessorNode instead of an AudioWorkletNode (default false;
33
+ * it is used automatically where AudioWorklet is unavailable)
34
+ */
32
35
  useScriptProcessor?: boolean;
36
+ /**
37
+ * ScriptProcessorNode buffer size in frames, a power of two from 256 to
38
+ * 16384 (default 4096). Adds roughly twice this much delay.
39
+ */
40
+ scriptProcessorBufferSize?: number;
33
41
  }
34
42
 
35
43
  export interface WasmProcessorNode extends AudioNode {
package/dist/index.js CHANGED
@@ -70,18 +70,22 @@ const fetchOk = (url) => fetch(url).then(resp => {
70
70
 
71
71
  const fetchBytes = (url) => fetchOk(url).then(resp => resp.arrayBuffer());
72
72
 
73
- // Compile while the file downloads. compileStreaming needs the server to send
74
- // Content-Type: application/wasm; compile from the bytes when it does not.
75
- const compileWasm = (url) => {
76
- if (typeof WebAssembly.compileStreaming !== 'function')
77
- return fetchBytes(url).then(bytes => WebAssembly.compile(bytes));
78
-
79
- return WebAssembly.compileStreaming(fetchOk(url)).catch(err => {
80
- console.warn('la-call: compileStreaming failed for ' + url + ' (served as application/wasm?), compiling from bytes', err);
81
- return fetchBytes(url).then(bytes => WebAssembly.compile(bytes));
82
- });
73
+ // The wasm is downloaded once and kept as bytes. The worklet gets a copy and
74
+ // compiles it itself, off the main thread: Chrome cannot receive a compiled
75
+ // WebAssembly.Module in an AudioWorklet, so compiling it here first would be
76
+ // wasted work there. Only the ScriptProcessor fallback, which runs on the main
77
+ // thread, needs a module compiled here.
78
+ const compiledModule = (files) => {
79
+ if (! files.wasmModule) {
80
+ files.wasmModule = WebAssembly.compile(files.wasmBytes);
81
+ files.wasmModule.catch(() => { files.wasmModule = null; });
82
+ }
83
+ return files.wasmModule;
83
84
  };
84
85
 
86
+ // a transferable copy, so the kept bytes stay usable for the next node
87
+ const wasmBytesCopy = (files) => files.wasmBytes.slice(0);
88
+
85
89
  const resolveAssetUrls = (variant, assetBaseUrl) => {
86
90
  if (! assetBaseUrl)
87
91
  return builtinAssetUrls[variant]();
@@ -99,7 +103,7 @@ const resolveAssetUrls = (variant, assetBaseUrl) => {
99
103
  let loaded = null;
100
104
 
101
105
  /**
102
- * Download and compile the processor. Optional: createWasmProcessor calls this
106
+ * Download the processor. Optional: createWasmProcessor calls this
103
107
  * itself, but calling it early (e.g. when the call page opens) hides the
104
108
  * download time. Safe to call more than once.
105
109
  */
@@ -118,7 +122,7 @@ const loadWasmProcessorFiles = (options = {}) => {
118
122
  if (loaded && loaded.key === key)
119
123
  return loaded.promise;
120
124
 
121
- const promise = compileWasm(urls.wasm.href).then(wasmModule => ({ variant, urls, wasmModule }));
125
+ const promise = fetchBytes(urls.wasm.href).then(wasmBytes => ({ variant, urls, wasmBytes, wasmModule: null }));
122
126
  loaded = { key, promise };
123
127
 
124
128
  // try again on the next call after a failure
@@ -169,40 +173,57 @@ const createWorkletNode = (audioContext, files) => {
169
173
  case 'error':
170
174
  reject(new Error('la-call: ' + event.data.error));
171
175
  break;
172
- case 'need-bytes':
173
- // this browser cannot pass a compiled module to the worklet
174
- fetchBytes(files.urls.wasm.href).then(bytes => {
175
- node.port.postMessage({ type: 'init', wasm: bytes }, [bytes]);
176
- }).catch(reject);
176
+ case 'need-bytes': {
177
+ // the worklet could not read the message; send the bytes again
178
+ const retry = wasmBytesCopy(files);
179
+ node.port.postMessage({ type: 'init', wasm: retry }, [retry]);
177
180
  break;
178
181
  }
182
+ }
179
183
  };
180
184
 
181
- // the compiled module is shared with the worklet instead of copied,
182
- // and only instantiated once per context
183
- node.port.postMessage({ type: 'init', wasm: files.wasmModule });
185
+ // the worklet compiles and instantiates the bytes once per context
186
+ const bytes = wasmBytesCopy(files);
187
+ node.port.postMessage({ type: 'init', wasm: bytes }, [bytes]);
184
188
  }));
185
189
  };
186
190
 
187
191
  // --------------------------------------------------------------------------------------------------------------------
188
- // script processor fallback, for devices where a worklet cannot keep up with 128-frame blocks
192
+ // script processor fallback, for browsers without AudioWorklet, or devices where
193
+ // a worklet cannot keep up with 128-frame blocks
194
+ //
195
+ // A ScriptProcessorNode runs on the main thread and typically adds about two
196
+ // buffers of delay: 4096 frames at 48 kHz is ~170 ms. Smaller buffers lower the
197
+ // delay, but leave less headroom before the main thread causes dropouts.
189
198
  //
190
199
  // This path evaluates the emscripten glue with `new Function`, so it needs
191
200
  // 'unsafe-eval' in a Content-Security-Policy. The worklet path does not.
192
201
 
193
- const createScriptProcessorNode = (audioContext, files) => {
194
- return fetchOk(files.urls.glue.href).then(resp => resp.text()).then(glue => new Promise((resolve, reject) => {
202
+ const defaultScriptProcessorBufferSize = 4096;
203
+
204
+ const checkBufferSize = (size) => {
205
+ if (size === undefined)
206
+ return defaultScriptProcessorBufferSize;
207
+ if (! [256, 512, 1024, 2048, 4096, 8192, 16384].includes(size))
208
+ throw new Error('la-call: scriptProcessorBufferSize must be a power of two from 256 to 16384, got ' + size);
209
+ return size;
210
+ };
211
+
212
+ const createScriptProcessorNode = (audioContext, files, bufferSize) => {
213
+ return Promise.all([
214
+ fetchOk(files.urls.glue.href).then(resp => resp.text()),
215
+ compiledModule(files),
216
+ ]).then(([glue, wasmModule]) => new Promise((resolve, reject) => {
195
217
  const createModule = new Function(glue + '\nreturn mapi_bbba;')();
196
218
 
197
- const bufferSize = 4096;
198
219
  const node = audioContext.createScriptProcessor(bufferSize, 1, 1);
199
220
  node.channelCount = 1;
200
221
  node.channelCountMode = 'explicit';
201
222
 
202
223
  createModule({
203
224
  instantiateWasm: (imports, successCallback) => {
204
- WebAssembly.instantiate(files.wasmModule, imports).then(instance => {
205
- successCallback(instance, files.wasmModule);
225
+ WebAssembly.instantiate(wasmModule, imports).then(instance => {
226
+ successCallback(instance, wasmModule);
206
227
  }).catch(reject);
207
228
  return {};
208
229
  },
@@ -301,12 +322,23 @@ const attachApi = (node) => {
301
322
  * it and its output to wherever the processed audio should go.
302
323
  */
303
324
  const createWasmProcessor = (audioContext, options = {}) => {
325
+ let bufferSize;
326
+ try {
327
+ bufferSize = checkBufferSize(options.scriptProcessorBufferSize);
328
+ } catch (err) {
329
+ return Promise.reject(err);
330
+ }
331
+
304
332
  return loadWasmProcessorFiles(options).then(files => {
305
- const useScriptProcessor = options.useScriptProcessor !== undefined
306
- ? !! options.useScriptProcessor
307
- : (typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent));
333
+ // AudioWorklet everywhere it exists, Android included; it runs off the
334
+ // main thread and adds only one 128-frame block of delay
335
+ const workletSupported = typeof AudioWorkletNode !== 'undefined' && !! audioContext.audioWorklet;
336
+ const useScriptProcessor = !! options.useScriptProcessor || ! workletSupported;
337
+
338
+ if (useScriptProcessor && ! options.useScriptProcessor)
339
+ console.warn('la-call: AudioWorklet unavailable (insecure context or old browser), using ScriptProcessorNode');
308
340
 
309
- return useScriptProcessor ? createScriptProcessorNode(audioContext, files)
341
+ return useScriptProcessor ? createScriptProcessorNode(audioContext, files, bufferSize)
310
342
  : createWorkletNode(audioContext, files);
311
343
  }).then(node => {
312
344
  attachApi(node);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libreaudio/la-call",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.2.0-rc.2",
4
4
  "description": "Voice isolation and optimization AudioWorklet/WASM module for web conferencing",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "type": "module",