@grame/faustwasm 0.9.6 → 0.10.0

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.
Binary file
@@ -0,0 +1,76 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <link rel="manifest" href="./manifest.json">
5
+
6
+ <head>
7
+ <meta charset="UTF-8">
8
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
9
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
10
+ <title>Faust DSP</title>
11
+ <style>
12
+ body {
13
+ color: #b0b0b0;
14
+ background-color: #1f1f1f;
15
+ display: flex;
16
+ top: 0;
17
+ left: 0;
18
+ width: 100%;
19
+ height: 100%;
20
+ margin: 0;
21
+ position: absolute;
22
+ }
23
+
24
+ main {
25
+ margin: 20px;
26
+ display: flex;
27
+ flex-direction: column;
28
+ flex: 1 1 100%;
29
+ }
30
+
31
+ main span {
32
+ position: relative;
33
+ display: flex;
34
+ }
35
+
36
+ main span[hidden] {
37
+ display: none;
38
+ }
39
+
40
+ main span span {
41
+ margin: 0px 10px;
42
+ flex: 1;
43
+ }
44
+
45
+ main span select {
46
+ flex: 2;
47
+ }
48
+
49
+ #dsp-switch {
50
+ margin: 20px auto;
51
+ }
52
+
53
+ #button-dsp {
54
+ padding: 10px;
55
+ }
56
+
57
+ #div-faust-ui {
58
+ flex: 1 1 auto;
59
+ display: flex;
60
+ position: relative;
61
+ flex-direction: column;
62
+ color: black;
63
+ }
64
+ </style>
65
+ <link rel="stylesheet" href="./faust-ui/index.css">
66
+ </head>
67
+
68
+ <body>
69
+ <main>
70
+ <div id="div-faust-ui">
71
+ </div>
72
+ </main>
73
+ <script src="./index.js"></script>
74
+ </body>
75
+
76
+ </html>
@@ -0,0 +1,201 @@
1
+ // Set to > 0 if the DSP is polyphonic
2
+ const FAUST_DSP_VOICES = 0;
3
+
4
+ /**
5
+ * @typedef {import("./faustwasm").FaustAudioWorkletNode} FaustAudioWorkletNode
6
+ * @typedef {import("./faustwasm").FaustDspMeta} FaustDspMeta
7
+ * @typedef {import("./faustwasm").FaustUIDescriptor} FaustUIDescriptor
8
+ * @typedef {import("./faustwasm").FaustUIGroup} FaustUIGroup
9
+ * @typedef {import("./faustwasm").FaustUIItem} FaustUIItem
10
+ */
11
+
12
+ /**
13
+ * Registers the service worker.
14
+ */
15
+ if ("serviceWorker" in navigator) {
16
+ window.addEventListener("load", () => {
17
+ navigator.serviceWorker.register("./service-worker.js")
18
+ .then(reg => console.log("Service Worker registered", reg))
19
+ .catch(err => console.log("Service Worker registration failed", err));
20
+ });
21
+ }
22
+
23
+ /** @type {HTMLDivElement} */
24
+ const $divFaustUI = document.getElementById("div-faust-ui");
25
+
26
+ /** @type {typeof AudioContext} */
27
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
28
+ const audioContext = new AudioCtx({ latencyHint: 0.00001 });
29
+ audioContext.destination.channelInterpretation = "discrete";
30
+ audioContext.suspend();
31
+
32
+ // Declare faustNode as a global variable
33
+ let faustNode;
34
+
35
+ // Called at load time
36
+ (async () => {
37
+
38
+ // Import the create-node module
39
+ const { createFaustNode, createFaustUI } = await import("./create-node.js");
40
+
41
+ // To test the ScriptProcessorNode mode
42
+ // const result = await createFaustNode(audioContext, "organ", FAUST_DSP_VOICES, true, 512);
43
+ const result = await createFaustNode(audioContext, "organ", FAUST_DSP_VOICES);
44
+ faustNode = result.faustNode; // Assign to the global variable
45
+ if (!faustNode) throw new Error("Faust DSP not compiled");
46
+
47
+ // Create the Faust UI
48
+ await createFaustUI($divFaustUI, faustNode);
49
+
50
+ })();
51
+
52
+ // Synchronous function to resume AudioContext, to be called first in the synchronous event listener
53
+ function resumeAudioContext() {
54
+ if (audioContext.state === 'suspended') {
55
+ audioContext.resume().then(() => {
56
+ console.log('AudioContext resumed successfully');
57
+ }).catch(error => {
58
+ console.error('Error when resuming AudioContext:', error);
59
+ });
60
+ }
61
+ }
62
+
63
+ // Function to start MIDI
64
+ function startMIDI() {
65
+ // Check if the browser supports the Web MIDI API
66
+ if (navigator.requestMIDIAccess) {
67
+ navigator.requestMIDIAccess().then(
68
+ midiAccess => {
69
+ console.log("MIDI Access obtained.");
70
+ for (let input of midiAccess.inputs.values()) {
71
+ input.onmidimessage = (event) => faustNode.midiMessage(event.data);
72
+ console.log(`Connected to input: ${input.name}`);
73
+ }
74
+ },
75
+ () => console.error("Failed to access MIDI devices.")
76
+ );
77
+ } else {
78
+ console.log("Web MIDI API is not supported in this browser.");
79
+ }
80
+ }
81
+
82
+ // Function to stop MIDI
83
+ function stopMIDI() {
84
+ // Check if the browser supports the Web MIDI API
85
+ if (navigator.requestMIDIAccess) {
86
+ navigator.requestMIDIAccess().then(
87
+ midiAccess => {
88
+ console.log("MIDI Access obtained.");
89
+ for (let input of midiAccess.inputs.values()) {
90
+ input.onmidimessage = null;
91
+ console.log(`Disconnected from input: ${input.name}`);
92
+ }
93
+ },
94
+ () => console.error("Failed to access MIDI devices.")
95
+ );
96
+ } else {
97
+ console.log("Web MIDI API is not supported in this browser.");
98
+ }
99
+ }
100
+
101
+ let sensorHandlersBound = false;
102
+ let midiHandlersBound = false;
103
+
104
+ // Keyboard to MIDI handing
105
+ let keyboard2MIDI = null;
106
+
107
+ async function startKeyboard2MIDI() {
108
+ // Import the create-node module
109
+ const { createKey2MIDI } = await import("./create-node.js");
110
+
111
+ keyboard2MIDI = createKey2MIDI((event) => faustNode.midiMessage(event));
112
+ keyboard2MIDI.start();
113
+ }
114
+
115
+ function stopKeyboard2MIDI() {
116
+ keyboard2MIDI.stop();
117
+ keyboard2MIDI = null;
118
+ }
119
+
120
+ // Function to activate MIDI and Sensors on user interaction
121
+ async function activateMIDISensors() {
122
+
123
+ // Import the create-node module
124
+ const { connectToAudioInput, requestPermissions } = await import("./create-node.js");
125
+
126
+ // Request permission for sensors
127
+ await requestPermissions();
128
+
129
+ // Activate sensor listeners
130
+ if (!sensorHandlersBound) {
131
+ await faustNode.startSensors();
132
+ sensorHandlersBound = true;
133
+ }
134
+
135
+ // Initialize the MIDI setup
136
+ if (!midiHandlersBound) {
137
+ startMIDI();
138
+ await startKeyboard2MIDI();
139
+ midiHandlersBound = true;
140
+ }
141
+
142
+ // Connect the Faust node to the audio output
143
+ faustNode.connect(audioContext.destination);
144
+
145
+ // Connect the Faust node to the audio input
146
+ if (faustNode.numberOfInputs > 0) {
147
+ await connectToAudioInput(audioContext, null, faustNode, null);
148
+ }
149
+
150
+ // Resume the AudioContext
151
+ if (audioContext.state === 'suspended') {
152
+ await audioContext.resume();
153
+ }
154
+ }
155
+
156
+ // Function to suspend AudioContext, deactivate MIDI and Sensors on user interaction
157
+ async function deactivateAudioMIDISensors() {
158
+
159
+ // Suspend the AudioContext
160
+ if (audioContext.state === 'running') {
161
+ await audioContext.suspend();
162
+ }
163
+
164
+ // Deactivate sensor listeners
165
+ if (sensorHandlersBound) {
166
+ faustNode.stopSensors();
167
+ sensorHandlersBound = false;
168
+ }
169
+
170
+ // Deactivate the MIDI setup
171
+ if (midiHandlersBound && FAUST_DSP_VOICES > 0) {
172
+ stopMIDI();
173
+ stopKeyboard2MIDI();
174
+ midiHandlersBound = false;
175
+ }
176
+ }
177
+
178
+ // Event listener to handle user interaction
179
+ function handleUserInteraction() {
180
+
181
+ // Resume AudioContext synchronously
182
+ resumeAudioContext();
183
+
184
+ // Launch the activation of MIDI and Sensors
185
+ activateMIDISensors().catch(error => {
186
+ console.error('Error when activating audio, MIDI and sensors:', error);
187
+ });
188
+ }
189
+
190
+ // Activate AudioContext, MIDI and Sensors on user interaction
191
+ window.addEventListener('click', handleUserInteraction);
192
+ window.addEventListener('touchstart', handleUserInteraction);
193
+
194
+ // Deactivate AudioContext, MIDI and Sensors on user interaction
195
+ window.addEventListener('visibilitychange', function () {
196
+ if (window.visibilityState === 'hidden') {
197
+ deactivateAudioMIDISensors();
198
+ }
199
+ });
200
+
201
+
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "Faust organ",
3
+ "short_name": "organ",
4
+ "start_url": "./index.html",
5
+ "description": "Progressive Web App for organ",
6
+ "display": "standalone",
7
+ "background_color": "#ffffff",
8
+ "theme_color": "#000000",
9
+ "orientation": "portrait",
10
+ "icons": [
11
+ {
12
+ "src": "./icon.png",
13
+ "sizes": "390x390",
14
+ "type": "image/png"
15
+ }
16
+ ]
17
+ }
Binary file
@@ -0,0 +1,165 @@
1
+ /// <reference lib="webworker" />
2
+
3
+ // Set to > 0 if the DSP is polyphonic
4
+ const FAUST_DSP_VOICES = 0;
5
+ // Set to true if the DSP has an effect
6
+ const FAUST_DSP_HAS_EFFECT = false;
7
+
8
+ const CACHE_NAME = "organ_20250522-1139"; // Cache name with versioning
9
+
10
+ /**
11
+ * List of essential resources required for the **Mono DSP** version of the application.
12
+ *
13
+ * - These files are cached to enable offline functionality and improve loading speed.
14
+ * - Includes the main HTML, JavaScript, and CSS files required for the app.
15
+ * - Contains Faust-related files needed for DSP processing.
16
+ */
17
+ const MONO_RESOURCES = [
18
+ "./index.html",
19
+ "./index.js",
20
+ "./create-node.js",
21
+ "./faust-ui/index.js",
22
+ "./faust-ui/index.css",
23
+ "./faustwasm/index.js",
24
+ "./dsp-module.wasm",
25
+ "./dsp-meta.json"
26
+ ];
27
+
28
+ /**
29
+ * List of resources for the **Polyphonic DSP** version of the application.
30
+ *
31
+ * - Extends the mono resource list by adding a **mixer module**.
32
+ * - The mixer module is required to handle multiple simultaneous voices used in a polyphonic instrument.
33
+ */
34
+ const POLY_RESOURCES = [
35
+ ...MONO_RESOURCES,
36
+ "./mixer-module.wasm",
37
+ ];
38
+
39
+ /**
40
+ * List of resources for the **Polyphonic DSP with Effects** version.
41
+ *
42
+ * - Extends the polyphonic resource list by adding an **effect module**.
43
+ * - The effect module allows applying audio effects to the polyphonic instrument.
44
+ */
45
+ const POLY_EFFECT_RESOURCES = [
46
+ ...POLY_RESOURCES,
47
+ "./effect-module.wasm",
48
+ "./effect-meta.json",
49
+ ];
50
+
51
+ /** @type {ServiceWorkerGlobalScope} */
52
+ const serviceWorkerGlobalScope = self;
53
+
54
+ /**
55
+ * Install the service worker, cache essential resources, and prepare for immediate activation.
56
+ *
57
+ * - Opens the cache and stores required assets based on the app's configuration.
58
+ * - Ensures resources are preloaded for offline access.
59
+ */
60
+ serviceWorkerGlobalScope.addEventListener("install", (event) => {
61
+ console.log("Service worker installed");
62
+ event.waitUntil((async () => {
63
+ const cache = await caches.open(CACHE_NAME);
64
+ const resources = (FAUST_DSP_VOICES && FAUST_DSP_HAS_EFFECT) ? POLY_EFFECT_RESOURCES : (FAUST_DSP_VOICES ? POLY_RESOURCES : MONO_RESOURCES);
65
+ try {
66
+ return cache.addAll(resources);
67
+ } catch (error) {
68
+ console.error("Failed to cache resources during install:", error);
69
+ }
70
+ })());
71
+ });
72
+
73
+ /**
74
+ * Handles the activation of the Service Worker.
75
+ *
76
+ * - Claims control over all clients immediately, bypassing the default behavior that
77
+ * requires a page reload before the new service worker takes effect.
78
+ * - Once claimed, it finds all active window clients and reloads them to ensure they are
79
+ * controlled by the latest version of the service worker.
80
+ * - This approach ensures that updates to the service worker take effect immediately
81
+ * across all open pages, preventing potential inconsistencies.
82
+ */
83
+ serviceWorkerGlobalScope.addEventListener("activate", (event) => {
84
+ console.log("Service worker activated");
85
+ event.waitUntil(
86
+ clients.claim().then(() => {
87
+ return clients.matchAll({ type: "window" }).then((clients) => {
88
+ clients.forEach((client) => {
89
+ client.navigate(client.url);
90
+ });
91
+ });
92
+ })
93
+ );
94
+ });
95
+
96
+ /**
97
+ * Adjusts response headers to enforce Cross-Origin Opener Policy (COOP) and Cross-Origin Embedder Policy (COEP).
98
+ *
99
+ * - Ensures that the response is served with `Cross-Origin-Opener-Policy: same-origin`
100
+ * and `Cross-Origin-Embedder-Policy: require-corp`.
101
+ * - Required for enabling **cross-origin isolated** environments in web applications.
102
+ * - Necessary for features like **SharedArrayBuffer**, WebAssembly threads, and
103
+ * high-performance APIs that require isolation.
104
+ * - Creates a new `Response` object with the modified headers while preserving
105
+ * the original response body and status.
106
+ *
107
+ * @param {Response} response - The original HTTP response object.
108
+ * @returns {Response} A new response with updated security headers.
109
+ */
110
+ const getCrossOriginIsolatedResponse = (response) => {
111
+ // Modify headers to include COOP & COEP
112
+ const headers = new Headers(response.headers);
113
+ headers.set("Cross-Origin-Opener-Policy", "same-origin");
114
+ headers.set("Cross-Origin-Embedder-Policy", "require-corp");
115
+
116
+ // Create a new response with the modified headers
117
+ const modifiedResponse = new Response(response.body, {
118
+ status: response.status,
119
+ statusText: response.statusText,
120
+ headers
121
+ });
122
+
123
+ return modifiedResponse;
124
+ };
125
+
126
+ /**
127
+ * Intercepts fetch requests and enforces COOP and COEP headers for security.
128
+ *
129
+ * - Checks if the requested resource is available in the cache:
130
+ * - If found, returns a cached response with `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` headers.
131
+ * - If not found, fetches the resource from the network, applies COOP/COEP headers, and caches the response (for GET requests).
132
+ * - Ensures cross-origin isolation, required for APIs like `SharedArrayBuffer` and WebAssembly threading.
133
+ * - Handles network errors gracefully by returning a 503 "Service Unavailable" response when needed.
134
+ *
135
+ * @param {FetchEvent} event - The fetch event triggered by the browser.
136
+ */
137
+ serviceWorkerGlobalScope.addEventListener("fetch", (event) => {
138
+
139
+ event.respondWith((async () => {
140
+ const cache = await caches.open(CACHE_NAME);
141
+ const cachedResponse = await cache.match(event.request);
142
+
143
+ if (cachedResponse) {
144
+ return getCrossOriginIsolatedResponse(cachedResponse);
145
+ } else {
146
+ try {
147
+ const fetchResponse = await fetch(event.request);
148
+
149
+ if (event.request.method === "GET" && fetchResponse && fetchResponse.status === 200 && fetchResponse.type === "basic") {
150
+ const modifiedResponse = getCrossOriginIsolatedResponse(fetchResponse);
151
+ // Store the modified response in the cache
152
+ await cache.put(event.request, modifiedResponse.clone());
153
+ // Return the modified response to the browser
154
+ return modifiedResponse;
155
+ }
156
+
157
+ return fetchResponse;
158
+ } catch (error) {
159
+ console.error("Network access error", error);
160
+ return new Response("Network error", { status: 503, statusText: "Service Unavailable" });
161
+ }
162
+ }
163
+ })());
164
+ });
165
+