@grame/faustwasm 0.16.4 → 0.16.5

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.
@@ -53,7 +53,7 @@ export class FaustPWA {
53
53
  /** @type {FaustPWAOptions} */
54
54
  this.fOptions = {
55
55
  voices: 0,
56
- useScriptProcessor: false,
56
+ useScriptProcessor: undefined,
57
57
  bufferSize: 512,
58
58
  uiContainer: null,
59
59
  ...options,
@@ -74,6 +74,7 @@ export class FaustPWA {
74
74
  // MIDI and Sensor handlers state
75
75
  this.fActive.sensors = false;
76
76
  this.fActive.midi = false;
77
+ this.fActive.audioConnected = false;
77
78
 
78
79
  // Keyboard to MIDI handing
79
80
  this.fKeyboard2MIDI = null;
@@ -187,15 +188,59 @@ export class FaustPWA {
187
188
  return this.fFaustNode;
188
189
  }
189
190
 
191
+ /**
192
+ * Choose the default audio backend for the current runtime.
193
+ *
194
+ * AudioWorklet is always preferred. ScriptProcessor is only requested up
195
+ * front when the runtime has no AudioWorklet support at all. iOS/WebKit
196
+ * cases where an AudioWorklet graph is created but stays silent are handled
197
+ * at node-creation time by the AudioWorklet→ScriptProcessor retry in
198
+ * `createFaustNode`, so no preemptive iOS heuristic is needed here. The
199
+ * explicit `useScriptProcessor` option still overrides this default.
200
+ *
201
+ * @returns {boolean} True only when AudioWorklet is unavailable.
202
+ */
203
+ shouldUseScriptProcessor() {
204
+ return !this.fAudioContext.audioWorklet;
205
+ }
206
+
207
+ /**
208
+ * Prime iOS audio output inside the same user gesture used to resume audio.
209
+ *
210
+ * Some iOS versions report a resumed AudioContext while the hardware output
211
+ * path remains locked until a source node is started from the activation
212
+ * gesture. A one-sample silent buffer is enough to unlock that path without
213
+ * producing audible sound. Failure is non-fatal because this is only a
214
+ * compatibility assist.
215
+ */
216
+ unlockAudioOutput() {
217
+ try {
218
+ const buffer = this.fAudioContext.createBuffer(1, 1, this.fAudioContext.sampleRate);
219
+ const source = this.fAudioContext.createBufferSource();
220
+ const gain = this.fAudioContext.createGain();
221
+ gain.gain.value = 0;
222
+ source.buffer = buffer;
223
+ source.connect(gain).connect(this.fAudioContext.destination);
224
+ source.start(0);
225
+ source.stop(this.fAudioContext.currentTime + 0.01);
226
+ } catch (error) {
227
+ console.warn("Silent audio unlock failed.", error);
228
+ }
229
+ }
230
+
190
231
  // Synchronous function to resume AudioContext, to be called first in the synchronous event listener
191
232
  resumeAudioContext() {
233
+ this.unlockAudioOutput();
192
234
  if (this.fAudioContext.state === 'suspended') {
193
- this.fAudioContext.resume().then(() => {
235
+ return this.fAudioContext.resume().then(() => {
194
236
  console.log('AudioContext resumed successfully');
237
+ return this.fAudioContext.state;
195
238
  }).catch(error => {
196
239
  console.error('Error when resuming AudioContext:', error);
240
+ throw error;
197
241
  });
198
242
  }
243
+ return Promise.resolve(this.fAudioContext.state);
199
244
  }
200
245
 
201
246
  // Asynchronous function to suspend AudioContext
@@ -212,6 +257,13 @@ export class FaustPWA {
212
257
  // Import the create-node module
213
258
  const { connectToAudioInput, requestPermissions } = await import("./create-node.js");
214
259
 
260
+ // Connect the Faust node to the audio output before optional permissions
261
+ // so a denied MIDI/sensor/input permission cannot leave a synth silent.
262
+ if (!this.fActive.audioConnected) {
263
+ this.fFaustNode.connect(this.fAudioContext.destination);
264
+ this.fActive.audioConnected = true;
265
+ }
266
+
215
267
  // Request permission for sensors
216
268
  await requestPermissions();
217
269
 
@@ -228,12 +280,13 @@ export class FaustPWA {
228
280
  this.fActive.midi = true;
229
281
  }
230
282
 
231
- // Connect the Faust node to the audio output@
232
- this.fFaustNode.connect(this.fAudioContext.destination);
233
-
234
283
  // Connect the Faust node to the audio input
235
284
  if (this.fFaustNode.numberOfInputs > 0) {
236
- await connectToAudioInput(this.fAudioContext, null, this.fFaustNode, null);
285
+ try {
286
+ await connectToAudioInput(this.fAudioContext, null, this.fFaustNode, null);
287
+ } catch (error) {
288
+ console.error("Error when connecting audio input:", error);
289
+ }
237
290
  }
238
291
  }
239
292
 
@@ -268,7 +321,7 @@ export class FaustPWA {
268
321
  this.fAudioContext,
269
322
  this.fOptions.dspName,
270
323
  this.fOptions.voices ?? 0,
271
- this.fOptions.useScriptProcessor ?? false,
324
+ this.fOptions.useScriptProcessor ?? this.shouldUseScriptProcessor(),
272
325
  this.fOptions.bufferSize ?? 512
273
326
  );
274
327
 
@@ -307,12 +360,10 @@ export class FaustPWA {
307
360
  */
308
361
  async start() {
309
362
  // Resume AudioContext synchronously
310
- this.resumeAudioContext();
311
-
363
+ await this.resumeAudioContext();
364
+
312
365
  // Launch the activation of MIDI and Sensors
313
- this.activateMIDISensors().catch(error => {
314
- console.error('Error when activating audio, MIDI and sensors:', error);
315
- });
366
+ await this.activateMIDISensors();
316
367
 
317
368
  // Dispatch the started event
318
369
  this.dispatch('started', { when: this.audioContext.currentTime });
@@ -40,19 +40,26 @@ const FAUST_DSP_VOICES = 0;
40
40
  // Create PWA and UI
41
41
  await pwa.create();
42
42
 
43
- // Event listener to handle user interaction
43
+ // Event listener to handle user interaction. The whole start sequence is
44
+ // launched from the event handler rather than split across delayed tasks so
45
+ // iOS keeps it associated with the user activation.
44
46
  function handleUserInteraction() {
45
-
47
+
46
48
  // Resume AudioContext synchronously
47
49
  pwa.resumeAudioContext();
48
50
 
49
51
  // Activate MIDI and Sensors
50
- pwa.activateMIDISensors()
51
- }
52
+ pwa.activateMIDISensors();
53
+ }
52
54
 
53
- // Activate AudioContext, MIDI and Sensors on user interaction
55
+ // Register several activation events because iOS standalone PWAs do not
56
+ // behave identically across versions: some fire pointer events reliably,
57
+ // others are more consistent with touchend or click.
58
+ window.addEventListener('pointerdown', handleUserInteraction, { passive: true });
59
+ window.addEventListener('touchend', handleUserInteraction, { passive: true });
54
60
  window.addEventListener('click', handleUserInteraction);
55
61
  window.addEventListener('touchstart', handleUserInteraction);
62
+ window.addEventListener('keydown', handleUserInteraction);
56
63
 
57
64
  // Deactivate AudioContext, MIDI and Sensors on user interaction
58
65
  window.addEventListener('visibilitychange', function () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grame/faustwasm",
3
- "version": "0.16.4",
3
+ "version": "0.16.5",
4
4
  "description": "WebAssembly version of Faust Compiler",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/esm/index.d.ts",
@@ -1,253 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * @typedef {{ dspModule: WebAssembly.Module; dspMeta: FaustDspMeta; effectModule?: WebAssembly.Module; effectMeta?: FaustDspMeta; mixerModule?: WebAssembly.Module }} FaustDspDistribution
5
- * @typedef {import("./faustwasm").FaustDspMeta} FaustDspMeta
6
- * @typedef {import("./faustwasm").FaustMonoAudioWorkletNode} FaustMonoAudioWorkletNode
7
- * @typedef {import("./faustwasm").FaustPolyAudioWorkletNode} FaustPolyAudioWorkletNode
8
- * @typedef {import("./faustwasm").FaustMonoScriptProcessorNode} FaustMonoScriptProcessorNode
9
- * @typedef {import("./faustwasm").FaustPolyScriptProcessorNode} FaustPolyScriptProcessorNode
10
- * @typedef {FaustMonoAudioWorkletNode | FaustPolyAudioWorkletNode | FaustMonoScriptProcessorNode | FaustPolyScriptProcessorNode} FaustNode
11
- */
12
-
13
- /**
14
- * Creates a Faust audio node for use in the Web Audio API.
15
- *
16
- * @param {AudioContext} audioContext - The Web Audio API AudioContext to which the Faust audio node will be connected.
17
- * @param {string} [dspName] - The name of the DSP to be loaded.
18
- * @param {number} [voices] - The number of voices to be used for polyphonic DSPs.
19
- * @param {boolean} [sp] - Whether to create a ScriptProcessorNode instead of an AudioWorkletNode.
20
- * @returns {Promise<{ faustNode: FaustNode | null; dspMeta: FaustDspMeta }>} - An object containing the Faust audio node and the DSP metadata.
21
- */
22
- const createFaustNode = async (audioContext, dspName = "template", voices = 0, sp = false, bufferSize = 512) => {
23
- // Set to true if the DSP has an effect
24
- const FAUST_DSP_HAS_EFFECT = false;
25
-
26
- // Import necessary Faust modules and data
27
- const { FaustMonoDspGenerator, FaustPolyDspGenerator } = await import("./faustwasm/index.js");
28
-
29
- // Load DSP metadata from JSON
30
- /** @type {FaustDspMeta} */
31
- const dspMeta = await (await fetch("./dsp-meta.json")).json();
32
-
33
- // Compile the DSP module from WebAssembly binary data
34
- const dspModule = await WebAssembly.compileStreaming(await fetch("./dsp-module.wasm"));
35
-
36
- // Create an object representing Faust DSP with metadata and module
37
- /** @type {FaustDspDistribution} */
38
- const faustDsp = { dspMeta, dspModule };
39
-
40
- /** @type {FaustNode | null} */
41
- let faustNode = null;
42
-
43
- // Create either a polyphonic or monophonic Faust audio node based on the number of voices
44
- if (voices > 0) {
45
-
46
- // Try to load optional mixer and effect modules
47
- faustDsp.mixerModule = await WebAssembly.compileStreaming(await fetch("./mixer-module.wasm"));
48
-
49
- if (FAUST_DSP_HAS_EFFECT) {
50
- faustDsp.effectMeta = await (await fetch("./effect-meta.json")).json();
51
- faustDsp.effectModule = await WebAssembly.compileStreaming(await fetch("./effect-module.wasm"));
52
- }
53
-
54
- // Create a polyphonic Faust audio node
55
- const generator = new FaustPolyDspGenerator();
56
- faustNode = await generator.createNode(
57
- audioContext,
58
- voices,
59
- dspName,
60
- { module: faustDsp.dspModule, json: JSON.stringify(faustDsp.dspMeta), soundfiles: {} },
61
- faustDsp.mixerModule,
62
- faustDsp.effectModule ? { module: faustDsp.effectModule, json: JSON.stringify(faustDsp.effectMeta), soundfiles: {} } : undefined,
63
- sp,
64
- bufferSize
65
- );
66
- } else {
67
- // Create a standard Faust audio node
68
- const generator = new FaustMonoDspGenerator();
69
- faustNode = await generator.createNode(
70
- audioContext,
71
- dspName,
72
- { module: faustDsp.dspModule, json: JSON.stringify(faustDsp.dspMeta), soundfiles: {} },
73
- sp,
74
- bufferSize
75
- );
76
- }
77
-
78
- // Return an object with the Faust audio node and the DSP metadata
79
- return { faustNode, dspMeta };
80
- }
81
-
82
- /**
83
- * Connects an audio input stream to a Faust WebAudio node.
84
- *
85
- * @param {AudioContext} audioContext - The Web Audio API AudioContext to which the Faust audio node is connected.
86
- * @param {string} id - The ID of the audio input device to connect.
87
- * @param {FaustNode} faustNode - The Faust audio node to which the audio input stream will be connected.
88
- * @param {MediaStreamAudioSourceNode} oldInputStreamNode - The old audio input stream node to be disconnected from the Faust audio node.
89
- * @returns {Promise<MediaStreamAudioSourceNode>} - The new audio input stream node connected to the Faust audio node.
90
- */
91
- async function connectToAudioInput(audioContext, id, faustNode, oldInputStreamNode) {
92
- // Create an audio input stream node
93
- const constraints = {
94
- audio: {
95
- echoCancellation: false,
96
- noiseSuppression: false,
97
- autoGainControl: false,
98
- deviceId: id ? { exact: id } : undefined,
99
- },
100
- };
101
- // Get the audio input stream
102
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
103
- if (stream) {
104
- if (oldInputStreamNode) oldInputStreamNode.disconnect();
105
- const newInputStreamNode = audioContext.createMediaStreamSource(stream);
106
- newInputStreamNode.connect(faustNode);
107
- return newInputStreamNode;
108
- } else {
109
- return oldInputStreamNode;
110
- }
111
- };
112
-
113
- /**
114
- * Creates a Faust UI for a Faust audio node.
115
- *
116
- * @param {FaustAudioWorkletNode} faustNode
117
- */
118
- async function createFaustUI(divFaustUI, faustNode) {
119
- const { FaustUI } = await import("./faust-ui/index.js");
120
- const $container = document.createElement("div");
121
- $container.style.margin = "0";
122
- $container.style.position = "absolute";
123
- $container.style.overflow = "auto";
124
- $container.style.display = "flex";
125
- $container.style.flexDirection = "column";
126
- $container.style.width = "100%";
127
- $container.style.height = "100%";
128
- divFaustUI.appendChild($container);
129
- const faustUI = new FaustUI({
130
- ui: faustNode.getUI(),
131
- root: $container,
132
- listenWindowMessage: false,
133
- listenWindowResize: true,
134
- });
135
- faustUI.paramChangeByUI = (path, value) => faustNode.setParamValue(path, value);
136
- faustNode.setOutputParamHandler((path, value) => faustUI.paramChangeByDSP(path, value));
137
- faustNode.setInputParamHandler((path, value) => faustUI.paramChangeByDSP(path, value));
138
- $container.style.minWidth = `${faustUI.minWidth}px`;
139
- $container.style.minHeight = `${faustUI.minHeight}px`;
140
- faustUI.resize();
141
- };
142
-
143
- /**
144
- * Request permission to use motion and orientation sensors.
145
- */
146
- async function requestPermissions() {
147
-
148
- // Explicitly request permission on iOS before calling startSensors()
149
- if (typeof window.DeviceMotionEvent !== "undefined" && typeof window.DeviceMotionEvent.requestPermission === "function") {
150
- try {
151
- const permissionState = await window.DeviceMotionEvent.requestPermission();
152
- if (permissionState !== "granted") {
153
- console.warn("Motion sensor permission denied.");
154
- } else {
155
- console.log("Motion sensor permission granted.");
156
- }
157
- } catch (error) {
158
- console.error("Error requesting motion sensor permission:", error);
159
- }
160
- }
161
-
162
- if (typeof window.DeviceOrientationEvent !== "undefined" && typeof window.DeviceOrientationEvent.requestPermission === "function") {
163
- try {
164
- const permissionState = await window.DeviceOrientationEvent.requestPermission();
165
- if (permissionState !== "granted") {
166
- console.warn("Orientation sensor permission denied.");
167
- } else {
168
- console.log("Orientation sensor permission granted.");
169
- }
170
- } catch (error) {
171
- console.error("Error requesting orientation sensor permission:", error);
172
- }
173
- }
174
- }
175
-
176
- /**
177
- * Key2Midi: maps keyboard input to MIDI messages.
178
- */
179
- class Key2Midi {
180
- static KEY_MAP = {
181
- a: 0, w: 1, s: 2, e: 3, d: 4, f: 5, t: 6, g: 7,
182
- y: 8, h: 9, u: 10, j: 11, k: 12, o: 13, l: 14, p: 15, ";": 16,
183
- z: "PREV", x: "NEXT", c: "VELDOWN", v: "VELUP"
184
- };
185
-
186
- constructor({ keyMap = Key2Midi.KEY_MAP, offset = 60, velocity = 100, handler = console.log } = {}) {
187
- this.keyMap = keyMap;
188
- this.offset = offset;
189
- this.velocity = velocity;
190
- this.velMap = [20, 40, 60, 80, 100, 127];
191
- this.handler = handler;
192
- this.pressed = {};
193
-
194
- this.onKeyDown = this.onKeyDown.bind(this);
195
- this.onKeyUp = this.onKeyUp.bind(this);
196
- }
197
-
198
- start() {
199
- window.addEventListener("keydown", this.onKeyDown);
200
- window.addEventListener("keyup", this.onKeyUp);
201
- }
202
-
203
- stop() {
204
- window.removeEventListener("keydown", this.onKeyDown);
205
- window.removeEventListener("keyup", this.onKeyUp);
206
- }
207
-
208
- onKeyDown(e) {
209
- const key = e.key.toLowerCase();
210
- if (this.pressed[key]) return;
211
- this.pressed[key] = true;
212
-
213
- const val = this.keyMap[key];
214
- if (typeof val === "number") {
215
- const note = val + this.offset;
216
- this.handler([0x90, note, this.velocity]);
217
- } else if (val === "PREV") {
218
- this.offset -= 1;
219
- } else if (val === "NEXT") {
220
- this.offset += 1;
221
- } else if (val === "VELDOWN") {
222
- const idx = Math.max(0, this.velMap.indexOf(this.velocity) - 1);
223
- this.velocity = this.velMap[idx];
224
- } else if (val === "VELUP") {
225
- const idx = Math.min(this.velMap.length - 1, this.velMap.indexOf(this.velocity) + 1);
226
- this.velocity = this.velMap[idx];
227
- }
228
- }
229
-
230
- onKeyUp(e) {
231
- const key = e.key.toLowerCase();
232
- const val = this.keyMap[key];
233
- if (typeof val === "number") {
234
- const note = val + this.offset;
235
- this.handler([0x80, note, this.velocity]);
236
- }
237
- delete this.pressed[key];
238
- }
239
- }
240
-
241
- /**
242
- * Creates a Key2Midi instance.
243
- *
244
- * @param {function} handler - The function to handle MIDI messages.
245
- * @returns {Key2Midi} - The Key2Midi instance.
246
- */
247
- function createKey2MIDI(handler) {
248
- return new Key2Midi({ handler: handler });
249
- }
250
-
251
- // Export the functions
252
- export { createFaustNode, createFaustUI, createKey2MIDI, connectToAudioInput, requestPermissions };
253
-
@@ -1,132 +0,0 @@
1
- {
2
- "name": "organ",
3
- "filename": "organ",
4
- "version": "2.85.8",
5
- "compile_options": "-lang wasm-i -fpga-mem-th 4 -ct 1 -es 1 -mcd 16 -mdd 1024 -mdy 33 -single -ftz 2",
6
- "library_list": [
7
- "/usr/share/faust/stdfaust.lib",
8
- "/usr/share/faust/oscillators.lib",
9
- "/usr/share/faust/platform.lib",
10
- "/usr/share/faust/maths.lib",
11
- "/usr/share/faust/basics.lib",
12
- "/usr/share/faust/envelopes.lib"
13
- ],
14
- "include_pathnames": [
15
- "/faust/user/inc0",
16
- "/share/faust",
17
- "/usr/local/share/faust",
18
- "/usr/share/faust",
19
- "."
20
- ],
21
- "size": 262264,
22
- "code": "cAbO",
23
- "inputs": 0,
24
- "outputs": 1,
25
- "meta": [
26
- {
27
- "basics.lib/name": "Faust Basic Element Library"
28
- },
29
- {
30
- "basics.lib/version": "1.22.0"
31
- },
32
- {
33
- "compile_options": "-lang wasm-i -fpga-mem-th 4 -ct 1 -es 1 -mcd 16 -mdd 1024 -mdy 33 -single -ftz 2"
34
- },
35
- {
36
- "envelopes.lib/adsr:author": "Yann Orlarey and Andrey Bundin"
37
- },
38
- {
39
- "envelopes.lib/author": "GRAME"
40
- },
41
- {
42
- "envelopes.lib/copyright": "GRAME"
43
- },
44
- {
45
- "envelopes.lib/license": "LGPL with exception"
46
- },
47
- {
48
- "envelopes.lib/name": "Faust Envelope Library"
49
- },
50
- {
51
- "envelopes.lib/version": "1.3.0"
52
- },
53
- {
54
- "filename": "organ"
55
- },
56
- {
57
- "maths.lib/author": "GRAME"
58
- },
59
- {
60
- "maths.lib/copyright": "GRAME"
61
- },
62
- {
63
- "maths.lib/license": "LGPL with exception"
64
- },
65
- {
66
- "maths.lib/name": "Faust Math Library"
67
- },
68
- {
69
- "maths.lib/version": "2.9.0"
70
- },
71
- {
72
- "name": "organ"
73
- },
74
- {
75
- "oscillators.lib/name": "Faust Oscillator Library"
76
- },
77
- {
78
- "oscillators.lib/version": "1.7.0"
79
- },
80
- {
81
- "platform.lib/name": "Generic Platform Library"
82
- },
83
- {
84
- "platform.lib/version": "1.3.0"
85
- }
86
- ],
87
- "ui": [
88
- {
89
- "type": "vgroup",
90
- "label": "organ",
91
- "items": [
92
- {
93
- "type": "hslider",
94
- "label": "freq",
95
- "varname": "fHslider1",
96
- "shortname": "freq",
97
- "address": "/organ/freq",
98
- "index": 262168,
99
- "meta": [
100
- {
101
- "midi": "ctrl 7"
102
- }
103
- ],
104
- "init": 440,
105
- "min": 20,
106
- "max": 3000,
107
- "step": 1
108
- },
109
- {
110
- "type": "hslider",
111
- "label": "gain",
112
- "varname": "fHslider0",
113
- "shortname": "gain",
114
- "address": "/organ/gain",
115
- "index": 262144,
116
- "init": 0.5,
117
- "min": 0,
118
- "max": 1,
119
- "step": 0.01
120
- },
121
- {
122
- "type": "button",
123
- "label": "gate",
124
- "varname": "fButton0",
125
- "shortname": "gate",
126
- "address": "/organ/gate",
127
- "index": 262212
128
- }
129
- ]
130
- }
131
- ]
132
- }
Binary file