@grame/faustwasm 0.1.4 → 0.1.6

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.
@@ -0,0 +1,4470 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
20
+ mod
21
+ ));
22
+
23
+ // node_modules/tslib/tslib.js
24
+ var require_tslib = __commonJS({
25
+ "node_modules/tslib/tslib.js"(exports, module) {
26
+ var __extends;
27
+ var __assign;
28
+ var __rest;
29
+ var __decorate;
30
+ var __param;
31
+ var __metadata;
32
+ var __awaiter;
33
+ var __generator;
34
+ var __exportStar;
35
+ var __values;
36
+ var __read;
37
+ var __spread;
38
+ var __spreadArrays;
39
+ var __await;
40
+ var __asyncGenerator;
41
+ var __asyncDelegator;
42
+ var __asyncValues;
43
+ var __makeTemplateObject;
44
+ var __importStar;
45
+ var __importDefault;
46
+ var __classPrivateFieldGet;
47
+ var __classPrivateFieldSet;
48
+ var __createBinding;
49
+ (function(factory) {
50
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
51
+ if (typeof define === "function" && define.amd) {
52
+ define("tslib", ["exports"], function(exports2) {
53
+ factory(createExporter(root, createExporter(exports2)));
54
+ });
55
+ } else if (typeof module === "object" && typeof module.exports === "object") {
56
+ factory(createExporter(root, createExporter(module.exports)));
57
+ } else {
58
+ factory(createExporter(root));
59
+ }
60
+ function createExporter(exports2, previous) {
61
+ if (exports2 !== root) {
62
+ if (typeof Object.create === "function") {
63
+ Object.defineProperty(exports2, "__esModule", { value: true });
64
+ } else {
65
+ exports2.__esModule = true;
66
+ }
67
+ }
68
+ return function(id, v) {
69
+ return exports2[id] = previous ? previous(id, v) : v;
70
+ };
71
+ }
72
+ })(function(exporter) {
73
+ var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
74
+ d.__proto__ = b;
75
+ } || function(d, b) {
76
+ for (var p in b)
77
+ if (b.hasOwnProperty(p))
78
+ d[p] = b[p];
79
+ };
80
+ __extends = function(d, b) {
81
+ extendStatics(d, b);
82
+ function __() {
83
+ this.constructor = d;
84
+ }
85
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
86
+ };
87
+ __assign = Object.assign || function(t) {
88
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
89
+ s = arguments[i];
90
+ for (var p in s)
91
+ if (Object.prototype.hasOwnProperty.call(s, p))
92
+ t[p] = s[p];
93
+ }
94
+ return t;
95
+ };
96
+ __rest = function(s, e) {
97
+ var t = {};
98
+ for (var p in s)
99
+ if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
100
+ t[p] = s[p];
101
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
102
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
103
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
104
+ t[p[i]] = s[p[i]];
105
+ }
106
+ return t;
107
+ };
108
+ __decorate = function(decorators, target, key, desc) {
109
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
110
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
111
+ r = Reflect.decorate(decorators, target, key, desc);
112
+ else
113
+ for (var i = decorators.length - 1; i >= 0; i--)
114
+ if (d = decorators[i])
115
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
116
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
117
+ };
118
+ __param = function(paramIndex, decorator) {
119
+ return function(target, key) {
120
+ decorator(target, key, paramIndex);
121
+ };
122
+ };
123
+ __metadata = function(metadataKey, metadataValue) {
124
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
125
+ return Reflect.metadata(metadataKey, metadataValue);
126
+ };
127
+ __awaiter = function(thisArg, _arguments, P, generator) {
128
+ function adopt(value) {
129
+ return value instanceof P ? value : new P(function(resolve) {
130
+ resolve(value);
131
+ });
132
+ }
133
+ return new (P || (P = Promise))(function(resolve, reject) {
134
+ function fulfilled(value) {
135
+ try {
136
+ step(generator.next(value));
137
+ } catch (e) {
138
+ reject(e);
139
+ }
140
+ }
141
+ function rejected(value) {
142
+ try {
143
+ step(generator["throw"](value));
144
+ } catch (e) {
145
+ reject(e);
146
+ }
147
+ }
148
+ function step(result) {
149
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
150
+ }
151
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
152
+ });
153
+ };
154
+ __generator = function(thisArg, body) {
155
+ var _ = { label: 0, sent: function() {
156
+ if (t[0] & 1)
157
+ throw t[1];
158
+ return t[1];
159
+ }, trys: [], ops: [] }, f, y, t, g;
160
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
161
+ return this;
162
+ }), g;
163
+ function verb(n) {
164
+ return function(v) {
165
+ return step([n, v]);
166
+ };
167
+ }
168
+ function step(op) {
169
+ if (f)
170
+ throw new TypeError("Generator is already executing.");
171
+ while (_)
172
+ try {
173
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
174
+ return t;
175
+ if (y = 0, t)
176
+ op = [op[0] & 2, t.value];
177
+ switch (op[0]) {
178
+ case 0:
179
+ case 1:
180
+ t = op;
181
+ break;
182
+ case 4:
183
+ _.label++;
184
+ return { value: op[1], done: false };
185
+ case 5:
186
+ _.label++;
187
+ y = op[1];
188
+ op = [0];
189
+ continue;
190
+ case 7:
191
+ op = _.ops.pop();
192
+ _.trys.pop();
193
+ continue;
194
+ default:
195
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
196
+ _ = 0;
197
+ continue;
198
+ }
199
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
200
+ _.label = op[1];
201
+ break;
202
+ }
203
+ if (op[0] === 6 && _.label < t[1]) {
204
+ _.label = t[1];
205
+ t = op;
206
+ break;
207
+ }
208
+ if (t && _.label < t[2]) {
209
+ _.label = t[2];
210
+ _.ops.push(op);
211
+ break;
212
+ }
213
+ if (t[2])
214
+ _.ops.pop();
215
+ _.trys.pop();
216
+ continue;
217
+ }
218
+ op = body.call(thisArg, _);
219
+ } catch (e) {
220
+ op = [6, e];
221
+ y = 0;
222
+ } finally {
223
+ f = t = 0;
224
+ }
225
+ if (op[0] & 5)
226
+ throw op[1];
227
+ return { value: op[0] ? op[1] : void 0, done: true };
228
+ }
229
+ };
230
+ __createBinding = function(o, m, k, k2) {
231
+ if (k2 === void 0)
232
+ k2 = k;
233
+ o[k2] = m[k];
234
+ };
235
+ __exportStar = function(m, exports2) {
236
+ for (var p in m)
237
+ if (p !== "default" && !exports2.hasOwnProperty(p))
238
+ exports2[p] = m[p];
239
+ };
240
+ __values = function(o) {
241
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
242
+ if (m)
243
+ return m.call(o);
244
+ if (o && typeof o.length === "number")
245
+ return {
246
+ next: function() {
247
+ if (o && i >= o.length)
248
+ o = void 0;
249
+ return { value: o && o[i++], done: !o };
250
+ }
251
+ };
252
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
253
+ };
254
+ __read = function(o, n) {
255
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
256
+ if (!m)
257
+ return o;
258
+ var i = m.call(o), r, ar = [], e;
259
+ try {
260
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
261
+ ar.push(r.value);
262
+ } catch (error) {
263
+ e = { error };
264
+ } finally {
265
+ try {
266
+ if (r && !r.done && (m = i["return"]))
267
+ m.call(i);
268
+ } finally {
269
+ if (e)
270
+ throw e.error;
271
+ }
272
+ }
273
+ return ar;
274
+ };
275
+ __spread = function() {
276
+ for (var ar = [], i = 0; i < arguments.length; i++)
277
+ ar = ar.concat(__read(arguments[i]));
278
+ return ar;
279
+ };
280
+ __spreadArrays = function() {
281
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++)
282
+ s += arguments[i].length;
283
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
284
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
285
+ r[k] = a[j];
286
+ return r;
287
+ };
288
+ __await = function(v) {
289
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
290
+ };
291
+ __asyncGenerator = function(thisArg, _arguments, generator) {
292
+ if (!Symbol.asyncIterator)
293
+ throw new TypeError("Symbol.asyncIterator is not defined.");
294
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
295
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
296
+ return this;
297
+ }, i;
298
+ function verb(n) {
299
+ if (g[n])
300
+ i[n] = function(v) {
301
+ return new Promise(function(a, b) {
302
+ q.push([n, v, a, b]) > 1 || resume(n, v);
303
+ });
304
+ };
305
+ }
306
+ function resume(n, v) {
307
+ try {
308
+ step(g[n](v));
309
+ } catch (e) {
310
+ settle(q[0][3], e);
311
+ }
312
+ }
313
+ function step(r) {
314
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
315
+ }
316
+ function fulfill(value) {
317
+ resume("next", value);
318
+ }
319
+ function reject(value) {
320
+ resume("throw", value);
321
+ }
322
+ function settle(f, v) {
323
+ if (f(v), q.shift(), q.length)
324
+ resume(q[0][0], q[0][1]);
325
+ }
326
+ };
327
+ __asyncDelegator = function(o) {
328
+ var i, p;
329
+ return i = {}, verb("next"), verb("throw", function(e) {
330
+ throw e;
331
+ }), verb("return"), i[Symbol.iterator] = function() {
332
+ return this;
333
+ }, i;
334
+ function verb(n, f) {
335
+ i[n] = o[n] ? function(v) {
336
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
337
+ } : f;
338
+ }
339
+ };
340
+ __asyncValues = function(o) {
341
+ if (!Symbol.asyncIterator)
342
+ throw new TypeError("Symbol.asyncIterator is not defined.");
343
+ var m = o[Symbol.asyncIterator], i;
344
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
345
+ return this;
346
+ }, i);
347
+ function verb(n) {
348
+ i[n] = o[n] && function(v) {
349
+ return new Promise(function(resolve, reject) {
350
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
351
+ });
352
+ };
353
+ }
354
+ function settle(resolve, reject, d, v) {
355
+ Promise.resolve(v).then(function(v2) {
356
+ resolve({ value: v2, done: d });
357
+ }, reject);
358
+ }
359
+ };
360
+ __makeTemplateObject = function(cooked, raw) {
361
+ if (Object.defineProperty) {
362
+ Object.defineProperty(cooked, "raw", { value: raw });
363
+ } else {
364
+ cooked.raw = raw;
365
+ }
366
+ return cooked;
367
+ };
368
+ __importStar = function(mod) {
369
+ if (mod && mod.__esModule)
370
+ return mod;
371
+ var result = {};
372
+ if (mod != null) {
373
+ for (var k in mod)
374
+ if (Object.hasOwnProperty.call(mod, k))
375
+ result[k] = mod[k];
376
+ }
377
+ result["default"] = mod;
378
+ return result;
379
+ };
380
+ __importDefault = function(mod) {
381
+ return mod && mod.__esModule ? mod : { "default": mod };
382
+ };
383
+ __classPrivateFieldGet = function(receiver, privateMap) {
384
+ if (!privateMap.has(receiver)) {
385
+ throw new TypeError("attempted to get private field on non-instance");
386
+ }
387
+ return privateMap.get(receiver);
388
+ };
389
+ __classPrivateFieldSet = function(receiver, privateMap, value) {
390
+ if (!privateMap.has(receiver)) {
391
+ throw new TypeError("attempted to set private field on non-instance");
392
+ }
393
+ privateMap.set(receiver, value);
394
+ return value;
395
+ };
396
+ exporter("__extends", __extends);
397
+ exporter("__assign", __assign);
398
+ exporter("__rest", __rest);
399
+ exporter("__decorate", __decorate);
400
+ exporter("__param", __param);
401
+ exporter("__metadata", __metadata);
402
+ exporter("__awaiter", __awaiter);
403
+ exporter("__generator", __generator);
404
+ exporter("__exportStar", __exportStar);
405
+ exporter("__createBinding", __createBinding);
406
+ exporter("__values", __values);
407
+ exporter("__read", __read);
408
+ exporter("__spread", __spread);
409
+ exporter("__spreadArrays", __spreadArrays);
410
+ exporter("__await", __await);
411
+ exporter("__asyncGenerator", __asyncGenerator);
412
+ exporter("__asyncDelegator", __asyncDelegator);
413
+ exporter("__asyncValues", __asyncValues);
414
+ exporter("__makeTemplateObject", __makeTemplateObject);
415
+ exporter("__importStar", __importStar);
416
+ exporter("__importDefault", __importDefault);
417
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
418
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
419
+ });
420
+ }
421
+ });
422
+
423
+ // node_modules/@aws-crypto/sha256-js/build/constants.js
424
+ var require_constants = __commonJS({
425
+ "node_modules/@aws-crypto/sha256-js/build/constants.js"(exports) {
426
+ "use strict";
427
+ Object.defineProperty(exports, "__esModule", { value: true });
428
+ exports.MAX_HASHABLE_LENGTH = exports.INIT = exports.KEY = exports.DIGEST_LENGTH = exports.BLOCK_SIZE = void 0;
429
+ exports.BLOCK_SIZE = 64;
430
+ exports.DIGEST_LENGTH = 32;
431
+ exports.KEY = new Uint32Array([
432
+ 1116352408,
433
+ 1899447441,
434
+ 3049323471,
435
+ 3921009573,
436
+ 961987163,
437
+ 1508970993,
438
+ 2453635748,
439
+ 2870763221,
440
+ 3624381080,
441
+ 310598401,
442
+ 607225278,
443
+ 1426881987,
444
+ 1925078388,
445
+ 2162078206,
446
+ 2614888103,
447
+ 3248222580,
448
+ 3835390401,
449
+ 4022224774,
450
+ 264347078,
451
+ 604807628,
452
+ 770255983,
453
+ 1249150122,
454
+ 1555081692,
455
+ 1996064986,
456
+ 2554220882,
457
+ 2821834349,
458
+ 2952996808,
459
+ 3210313671,
460
+ 3336571891,
461
+ 3584528711,
462
+ 113926993,
463
+ 338241895,
464
+ 666307205,
465
+ 773529912,
466
+ 1294757372,
467
+ 1396182291,
468
+ 1695183700,
469
+ 1986661051,
470
+ 2177026350,
471
+ 2456956037,
472
+ 2730485921,
473
+ 2820302411,
474
+ 3259730800,
475
+ 3345764771,
476
+ 3516065817,
477
+ 3600352804,
478
+ 4094571909,
479
+ 275423344,
480
+ 430227734,
481
+ 506948616,
482
+ 659060556,
483
+ 883997877,
484
+ 958139571,
485
+ 1322822218,
486
+ 1537002063,
487
+ 1747873779,
488
+ 1955562222,
489
+ 2024104815,
490
+ 2227730452,
491
+ 2361852424,
492
+ 2428436474,
493
+ 2756734187,
494
+ 3204031479,
495
+ 3329325298
496
+ ]);
497
+ exports.INIT = [
498
+ 1779033703,
499
+ 3144134277,
500
+ 1013904242,
501
+ 2773480762,
502
+ 1359893119,
503
+ 2600822924,
504
+ 528734635,
505
+ 1541459225
506
+ ];
507
+ exports.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;
508
+ }
509
+ });
510
+
511
+ // node_modules/@aws-crypto/sha256-js/build/RawSha256.js
512
+ var require_RawSha256 = __commonJS({
513
+ "node_modules/@aws-crypto/sha256-js/build/RawSha256.js"(exports) {
514
+ "use strict";
515
+ Object.defineProperty(exports, "__esModule", { value: true });
516
+ exports.RawSha256 = void 0;
517
+ var constants_1 = require_constants();
518
+ var RawSha256 = function() {
519
+ function RawSha2562() {
520
+ this.state = Int32Array.from(constants_1.INIT);
521
+ this.temp = new Int32Array(64);
522
+ this.buffer = new Uint8Array(64);
523
+ this.bufferLength = 0;
524
+ this.bytesHashed = 0;
525
+ this.finished = false;
526
+ }
527
+ RawSha2562.prototype.update = function(data) {
528
+ if (this.finished) {
529
+ throw new Error("Attempted to update an already finished hash.");
530
+ }
531
+ var position = 0;
532
+ var byteLength = data.byteLength;
533
+ this.bytesHashed += byteLength;
534
+ if (this.bytesHashed * 8 > constants_1.MAX_HASHABLE_LENGTH) {
535
+ throw new Error("Cannot hash more than 2^53 - 1 bits");
536
+ }
537
+ while (byteLength > 0) {
538
+ this.buffer[this.bufferLength++] = data[position++];
539
+ byteLength--;
540
+ if (this.bufferLength === constants_1.BLOCK_SIZE) {
541
+ this.hashBuffer();
542
+ this.bufferLength = 0;
543
+ }
544
+ }
545
+ };
546
+ RawSha2562.prototype.digest = function() {
547
+ if (!this.finished) {
548
+ var bitsHashed = this.bytesHashed * 8;
549
+ var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
550
+ var undecoratedLength = this.bufferLength;
551
+ bufferView.setUint8(this.bufferLength++, 128);
552
+ if (undecoratedLength % constants_1.BLOCK_SIZE >= constants_1.BLOCK_SIZE - 8) {
553
+ for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE; i++) {
554
+ bufferView.setUint8(i, 0);
555
+ }
556
+ this.hashBuffer();
557
+ this.bufferLength = 0;
558
+ }
559
+ for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE - 8; i++) {
560
+ bufferView.setUint8(i, 0);
561
+ }
562
+ bufferView.setUint32(constants_1.BLOCK_SIZE - 8, Math.floor(bitsHashed / 4294967296), true);
563
+ bufferView.setUint32(constants_1.BLOCK_SIZE - 4, bitsHashed);
564
+ this.hashBuffer();
565
+ this.finished = true;
566
+ }
567
+ var out = new Uint8Array(constants_1.DIGEST_LENGTH);
568
+ for (var i = 0; i < 8; i++) {
569
+ out[i * 4] = this.state[i] >>> 24 & 255;
570
+ out[i * 4 + 1] = this.state[i] >>> 16 & 255;
571
+ out[i * 4 + 2] = this.state[i] >>> 8 & 255;
572
+ out[i * 4 + 3] = this.state[i] >>> 0 & 255;
573
+ }
574
+ return out;
575
+ };
576
+ RawSha2562.prototype.hashBuffer = function() {
577
+ var _a = this, buffer = _a.buffer, state = _a.state;
578
+ var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];
579
+ for (var i = 0; i < constants_1.BLOCK_SIZE; i++) {
580
+ if (i < 16) {
581
+ this.temp[i] = (buffer[i * 4] & 255) << 24 | (buffer[i * 4 + 1] & 255) << 16 | (buffer[i * 4 + 2] & 255) << 8 | buffer[i * 4 + 3] & 255;
582
+ } else {
583
+ var u = this.temp[i - 2];
584
+ var t1_1 = (u >>> 17 | u << 15) ^ (u >>> 19 | u << 13) ^ u >>> 10;
585
+ u = this.temp[i - 15];
586
+ var t2_1 = (u >>> 7 | u << 25) ^ (u >>> 18 | u << 14) ^ u >>> 3;
587
+ this.temp[i] = (t1_1 + this.temp[i - 7] | 0) + (t2_1 + this.temp[i - 16] | 0);
588
+ }
589
+ var t1 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (constants_1.KEY[i] + this.temp[i] | 0) | 0) | 0;
590
+ var t2 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0;
591
+ state7 = state6;
592
+ state6 = state5;
593
+ state5 = state4;
594
+ state4 = state3 + t1 | 0;
595
+ state3 = state2;
596
+ state2 = state1;
597
+ state1 = state0;
598
+ state0 = t1 + t2 | 0;
599
+ }
600
+ state[0] += state0;
601
+ state[1] += state1;
602
+ state[2] += state2;
603
+ state[3] += state3;
604
+ state[4] += state4;
605
+ state[5] += state5;
606
+ state[6] += state6;
607
+ state[7] += state7;
608
+ };
609
+ return RawSha2562;
610
+ }();
611
+ exports.RawSha256 = RawSha256;
612
+ }
613
+ });
614
+
615
+ // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js
616
+ var require_pureJs = __commonJS({
617
+ "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js"(exports) {
618
+ "use strict";
619
+ Object.defineProperty(exports, "__esModule", { value: true });
620
+ exports.toUtf8 = exports.fromUtf8 = void 0;
621
+ var fromUtf8 = (input) => {
622
+ const bytes = [];
623
+ for (let i = 0, len = input.length; i < len; i++) {
624
+ const value = input.charCodeAt(i);
625
+ if (value < 128) {
626
+ bytes.push(value);
627
+ } else if (value < 2048) {
628
+ bytes.push(value >> 6 | 192, value & 63 | 128);
629
+ } else if (i + 1 < input.length && (value & 64512) === 55296 && (input.charCodeAt(i + 1) & 64512) === 56320) {
630
+ const surrogatePair = 65536 + ((value & 1023) << 10) + (input.charCodeAt(++i) & 1023);
631
+ bytes.push(surrogatePair >> 18 | 240, surrogatePair >> 12 & 63 | 128, surrogatePair >> 6 & 63 | 128, surrogatePair & 63 | 128);
632
+ } else {
633
+ bytes.push(value >> 12 | 224, value >> 6 & 63 | 128, value & 63 | 128);
634
+ }
635
+ }
636
+ return Uint8Array.from(bytes);
637
+ };
638
+ exports.fromUtf8 = fromUtf8;
639
+ var toUtf8 = (input) => {
640
+ let decoded = "";
641
+ for (let i = 0, len = input.length; i < len; i++) {
642
+ const byte = input[i];
643
+ if (byte < 128) {
644
+ decoded += String.fromCharCode(byte);
645
+ } else if (192 <= byte && byte < 224) {
646
+ const nextByte = input[++i];
647
+ decoded += String.fromCharCode((byte & 31) << 6 | nextByte & 63);
648
+ } else if (240 <= byte && byte < 365) {
649
+ const surrogatePair = [byte, input[++i], input[++i], input[++i]];
650
+ const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%");
651
+ decoded += decodeURIComponent(encoded);
652
+ } else {
653
+ decoded += String.fromCharCode((byte & 15) << 12 | (input[++i] & 63) << 6 | input[++i] & 63);
654
+ }
655
+ }
656
+ return decoded;
657
+ };
658
+ exports.toUtf8 = toUtf8;
659
+ }
660
+ });
661
+
662
+ // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js
663
+ var require_whatwgEncodingApi = __commonJS({
664
+ "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js"(exports) {
665
+ "use strict";
666
+ Object.defineProperty(exports, "__esModule", { value: true });
667
+ exports.toUtf8 = exports.fromUtf8 = void 0;
668
+ function fromUtf8(input) {
669
+ return new TextEncoder().encode(input);
670
+ }
671
+ exports.fromUtf8 = fromUtf8;
672
+ function toUtf8(input) {
673
+ return new TextDecoder("utf-8").decode(input);
674
+ }
675
+ exports.toUtf8 = toUtf8;
676
+ }
677
+ });
678
+
679
+ // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js
680
+ var require_dist_cjs = __commonJS({
681
+ "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js"(exports) {
682
+ "use strict";
683
+ Object.defineProperty(exports, "__esModule", { value: true });
684
+ exports.toUtf8 = exports.fromUtf8 = void 0;
685
+ var pureJs_1 = require_pureJs();
686
+ var whatwgEncodingApi_1 = require_whatwgEncodingApi();
687
+ var fromUtf8 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input);
688
+ exports.fromUtf8 = fromUtf8;
689
+ var toUtf8 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input);
690
+ exports.toUtf8 = toUtf8;
691
+ }
692
+ });
693
+
694
+ // node_modules/@aws-crypto/util/build/convertToBuffer.js
695
+ var require_convertToBuffer = __commonJS({
696
+ "node_modules/@aws-crypto/util/build/convertToBuffer.js"(exports) {
697
+ "use strict";
698
+ Object.defineProperty(exports, "__esModule", { value: true });
699
+ exports.convertToBuffer = void 0;
700
+ var util_utf8_browser_1 = require_dist_cjs();
701
+ var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
702
+ return Buffer.from(input, "utf8");
703
+ } : util_utf8_browser_1.fromUtf8;
704
+ function convertToBuffer(data) {
705
+ if (data instanceof Uint8Array)
706
+ return data;
707
+ if (typeof data === "string") {
708
+ return fromUtf8(data);
709
+ }
710
+ if (ArrayBuffer.isView(data)) {
711
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
712
+ }
713
+ return new Uint8Array(data);
714
+ }
715
+ exports.convertToBuffer = convertToBuffer;
716
+ }
717
+ });
718
+
719
+ // node_modules/@aws-crypto/util/build/isEmptyData.js
720
+ var require_isEmptyData = __commonJS({
721
+ "node_modules/@aws-crypto/util/build/isEmptyData.js"(exports) {
722
+ "use strict";
723
+ Object.defineProperty(exports, "__esModule", { value: true });
724
+ exports.isEmptyData = void 0;
725
+ function isEmptyData(data) {
726
+ if (typeof data === "string") {
727
+ return data.length === 0;
728
+ }
729
+ return data.byteLength === 0;
730
+ }
731
+ exports.isEmptyData = isEmptyData;
732
+ }
733
+ });
734
+
735
+ // node_modules/@aws-crypto/util/build/numToUint8.js
736
+ var require_numToUint8 = __commonJS({
737
+ "node_modules/@aws-crypto/util/build/numToUint8.js"(exports) {
738
+ "use strict";
739
+ Object.defineProperty(exports, "__esModule", { value: true });
740
+ exports.numToUint8 = void 0;
741
+ function numToUint8(num) {
742
+ return new Uint8Array([
743
+ (num & 4278190080) >> 24,
744
+ (num & 16711680) >> 16,
745
+ (num & 65280) >> 8,
746
+ num & 255
747
+ ]);
748
+ }
749
+ exports.numToUint8 = numToUint8;
750
+ }
751
+ });
752
+
753
+ // node_modules/@aws-crypto/util/build/uint32ArrayFrom.js
754
+ var require_uint32ArrayFrom = __commonJS({
755
+ "node_modules/@aws-crypto/util/build/uint32ArrayFrom.js"(exports) {
756
+ "use strict";
757
+ Object.defineProperty(exports, "__esModule", { value: true });
758
+ exports.uint32ArrayFrom = void 0;
759
+ function uint32ArrayFrom(a_lookUpTable) {
760
+ if (!Uint32Array.from) {
761
+ var return_array = new Uint32Array(a_lookUpTable.length);
762
+ var a_index = 0;
763
+ while (a_index < a_lookUpTable.length) {
764
+ return_array[a_index] = a_lookUpTable[a_index];
765
+ a_index += 1;
766
+ }
767
+ return return_array;
768
+ }
769
+ return Uint32Array.from(a_lookUpTable);
770
+ }
771
+ exports.uint32ArrayFrom = uint32ArrayFrom;
772
+ }
773
+ });
774
+
775
+ // node_modules/@aws-crypto/util/build/index.js
776
+ var require_build = __commonJS({
777
+ "node_modules/@aws-crypto/util/build/index.js"(exports) {
778
+ "use strict";
779
+ Object.defineProperty(exports, "__esModule", { value: true });
780
+ exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0;
781
+ var convertToBuffer_1 = require_convertToBuffer();
782
+ Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() {
783
+ return convertToBuffer_1.convertToBuffer;
784
+ } });
785
+ var isEmptyData_1 = require_isEmptyData();
786
+ Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() {
787
+ return isEmptyData_1.isEmptyData;
788
+ } });
789
+ var numToUint8_1 = require_numToUint8();
790
+ Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() {
791
+ return numToUint8_1.numToUint8;
792
+ } });
793
+ var uint32ArrayFrom_1 = require_uint32ArrayFrom();
794
+ Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() {
795
+ return uint32ArrayFrom_1.uint32ArrayFrom;
796
+ } });
797
+ }
798
+ });
799
+
800
+ // node_modules/@aws-crypto/sha256-js/build/jsSha256.js
801
+ var require_jsSha256 = __commonJS({
802
+ "node_modules/@aws-crypto/sha256-js/build/jsSha256.js"(exports) {
803
+ "use strict";
804
+ Object.defineProperty(exports, "__esModule", { value: true });
805
+ exports.Sha256 = void 0;
806
+ var tslib_1 = require_tslib();
807
+ var constants_1 = require_constants();
808
+ var RawSha256_1 = require_RawSha256();
809
+ var util_1 = require_build();
810
+ var Sha2562 = function() {
811
+ function Sha2563(secret) {
812
+ this.hash = new RawSha256_1.RawSha256();
813
+ if (secret) {
814
+ this.outer = new RawSha256_1.RawSha256();
815
+ var inner = bufferFromSecret(secret);
816
+ var outer = new Uint8Array(constants_1.BLOCK_SIZE);
817
+ outer.set(inner);
818
+ for (var i = 0; i < constants_1.BLOCK_SIZE; i++) {
819
+ inner[i] ^= 54;
820
+ outer[i] ^= 92;
821
+ }
822
+ this.hash.update(inner);
823
+ this.outer.update(outer);
824
+ for (var i = 0; i < inner.byteLength; i++) {
825
+ inner[i] = 0;
826
+ }
827
+ }
828
+ }
829
+ Sha2563.prototype.update = function(toHash) {
830
+ if ((0, util_1.isEmptyData)(toHash) || this.error) {
831
+ return;
832
+ }
833
+ try {
834
+ this.hash.update((0, util_1.convertToBuffer)(toHash));
835
+ } catch (e) {
836
+ this.error = e;
837
+ }
838
+ };
839
+ Sha2563.prototype.digestSync = function() {
840
+ if (this.error) {
841
+ throw this.error;
842
+ }
843
+ if (this.outer) {
844
+ if (!this.outer.finished) {
845
+ this.outer.update(this.hash.digest());
846
+ }
847
+ return this.outer.digest();
848
+ }
849
+ return this.hash.digest();
850
+ };
851
+ Sha2563.prototype.digest = function() {
852
+ return tslib_1.__awaiter(this, void 0, void 0, function() {
853
+ return tslib_1.__generator(this, function(_a) {
854
+ return [2, this.digestSync()];
855
+ });
856
+ });
857
+ };
858
+ return Sha2563;
859
+ }();
860
+ exports.Sha256 = Sha2562;
861
+ function bufferFromSecret(secret) {
862
+ var input = (0, util_1.convertToBuffer)(secret);
863
+ if (input.byteLength > constants_1.BLOCK_SIZE) {
864
+ var bufferHash = new RawSha256_1.RawSha256();
865
+ bufferHash.update(input);
866
+ input = bufferHash.digest();
867
+ }
868
+ var buffer = new Uint8Array(constants_1.BLOCK_SIZE);
869
+ buffer.set(input);
870
+ return buffer;
871
+ }
872
+ }
873
+ });
874
+
875
+ // node_modules/@aws-crypto/sha256-js/build/index.js
876
+ var require_build2 = __commonJS({
877
+ "node_modules/@aws-crypto/sha256-js/build/index.js"(exports) {
878
+ "use strict";
879
+ Object.defineProperty(exports, "__esModule", { value: true });
880
+ var tslib_1 = require_tslib();
881
+ tslib_1.__exportStar(require_jsSha256(), exports);
882
+ }
883
+ });
884
+
885
+ // src/instantiateFaustModuleFromFile.ts
886
+ var instantiateFaustModuleFromFile = async (jsFile, dataFile = jsFile.replace(/c?js$/, "data"), wasmFile = jsFile.replace(/c?js$/, "wasm")) => {
887
+ var _a, _b;
888
+ let FaustModule;
889
+ let dataBinary;
890
+ let wasmBinary;
891
+ const jsCodeHead = /var (.+) = \(/;
892
+ if (typeof window === "object") {
893
+ let jsCode = await (await fetch(jsFile)).text();
894
+ jsCode = `${jsCode}
895
+ export default ${(_a = jsCode.match(jsCodeHead)) == null ? void 0 : _a[1]};
896
+ `;
897
+ const jsFileMod = URL.createObjectURL(new Blob([jsCode], { type: "text/javascript" }));
898
+ FaustModule = (await import(
899
+ /* webpackIgnore: true */
900
+ jsFileMod
901
+ )).default;
902
+ dataBinary = await (await fetch(dataFile)).arrayBuffer();
903
+ wasmBinary = new Uint8Array(await (await fetch(wasmFile)).arrayBuffer());
904
+ } else {
905
+ const { promises: fs } = await import("fs");
906
+ const { pathToFileURL } = await import("url");
907
+ let jsCode = await fs.readFile(jsFile, { encoding: "utf-8" });
908
+ jsCode = `
909
+ import process from "process";
910
+ import * as path from "path";
911
+ import { createRequire } from "module";
912
+ import { fileURLToPath } from "url";
913
+
914
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
915
+ const __filename = fileURLToPath(import.meta.url);
916
+ const require = createRequire(import.meta.url);
917
+
918
+ ${jsCode}
919
+
920
+ export default ${(_b = jsCode.match(jsCodeHead)) == null ? void 0 : _b[1]};
921
+ `;
922
+ const jsFileMod = jsFile.replace(/c?js$/, "mjs");
923
+ await fs.writeFile(jsFileMod, jsCode);
924
+ FaustModule = (await import(
925
+ /* webpackIgnore: true */
926
+ pathToFileURL(jsFileMod).href
927
+ )).default;
928
+ await fs.unlink(jsFileMod);
929
+ dataBinary = (await fs.readFile(dataFile)).buffer;
930
+ wasmBinary = (await fs.readFile(wasmFile)).buffer;
931
+ }
932
+ const faustModule = await FaustModule({
933
+ wasmBinary,
934
+ getPreloadedPackage: (remotePackageName, remotePackageSize) => {
935
+ if (remotePackageName === "libfaust-wasm.data")
936
+ return dataBinary;
937
+ return new ArrayBuffer(0);
938
+ }
939
+ });
940
+ return faustModule;
941
+ };
942
+ var instantiateFaustModuleFromFile_default = instantiateFaustModuleFromFile;
943
+
944
+ // src/FaustAudioWorkletProcessor.ts
945
+ var getFaustAudioWorkletProcessor = (dependencies, faustData, register = true) => {
946
+ const { registerProcessor, AudioWorkletProcessor, sampleRate } = globalThis;
947
+ const {
948
+ FaustBaseWebAudioDsp: FaustBaseWebAudioDsp2,
949
+ FaustWasmInstantiator: FaustWasmInstantiator2
950
+ } = dependencies;
951
+ const {
952
+ processorName,
953
+ dspName,
954
+ dspMeta,
955
+ effectMeta,
956
+ poly
957
+ } = faustData;
958
+ const analysePolyParameters = (item) => {
959
+ const polyKeywords = ["/gate", "/freq", "/gain", "/key", "/vel", "/velocity"];
960
+ const isPolyReserved = "address" in item && !!polyKeywords.find((k) => item.address.endsWith(k));
961
+ if (poly && isPolyReserved)
962
+ return null;
963
+ if (item.type === "vslider" || item.type === "hslider" || item.type === "nentry") {
964
+ return { name: item.address, defaultValue: item.init || 0, minValue: item.min || 0, maxValue: item.max || 0 };
965
+ } else if (item.type === "button" || item.type === "checkbox") {
966
+ return { name: item.address, defaultValue: item.init || 0, minValue: 0, maxValue: 1 };
967
+ }
968
+ return null;
969
+ };
970
+ class FaustAudioWorkletProcessor extends AudioWorkletProcessor {
971
+ constructor(options) {
972
+ super(options);
973
+ this.paramValuesCache = {};
974
+ this.port.onmessage = (e) => this.handleMessageAux(e);
975
+ const { parameterDescriptors } = this.constructor;
976
+ parameterDescriptors.forEach((pd) => {
977
+ this.paramValuesCache[pd.name] = pd.defaultValue || 0;
978
+ });
979
+ }
980
+ static get parameterDescriptors() {
981
+ const params = [];
982
+ const callback = (item) => {
983
+ const param = analysePolyParameters(item);
984
+ if (param)
985
+ params.push(param);
986
+ };
987
+ FaustBaseWebAudioDsp2.parseUI(dspMeta.ui, callback);
988
+ if (effectMeta)
989
+ FaustBaseWebAudioDsp2.parseUI(effectMeta.ui, callback);
990
+ return params;
991
+ }
992
+ process(inputs, outputs, parameters) {
993
+ for (const path in parameters) {
994
+ const [paramValue] = parameters[path];
995
+ if (paramValue !== this.paramValuesCache[path]) {
996
+ this.fDSPCode.setParamValue(path, paramValue);
997
+ this.paramValuesCache[path] = paramValue;
998
+ }
999
+ }
1000
+ return this.fDSPCode.compute(inputs[0], outputs[0]);
1001
+ }
1002
+ handleMessageAux(e) {
1003
+ const msg = e.data;
1004
+ switch (msg.type) {
1005
+ case "midi":
1006
+ this.midiMessage(msg.data);
1007
+ break;
1008
+ case "ctrlChange":
1009
+ this.ctrlChange(msg.data[0], msg.data[1], msg.data[2]);
1010
+ break;
1011
+ case "pitchWheel":
1012
+ this.pitchWheel(msg.data[0], msg.data[1]);
1013
+ break;
1014
+ case "param":
1015
+ this.setParamValue(msg.data.path, msg.data.value);
1016
+ break;
1017
+ case "setPlotHandler": {
1018
+ if (msg.data) {
1019
+ this.fDSPCode.setPlotHandler((output, index, events) => this.port.postMessage({ type: "plot", value: output, index, events }));
1020
+ } else {
1021
+ this.fDSPCode.setPlotHandler(null);
1022
+ }
1023
+ break;
1024
+ }
1025
+ case "start": {
1026
+ this.fDSPCode.start();
1027
+ break;
1028
+ }
1029
+ case "stop": {
1030
+ this.fDSPCode.stop();
1031
+ break;
1032
+ }
1033
+ case "destroy": {
1034
+ this.port.close();
1035
+ this.fDSPCode.destroy();
1036
+ break;
1037
+ }
1038
+ default:
1039
+ break;
1040
+ }
1041
+ }
1042
+ setParamValue(path, value) {
1043
+ this.fDSPCode.setParamValue(path, value);
1044
+ this.paramValuesCache[path] = value;
1045
+ }
1046
+ midiMessage(data) {
1047
+ this.fDSPCode.midiMessage(data);
1048
+ }
1049
+ ctrlChange(channel, ctrl, value) {
1050
+ this.fDSPCode.ctrlChange(channel, ctrl, value);
1051
+ }
1052
+ pitchWheel(channel, wheel) {
1053
+ this.fDSPCode.pitchWheel(channel, wheel);
1054
+ }
1055
+ }
1056
+ class FaustMonoAudioWorkletProcessor extends FaustAudioWorkletProcessor {
1057
+ constructor(options) {
1058
+ super(options);
1059
+ const { FaustMonoWebAudioDsp: FaustMonoWebAudioDsp2 } = dependencies;
1060
+ const { factory, sampleSize } = options.processorOptions;
1061
+ const instance = FaustWasmInstantiator2.createSyncMonoDSPInstance(factory);
1062
+ this.fDSPCode = new FaustMonoWebAudioDsp2(instance, sampleRate, sampleSize, 128);
1063
+ if (this.fDSPCode.hasSoundfiles()) {
1064
+ console.error("FaustAudioWorkletProcessor: Soundfile support is not implemented yet, switch to ScriptProcessorNode for now");
1065
+ return;
1066
+ }
1067
+ this.fDSPCode.setOutputParamHandler((path, value) => this.port.postMessage({ path, value, type: "param" }));
1068
+ this.fDSPCode.start();
1069
+ }
1070
+ }
1071
+ class FaustPolyAudioWorkletProcessor extends FaustAudioWorkletProcessor {
1072
+ constructor(options) {
1073
+ super(options);
1074
+ this.handleMessageAux = (e) => {
1075
+ const msg = e.data;
1076
+ switch (msg.type) {
1077
+ case "keyOn":
1078
+ this.keyOn(msg.data[0], msg.data[1], msg.data[2]);
1079
+ break;
1080
+ case "keyOff":
1081
+ this.keyOff(msg.data[0], msg.data[1], msg.data[2]);
1082
+ break;
1083
+ default:
1084
+ super.handleMessageAux(e);
1085
+ break;
1086
+ }
1087
+ };
1088
+ const { FaustPolyWebAudioDsp: FaustPolyWebAudioDsp3 } = dependencies;
1089
+ const { voiceFactory, mixerModule, voices, effectFactory, sampleSize } = options.processorOptions;
1090
+ const instance = FaustWasmInstantiator2.createSyncPolyDSPInstance(voiceFactory, mixerModule, voices, effectFactory);
1091
+ this.fDSPCode = new FaustPolyWebAudioDsp3(instance, sampleRate, sampleSize, 128);
1092
+ if (this.fDSPCode.hasSoundfiles()) {
1093
+ console.error("FaustAudioWorkletProcessor: Soundfile support is not implemented yet, switch to ScriptProcessorNode for now");
1094
+ return;
1095
+ }
1096
+ this.port.onmessage = (e) => this.handleMessageAux(e);
1097
+ this.fDSPCode.setOutputParamHandler((path, value) => this.port.postMessage({ path, value, type: "param" }));
1098
+ this.fDSPCode.start();
1099
+ }
1100
+ midiMessage(data) {
1101
+ const cmd = data[0] >> 4;
1102
+ const channel = data[0] & 15;
1103
+ const data1 = data[1];
1104
+ const data2 = data[2];
1105
+ if (cmd === 8 || cmd === 9 && data2 === 0)
1106
+ this.keyOff(channel, data1, data2);
1107
+ else if (cmd === 9)
1108
+ this.keyOn(channel, data1, data2);
1109
+ else
1110
+ super.midiMessage(data);
1111
+ }
1112
+ keyOn(channel, pitch, velocity) {
1113
+ this.fDSPCode.keyOn(channel, pitch, velocity);
1114
+ }
1115
+ keyOff(channel, pitch, velocity) {
1116
+ this.fDSPCode.keyOff(channel, pitch, velocity);
1117
+ }
1118
+ allNotesOff(hard) {
1119
+ this.fDSPCode.allNotesOff(hard);
1120
+ }
1121
+ }
1122
+ const Processor = poly ? FaustPolyAudioWorkletProcessor : FaustMonoAudioWorkletProcessor;
1123
+ if (register) {
1124
+ try {
1125
+ registerProcessor(processorName || dspName || (poly ? "mydsp_poly" : "mydsp"), Processor);
1126
+ } catch (error) {
1127
+ console.warn(error);
1128
+ }
1129
+ }
1130
+ return poly ? FaustPolyAudioWorkletProcessor : FaustMonoAudioWorkletProcessor;
1131
+ };
1132
+ var FaustAudioWorkletProcessor_default = getFaustAudioWorkletProcessor;
1133
+
1134
+ // src/FaustFFTAudioWorkletProcessor.ts
1135
+ var getFaustFFTAudioWorkletProcessor = (dependencies, faustData, register = true) => {
1136
+ const { registerProcessor, AudioWorkletProcessor, sampleRate } = globalThis;
1137
+ const {
1138
+ FaustBaseWebAudioDsp: FaustBaseWebAudioDsp2,
1139
+ FaustWasmInstantiator: FaustWasmInstantiator2,
1140
+ FaustMonoWebAudioDsp: FaustMonoWebAudioDsp2,
1141
+ FFTUtils
1142
+ } = dependencies;
1143
+ const {
1144
+ processorName,
1145
+ dspName,
1146
+ dspMeta,
1147
+ fftOptions
1148
+ } = faustData;
1149
+ const {
1150
+ windowFunctions,
1151
+ getFFT,
1152
+ fftToSignal,
1153
+ signalToFFT,
1154
+ signalToNoFFT
1155
+ } = FFTUtils;
1156
+ const ceil = (x, to) => Math.abs(to) < 1 ? Math.ceil(x * (1 / to)) / (1 / to) : Math.ceil(x / to) * to;
1157
+ const mod = (x, y) => (x % y + y) % y;
1158
+ const apply = (array, windowFunction) => {
1159
+ for (let i = 0; i < array.length; i++) {
1160
+ array[i] *= windowFunction(i, array.length);
1161
+ }
1162
+ };
1163
+ const fftParamKeywords = ["/fftSize", "/fftHopSize", "/fftOverlap", "/windowFunction", "/noIFFT"];
1164
+ const setTypedArray = (to, from, offsetTo = 0, offsetFrom = 0) => {
1165
+ const toLength = to.length;
1166
+ const fromLength = from.length;
1167
+ const spillLength = Math.min(toLength, fromLength);
1168
+ let spilled = 0;
1169
+ let $to = mod(offsetTo, toLength) || 0;
1170
+ let $from = mod(offsetFrom, fromLength) || 0;
1171
+ while (spilled < spillLength) {
1172
+ const $spillLength = Math.min(spillLength - spilled, toLength - $to, fromLength - $from);
1173
+ const $fromEnd = $from + $spillLength;
1174
+ if ($from === 0 && $fromEnd === fromLength)
1175
+ to.set(from, $to);
1176
+ else
1177
+ to.set(from.subarray($from, $fromEnd), $to);
1178
+ $to = ($to + $spillLength) % toLength;
1179
+ $from = $fromEnd % fromLength;
1180
+ spilled += $spillLength;
1181
+ }
1182
+ return $to;
1183
+ };
1184
+ const analyseParameters = (item) => {
1185
+ const isFFTReserved = "address" in item && !!fftParamKeywords.find((k) => item.address.endsWith(k));
1186
+ if (isFFTReserved)
1187
+ return null;
1188
+ if (item.type === "vslider" || item.type === "hslider" || item.type === "nentry") {
1189
+ return { name: item.address, defaultValue: item.init || 0, minValue: item.min || 0, maxValue: item.max || 0 };
1190
+ } else if (item.type === "button" || item.type === "checkbox") {
1191
+ return { name: item.address, defaultValue: item.init || 0, minValue: 0, maxValue: 1 };
1192
+ }
1193
+ return null;
1194
+ };
1195
+ class FaustFFTAudioWorkletProcessor extends AudioWorkletProcessor {
1196
+ constructor(options) {
1197
+ super(options);
1198
+ this.paramValuesCache = {};
1199
+ this.destroyed = false;
1200
+ this.$inputWrite = 0;
1201
+ this.$inputRead = 0;
1202
+ this.$outputWrite = 0;
1203
+ this.$outputRead = 0;
1204
+ this.noIFFT = false;
1205
+ this.fftInput = [];
1206
+ this.fftOutput = [];
1207
+ this.fftOverlap = 0;
1208
+ this.fftHopSize = 0;
1209
+ this.fftSize = 0;
1210
+ this.fftBufferSize = 0;
1211
+ this.fPlotHandler = null;
1212
+ this.fCachedEvents = [];
1213
+ this.fBufferNum = 0;
1214
+ this.windowFunction = null;
1215
+ this.port.onmessage = (e) => this.handleMessageAux(e);
1216
+ const { parameterDescriptors } = this.constructor;
1217
+ parameterDescriptors.forEach((pd) => {
1218
+ this.paramValuesCache[pd.name] = pd.defaultValue || 0;
1219
+ });
1220
+ const { factory, sampleSize } = options.processorOptions;
1221
+ this.dspInstance = FaustWasmInstantiator2.createSyncMonoDSPInstance(factory);
1222
+ this.sampleSize = sampleSize;
1223
+ this.initFFT();
1224
+ }
1225
+ get fftProcessorBufferSize() {
1226
+ return this.fftSize / 2 + 1;
1227
+ }
1228
+ async initFFT() {
1229
+ this.FFT = await getFFT();
1230
+ await this.createFFTProcessor();
1231
+ return true;
1232
+ }
1233
+ static get parameterDescriptors() {
1234
+ const params = [];
1235
+ const callback = (item) => {
1236
+ const param = analyseParameters(item);
1237
+ if (param)
1238
+ params.push(param);
1239
+ };
1240
+ FaustBaseWebAudioDsp2.parseUI(dspMeta.ui, callback);
1241
+ return [
1242
+ ...params,
1243
+ {
1244
+ defaultValue: (fftOptions == null ? void 0 : fftOptions.fftSize) || 1024,
1245
+ maxValue: 2 ** 32,
1246
+ minValue: 2,
1247
+ name: "fftSize"
1248
+ },
1249
+ {
1250
+ defaultValue: (fftOptions == null ? void 0 : fftOptions.fftOverlap) || 2,
1251
+ maxValue: 32,
1252
+ minValue: 1,
1253
+ name: "fftOverlap"
1254
+ },
1255
+ {
1256
+ defaultValue: typeof (fftOptions == null ? void 0 : fftOptions.defaultWindowFunction) === "number" ? fftOptions.defaultWindowFunction + 1 : 0,
1257
+ maxValue: (windowFunctions == null ? void 0 : windowFunctions.length) || 0,
1258
+ minValue: 0,
1259
+ name: "windowFunction"
1260
+ },
1261
+ {
1262
+ defaultValue: +!!(fftOptions == null ? void 0 : fftOptions.noIFFT) || 0,
1263
+ maxValue: 1,
1264
+ minValue: 0,
1265
+ name: "noIFFT"
1266
+ }
1267
+ ];
1268
+ }
1269
+ processFFT() {
1270
+ let samplesForFFT = mod(this.$inputWrite - this.$inputRead, this.fftBufferSize) || this.fftBufferSize;
1271
+ while (samplesForFFT >= this.fftSize) {
1272
+ let fftProcessorOutputs = [];
1273
+ this.fDSPCode.compute((inputs) => {
1274
+ for (let i = 0; i < Math.min(this.fftInput.length, Math.ceil(inputs.length / 3)); i++) {
1275
+ const ffted = this.rfft.forward((fftBuffer) => {
1276
+ setTypedArray(fftBuffer, this.fftInput[i], 0, this.$inputRead);
1277
+ for (let j = 0; j < fftBuffer.length; j++) {
1278
+ fftBuffer[j] *= this.window[j];
1279
+ }
1280
+ });
1281
+ fftToSignal(ffted, inputs[i * 3], inputs[i * 3 + 1], inputs[i * 3 + 2]);
1282
+ }
1283
+ for (let i = this.fftInput.length * 3; i < inputs.length; i++) {
1284
+ if (i % 3 === 2)
1285
+ inputs[i].forEach((v, j) => inputs[i][j] = j);
1286
+ else
1287
+ inputs[i].fill(0);
1288
+ }
1289
+ }, (outputs) => {
1290
+ fftProcessorOutputs = outputs;
1291
+ });
1292
+ this.$inputRead += this.fftHopSize;
1293
+ this.$inputRead %= this.fftBufferSize;
1294
+ samplesForFFT -= this.fftHopSize;
1295
+ for (let i = 0; i < this.fftOutput.length; i++) {
1296
+ let iffted;
1297
+ if (this.noIFFT) {
1298
+ iffted = this.noIFFTBuffer;
1299
+ signalToNoFFT(fftProcessorOutputs[i * 2] || this.fftProcessorZeros, fftProcessorOutputs[i * 2 + 1] || this.fftProcessorZeros, iffted);
1300
+ } else {
1301
+ iffted = this.rfft.inverse((ifftBuffer) => {
1302
+ signalToFFT(fftProcessorOutputs[i * 2] || this.fftProcessorZeros, fftProcessorOutputs[i * 2 + 1] || this.fftProcessorZeros, ifftBuffer);
1303
+ });
1304
+ }
1305
+ for (let j = 0; j < iffted.length; j++) {
1306
+ iffted[j] *= this.window[j];
1307
+ }
1308
+ let $;
1309
+ for (let j = 0; j < iffted.length - this.fftHopSize; j++) {
1310
+ $ = mod(this.$outputWrite + j, this.fftBufferSize);
1311
+ this.fftOutput[i][$] += iffted[j];
1312
+ if (i === 0)
1313
+ this.windowSumSquare[$] += this.noIFFT ? this.window[j] : this.window[j] ** 2;
1314
+ }
1315
+ for (let j = iffted.length - this.fftHopSize; j < iffted.length; j++) {
1316
+ $ = mod(this.$outputWrite + j, this.fftBufferSize);
1317
+ this.fftOutput[i][$] = iffted[j];
1318
+ if (i === 0)
1319
+ this.windowSumSquare[$] = this.noIFFT ? this.window[j] : this.window[j] ** 2;
1320
+ }
1321
+ }
1322
+ this.$outputWrite += this.fftHopSize;
1323
+ this.$outputWrite %= this.fftBufferSize;
1324
+ }
1325
+ }
1326
+ process(inputs, outputs, parameters) {
1327
+ if (this.destroyed)
1328
+ return false;
1329
+ if (!this.FFT)
1330
+ return true;
1331
+ const input = inputs[0];
1332
+ const output = outputs[0];
1333
+ const inputChannels = (input == null ? void 0 : input.length) || 0;
1334
+ const outputChannels = (output == null ? void 0 : output.length) || 0;
1335
+ const bufferSize = (input == null ? void 0 : input.length) ? Math.max(...input.map((c) => c.length)) || 128 : 128;
1336
+ this.noIFFT = !!parameters.noIFFT[0];
1337
+ this.resetFFT(~~parameters.fftSize[0], ~~parameters.fftOverlap[0], ~~parameters.windowFunction[0], inputChannels, outputChannels, bufferSize);
1338
+ if (!this.fDSPCode)
1339
+ return true;
1340
+ for (const path in parameters) {
1341
+ if (!!fftParamKeywords.find((k) => `/${path}`.endsWith(k)))
1342
+ continue;
1343
+ const [paramValue] = parameters[path];
1344
+ if (paramValue !== this.paramValuesCache[path]) {
1345
+ this.fDSPCode.setParamValue(path, paramValue);
1346
+ this.paramValuesCache[path] = paramValue;
1347
+ }
1348
+ }
1349
+ if (input == null ? void 0 : input.length) {
1350
+ let $inputWrite = 0;
1351
+ for (let i = 0; i < input.length; i++) {
1352
+ const inputWindow = this.fftInput[i];
1353
+ const channel = input[i].length ? input[i] : new Float32Array(bufferSize);
1354
+ $inputWrite = setTypedArray(inputWindow, channel, this.$inputWrite);
1355
+ }
1356
+ this.$inputWrite = $inputWrite;
1357
+ } else {
1358
+ this.$inputWrite += bufferSize;
1359
+ this.$inputWrite %= this.fftBufferSize;
1360
+ }
1361
+ this.processFFT();
1362
+ for (let i = 0; i < output.length; i++) {
1363
+ setTypedArray(output[i], this.fftOutput[i], 0, this.$outputRead);
1364
+ let div = 0;
1365
+ for (let j = 0; j < bufferSize; j++) {
1366
+ div = this.windowSumSquare[mod(this.$outputRead + j, this.fftBufferSize)];
1367
+ output[i][j] /= div < 1e-8 ? 1 : div;
1368
+ }
1369
+ }
1370
+ this.$outputRead += bufferSize;
1371
+ this.$outputRead %= this.fftBufferSize;
1372
+ if (this.fPlotHandler) {
1373
+ this.port.postMessage({ type: "plot", value: output, index: this.fBufferNum++, events: this.fCachedEvents });
1374
+ this.fCachedEvents = [];
1375
+ }
1376
+ return true;
1377
+ }
1378
+ handleMessageAux(e) {
1379
+ var _a, _b, _c;
1380
+ const msg = e.data;
1381
+ switch (msg.type) {
1382
+ case "midi":
1383
+ this.midiMessage(msg.data);
1384
+ break;
1385
+ case "ctrlChange":
1386
+ this.ctrlChange(msg.data[0], msg.data[1], msg.data[2]);
1387
+ break;
1388
+ case "pitchWheel":
1389
+ this.pitchWheel(msg.data[0], msg.data[1]);
1390
+ break;
1391
+ case "param":
1392
+ this.setParamValue(msg.data.path, msg.data.value);
1393
+ break;
1394
+ case "setPlotHandler": {
1395
+ if (msg.data) {
1396
+ this.fPlotHandler = (output, index, events) => {
1397
+ if (events)
1398
+ this.fCachedEvents.push(...events);
1399
+ };
1400
+ } else {
1401
+ this.fPlotHandler = null;
1402
+ }
1403
+ (_a = this.fDSPCode) == null ? void 0 : _a.setPlotHandler(this.fPlotHandler);
1404
+ break;
1405
+ }
1406
+ case "start": {
1407
+ (_b = this.fDSPCode) == null ? void 0 : _b.start();
1408
+ break;
1409
+ }
1410
+ case "stop": {
1411
+ (_c = this.fDSPCode) == null ? void 0 : _c.stop();
1412
+ break;
1413
+ }
1414
+ case "destroy": {
1415
+ this.port.close();
1416
+ this.destroy();
1417
+ break;
1418
+ }
1419
+ default:
1420
+ break;
1421
+ }
1422
+ }
1423
+ setParamValue(path, value) {
1424
+ var _a;
1425
+ (_a = this.fDSPCode) == null ? void 0 : _a.setParamValue(path, value);
1426
+ this.paramValuesCache[path] = value;
1427
+ }
1428
+ midiMessage(data) {
1429
+ var _a;
1430
+ (_a = this.fDSPCode) == null ? void 0 : _a.midiMessage(data);
1431
+ }
1432
+ ctrlChange(channel, ctrl, value) {
1433
+ var _a;
1434
+ (_a = this.fDSPCode) == null ? void 0 : _a.ctrlChange(channel, ctrl, value);
1435
+ }
1436
+ pitchWheel(channel, wheel) {
1437
+ var _a;
1438
+ (_a = this.fDSPCode) == null ? void 0 : _a.pitchWheel(channel, wheel);
1439
+ }
1440
+ resetFFT(sizeIn, overlapIn, windowFunctionIn, inputChannels, outputChannels, bufferSize) {
1441
+ var _a, _b;
1442
+ const fftSize = ~~ceil(Math.max(2, sizeIn || 1024), 2);
1443
+ const fftOverlap = ~~Math.min(fftSize, Math.max(1, overlapIn));
1444
+ const fftHopSize = ~~Math.max(1, fftSize / fftOverlap);
1445
+ const latency = fftSize - Math.min(fftHopSize, bufferSize);
1446
+ let windowFunction = null;
1447
+ if (windowFunctionIn !== 0) {
1448
+ windowFunction = typeof windowFunctions === "object" ? windowFunctions[~~windowFunctionIn - 1] || null : null;
1449
+ }
1450
+ const fftSizeChanged = fftSize !== this.fftSize;
1451
+ const fftOverlapChanged = fftOverlap !== this.fftOverlap;
1452
+ if (fftSizeChanged || fftOverlapChanged) {
1453
+ this.fftSize = fftSize;
1454
+ this.fftOverlap = fftOverlap;
1455
+ this.fftHopSize = fftHopSize;
1456
+ this.$inputWrite = 0;
1457
+ this.$inputRead = 0;
1458
+ this.$outputWrite = 0;
1459
+ this.$outputRead = -latency;
1460
+ this.fftBufferSize = Math.max(fftSize * 2 - this.fftHopSize, bufferSize * 2);
1461
+ if (!fftSizeChanged && this.fftHopSizeParam)
1462
+ (_a = this.fDSPCode) == null ? void 0 : _a.setParamValue(this.fftHopSizeParam, this.fftHopSize);
1463
+ }
1464
+ if (fftSizeChanged) {
1465
+ (_b = this.rfft) == null ? void 0 : _b.dispose();
1466
+ this.rfft = new this.FFT(fftSize);
1467
+ this.noIFFTBuffer = new Float32Array(this.fftSize);
1468
+ this.createFFTProcessor();
1469
+ }
1470
+ if (fftSizeChanged || fftOverlapChanged || windowFunction !== this.windowFunction) {
1471
+ this.windowFunction = windowFunction;
1472
+ this.window = new Float32Array(fftSize);
1473
+ this.window.fill(1);
1474
+ if (windowFunction)
1475
+ apply(this.window, windowFunction);
1476
+ this.windowSumSquare = new Float32Array(this.fftBufferSize);
1477
+ }
1478
+ if (this.fftInput.length > inputChannels) {
1479
+ this.fftInput.splice(inputChannels);
1480
+ }
1481
+ if (this.fftOutput.length > outputChannels) {
1482
+ this.fftOutput.splice(outputChannels);
1483
+ }
1484
+ if (fftSizeChanged || fftOverlapChanged) {
1485
+ for (let i = 0; i < inputChannels; i++) {
1486
+ this.fftInput[i] = new Float32Array(this.fftBufferSize);
1487
+ }
1488
+ for (let i = 0; i < outputChannels; i++) {
1489
+ this.fftOutput[i] = new Float32Array(this.fftBufferSize);
1490
+ }
1491
+ } else {
1492
+ if (this.fftInput.length < inputChannels) {
1493
+ for (let i = this.fftInput.length; i < inputChannels; i++) {
1494
+ this.fftInput[i] = new Float32Array(this.fftBufferSize);
1495
+ }
1496
+ }
1497
+ if (this.fftOutput.length < outputChannels) {
1498
+ for (let i = this.fftOutput.length; i < outputChannels; i++) {
1499
+ this.fftOutput[i] = new Float32Array(this.fftBufferSize);
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1504
+ async createFFTProcessor() {
1505
+ var _a, _b;
1506
+ (_a = this.fDSPCode) == null ? void 0 : _a.stop();
1507
+ (_b = this.fDSPCode) == null ? void 0 : _b.destroy();
1508
+ this.fDSPCode = new FaustMonoWebAudioDsp2(this.dspInstance, sampleRate, this.sampleSize, this.fftProcessorBufferSize);
1509
+ this.fDSPCode.setOutputParamHandler((path, value) => this.port.postMessage({ path, value, type: "param" }));
1510
+ this.fDSPCode.setPlotHandler(this.fPlotHandler);
1511
+ const params = this.fDSPCode.getParams();
1512
+ this.fDSPCode.start();
1513
+ for (const path in this.paramValuesCache) {
1514
+ if (!!fftParamKeywords.find((k) => `/${path}`.endsWith(k)))
1515
+ continue;
1516
+ this.fDSPCode.setParamValue(path, this.paramValuesCache[path]);
1517
+ }
1518
+ const fftSizeParam = params.find((s) => s.endsWith("/fftSize"));
1519
+ if (fftSizeParam)
1520
+ this.fDSPCode.setParamValue(fftSizeParam, this.fftSize);
1521
+ this.fftHopSizeParam = params.find((s) => s.endsWith("/fftHopSize"));
1522
+ if (this.fftHopSizeParam)
1523
+ this.fDSPCode.setParamValue(this.fftHopSizeParam, this.fftHopSize);
1524
+ this.fftProcessorZeros = new Float32Array(this.fftProcessorBufferSize);
1525
+ }
1526
+ destroy() {
1527
+ var _a, _b, _c;
1528
+ (_a = this.fDSPCode) == null ? void 0 : _a.stop();
1529
+ (_b = this.fDSPCode) == null ? void 0 : _b.destroy();
1530
+ (_c = this.rfft) == null ? void 0 : _c.dispose();
1531
+ this.destroyed = true;
1532
+ }
1533
+ }
1534
+ const Processor = FaustFFTAudioWorkletProcessor;
1535
+ if (register) {
1536
+ try {
1537
+ registerProcessor(processorName || dspName || "myfftdsp", Processor);
1538
+ } catch (error) {
1539
+ console.warn(error);
1540
+ }
1541
+ }
1542
+ return FaustFFTAudioWorkletProcessor;
1543
+ };
1544
+ var FaustFFTAudioWorkletProcessor_default = getFaustFFTAudioWorkletProcessor;
1545
+
1546
+ // src/FaustCompiler.ts
1547
+ var import_sha256_js = __toESM(require_build2(), 1);
1548
+ var ab2str = (buf) => String.fromCharCode.apply(null, buf);
1549
+ var str2ab = (str) => {
1550
+ const buf = new ArrayBuffer(str.length);
1551
+ const bufView = new Uint8Array(buf);
1552
+ for (let i = 0, strLen = str.length; i < strLen; i++) {
1553
+ bufView[i] = str.charCodeAt(i);
1554
+ }
1555
+ return bufView;
1556
+ };
1557
+ var sha256 = async (str) => {
1558
+ const sha2562 = new import_sha256_js.Sha256();
1559
+ sha2562.update(str);
1560
+ const hashArray = Array.from(await sha2562.digest());
1561
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1562
+ return hashHex;
1563
+ };
1564
+ var _FaustCompiler = class {
1565
+ static serializeDSPFactories() {
1566
+ const table = {};
1567
+ this.gFactories.forEach((factory, shaKey) => {
1568
+ const { code, json, poly } = factory;
1569
+ table[shaKey] = { code: btoa(ab2str(code)), json: JSON.parse(json), poly };
1570
+ });
1571
+ return table;
1572
+ }
1573
+ static stringifyDSPFactories() {
1574
+ return JSON.stringify(this.serializeDSPFactories());
1575
+ }
1576
+ static deserializeDSPFactories(table) {
1577
+ const awaited = [];
1578
+ for (const shaKey in table) {
1579
+ const factory = table[shaKey];
1580
+ const { code, json, poly } = factory;
1581
+ const ab = str2ab(atob(code));
1582
+ awaited.push(WebAssembly.compile(ab).then((module) => this.gFactories.set(shaKey, { shaKey, cfactory: 0, code: ab, module, json: JSON.stringify(json), poly })));
1583
+ }
1584
+ return Promise.all(awaited);
1585
+ }
1586
+ static importDSPFactories(tableStr) {
1587
+ const table = JSON.parse(tableStr);
1588
+ return this.deserializeDSPFactories(table);
1589
+ }
1590
+ constructor(libFaust) {
1591
+ this.fLibFaust = libFaust;
1592
+ this.fErrorMessage = "";
1593
+ }
1594
+ intVec2intArray(vec) {
1595
+ const size = vec.size();
1596
+ const ui8Code = new Uint8Array(size);
1597
+ for (let i = 0; i < size; i++) {
1598
+ ui8Code[i] = vec.get(i);
1599
+ }
1600
+ return ui8Code;
1601
+ }
1602
+ async createDSPFactory(name, code, args, poly) {
1603
+ if (_FaustCompiler.gFactories.size > 10) {
1604
+ _FaustCompiler.gFactories.clear();
1605
+ }
1606
+ let shaKey = await sha256(name + code + args + (poly ? "poly" : "mono"));
1607
+ if (_FaustCompiler.gFactories.has(shaKey)) {
1608
+ return _FaustCompiler.gFactories.get(shaKey) || null;
1609
+ } else {
1610
+ try {
1611
+ const faustDspWasm = this.fLibFaust.createDSPFactory(name, code, args, !poly);
1612
+ const ui8Code = this.intVec2intArray(faustDspWasm.data);
1613
+ faustDspWasm.data.delete();
1614
+ const module = await WebAssembly.compile(ui8Code);
1615
+ const factory = { shaKey, cfactory: faustDspWasm.cfactory, code: ui8Code, module, json: faustDspWasm.json, poly };
1616
+ this.deleteDSPFactory(factory);
1617
+ _FaustCompiler.gFactories.set(shaKey, factory);
1618
+ return factory;
1619
+ } catch (e) {
1620
+ this.fErrorMessage = this.fLibFaust.getErrorAfterException();
1621
+ this.fLibFaust.cleanupAfterException();
1622
+ throw this.fErrorMessage ? new Error(this.fErrorMessage) : e;
1623
+ }
1624
+ }
1625
+ }
1626
+ version() {
1627
+ return this.fLibFaust.version();
1628
+ }
1629
+ getErrorMessage() {
1630
+ return this.fErrorMessage;
1631
+ }
1632
+ async createMonoDSPFactory(name, code, args) {
1633
+ return this.createDSPFactory(name, code, args, false);
1634
+ }
1635
+ async createPolyDSPFactory(name, code, args) {
1636
+ return this.createDSPFactory(name, code, args, true);
1637
+ }
1638
+ deleteDSPFactory(factory) {
1639
+ this.fLibFaust.deleteDSPFactory(factory.cfactory);
1640
+ factory.cfactory = 0;
1641
+ }
1642
+ expandDSP(code, args) {
1643
+ try {
1644
+ return this.fLibFaust.expandDSP("FaustDSP", code, args);
1645
+ } catch (e) {
1646
+ this.fErrorMessage = this.fLibFaust.getErrorAfterException();
1647
+ this.fLibFaust.cleanupAfterException();
1648
+ throw this.fErrorMessage ? new Error(this.fErrorMessage) : e;
1649
+ }
1650
+ }
1651
+ generateAuxFiles(name, code, args) {
1652
+ try {
1653
+ return this.fLibFaust.generateAuxFiles(name, code, args);
1654
+ } catch (e) {
1655
+ this.fErrorMessage = this.fLibFaust.getErrorAfterException();
1656
+ this.fLibFaust.cleanupAfterException();
1657
+ throw this.fErrorMessage ? new Error(this.fErrorMessage) : e;
1658
+ }
1659
+ }
1660
+ deleteAllDSPFactories() {
1661
+ this.fLibFaust.deleteAllDSPFactories();
1662
+ }
1663
+ fs() {
1664
+ return this.fLibFaust.fs();
1665
+ }
1666
+ async getAsyncInternalMixerModule(isDouble = false) {
1667
+ const bufferKey = isDouble ? "mixer64Buffer" : "mixer32Buffer";
1668
+ const moduleKey = isDouble ? "mixer64Module" : "mixer32Module";
1669
+ if (this[moduleKey])
1670
+ return { mixerBuffer: this[bufferKey], mixerModule: this[moduleKey] };
1671
+ const path = isDouble ? "/usr/rsrc/mixer64.wasm" : "/usr/rsrc/mixer32.wasm";
1672
+ const mixerBuffer = this.fs().readFile(path, { encoding: "binary" });
1673
+ this[bufferKey] = mixerBuffer;
1674
+ const mixerModule = await WebAssembly.compile(mixerBuffer);
1675
+ this[moduleKey] = mixerModule;
1676
+ return { mixerBuffer, mixerModule };
1677
+ }
1678
+ getSyncInternalMixerModule(isDouble = false) {
1679
+ const bufferKey = isDouble ? "mixer64Buffer" : "mixer32Buffer";
1680
+ const moduleKey = isDouble ? "mixer64Module" : "mixer32Module";
1681
+ if (this[moduleKey])
1682
+ return { mixerBuffer: this[bufferKey], mixerModule: this[moduleKey] };
1683
+ const path = isDouble ? "/usr/rsrc/mixer64.wasm" : "/usr/rsrc/mixer32.wasm";
1684
+ const mixerBuffer = this.fs().readFile(path, { encoding: "binary" });
1685
+ this[bufferKey] = mixerBuffer;
1686
+ const mixerModule = new WebAssembly.Module(mixerBuffer);
1687
+ this[moduleKey] = mixerModule;
1688
+ return { mixerBuffer, mixerModule };
1689
+ }
1690
+ };
1691
+ var FaustCompiler = _FaustCompiler;
1692
+ FaustCompiler.gFactories = /* @__PURE__ */ new Map();
1693
+ var FaustCompiler_default = FaustCompiler;
1694
+
1695
+ // src/FaustDspInstance.ts
1696
+ var FaustDspInstance = class {
1697
+ constructor(exports) {
1698
+ this.fExports = exports;
1699
+ }
1700
+ compute($dsp, count, $input, $output) {
1701
+ this.fExports.compute($dsp, count, $input, $output);
1702
+ }
1703
+ getNumInputs($dsp) {
1704
+ return this.fExports.getNumInputs($dsp);
1705
+ }
1706
+ getNumOutputs($dsp) {
1707
+ return this.fExports.getNumOutputs($dsp);
1708
+ }
1709
+ getParamValue($dsp, index) {
1710
+ return this.fExports.getParamValue($dsp, index);
1711
+ }
1712
+ getSampleRate($dsp) {
1713
+ return this.fExports.getSampleRate($dsp);
1714
+ }
1715
+ init($dsp, sampleRate) {
1716
+ this.fExports.init($dsp, sampleRate);
1717
+ }
1718
+ instanceClear($dsp) {
1719
+ this.fExports.instanceClear($dsp);
1720
+ }
1721
+ instanceConstants($dsp, sampleRate) {
1722
+ this.fExports.instanceConstants($dsp, sampleRate);
1723
+ }
1724
+ instanceInit($dsp, sampleRate) {
1725
+ this.fExports.instanceInit($dsp, sampleRate);
1726
+ }
1727
+ instanceResetUserInterface($dsp) {
1728
+ this.fExports.instanceResetUserInterface($dsp);
1729
+ }
1730
+ setParamValue($dsp, index, value) {
1731
+ this.fExports.setParamValue($dsp, index, value);
1732
+ }
1733
+ };
1734
+
1735
+ // src/FaustWasmInstantiator.ts
1736
+ var FaustWasmInstantiator = class {
1737
+ static createWasmImport(memory) {
1738
+ return {
1739
+ env: {
1740
+ memory: memory || new WebAssembly.Memory({ initial: 100 }),
1741
+ memoryBase: 0,
1742
+ tableBase: 0,
1743
+ _abs: Math.abs,
1744
+ _acosf: Math.acos,
1745
+ _asinf: Math.asin,
1746
+ _atanf: Math.atan,
1747
+ _atan2f: Math.atan2,
1748
+ _ceilf: Math.ceil,
1749
+ _cosf: Math.cos,
1750
+ _expf: Math.exp,
1751
+ _floorf: Math.floor,
1752
+ _fmodf: (x, y) => x % y,
1753
+ _logf: Math.log,
1754
+ _log10f: Math.log10,
1755
+ _max_f: Math.max,
1756
+ _min_f: Math.min,
1757
+ _remainderf: (x, y) => x - Math.round(x / y) * y,
1758
+ _powf: Math.pow,
1759
+ _roundf: Math.round,
1760
+ _sinf: Math.sin,
1761
+ _sqrtf: Math.sqrt,
1762
+ _tanf: Math.tan,
1763
+ _acoshf: Math.acosh,
1764
+ _asinhf: Math.asinh,
1765
+ _atanhf: Math.atanh,
1766
+ _coshf: Math.cosh,
1767
+ _sinhf: Math.sinh,
1768
+ _tanhf: Math.tanh,
1769
+ _isnanf: Number.isNaN,
1770
+ _isinff: (x) => !isFinite(x),
1771
+ _copysignf: (x, y) => Math.sign(x) === Math.sign(y) ? x : -x,
1772
+ _acos: Math.acos,
1773
+ _asin: Math.asin,
1774
+ _atan: Math.atan,
1775
+ _atan2: Math.atan2,
1776
+ _ceil: Math.ceil,
1777
+ _cos: Math.cos,
1778
+ _exp: Math.exp,
1779
+ _floor: Math.floor,
1780
+ _fmod: (x, y) => x % y,
1781
+ _log: Math.log,
1782
+ _log10: Math.log10,
1783
+ _max_: Math.max,
1784
+ _min_: Math.min,
1785
+ _remainder: (x, y) => x - Math.round(x / y) * y,
1786
+ _pow: Math.pow,
1787
+ _round: Math.round,
1788
+ _sin: Math.sin,
1789
+ _sqrt: Math.sqrt,
1790
+ _tan: Math.tan,
1791
+ _acosh: Math.acosh,
1792
+ _asinh: Math.asinh,
1793
+ _atanh: Math.atanh,
1794
+ _cosh: Math.cosh,
1795
+ _sinh: Math.sinh,
1796
+ _tanh: Math.tanh,
1797
+ _isnan: Number.isNaN,
1798
+ _isinf: (x) => !isFinite(x),
1799
+ _copysign: (x, y) => Math.sign(x) === Math.sign(y) ? x : -x,
1800
+ table: new WebAssembly.Table({ initial: 0, element: "anyfunc" })
1801
+ }
1802
+ };
1803
+ }
1804
+ static createWasmMemoryPoly(voicesIn, sampleSize, dspMeta, effectMeta, bufferSize) {
1805
+ const voices = Math.max(4, voicesIn);
1806
+ const ptrSize = sampleSize;
1807
+ const pow2limit = (x) => {
1808
+ let n = 65536;
1809
+ while (n < x) {
1810
+ n *= 2;
1811
+ }
1812
+ return n;
1813
+ };
1814
+ const effectSize = effectMeta ? effectMeta.size : 0;
1815
+ let memorySize = pow2limit(
1816
+ effectSize + dspMeta.size * voices + (dspMeta.inputs + dspMeta.outputs * 2) * (ptrSize + bufferSize * sampleSize)
1817
+ ) / 65536;
1818
+ memorySize = Math.max(2, memorySize);
1819
+ return new WebAssembly.Memory({ initial: memorySize });
1820
+ }
1821
+ static createWasmMemoryMono(sampleSize, dspMeta, bufferSize) {
1822
+ const ptrSize = sampleSize;
1823
+ const memorySize = (dspMeta.size + (dspMeta.inputs + dspMeta.outputs) * (ptrSize + bufferSize * sampleSize)) / 65536;
1824
+ return new WebAssembly.Memory({ initial: memorySize * 2 });
1825
+ }
1826
+ static createMonoDSPInstanceAux(instance, json, mem = null) {
1827
+ const functions = instance.exports;
1828
+ const api = new FaustDspInstance(functions);
1829
+ const memory = mem ? mem : instance.exports.memory;
1830
+ return { memory, api, json };
1831
+ }
1832
+ static createMemoryMono(monoFactory) {
1833
+ const monoMeta = JSON.parse(monoFactory.json);
1834
+ const sampleSize = monoMeta.compile_options.match("-double") ? 8 : 4;
1835
+ return this.createWasmMemoryMono(sampleSize, monoMeta, 8192);
1836
+ }
1837
+ static createMemoryPoly(voices, voiceFactory, effectFactory) {
1838
+ const voiceMeta = JSON.parse(voiceFactory.json);
1839
+ const effectMeta = effectFactory && effectFactory.json ? JSON.parse(effectFactory.json) : null;
1840
+ const sampleSize = voiceMeta.compile_options.match("-double") ? 8 : 4;
1841
+ return this.createWasmMemoryPoly(voices, sampleSize, voiceMeta, effectMeta, 8192);
1842
+ }
1843
+ static createMixerAux(mixerModule, memory) {
1844
+ const mixerImport = {
1845
+ imports: { print: console.log },
1846
+ memory: { memory }
1847
+ };
1848
+ const mixerInstance = new WebAssembly.Instance(mixerModule, mixerImport);
1849
+ const mixerFunctions = mixerInstance.exports;
1850
+ return mixerFunctions;
1851
+ }
1852
+ static async loadDSPFactory(wasmPath, jsonPath) {
1853
+ const wasmFile = await fetch(wasmPath);
1854
+ if (!wasmFile.ok) {
1855
+ throw new Error(`=> exception raised while running loadDSPFactory, file not found: ${wasmPath}`);
1856
+ }
1857
+ try {
1858
+ const wasmBuffer = await wasmFile.arrayBuffer();
1859
+ const module = await WebAssembly.compile(wasmBuffer);
1860
+ const jsonFile = await fetch(jsonPath);
1861
+ const json = await jsonFile.text();
1862
+ const meta = JSON.parse(json);
1863
+ const cOptions = meta.compile_options;
1864
+ const poly = cOptions.indexOf("wasm-e") !== -1;
1865
+ return { cfactory: 0, code: new Uint8Array(wasmBuffer), module, json, poly };
1866
+ } catch (e) {
1867
+ throw e;
1868
+ }
1869
+ }
1870
+ static async loadDSPMixer(mixerPath, fs) {
1871
+ try {
1872
+ let mixerBuffer = null;
1873
+ if (fs) {
1874
+ mixerBuffer = fs.readFile(mixerPath, { encoding: "binary" });
1875
+ } else {
1876
+ const mixerFile = await fetch(mixerPath);
1877
+ mixerBuffer = await mixerFile.arrayBuffer();
1878
+ }
1879
+ return WebAssembly.compile(mixerBuffer);
1880
+ } catch (e) {
1881
+ throw e;
1882
+ }
1883
+ }
1884
+ static async createAsyncMonoDSPInstance(factory) {
1885
+ const pattern = /"type":\s*"soundfile"/;
1886
+ const isDetected = pattern.test(factory.json);
1887
+ if (isDetected) {
1888
+ const memory = this.createMemoryMono(factory);
1889
+ const instance = await WebAssembly.instantiate(factory.module, this.createWasmImport(memory));
1890
+ return this.createMonoDSPInstanceAux(instance, factory.json, memory);
1891
+ } else {
1892
+ const instance = await WebAssembly.instantiate(factory.module, this.createWasmImport());
1893
+ return this.createMonoDSPInstanceAux(instance, factory.json);
1894
+ }
1895
+ }
1896
+ static createSyncMonoDSPInstance(factory) {
1897
+ const pattern = /"type":\s*"soundfile"/;
1898
+ const isDetected = pattern.test(factory.json);
1899
+ if (isDetected) {
1900
+ const memory = this.createMemoryMono(factory);
1901
+ const instance = new WebAssembly.Instance(factory.module, this.createWasmImport(memory));
1902
+ return this.createMonoDSPInstanceAux(instance, factory.json, memory);
1903
+ } else {
1904
+ const instance = new WebAssembly.Instance(factory.module, this.createWasmImport());
1905
+ return this.createMonoDSPInstanceAux(instance, factory.json);
1906
+ }
1907
+ }
1908
+ static async createAsyncPolyDSPInstance(voiceFactory, mixerModule, voices, effectFactory) {
1909
+ const memory = this.createMemoryPoly(voices, voiceFactory, effectFactory);
1910
+ const voiceInstance = await WebAssembly.instantiate(voiceFactory.module, this.createWasmImport(memory));
1911
+ const voiceFunctions = voiceInstance.exports;
1912
+ const voiceAPI = new FaustDspInstance(voiceFunctions);
1913
+ const mixerAPI = this.createMixerAux(mixerModule, memory);
1914
+ if (effectFactory) {
1915
+ const effectInstance = await WebAssembly.instantiate(effectFactory.module, this.createWasmImport(memory));
1916
+ const effectFunctions = effectInstance.exports;
1917
+ const effectAPI = new FaustDspInstance(effectFunctions);
1918
+ return {
1919
+ memory,
1920
+ voices,
1921
+ voiceAPI,
1922
+ effectAPI,
1923
+ mixerAPI,
1924
+ voiceJSON: voiceFactory.json,
1925
+ effectJSON: effectFactory.json
1926
+ };
1927
+ } else {
1928
+ return {
1929
+ memory,
1930
+ voices,
1931
+ voiceAPI,
1932
+ mixerAPI,
1933
+ voiceJSON: voiceFactory.json
1934
+ };
1935
+ }
1936
+ }
1937
+ static createSyncPolyDSPInstance(voiceFactory, mixerModule, voices, effectFactory) {
1938
+ const memory = this.createMemoryPoly(voices, voiceFactory, effectFactory);
1939
+ const voiceInstance = new WebAssembly.Instance(voiceFactory.module, this.createWasmImport(memory));
1940
+ const voiceFunctions = voiceInstance.exports;
1941
+ const voiceAPI = new FaustDspInstance(voiceFunctions);
1942
+ const mixerAPI = this.createMixerAux(mixerModule, memory);
1943
+ if (effectFactory) {
1944
+ const effectInstance = new WebAssembly.Instance(effectFactory.module, this.createWasmImport(memory));
1945
+ const effectFunctions = effectInstance.exports;
1946
+ const effectAPI = new FaustDspInstance(effectFunctions);
1947
+ return {
1948
+ memory,
1949
+ voices,
1950
+ voiceAPI,
1951
+ effectAPI,
1952
+ mixerAPI,
1953
+ voiceJSON: voiceFactory.json,
1954
+ effectJSON: effectFactory.json
1955
+ };
1956
+ } else {
1957
+ return {
1958
+ memory,
1959
+ voices,
1960
+ voiceAPI,
1961
+ mixerAPI,
1962
+ voiceJSON: voiceFactory.json
1963
+ };
1964
+ }
1965
+ }
1966
+ };
1967
+ var FaustWasmInstantiator_default = FaustWasmInstantiator;
1968
+
1969
+ // src/FaustSensors.ts
1970
+ var Range = class {
1971
+ constructor(x, y) {
1972
+ this.fLo = Math.min(x, y);
1973
+ this.fHi = Math.max(x, y);
1974
+ }
1975
+ clip(x) {
1976
+ if (x < this.fLo) {
1977
+ return this.fLo;
1978
+ } else if (x > this.fHi) {
1979
+ return this.fHi;
1980
+ } else {
1981
+ return x;
1982
+ }
1983
+ }
1984
+ };
1985
+ var Interpolator = class {
1986
+ constructor(lo, hi, v1, v2) {
1987
+ this.fRange = new Range(lo, hi);
1988
+ if (hi != lo) {
1989
+ this.fCoef = (v2 - v1) / (hi - lo);
1990
+ this.fOffset = v1 - lo * this.fCoef;
1991
+ } else {
1992
+ this.fCoef = 0;
1993
+ this.fOffset = (v1 + v2) / 2;
1994
+ }
1995
+ }
1996
+ returnMappedValue(v) {
1997
+ var x = this.fRange.clip(v);
1998
+ return this.fOffset + x * this.fCoef;
1999
+ }
2000
+ getLowHigh(amin, amax) {
2001
+ return { amin: this.fRange.fLo, amax: this.fRange.fHi };
2002
+ }
2003
+ };
2004
+ var Interpolator3pt = class {
2005
+ constructor(lo, mid, hi, v1, vMid, v2) {
2006
+ this.fSegment1 = new Interpolator(lo, mid, v1, vMid);
2007
+ this.fSegment2 = new Interpolator(mid, hi, vMid, v2);
2008
+ this.fMid = mid;
2009
+ }
2010
+ returnMappedValue(x) {
2011
+ return x < this.fMid ? this.fSegment1.returnMappedValue(x) : this.fSegment2.returnMappedValue(x);
2012
+ }
2013
+ getMappingValues(amin, amid, amax) {
2014
+ var lowHighSegment1 = this.fSegment1.getLowHigh(amin, amid);
2015
+ var lowHighSegment2 = this.fSegment2.getLowHigh(amid, amax);
2016
+ return { amin: lowHighSegment1.amin, amid: lowHighSegment2.amin, amax: lowHighSegment2.amax };
2017
+ }
2018
+ };
2019
+ var AccUpConverter = class {
2020
+ constructor(amin, amid, amax, fmin, fmid, fmax) {
2021
+ this.fActive = true;
2022
+ this.fA2F = new Interpolator3pt(amin, amid, amax, fmin, fmid, fmax);
2023
+ this.fF2A = new Interpolator3pt(fmin, fmid, fmax, amin, amid, amax);
2024
+ }
2025
+ uiToFaust(x) {
2026
+ return this.fA2F.returnMappedValue(x);
2027
+ }
2028
+ faustToUi(x) {
2029
+ return this.fF2A.returnMappedValue(x);
2030
+ }
2031
+ setMappingValues(amin, amid, amax, min, init, max) {
2032
+ this.fA2F = new Interpolator3pt(amin, amid, amax, min, init, max);
2033
+ this.fF2A = new Interpolator3pt(min, init, max, amin, amid, amax);
2034
+ }
2035
+ getMappingValues(amin, amid, amax) {
2036
+ return this.fA2F.getMappingValues(amin, amid, amax);
2037
+ }
2038
+ setActive(onOff) {
2039
+ this.fActive = onOff;
2040
+ }
2041
+ getActive() {
2042
+ return this.fActive;
2043
+ }
2044
+ };
2045
+ var AccDownConverter = class {
2046
+ constructor(amin, amid, amax, fmin, fmid, fmax) {
2047
+ this.fActive = true;
2048
+ this.fA2F = new Interpolator3pt(amin, amid, amax, fmax, fmid, fmin);
2049
+ this.fF2A = new Interpolator3pt(fmin, fmid, fmax, amax, amid, amin);
2050
+ }
2051
+ uiToFaust(x) {
2052
+ return this.fA2F.returnMappedValue(x);
2053
+ }
2054
+ faustToUi(x) {
2055
+ return this.fF2A.returnMappedValue(x);
2056
+ }
2057
+ setMappingValues(amin, amid, amax, min, init, max) {
2058
+ this.fA2F = new Interpolator3pt(amin, amid, amax, max, init, min);
2059
+ this.fF2A = new Interpolator3pt(min, init, max, amax, amid, amin);
2060
+ }
2061
+ getMappingValues(amin, amid, amax) {
2062
+ return this.fA2F.getMappingValues(amin, amid, amax);
2063
+ }
2064
+ setActive(onOff) {
2065
+ this.fActive = onOff;
2066
+ }
2067
+ getActive() {
2068
+ return this.fActive;
2069
+ }
2070
+ };
2071
+ var AccUpDownConverter = class {
2072
+ constructor(amin, amid, amax, fmin, fmid, fmax) {
2073
+ this.fActive = true;
2074
+ this.fA2F = new Interpolator3pt(amin, amid, amax, fmin, fmax, fmin);
2075
+ this.fF2A = new Interpolator(fmin, fmax, amin, amax);
2076
+ }
2077
+ uiToFaust(x) {
2078
+ return this.fA2F.returnMappedValue(x);
2079
+ }
2080
+ faustToUi(x) {
2081
+ return this.fF2A.returnMappedValue(x);
2082
+ }
2083
+ setMappingValues(amin, amid, amax, min, init, max) {
2084
+ this.fA2F = new Interpolator3pt(amin, amid, amax, min, max, min);
2085
+ this.fF2A = new Interpolator(min, max, amin, amax);
2086
+ }
2087
+ getMappingValues(amin, amid, amax) {
2088
+ return this.fA2F.getMappingValues(amin, amid, amax);
2089
+ }
2090
+ setActive(onOff) {
2091
+ this.fActive = onOff;
2092
+ }
2093
+ getActive() {
2094
+ return this.fActive;
2095
+ }
2096
+ };
2097
+ var AccDownUpConverter = class {
2098
+ constructor(amin, amid, amax, fmin, fmid, fmax) {
2099
+ this.fActive = true;
2100
+ this.fA2F = new Interpolator3pt(amin, amid, amax, fmax, fmin, fmax);
2101
+ this.fF2A = new Interpolator(fmin, fmax, amin, amax);
2102
+ }
2103
+ uiToFaust(x) {
2104
+ return this.fA2F.returnMappedValue(x);
2105
+ }
2106
+ faustToUi(x) {
2107
+ return this.fF2A.returnMappedValue(x);
2108
+ }
2109
+ setMappingValues(amin, amid, amax, min, init, max) {
2110
+ this.fA2F = new Interpolator3pt(amin, amid, amax, max, min, max);
2111
+ this.fF2A = new Interpolator(min, max, amin, amax);
2112
+ }
2113
+ getMappingValues(amin, amid, amax) {
2114
+ return this.fA2F.getMappingValues(amin, amid, amax);
2115
+ }
2116
+ setActive(onOff) {
2117
+ this.fActive = onOff;
2118
+ }
2119
+ getActive() {
2120
+ return this.fActive;
2121
+ }
2122
+ };
2123
+ function buildAccHandler(curve, amin, amid, amax, min, init, max) {
2124
+ switch (curve) {
2125
+ case 0 /* Up */:
2126
+ return new AccUpConverter(amin, amid, amax, min, init, max);
2127
+ case 1 /* Down */:
2128
+ return new AccDownConverter(amin, amid, amax, min, init, max);
2129
+ case 2 /* UpDown */:
2130
+ return new AccUpDownConverter(amin, amid, amax, min, init, max);
2131
+ case 3 /* DownUp */:
2132
+ return new AccDownUpConverter(amin, amid, amax, min, init, max);
2133
+ default:
2134
+ return new AccUpConverter(amin, amid, amax, min, init, max);
2135
+ }
2136
+ }
2137
+
2138
+ // src/FaustWebAudioDsp.ts
2139
+ var WasmAllocator = class {
2140
+ constructor(memory, offset) {
2141
+ this.memory = memory;
2142
+ this.allocatedBytes = offset;
2143
+ }
2144
+ alloc(sizeInBytes) {
2145
+ const currentOffset = this.allocatedBytes;
2146
+ const newOffset = currentOffset + sizeInBytes;
2147
+ const totalMemoryBytes = this.memory.buffer.byteLength;
2148
+ if (newOffset > totalMemoryBytes) {
2149
+ const neededPages = Math.ceil((newOffset - totalMemoryBytes) / 65536);
2150
+ console.log(`GROW: ${neededPages} pages`);
2151
+ this.memory.grow(neededPages);
2152
+ }
2153
+ this.allocatedBytes = newOffset;
2154
+ return currentOffset;
2155
+ }
2156
+ getBuffer() {
2157
+ return this.memory.buffer;
2158
+ }
2159
+ getInt32Array() {
2160
+ return new Int32Array(this.memory.buffer);
2161
+ }
2162
+ getInt64Array() {
2163
+ return new BigInt64Array(this.memory.buffer);
2164
+ }
2165
+ getFloat32Array() {
2166
+ return new Float32Array(this.memory.buffer);
2167
+ }
2168
+ getFloat64Array() {
2169
+ return new Float64Array(this.memory.buffer);
2170
+ }
2171
+ };
2172
+ var MAX_SOUNDFILE_PARTS = 256;
2173
+ var MAX_CHAN = 64;
2174
+ var BUFFER_SIZE = 1024;
2175
+ var SAMPLE_RATE = 44100;
2176
+ var Soundfile = class {
2177
+ constructor(allocator, sampleSize, curChan, length2, maxChan, totalParts) {
2178
+ this.fSampleSize = sampleSize;
2179
+ this.fIntSize = this.fSampleSize;
2180
+ this.fPtrSize = 4;
2181
+ this.fAllocator = allocator;
2182
+ console.log(`Soundfile constructor: curChan: ${curChan}, length: ${length2}, maxChan: ${maxChan}, totalParts: ${totalParts}`);
2183
+ this.fPtr = allocator.alloc(4 * this.fPtrSize);
2184
+ this.fLength = allocator.alloc(MAX_SOUNDFILE_PARTS * this.fIntSize);
2185
+ this.fSR = allocator.alloc(MAX_SOUNDFILE_PARTS * this.fIntSize);
2186
+ this.fOffset = allocator.alloc(MAX_SOUNDFILE_PARTS * this.fIntSize);
2187
+ this.fBuffers = this.allocBuffers(curChan, length2, maxChan);
2188
+ const HEAP32 = this.fAllocator.getInt32Array();
2189
+ HEAP32[this.fPtr >> 2] = this.fBuffers;
2190
+ HEAP32[this.fPtr + this.fPtrSize >> 2] = this.fLength;
2191
+ HEAP32[this.fPtr + 2 * this.fPtrSize >> 2] = this.fSR;
2192
+ HEAP32[this.fPtr + 3 * this.fPtrSize >> 2] = this.fOffset;
2193
+ for (let chan = 0; chan < curChan; chan++) {
2194
+ const buffer = HEAP32[(this.fBuffers >> 2) + chan];
2195
+ console.log(`allocBuffers AFTER: ${chan} - ${buffer}`);
2196
+ }
2197
+ }
2198
+ allocBuffers(curChan, length2, maxChan) {
2199
+ const buffers = this.fAllocator.alloc(maxChan * this.fPtrSize);
2200
+ console.log(`allocBuffers buffers: ${buffers}`);
2201
+ for (let chan = 0; chan < curChan; chan++) {
2202
+ const buffer = this.fAllocator.alloc(length2 * this.fSampleSize);
2203
+ const HEAP32 = this.fAllocator.getInt32Array();
2204
+ HEAP32[(buffers >> 2) + chan] = buffer;
2205
+ }
2206
+ return buffers;
2207
+ }
2208
+ shareBuffers(curChan, maxChan) {
2209
+ const HEAP32 = this.fAllocator.getInt32Array();
2210
+ for (let chan = curChan; chan < maxChan; chan++) {
2211
+ HEAP32[(this.fBuffers >> 2) + chan] = HEAP32[(this.fBuffers >> 2) + chan % curChan];
2212
+ }
2213
+ }
2214
+ copyToOut(part, maxChannels, offset, buffer) {
2215
+ if (this.fIntSize === 4) {
2216
+ const HEAP32 = this.fAllocator.getInt32Array();
2217
+ HEAP32[(this.fLength >> Math.log2(this.fIntSize)) + part] = buffer.length;
2218
+ HEAP32[(this.fSR >> Math.log2(this.fIntSize)) + part] = buffer.sampleRate;
2219
+ HEAP32[(this.fOffset >> Math.log2(this.fIntSize)) + part] = offset;
2220
+ } else {
2221
+ const HEAP64 = this.fAllocator.getInt64Array();
2222
+ HEAP64[(this.fLength >> Math.log2(this.fIntSize)) + part] = BigInt(buffer.length);
2223
+ HEAP64[(this.fSR >> Math.log2(this.fIntSize)) + part] = BigInt(buffer.sampleRate);
2224
+ HEAP64[(this.fOffset >> Math.log2(this.fIntSize)) + part] = BigInt(offset);
2225
+ }
2226
+ console.log(`copyToOut: part: ${part}, maxChannels: ${maxChannels}, offset: ${offset}, buffer: ${buffer}`);
2227
+ if (this.fSampleSize === 8) {
2228
+ this.copyToOutReal64(maxChannels, offset, buffer);
2229
+ } else {
2230
+ this.copyToOutReal32(maxChannels, offset, buffer);
2231
+ }
2232
+ }
2233
+ copyToOutReal32(maxChannels, offset, buffer) {
2234
+ const HEAP32 = this.fAllocator.getInt32Array();
2235
+ const HEAPF = this.fAllocator.getFloat32Array();
2236
+ for (let chan = 0; chan < buffer.numberOfChannels; chan++) {
2237
+ const input = buffer.getChannelData(chan);
2238
+ const output = HEAP32[(this.fBuffers >> 2) + chan];
2239
+ const begin = output + offset * this.fSampleSize >> Math.log2(this.fSampleSize);
2240
+ const end = output + (offset + input.length) * this.fSampleSize >> Math.log2(this.fSampleSize);
2241
+ console.log(`copyToOutReal32 begin: ${begin}, end: ${end}, delta: ${end - begin}`);
2242
+ const outputReal = HEAPF.subarray(
2243
+ output + offset * this.fSampleSize >> Math.log2(this.fSampleSize),
2244
+ output + (offset + input.length) * this.fSampleSize >> Math.log2(this.fSampleSize)
2245
+ );
2246
+ for (let sample = 0; sample < input.length; sample++) {
2247
+ outputReal[sample] = input[sample];
2248
+ }
2249
+ }
2250
+ }
2251
+ copyToOutReal64(maxChannels, offset, buffer) {
2252
+ const HEAP32 = this.fAllocator.getInt32Array();
2253
+ const HEAPF = this.fAllocator.getFloat64Array();
2254
+ for (let chan = 0; chan < buffer.numberOfChannels; chan++) {
2255
+ const input = buffer.getChannelData(chan);
2256
+ const output = HEAP32[(this.fBuffers >> 2) + chan];
2257
+ const begin = output + offset * this.fSampleSize >> Math.log2(this.fSampleSize);
2258
+ const end = output + (offset + input.length) * this.fSampleSize >> Math.log2(this.fSampleSize);
2259
+ console.log(`copyToOutReal64 begin: ${begin}, end: ${end}, delta: ${end - begin}`);
2260
+ const outputReal = HEAPF.subarray(
2261
+ output + offset * this.fSampleSize >> Math.log2(this.fSampleSize),
2262
+ output + (offset + input.length) * this.fSampleSize >> Math.log2(this.fSampleSize)
2263
+ );
2264
+ for (let sample = 0; sample < input.length; sample++) {
2265
+ outputReal[sample] = input[sample];
2266
+ }
2267
+ }
2268
+ }
2269
+ emptyFile(part, offset) {
2270
+ if (this.fIntSize === 4) {
2271
+ const HEAP32 = this.fAllocator.getInt32Array();
2272
+ HEAP32[(this.fLength >> Math.log2(this.fIntSize)) + part] = BUFFER_SIZE;
2273
+ HEAP32[(this.fSR >> Math.log2(this.fIntSize)) + part] = SAMPLE_RATE;
2274
+ HEAP32[(this.fOffset >> Math.log2(this.fIntSize)) + part] = offset;
2275
+ } else {
2276
+ const HEAP64 = this.fAllocator.getInt64Array();
2277
+ HEAP64[(this.fLength >> Math.log2(this.fIntSize)) + part] = BigInt(BUFFER_SIZE);
2278
+ HEAP64[(this.fSR >> Math.log2(this.fIntSize)) + part] = BigInt(SAMPLE_RATE);
2279
+ HEAP64[(this.fOffset >> Math.log2(this.fIntSize)) + part] = BigInt(offset);
2280
+ }
2281
+ return offset + BUFFER_SIZE;
2282
+ }
2283
+ displayMemory(where = "", mem = false) {
2284
+ console.log("Soundfile memory: " + where);
2285
+ console.log(`fPtr: ${this.fPtr}`);
2286
+ console.log(`fBuffers: ${this.fBuffers}`);
2287
+ console.log(`fLength: ${this.fLength}`);
2288
+ console.log(`fSR: ${this.fSR}`);
2289
+ console.log(`fOffset: ${this.fOffset}`);
2290
+ const HEAP32 = this.fAllocator.getInt32Array();
2291
+ if (mem)
2292
+ console.log(`HEAP32: ${HEAP32}`);
2293
+ console.log(`HEAP32[this.fPtr >> 2]: ${HEAP32[this.fPtr >> 2]}`);
2294
+ console.log(`HEAP32[(this.fPtr + ptrSize) >> 2]: ${HEAP32[this.fPtr + this.fPtrSize >> 2]}`);
2295
+ console.log(`HEAP32[(this.fPtr + 2 * ptrSize) >> 2]: ${HEAP32[this.fPtr + 2 * this.fPtrSize >> 2]}`);
2296
+ console.log(`HEAP32[(this.fPtr + 3 * ptrSize) >> 2]: ${HEAP32[this.fPtr + 3 * this.fPtrSize >> 2]}`);
2297
+ }
2298
+ getPtr() {
2299
+ return this.fPtr;
2300
+ }
2301
+ getHEAP32() {
2302
+ return this.fAllocator.getInt32Array();
2303
+ }
2304
+ getHEAPFloat32() {
2305
+ return this.fAllocator.getFloat32Array();
2306
+ }
2307
+ getHEAPFloat64() {
2308
+ return this.fAllocator.getFloat64Array();
2309
+ }
2310
+ };
2311
+ var SoundfileReader = class {
2312
+ constructor(allocator, context, sampleSize) {
2313
+ this.fAllocator = allocator;
2314
+ this.fSampleSize = sampleSize;
2315
+ this.fContext = context;
2316
+ this.fAudioBuffers = [];
2317
+ }
2318
+ async checkFileExists(url) {
2319
+ try {
2320
+ console.log(`"checkFileExists" url: ${url}`);
2321
+ const response = await fetch(url, { method: "HEAD" });
2322
+ return response.ok;
2323
+ } catch (error) {
2324
+ console.error("Fetch error:", error);
2325
+ return false;
2326
+ }
2327
+ }
2328
+ async checkFile(directories, fileName) {
2329
+ if (await this.checkFileExists(fileName)) {
2330
+ return fileName;
2331
+ } else {
2332
+ for (let i = 0; i < directories.length; i++) {
2333
+ const pathName = directories[i] + "/" + fileName;
2334
+ if (await this.checkFileExists(pathName)) {
2335
+ return pathName;
2336
+ }
2337
+ }
2338
+ return "";
2339
+ }
2340
+ }
2341
+ async checkFiles(directories, fileNameList) {
2342
+ const pathNameList = [];
2343
+ for (let i = 0; i < fileNameList.length; i++) {
2344
+ const pathName = await this.checkFile(directories, fileNameList[i]);
2345
+ console.log(`checkFiles pathName: ${pathName}`);
2346
+ pathNameList.push(pathName === "" ? "__empty_sound__" : pathName);
2347
+ }
2348
+ return pathNameList;
2349
+ }
2350
+ async getParamsFile(pathName) {
2351
+ console.log(`Loading sound file from ${pathName}`);
2352
+ const item = this.fAudioBuffers.find((element) => element.pathName === pathName);
2353
+ if (item) {
2354
+ console.log(`getItemByPathName FOUND`);
2355
+ return { channels: item.audioBuffer.numberOfChannels, length: item.audioBuffer.length };
2356
+ } else {
2357
+ const response = await fetch(pathName);
2358
+ if (!response.ok) {
2359
+ console.log(`Failed to load sound file from ${pathName}: ${response.statusText}`);
2360
+ return { channels: 1, length: BUFFER_SIZE };
2361
+ } else {
2362
+ const arrayBuffer = await response.arrayBuffer();
2363
+ const audioBuffer = await this.fContext.decodeAudioData(arrayBuffer);
2364
+ const { numberOfChannels, length: length2 } = audioBuffer;
2365
+ this.fAudioBuffers.push({ pathName, audioBuffer });
2366
+ return { channels: numberOfChannels, length: length2 };
2367
+ }
2368
+ }
2369
+ }
2370
+ readFile(soundfile, pathName, part, offset, maxChan) {
2371
+ const item = this.fAudioBuffers.find((entry) => entry.pathName === pathName);
2372
+ if (item) {
2373
+ soundfile.copyToOut(part, maxChan, offset, item.audioBuffer);
2374
+ return offset + item.audioBuffer.length;
2375
+ } else {
2376
+ console.error(`Failed to access sound file from ${pathName}`);
2377
+ return offset + BUFFER_SIZE;
2378
+ }
2379
+ }
2380
+ async createSoundfile(pathNameList, maxChan) {
2381
+ try {
2382
+ let curChan = 1;
2383
+ let totalLength = 0;
2384
+ for (const pathName of pathNameList) {
2385
+ let chan = 0, len = 0;
2386
+ if (pathName === "__empty_sound__") {
2387
+ length = BUFFER_SIZE;
2388
+ chan = 1;
2389
+ } else {
2390
+ const { channels, length: length2 } = await this.getParamsFile(pathName);
2391
+ chan = channels;
2392
+ len = length2;
2393
+ }
2394
+ curChan = Math.max(curChan, chan);
2395
+ totalLength += len;
2396
+ }
2397
+ totalLength += (MAX_SOUNDFILE_PARTS - pathNameList.length) * BUFFER_SIZE;
2398
+ let soundfile = new Soundfile(this.fAllocator, this.fSampleSize, curChan, totalLength, maxChan, pathNameList.length);
2399
+ let offset = 0;
2400
+ for (let part = 0; part < pathNameList.length; part++) {
2401
+ if (pathNameList[part] === "__empty_sound__") {
2402
+ offset = soundfile.emptyFile(part, offset);
2403
+ } else {
2404
+ offset = await this.readFile(soundfile, pathNameList[part], part, offset, maxChan);
2405
+ }
2406
+ }
2407
+ for (let part = pathNameList.length; part < MAX_SOUNDFILE_PARTS; part++) {
2408
+ offset = soundfile.emptyFile(part, offset);
2409
+ }
2410
+ soundfile.shareBuffers(curChan, maxChan);
2411
+ return soundfile;
2412
+ } catch (error) {
2413
+ console.error("Failed to create soundfile:", error);
2414
+ return null;
2415
+ }
2416
+ }
2417
+ getHEAP32() {
2418
+ return this.fAllocator.getInt32Array();
2419
+ }
2420
+ };
2421
+ var FaustBaseWebAudioDsp = class {
2422
+ constructor(sampleSize, bufferSize) {
2423
+ this.fOutputHandler = null;
2424
+ this.fComputeHandler = null;
2425
+ this.fCachedEvents = [];
2426
+ this.fBufferNum = 0;
2427
+ this.fPlotHandler = null;
2428
+ this.fBufferSize = bufferSize;
2429
+ this.fInChannels = [];
2430
+ this.fOutChannels = [];
2431
+ this.fPtrSize = sampleSize;
2432
+ this.fSampleSize = sampleSize;
2433
+ this.fOutputsTimer = 5;
2434
+ this.fInputsItems = [];
2435
+ this.fOutputsItems = [];
2436
+ this.fDescriptor = [];
2437
+ this.fSoundfiles = [];
2438
+ this.fPitchwheelLabel = [];
2439
+ this.fCtrlLabel = new Array(128).fill(null).map(() => []);
2440
+ this.fPathTable = {};
2441
+ this.fProcessing = false;
2442
+ this.fDestroyed = false;
2443
+ this.fFirstCall = true;
2444
+ this.fUICallback = (item) => {
2445
+ if (item.type === "hbargraph" || item.type === "vbargraph") {
2446
+ this.fOutputsItems.push(item.address);
2447
+ this.fPathTable[item.address] = item.index;
2448
+ } else if (item.type === "vslider" || item.type === "hslider" || item.type === "button" || item.type === "checkbox" || item.type === "nentry") {
2449
+ this.fInputsItems.push(item.address);
2450
+ this.fPathTable[item.address] = item.index;
2451
+ this.fDescriptor.push(item);
2452
+ if (!item.meta)
2453
+ return;
2454
+ item.meta.forEach((meta) => {
2455
+ const { midi } = meta;
2456
+ if (midi) {
2457
+ const strMidi = midi.trim();
2458
+ if (strMidi === "pitchwheel") {
2459
+ this.fPitchwheelLabel.push({ path: item.address, min: item.min, max: item.max });
2460
+ } else {
2461
+ const matched = strMidi.match(/^ctrl\s(\d+)/);
2462
+ if (matched) {
2463
+ this.fCtrlLabel[parseInt(matched[1])].push({ path: item.address, min: item.min, max: item.max });
2464
+ }
2465
+ }
2466
+ }
2467
+ const { acc } = meta;
2468
+ if (acc) {
2469
+ const strAcc = acc.trim().split(" ");
2470
+ }
2471
+ });
2472
+ } else if (item.type === "soundfile") {
2473
+ this.fSoundfiles.push({ name: item.label, url: item.url, index: item.index, basePtr: -1 });
2474
+ }
2475
+ };
2476
+ }
2477
+ static remap(v, mn0, mx0, mn1, mx1) {
2478
+ return (v - mn0) / (mx0 - mn0) * (mx1 - mn1) + mn1;
2479
+ }
2480
+ static parseUI(ui, callback) {
2481
+ ui.forEach((group) => this.parseGroup(group, callback));
2482
+ }
2483
+ static parseGroup(group, callback) {
2484
+ if (group.items) {
2485
+ this.parseItems(group.items, callback);
2486
+ }
2487
+ }
2488
+ static parseItems(items, callback) {
2489
+ items.forEach((item) => this.parseItem(item, callback));
2490
+ }
2491
+ static parseItem(item, callback) {
2492
+ if (item.type === "vgroup" || item.type === "hgroup" || item.type === "tgroup") {
2493
+ this.parseItems(item.items, callback);
2494
+ } else {
2495
+ callback(item);
2496
+ }
2497
+ }
2498
+ static splitNames(input) {
2499
+ let trimmed = input.replace(/^\{|\}$/g, "");
2500
+ return trimmed.split(";").map((str) => str.length <= 2 ? "" : str.substring(1, str.length - 1));
2501
+ }
2502
+ setupAccHandler(path, curve, amin, amid, amax, min, init, max) {
2503
+ const handler = buildAccHandler(curve, amin, amid, amax, min, init, max);
2504
+ }
2505
+ extractURLsFromJSON() {
2506
+ const soundfilesEntry = this.fJSONDsp.meta.find((entry) => entry.soundfiles !== void 0);
2507
+ if (soundfilesEntry) {
2508
+ return soundfilesEntry.soundfiles.split(";").filter((url) => url !== "");
2509
+ } else {
2510
+ return [];
2511
+ }
2512
+ }
2513
+ async loadSoundfile(sfReader, baseDSP, name, url) {
2514
+ console.log(`Soundfile ${name} paths: ${url}`);
2515
+ const sfReaderURLs = this.extractURLsFromJSON();
2516
+ console.log(`sfReaderURLs ${sfReaderURLs}`);
2517
+ const sfDirectories = ["", ".", "http://127.0.0.1:8000"];
2518
+ sfDirectories.push(...sfReaderURLs);
2519
+ console.log(`sfDirectories ${sfDirectories}`);
2520
+ const sfPathNames = await sfReader.checkFiles(sfDirectories, FaustBaseWebAudioDsp.splitNames(url));
2521
+ console.log(`Soundfile ${name} paths: ${sfPathNames}`);
2522
+ const item = this.fSoundfiles.find((element) => element.url === url);
2523
+ if (item) {
2524
+ if (item.basePtr !== -1) {
2525
+ const HEAP32 = sfReader.getHEAP32();
2526
+ console.log(`Soundfile CACHE ${url}} : ${name} loaded at ${item.basePtr} in wasm memory with index ${item.index}`);
2527
+ HEAP32[baseDSP + item.index >> 2] = item.basePtr;
2528
+ } else {
2529
+ const soundfile = await sfReader.createSoundfile(sfPathNames, MAX_CHAN);
2530
+ if (soundfile) {
2531
+ const HEAP32 = soundfile.getHEAP32();
2532
+ item.basePtr = soundfile.getPtr();
2533
+ console.log(`Soundfile ${name} loaded at ${item.basePtr} in wasm memory with index ${item.index}`);
2534
+ HEAP32[baseDSP + item.index >> 2] = item.basePtr;
2535
+ } else {
2536
+ console.log(`Soundfile ${name} for ${url} cannot be created !}`);
2537
+ }
2538
+ }
2539
+ } else {
2540
+ console.log(`Soundfile with ${url} cannot be found !}`);
2541
+ }
2542
+ }
2543
+ async initSoundfileMemory(allocator, sfReader, baseDSP) {
2544
+ for (const { name, url } of this.fSoundfiles) {
2545
+ await this.loadSoundfile(sfReader, baseDSP, name, url);
2546
+ }
2547
+ ;
2548
+ }
2549
+ updateOutputs() {
2550
+ if (this.fOutputsItems.length > 0 && this.fOutputHandler && this.fOutputsTimer-- === 0) {
2551
+ this.fOutputsTimer = 5;
2552
+ this.fOutputsItems.forEach((item) => {
2553
+ var _a;
2554
+ return (_a = this.fOutputHandler) == null ? void 0 : _a.call(this, item, this.getParamValue(item));
2555
+ });
2556
+ }
2557
+ }
2558
+ metadata(handler) {
2559
+ if (this.fJSONDsp.meta) {
2560
+ this.fJSONDsp.meta.forEach((meta) => handler(Object.keys(meta)[0], meta[Object.keys(meta)[0]]));
2561
+ }
2562
+ }
2563
+ compute(input, output) {
2564
+ return false;
2565
+ }
2566
+ setOutputParamHandler(handler) {
2567
+ this.fOutputHandler = handler;
2568
+ }
2569
+ getOutputParamHandler() {
2570
+ return this.fOutputHandler;
2571
+ }
2572
+ setComputeHandler(handler) {
2573
+ this.fComputeHandler = handler;
2574
+ }
2575
+ getComputeHandler() {
2576
+ return this.fComputeHandler;
2577
+ }
2578
+ setPlotHandler(handler) {
2579
+ this.fPlotHandler = handler;
2580
+ }
2581
+ getPlotHandler() {
2582
+ return this.fPlotHandler;
2583
+ }
2584
+ getNumInputs() {
2585
+ return -1;
2586
+ }
2587
+ getNumOutputs() {
2588
+ return -1;
2589
+ }
2590
+ midiMessage(data) {
2591
+ if (this.fPlotHandler)
2592
+ this.fCachedEvents.push({ data, type: "midi" });
2593
+ const cmd = data[0] >> 4;
2594
+ const channel = data[0] & 15;
2595
+ const data1 = data[1];
2596
+ const data2 = data[2];
2597
+ if (cmd === 11)
2598
+ return this.ctrlChange(channel, data1, data2);
2599
+ if (cmd === 14)
2600
+ return this.pitchWheel(channel, data2 * 128 + data1);
2601
+ }
2602
+ ctrlChange(channel, ctrl, value) {
2603
+ if (this.fPlotHandler)
2604
+ this.fCachedEvents.push({ type: "ctrlChange", data: [channel, ctrl, value] });
2605
+ if (this.fCtrlLabel[ctrl].length) {
2606
+ this.fCtrlLabel[ctrl].forEach((ctrl2) => {
2607
+ const { path } = ctrl2;
2608
+ this.setParamValue(path, FaustBaseWebAudioDsp.remap(value, 0, 127, ctrl2.min, ctrl2.max));
2609
+ if (this.fOutputHandler)
2610
+ this.fOutputHandler(path, this.getParamValue(path));
2611
+ });
2612
+ }
2613
+ }
2614
+ pitchWheel(channel, wheel) {
2615
+ if (this.fPlotHandler)
2616
+ this.fCachedEvents.push({ type: "pitchWheel", data: [channel, wheel] });
2617
+ this.fPitchwheelLabel.forEach((pw) => {
2618
+ this.setParamValue(pw.path, FaustBaseWebAudioDsp.remap(wheel, 0, 16383, pw.min, pw.max));
2619
+ if (this.fOutputHandler)
2620
+ this.fOutputHandler(pw.path, this.getParamValue(pw.path));
2621
+ });
2622
+ }
2623
+ setParamValue(path, value) {
2624
+ }
2625
+ getParamValue(path) {
2626
+ return 0;
2627
+ }
2628
+ getParams() {
2629
+ return this.fInputsItems;
2630
+ }
2631
+ getMeta() {
2632
+ return this.fJSONDsp;
2633
+ }
2634
+ getJSON() {
2635
+ return JSON.stringify(this.getMeta());
2636
+ }
2637
+ getUI() {
2638
+ return this.fJSONDsp.ui;
2639
+ }
2640
+ getDescriptors() {
2641
+ return this.fDescriptor;
2642
+ }
2643
+ hasSoundfiles() {
2644
+ return this.fSoundfiles.length > 0;
2645
+ }
2646
+ start() {
2647
+ this.fProcessing = true;
2648
+ }
2649
+ stop() {
2650
+ this.fProcessing = false;
2651
+ }
2652
+ destroy() {
2653
+ this.fDestroyed = true;
2654
+ this.fOutputHandler = null;
2655
+ this.fComputeHandler = null;
2656
+ this.fPlotHandler = null;
2657
+ }
2658
+ };
2659
+ var FaustMonoWebAudioDsp = class extends FaustBaseWebAudioDsp {
2660
+ constructor(instance, sampleRate, sampleSize, bufferSize) {
2661
+ super(sampleSize, bufferSize);
2662
+ this.fInstance = instance;
2663
+ console.log("sampleSize: " + sampleSize + " bufferSize: " + bufferSize);
2664
+ this.fJSONDsp = JSON.parse(this.fInstance.json);
2665
+ FaustBaseWebAudioDsp.parseUI(this.fJSONDsp.ui, this.fUICallback);
2666
+ this.fEndMemory = this.initMemory();
2667
+ this.fInstance.api.init(this.fDSP, sampleRate);
2668
+ }
2669
+ async init(context) {
2670
+ if (this.fSoundfiles.length > 0 && context) {
2671
+ const allocator = new WasmAllocator(this.fInstance.memory, this.fEndMemory);
2672
+ const sfReader = new SoundfileReader(allocator, context, this.fSampleSize);
2673
+ await this.initSoundfileMemory(allocator, sfReader, this.fDSP);
2674
+ }
2675
+ }
2676
+ initMemory() {
2677
+ this.fDSP = 0;
2678
+ const $audio = this.fJSONDsp.size;
2679
+ this.fAudioInputs = $audio;
2680
+ this.fAudioOutputs = this.fAudioInputs + this.getNumInputs() * this.fPtrSize;
2681
+ const $audioInputs = this.fAudioOutputs + this.getNumOutputs() * this.fPtrSize;
2682
+ const $audioOutputs = $audioInputs + this.getNumInputs() * this.fBufferSize * this.fSampleSize;
2683
+ const endMemory = $audioOutputs + this.getNumOutputs() * this.fBufferSize * this.fSampleSize;
2684
+ const HEAP = this.fInstance.memory.buffer;
2685
+ const HEAP32 = new Int32Array(HEAP);
2686
+ const HEAPF = this.fSampleSize === 4 ? new Float32Array(HEAP) : new Float64Array(HEAP);
2687
+ if (this.getNumInputs() > 0) {
2688
+ for (let chan = 0; chan < this.getNumInputs(); chan++) {
2689
+ HEAP32[(this.fAudioInputs >> 2) + chan] = $audioInputs + this.fBufferSize * this.fSampleSize * chan;
2690
+ }
2691
+ const dspInChans = HEAP32.subarray(this.fAudioInputs >> 2, this.fAudioInputs + this.getNumInputs() * this.fPtrSize >> 2);
2692
+ for (let chan = 0; chan < this.getNumInputs(); chan++) {
2693
+ this.fInChannels[chan] = HEAPF.subarray(dspInChans[chan] >> Math.log2(this.fSampleSize), dspInChans[chan] + this.fBufferSize * this.fSampleSize >> Math.log2(this.fSampleSize));
2694
+ }
2695
+ }
2696
+ if (this.getNumOutputs() > 0) {
2697
+ for (let chan = 0; chan < this.getNumOutputs(); chan++) {
2698
+ HEAP32[(this.fAudioOutputs >> 2) + chan] = $audioOutputs + this.fBufferSize * this.fSampleSize * chan;
2699
+ }
2700
+ const dspOutChans = HEAP32.subarray(this.fAudioOutputs >> 2, this.fAudioOutputs + this.getNumOutputs() * this.fPtrSize >> 2);
2701
+ for (let chan = 0; chan < this.getNumOutputs(); chan++) {
2702
+ this.fOutChannels[chan] = HEAPF.subarray(dspOutChans[chan] >> Math.log2(this.fSampleSize), dspOutChans[chan] + this.fBufferSize * this.fSampleSize >> Math.log2(this.fSampleSize));
2703
+ }
2704
+ }
2705
+ return endMemory;
2706
+ }
2707
+ toString() {
2708
+ return `============== Mono Memory layout ==============
2709
+ this.fBufferSize: ${this.fBufferSize}
2710
+ this.fJSONDsp.size: ${this.fJSONDsp.size}
2711
+ this.fAudioInputs: ${this.fAudioInputs}
2712
+ this.fAudioOutputs: ${this.fAudioOutputs}
2713
+ this.fDSP: ${this.fDSP}`;
2714
+ }
2715
+ compute(input, output) {
2716
+ if (this.fDestroyed)
2717
+ return false;
2718
+ if (!this.fProcessing)
2719
+ return true;
2720
+ if (this.fFirstCall) {
2721
+ this.initMemory();
2722
+ this.fFirstCall = false;
2723
+ }
2724
+ if (typeof input === "function") {
2725
+ input(this.fInChannels);
2726
+ } else {
2727
+ if (this.getNumInputs() > 0 && (!input || !input[0] || input[0].length === 0)) {
2728
+ return true;
2729
+ }
2730
+ if (this.getNumOutputs() > 0 && typeof output !== "function" && (!output || !output[0] || output[0].length === 0)) {
2731
+ return true;
2732
+ }
2733
+ if (input !== void 0) {
2734
+ for (let chan = 0; chan < Math.min(this.getNumInputs(), input.length); chan++) {
2735
+ const dspInput = this.fInChannels[chan];
2736
+ dspInput.set(input[chan]);
2737
+ }
2738
+ }
2739
+ }
2740
+ if (this.fComputeHandler)
2741
+ this.fComputeHandler(this.fBufferSize);
2742
+ this.fInstance.api.compute(this.fDSP, this.fBufferSize, this.fAudioInputs, this.fAudioOutputs);
2743
+ this.updateOutputs();
2744
+ let forPlot = this.fOutChannels;
2745
+ if (typeof output === "function") {
2746
+ output(this.fOutChannels);
2747
+ } else {
2748
+ for (let chan = 0; chan < Math.min(this.getNumOutputs(), output.length); chan++) {
2749
+ const dspOutput = this.fOutChannels[chan];
2750
+ output[chan].set(dspOutput);
2751
+ }
2752
+ forPlot = output;
2753
+ }
2754
+ if (this.fPlotHandler) {
2755
+ this.fPlotHandler(forPlot, this.fBufferNum++, this.fCachedEvents.length ? this.fCachedEvents : void 0);
2756
+ this.fCachedEvents = [];
2757
+ }
2758
+ return true;
2759
+ }
2760
+ metadata(handler) {
2761
+ super.metadata(handler);
2762
+ }
2763
+ getNumInputs() {
2764
+ return this.fInstance.api.getNumInputs(this.fDSP);
2765
+ }
2766
+ getNumOutputs() {
2767
+ return this.fInstance.api.getNumOutputs(this.fDSP);
2768
+ }
2769
+ setParamValue(path, value) {
2770
+ if (this.fPlotHandler)
2771
+ this.fCachedEvents.push({ type: "param", data: { path, value } });
2772
+ this.fInstance.api.setParamValue(this.fDSP, this.fPathTable[path], value);
2773
+ }
2774
+ getParamValue(path) {
2775
+ return this.fInstance.api.getParamValue(this.fDSP, this.fPathTable[path]);
2776
+ }
2777
+ getMeta() {
2778
+ return this.fJSONDsp;
2779
+ }
2780
+ getJSON() {
2781
+ return this.fInstance.json;
2782
+ }
2783
+ getDescriptors() {
2784
+ return this.fDescriptor;
2785
+ }
2786
+ getUI() {
2787
+ return this.fJSONDsp.ui;
2788
+ }
2789
+ };
2790
+ var FaustWebAudioDspVoice = class {
2791
+ constructor($dsp, api, inputItems, pathTable, sampleRate) {
2792
+ FaustWebAudioDspVoice.kActiveVoice = 0;
2793
+ FaustWebAudioDspVoice.kFreeVoice = -1;
2794
+ FaustWebAudioDspVoice.kReleaseVoice = -2;
2795
+ FaustWebAudioDspVoice.kLegatoVoice = -3;
2796
+ FaustWebAudioDspVoice.kNoVoice = -4;
2797
+ FaustWebAudioDspVoice.VOICE_STOP_LEVEL = 5e-4;
2798
+ this.fCurNote = FaustWebAudioDspVoice.kFreeVoice;
2799
+ this.fNextNote = this.fNextVel = -1;
2800
+ this.fLevel = 0;
2801
+ this.fDate = this.fRelease = 0;
2802
+ this.fDSP = $dsp;
2803
+ this.fAPI = api;
2804
+ this.fGateLabel = [];
2805
+ this.fGainLabel = [];
2806
+ this.fFreqLabel = [];
2807
+ this.fKeyLabel = [];
2808
+ this.fVelLabel = [];
2809
+ this.fAPI.init(this.fDSP, sampleRate);
2810
+ this.extractPaths(inputItems, pathTable);
2811
+ }
2812
+ static midiToFreq(note) {
2813
+ return 440 * 2 ** ((note - 69) / 12);
2814
+ }
2815
+ static normalizeVelocity(velocity) {
2816
+ return velocity / 127;
2817
+ }
2818
+ extractPaths(inputItems, pathTable) {
2819
+ inputItems.forEach((item) => {
2820
+ if (item.endsWith("/gate")) {
2821
+ this.fGateLabel.push(pathTable[item]);
2822
+ } else if (item.endsWith("/freq")) {
2823
+ this.fFreqLabel.push(pathTable[item]);
2824
+ } else if (item.endsWith("/key")) {
2825
+ this.fKeyLabel.push(pathTable[item]);
2826
+ } else if (item.endsWith("/gain")) {
2827
+ this.fGainLabel.push(pathTable[item]);
2828
+ } else if (item.endsWith("/vel") && item.endsWith("/velocity")) {
2829
+ this.fVelLabel.push(pathTable[item]);
2830
+ }
2831
+ });
2832
+ }
2833
+ keyOn(pitch, velocity, legato = false) {
2834
+ if (legato) {
2835
+ this.fNextNote = pitch;
2836
+ this.fNextVel = velocity;
2837
+ } else {
2838
+ this.fFreqLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, FaustWebAudioDspVoice.midiToFreq(pitch)));
2839
+ this.fGateLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, 1));
2840
+ this.fGainLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, FaustWebAudioDspVoice.normalizeVelocity(velocity)));
2841
+ this.fKeyLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, pitch));
2842
+ this.fVelLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, velocity));
2843
+ this.fCurNote = pitch;
2844
+ }
2845
+ }
2846
+ keyOff(hard = false) {
2847
+ this.fGateLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, 0));
2848
+ if (hard) {
2849
+ this.fCurNote = FaustWebAudioDspVoice.kFreeVoice;
2850
+ } else {
2851
+ this.fRelease = this.fAPI.getSampleRate(this.fDSP) / 2;
2852
+ this.fCurNote = FaustWebAudioDspVoice.kReleaseVoice;
2853
+ }
2854
+ }
2855
+ computeLegato(bufferSize, $inputs, $outputZero, $outputsHalf) {
2856
+ let size = bufferSize / 2;
2857
+ this.fGateLabel.forEach((index) => this.fAPI.setParamValue(this.fDSP, index, 0));
2858
+ this.fAPI.compute(this.fDSP, size, $inputs, $outputZero);
2859
+ this.keyOn(this.fNextNote, this.fNextVel);
2860
+ this.fAPI.compute(this.fDSP, size, $inputs, $outputsHalf);
2861
+ }
2862
+ compute(bufferSize, $inputs, $outputs) {
2863
+ this.fAPI.compute(this.fDSP, bufferSize, $inputs, $outputs);
2864
+ }
2865
+ setParamValue(index, value) {
2866
+ this.fAPI.setParamValue(this.fDSP, index, value);
2867
+ }
2868
+ getParamValue(index) {
2869
+ return this.fAPI.getParamValue(this.fDSP, index);
2870
+ }
2871
+ };
2872
+ var FaustPolyWebAudioDsp = class extends FaustBaseWebAudioDsp {
2873
+ constructor(instance, sampleRate, sampleSize, bufferSize) {
2874
+ super(sampleSize, bufferSize);
2875
+ this.fInstance = instance;
2876
+ console.log("sampleSize: " + sampleSize + " bufferSize: " + bufferSize);
2877
+ this.fJSONDsp = JSON.parse(this.fInstance.voiceJSON);
2878
+ this.fJSONEffect = this.fInstance.effectAPI && this.fInstance.effectJSON ? JSON.parse(this.fInstance.effectJSON) : null;
2879
+ FaustBaseWebAudioDsp.parseUI(this.fJSONDsp.ui, this.fUICallback);
2880
+ if (this.fJSONEffect)
2881
+ FaustBaseWebAudioDsp.parseUI(this.fJSONEffect.ui, this.fUICallback);
2882
+ this.fEndMemory = this.initMemory();
2883
+ this.fVoiceTable = [];
2884
+ for (let voice = 0; voice < this.fInstance.voices; voice++) {
2885
+ this.fVoiceTable.push(new FaustWebAudioDspVoice(
2886
+ this.fJSONDsp.size * voice,
2887
+ this.fInstance.voiceAPI,
2888
+ this.fInputsItems,
2889
+ this.fPathTable,
2890
+ sampleRate
2891
+ ));
2892
+ }
2893
+ if (this.fInstance.effectAPI)
2894
+ this.fInstance.effectAPI.init(this.fEffect, sampleRate);
2895
+ }
2896
+ async init(context) {
2897
+ if (this.fSoundfiles.length > 0 && context) {
2898
+ const allocator = new WasmAllocator(this.fInstance.memory, this.fEndMemory);
2899
+ const sfReader = new SoundfileReader(allocator, context, this.fSampleSize);
2900
+ for (let voice = 0; voice < this.fInstance.voices; voice++) {
2901
+ await this.initSoundfileMemory(allocator, sfReader, this.fJSONDsp.size * voice);
2902
+ }
2903
+ }
2904
+ }
2905
+ initMemory() {
2906
+ this.fEffect = this.fJSONDsp.size * this.fInstance.voices;
2907
+ const $audio = this.fEffect + (this.fJSONEffect ? this.fJSONEffect.size : 0);
2908
+ this.fAudioInputs = $audio;
2909
+ this.fAudioOutputs = this.fAudioInputs + this.getNumInputs() * this.fPtrSize;
2910
+ this.fAudioMixing = this.fAudioOutputs + this.getNumOutputs() * this.fPtrSize;
2911
+ this.fAudioMixingHalf = this.fAudioMixing + this.getNumOutputs() * this.fPtrSize;
2912
+ const $audioInputs = this.fAudioMixingHalf + this.getNumOutputs() * this.fPtrSize;
2913
+ const $audioOutputs = $audioInputs + this.getNumInputs() * this.fBufferSize * this.fSampleSize;
2914
+ const $audioMixing = $audioOutputs + this.getNumOutputs() * this.fBufferSize * this.fSampleSize;
2915
+ const endMemory = $audioMixing + this.getNumOutputs() * this.fBufferSize * this.fSampleSize;
2916
+ const HEAP = this.fInstance.memory.buffer;
2917
+ const HEAP32 = new Int32Array(HEAP);
2918
+ const HEAPF = this.fSampleSize === 4 ? new Float32Array(HEAP) : new Float64Array(HEAP);
2919
+ if (this.getNumInputs() > 0) {
2920
+ for (let chan = 0; chan < this.getNumInputs(); chan++) {
2921
+ HEAP32[(this.fAudioInputs >> 2) + chan] = $audioInputs + this.fBufferSize * this.fSampleSize * chan;
2922
+ }
2923
+ const dspInChans = HEAP32.subarray(this.fAudioInputs >> 2, this.fAudioInputs + this.getNumInputs() * this.fPtrSize >> 2);
2924
+ for (let chan = 0; chan < this.getNumInputs(); chan++) {
2925
+ this.fInChannels[chan] = HEAPF.subarray(dspInChans[chan] >> Math.log2(this.fSampleSize), dspInChans[chan] + this.fBufferSize * this.fSampleSize >> Math.log2(this.fSampleSize));
2926
+ }
2927
+ }
2928
+ if (this.getNumOutputs() > 0) {
2929
+ for (let chan = 0; chan < this.getNumOutputs(); chan++) {
2930
+ HEAP32[(this.fAudioOutputs >> 2) + chan] = $audioOutputs + this.fBufferSize * this.fSampleSize * chan;
2931
+ HEAP32[(this.fAudioMixing >> 2) + chan] = $audioMixing + this.fBufferSize * this.fSampleSize * chan;
2932
+ HEAP32[(this.fAudioMixingHalf >> 2) + chan] = $audioMixing + this.fBufferSize * this.fSampleSize * chan + this.fBufferSize / 2 * this.fSampleSize;
2933
+ }
2934
+ const dspOutChans = HEAP32.subarray(this.fAudioOutputs >> 2, this.fAudioOutputs + this.getNumOutputs() * this.fPtrSize >> 2);
2935
+ for (let chan = 0; chan < this.getNumOutputs(); chan++) {
2936
+ this.fOutChannels[chan] = HEAPF.subarray(dspOutChans[chan] >> Math.log2(this.fSampleSize), dspOutChans[chan] + this.fBufferSize * this.fSampleSize >> Math.log2(this.fSampleSize));
2937
+ }
2938
+ }
2939
+ return endMemory;
2940
+ }
2941
+ toString() {
2942
+ return `============== Poly Memory layout ==============
2943
+ this.fBufferSize: ${this.fBufferSize}
2944
+ this.fJSONDsp.size: ${this.fJSONDsp.size}
2945
+ this.fAudioInputs: ${this.fAudioInputs}
2946
+ this.fAudioOutputs: ${this.fAudioOutputs}
2947
+ this.fAudioMixing: ${this.fAudioMixing}
2948
+ this.fAudioMixingHalf: ${this.fAudioMixingHalf}`;
2949
+ }
2950
+ allocVoice(voice, type) {
2951
+ this.fVoiceTable[voice].fDate++;
2952
+ this.fVoiceTable[voice].fCurNote = type;
2953
+ return voice;
2954
+ }
2955
+ getPlayingVoice(pitch) {
2956
+ let voicePlaying = FaustWebAudioDspVoice.kNoVoice;
2957
+ let oldestDatePlaying = Number.MAX_VALUE;
2958
+ for (let voice = 0; voice < this.fInstance.voices; voice++) {
2959
+ if (this.fVoiceTable[voice].fCurNote === pitch) {
2960
+ if (this.fVoiceTable[voice].fDate < oldestDatePlaying) {
2961
+ oldestDatePlaying = this.fVoiceTable[voice].fDate;
2962
+ voicePlaying = voice;
2963
+ }
2964
+ }
2965
+ }
2966
+ return voicePlaying;
2967
+ }
2968
+ getFreeVoice() {
2969
+ for (let voice = 0; voice < this.fInstance.voices; voice++) {
2970
+ if (this.fVoiceTable[voice].fCurNote === FaustWebAudioDspVoice.kFreeVoice) {
2971
+ return this.allocVoice(voice, FaustWebAudioDspVoice.kActiveVoice);
2972
+ }
2973
+ }
2974
+ let voiceRelease = FaustWebAudioDspVoice.kNoVoice;
2975
+ let voicePlaying = FaustWebAudioDspVoice.kNoVoice;
2976
+ let oldestDateRelease = Number.MAX_VALUE;
2977
+ let oldestDatePlaying = Number.MAX_VALUE;
2978
+ for (let voice = 0; voice < this.fInstance.voices; voice++) {
2979
+ if (this.fVoiceTable[voice].fCurNote === FaustWebAudioDspVoice.kReleaseVoice) {
2980
+ if (this.fVoiceTable[voice].fDate < oldestDateRelease) {
2981
+ oldestDateRelease = this.fVoiceTable[voice].fDate;
2982
+ voiceRelease = voice;
2983
+ }
2984
+ } else if (this.fVoiceTable[voice].fDate < oldestDatePlaying) {
2985
+ oldestDatePlaying = this.fVoiceTable[voice].fDate;
2986
+ voicePlaying = voice;
2987
+ }
2988
+ }
2989
+ if (oldestDateRelease !== Number.MAX_VALUE) {
2990
+ console.log(`Steal release voice : voice_date = ${this.fVoiceTable[voiceRelease].fDate} voice = ${voiceRelease}`);
2991
+ return this.allocVoice(voiceRelease, FaustWebAudioDspVoice.kLegatoVoice);
2992
+ }
2993
+ if (oldestDatePlaying !== Number.MAX_VALUE) {
2994
+ console.log(`Steal playing voice : voice_date = ${this.fVoiceTable[voicePlaying].fDate} voice = ${voicePlaying}`);
2995
+ return this.allocVoice(voicePlaying, FaustWebAudioDspVoice.kLegatoVoice);
2996
+ }
2997
+ return FaustWebAudioDspVoice.kNoVoice;
2998
+ }
2999
+ compute(input, output) {
3000
+ if (this.fDestroyed)
3001
+ return false;
3002
+ if (this.fFirstCall) {
3003
+ this.initMemory();
3004
+ this.fFirstCall = false;
3005
+ }
3006
+ if (!this.fProcessing)
3007
+ return true;
3008
+ if (this.getNumInputs() > 0 && (!input || !input[0] || input[0].length === 0)) {
3009
+ return true;
3010
+ }
3011
+ if (this.getNumOutputs() > 0 && (!output || !output[0] || output[0].length === 0)) {
3012
+ return true;
3013
+ }
3014
+ if (input !== void 0) {
3015
+ for (let chan = 0; chan < Math.min(this.getNumInputs(), input.length); ++chan) {
3016
+ const dspInput = this.fInChannels[chan];
3017
+ dspInput.set(input[chan]);
3018
+ }
3019
+ }
3020
+ if (this.fComputeHandler)
3021
+ this.fComputeHandler(this.fBufferSize);
3022
+ this.fInstance.mixerAPI.clearOutput(this.fBufferSize, this.getNumOutputs(), this.fAudioOutputs);
3023
+ this.fVoiceTable.forEach((voice) => {
3024
+ if (voice.fCurNote === FaustWebAudioDspVoice.kLegatoVoice) {
3025
+ voice.computeLegato(this.fBufferSize, this.fAudioInputs, this.fAudioMixing, this.fAudioMixingHalf);
3026
+ this.fInstance.mixerAPI.fadeOut(this.fBufferSize / 2, this.getNumOutputs(), this.fAudioMixing);
3027
+ voice.fLevel = this.fInstance.mixerAPI.mixCheckVoice(this.fBufferSize, this.getNumOutputs(), this.fAudioMixing, this.fAudioOutputs);
3028
+ } else if (voice.fCurNote !== FaustWebAudioDspVoice.kFreeVoice) {
3029
+ voice.compute(this.fBufferSize, this.fAudioInputs, this.fAudioMixing);
3030
+ voice.fLevel = this.fInstance.mixerAPI.mixCheckVoice(this.fBufferSize, this.getNumOutputs(), this.fAudioMixing, this.fAudioOutputs);
3031
+ voice.fRelease -= this.fBufferSize;
3032
+ if (voice.fCurNote == FaustWebAudioDspVoice.kReleaseVoice && (voice.fLevel < FaustWebAudioDspVoice.VOICE_STOP_LEVEL && voice.fRelease < 0)) {
3033
+ voice.fCurNote = FaustWebAudioDspVoice.kFreeVoice;
3034
+ }
3035
+ }
3036
+ });
3037
+ if (this.fInstance.effectAPI)
3038
+ this.fInstance.effectAPI.compute(this.fEffect, this.fBufferSize, this.fAudioOutputs, this.fAudioOutputs);
3039
+ this.updateOutputs();
3040
+ if (output !== void 0) {
3041
+ for (let chan = 0; chan < Math.min(this.getNumOutputs(), output.length); chan++) {
3042
+ const dspOutput = this.fOutChannels[chan];
3043
+ output[chan].set(dspOutput);
3044
+ }
3045
+ if (this.fPlotHandler) {
3046
+ this.fPlotHandler(output, this.fBufferNum++, this.fCachedEvents.length ? this.fCachedEvents : void 0);
3047
+ this.fCachedEvents = [];
3048
+ }
3049
+ }
3050
+ return true;
3051
+ }
3052
+ getNumInputs() {
3053
+ return this.fInstance.voiceAPI.getNumInputs(0);
3054
+ }
3055
+ getNumOutputs() {
3056
+ return this.fInstance.voiceAPI.getNumOutputs(0);
3057
+ }
3058
+ static findPath(o, p) {
3059
+ if (typeof o !== "object") {
3060
+ return false;
3061
+ } else if (o.address) {
3062
+ return o.address === p;
3063
+ } else {
3064
+ for (const k in o) {
3065
+ if (FaustPolyWebAudioDsp.findPath(o[k], p))
3066
+ return true;
3067
+ }
3068
+ return false;
3069
+ }
3070
+ }
3071
+ setParamValue(path, value) {
3072
+ if (this.fPlotHandler)
3073
+ this.fCachedEvents.push({ type: "param", data: { path, value } });
3074
+ if (this.fJSONEffect && FaustPolyWebAudioDsp.findPath(this.fJSONEffect.ui, path) && this.fInstance.effectAPI) {
3075
+ this.fInstance.effectAPI.setParamValue(this.fEffect, this.fPathTable[path], value);
3076
+ } else {
3077
+ this.fVoiceTable.forEach((voice) => voice.setParamValue(this.fPathTable[path], value));
3078
+ }
3079
+ }
3080
+ getParamValue(path) {
3081
+ if (this.fJSONEffect && FaustPolyWebAudioDsp.findPath(this.fJSONEffect.ui, path) && this.fInstance.effectAPI) {
3082
+ return this.fInstance.effectAPI.getParamValue(this.fEffect, this.fPathTable[path]);
3083
+ } else {
3084
+ return this.fVoiceTable[0].getParamValue(this.fPathTable[path]);
3085
+ }
3086
+ }
3087
+ getMeta() {
3088
+ const o = this.fJSONDsp;
3089
+ const e = this.fJSONEffect;
3090
+ const r = { ...o };
3091
+ if (e) {
3092
+ r.ui = [{
3093
+ type: "tgroup",
3094
+ label: "Sequencer",
3095
+ items: [
3096
+ { type: "vgroup", label: "Instrument", items: o.ui },
3097
+ { type: "vgroup", label: "Effect", items: e.ui }
3098
+ ]
3099
+ }];
3100
+ } else {
3101
+ r.ui = [{
3102
+ type: "tgroup",
3103
+ label: "Polyphonic",
3104
+ items: [
3105
+ { type: "vgroup", label: "Voices", items: o.ui }
3106
+ ]
3107
+ }];
3108
+ }
3109
+ return r;
3110
+ }
3111
+ getJSON() {
3112
+ return JSON.stringify(this.getMeta());
3113
+ }
3114
+ getUI() {
3115
+ return this.getMeta().ui;
3116
+ }
3117
+ getDescriptors() {
3118
+ return this.fDescriptor;
3119
+ }
3120
+ midiMessage(data) {
3121
+ const cmd = data[0] >> 4;
3122
+ const channel = data[0] & 15;
3123
+ const data1 = data[1];
3124
+ const data2 = data[2];
3125
+ if (cmd === 8 || cmd === 9 && data2 === 0)
3126
+ return this.keyOff(channel, data1, data2);
3127
+ else if (cmd === 9)
3128
+ return this.keyOn(channel, data1, data2);
3129
+ else
3130
+ super.midiMessage(data);
3131
+ }
3132
+ ctrlChange(channel, ctrl, value) {
3133
+ if (ctrl === 123 || ctrl === 120) {
3134
+ this.allNotesOff(true);
3135
+ } else {
3136
+ super.ctrlChange(channel, ctrl, value);
3137
+ }
3138
+ }
3139
+ keyOn(channel, pitch, velocity) {
3140
+ if (this.fPlotHandler)
3141
+ this.fCachedEvents.push({ type: "keyOn", data: [channel, pitch, velocity] });
3142
+ const voice = this.getFreeVoice();
3143
+ this.fVoiceTable[voice].keyOn(pitch, velocity, this.fVoiceTable[voice].fCurNote == FaustWebAudioDspVoice.kLegatoVoice);
3144
+ }
3145
+ keyOff(channel, pitch, velocity) {
3146
+ if (this.fPlotHandler)
3147
+ this.fCachedEvents.push({ type: "keyOff", data: [channel, pitch, velocity] });
3148
+ const voice = this.getPlayingVoice(pitch);
3149
+ if (voice !== FaustWebAudioDspVoice.kNoVoice) {
3150
+ this.fVoiceTable[voice].keyOff();
3151
+ } else {
3152
+ console.log("Playing pitch = %d not found\n", pitch);
3153
+ }
3154
+ }
3155
+ allNotesOff(hard = true) {
3156
+ this.fCachedEvents.push({ type: "ctrlChange", data: [0, 123, 0] });
3157
+ this.fVoiceTable.forEach((voice) => voice.keyOff(hard));
3158
+ }
3159
+ };
3160
+
3161
+ // src/FaustOfflineProcessor.ts
3162
+ var FaustOfflineProcessor = class {
3163
+ constructor(instance, bufferSize) {
3164
+ this.fDSPCode = instance;
3165
+ this.fBufferSize = bufferSize;
3166
+ this.fInputs = new Array(this.fDSPCode.getNumInputs()).fill(null).map(() => new Float32Array(bufferSize));
3167
+ this.fOutputs = new Array(this.fDSPCode.getNumOutputs()).fill(null).map(() => new Float32Array(bufferSize));
3168
+ }
3169
+ getParameterDescriptors() {
3170
+ const params = [];
3171
+ const callback = (item) => {
3172
+ let param = null;
3173
+ const polyKeywords = ["/gate", "/freq", "/gain", "/key", "/vel", "/velocity"];
3174
+ const isPolyReserved = "address" in item && !!polyKeywords.find((k) => item.address.endsWith(k));
3175
+ if (this.fDSPCode instanceof FaustMonoWebAudioDsp || !isPolyReserved) {
3176
+ if (item.type === "vslider" || item.type === "hslider" || item.type === "nentry") {
3177
+ param = { name: item.address, defaultValue: item.init || 0, minValue: item.min || 0, maxValue: item.max || 0 };
3178
+ } else if (item.type === "button" || item.type === "checkbox") {
3179
+ param = { name: item.address, defaultValue: item.init || 0, minValue: 0, maxValue: 1 };
3180
+ }
3181
+ }
3182
+ if (param)
3183
+ params.push(param);
3184
+ };
3185
+ FaustBaseWebAudioDsp.parseUI(this.fDSPCode.getUI(), callback);
3186
+ return params;
3187
+ }
3188
+ compute(input, output) {
3189
+ return this.fDSPCode.compute(input, output);
3190
+ }
3191
+ setOutputParamHandler(handler) {
3192
+ this.fDSPCode.setOutputParamHandler(handler);
3193
+ }
3194
+ getOutputParamHandler() {
3195
+ return this.fDSPCode.getOutputParamHandler();
3196
+ }
3197
+ setComputeHandler(handler) {
3198
+ this.fDSPCode.setComputeHandler(handler);
3199
+ }
3200
+ getComputeHandler() {
3201
+ return this.fDSPCode.getComputeHandler();
3202
+ }
3203
+ setPlotHandler(handler) {
3204
+ this.fDSPCode.setPlotHandler(handler);
3205
+ }
3206
+ getPlotHandler() {
3207
+ return this.fDSPCode.getPlotHandler();
3208
+ }
3209
+ getNumInputs() {
3210
+ return this.fDSPCode.getNumInputs();
3211
+ }
3212
+ getNumOutputs() {
3213
+ return this.fDSPCode.getNumOutputs();
3214
+ }
3215
+ metadata(handler) {
3216
+ }
3217
+ midiMessage(data) {
3218
+ this.fDSPCode.midiMessage(data);
3219
+ }
3220
+ ctrlChange(chan, ctrl, value) {
3221
+ this.fDSPCode.ctrlChange(chan, ctrl, value);
3222
+ }
3223
+ pitchWheel(chan, value) {
3224
+ this.fDSPCode.pitchWheel(chan, value);
3225
+ }
3226
+ setParamValue(path, value) {
3227
+ this.fDSPCode.setParamValue(path, value);
3228
+ }
3229
+ getParamValue(path) {
3230
+ return this.fDSPCode.getParamValue(path);
3231
+ }
3232
+ getParams() {
3233
+ return this.fDSPCode.getParams();
3234
+ }
3235
+ getMeta() {
3236
+ return this.fDSPCode.getMeta();
3237
+ }
3238
+ getJSON() {
3239
+ return this.fDSPCode.getJSON();
3240
+ }
3241
+ getDescriptors() {
3242
+ return this.fDSPCode.getDescriptors();
3243
+ }
3244
+ getUI() {
3245
+ return this.fDSPCode.getUI();
3246
+ }
3247
+ start() {
3248
+ this.fDSPCode.start();
3249
+ }
3250
+ stop() {
3251
+ this.fDSPCode.stop();
3252
+ }
3253
+ destroy() {
3254
+ this.fDSPCode.destroy();
3255
+ }
3256
+ render(inputs = [], length2 = this.fBufferSize, onUpdate) {
3257
+ let l = 0;
3258
+ const outputs = new Array(this.fDSPCode.getNumOutputs()).fill(null).map(() => new Float32Array(length2));
3259
+ this.fDSPCode.start();
3260
+ while (l < length2) {
3261
+ const sliceLength = Math.min(length2 - l, this.fBufferSize);
3262
+ for (let i = 0; i < this.fDSPCode.getNumInputs(); i++) {
3263
+ let input;
3264
+ if (inputs[i]) {
3265
+ if (inputs[i].length <= l) {
3266
+ input = new Float32Array(sliceLength);
3267
+ } else if (inputs[i].length > l + sliceLength) {
3268
+ input = inputs[i].subarray(l, l + sliceLength);
3269
+ } else {
3270
+ input = inputs[i].subarray(l, inputs[i].length);
3271
+ }
3272
+ } else {
3273
+ input = new Float32Array(sliceLength);
3274
+ }
3275
+ this.fInputs[i] = input;
3276
+ }
3277
+ this.fDSPCode.compute(this.fInputs, this.fOutputs);
3278
+ for (let i = 0; i < this.fDSPCode.getNumOutputs(); i++) {
3279
+ const output = this.fOutputs[i];
3280
+ if (sliceLength < this.fBufferSize) {
3281
+ outputs[i].set(output.subarray(0, sliceLength), l);
3282
+ } else {
3283
+ outputs[i].set(output, l);
3284
+ }
3285
+ }
3286
+ l += this.fBufferSize;
3287
+ onUpdate == null ? void 0 : onUpdate(l);
3288
+ }
3289
+ this.fDSPCode.stop();
3290
+ return outputs;
3291
+ }
3292
+ };
3293
+ var FaustMonoOfflineProcessor = class extends FaustOfflineProcessor {
3294
+ };
3295
+ var FaustPolyOfflineProcessor = class extends FaustOfflineProcessor {
3296
+ keyOn(channel, pitch, velocity) {
3297
+ this.fDSPCode.keyOn(channel, pitch, velocity);
3298
+ }
3299
+ keyOff(channel, pitch, velocity) {
3300
+ this.fDSPCode.keyOff(channel, pitch, velocity);
3301
+ }
3302
+ allNotesOff(hard) {
3303
+ this.fDSPCode.allNotesOff(hard);
3304
+ }
3305
+ };
3306
+ var FaustOfflineProcessor_default = FaustOfflineProcessor;
3307
+
3308
+ // src/FaustSvgDiagrams.ts
3309
+ var FaustSvgDiagrams = class {
3310
+ constructor(compiler) {
3311
+ this.compiler = compiler;
3312
+ }
3313
+ from(name, code, args) {
3314
+ const fs = this.compiler.fs();
3315
+ try {
3316
+ const files2 = fs.readdir(`/${name}-svg/`);
3317
+ files2.filter((file) => file !== "." && file !== "..").forEach((file) => fs.unlink(`/${name}-svg/${file}`));
3318
+ } catch {
3319
+ }
3320
+ const success = this.compiler.generateAuxFiles(name, code, `-lang wasm -o binary -svg ${args}`);
3321
+ if (!success)
3322
+ throw new Error(this.compiler.getErrorMessage());
3323
+ const svgs = {};
3324
+ const files = fs.readdir(`/${name}-svg/`);
3325
+ files.filter((file) => file !== "." && file !== "..").forEach((file) => svgs[file] = fs.readFile(`/${name}-svg/${file}`, { encoding: "utf8" }));
3326
+ return svgs;
3327
+ }
3328
+ };
3329
+ var FaustSvgDiagrams_default = FaustSvgDiagrams;
3330
+
3331
+ // src/FaustCmajor.ts
3332
+ var FaustCmajor = class {
3333
+ constructor(libfaust) {
3334
+ this.fLibFaust = libfaust;
3335
+ }
3336
+ compile(name, code, args) {
3337
+ const fs = this.fLibFaust.fs();
3338
+ const success = this.fLibFaust.generateAuxFiles(name, code, `-lang cmajor-hybrid -cn ${name} -o ${name}.cmajor`);
3339
+ return success ? fs.readFile(`${name}.cmajor`, { encoding: "utf8" }) : "";
3340
+ }
3341
+ };
3342
+ var FaustCmajor_default = FaustCmajor;
3343
+
3344
+ // src/LibFaust.ts
3345
+ var LibFaust = class {
3346
+ constructor(module) {
3347
+ this.fModule = module;
3348
+ this.fCompiler = new module.libFaustWasm();
3349
+ this.fFileSystem = this.fModule.FS;
3350
+ }
3351
+ module() {
3352
+ return this.fModule;
3353
+ }
3354
+ fs() {
3355
+ return this.fFileSystem;
3356
+ }
3357
+ version() {
3358
+ return this.fCompiler.version();
3359
+ }
3360
+ createDSPFactory(name, code, args, useInternalMemory) {
3361
+ return this.fCompiler.createDSPFactory(name, code, args, useInternalMemory);
3362
+ }
3363
+ deleteDSPFactory(cFactory) {
3364
+ return this.fCompiler.deleteDSPFactory(cFactory);
3365
+ }
3366
+ expandDSP(name, code, args) {
3367
+ return this.fCompiler.expandDSP(name, code, args);
3368
+ }
3369
+ generateAuxFiles(name, code, args) {
3370
+ return this.fCompiler.generateAuxFiles(name, code, args);
3371
+ }
3372
+ deleteAllDSPFactories() {
3373
+ return this.fCompiler.deleteAllDSPFactories();
3374
+ }
3375
+ getErrorAfterException() {
3376
+ return this.fCompiler.getErrorAfterException();
3377
+ }
3378
+ cleanupAfterException() {
3379
+ return this.fCompiler.cleanupAfterException();
3380
+ }
3381
+ getInfos(what) {
3382
+ return this.fCompiler.getInfos(what);
3383
+ }
3384
+ toString() {
3385
+ return `LibFaust module: ${this.fModule}, compiler: ${this.fCompiler}`;
3386
+ }
3387
+ };
3388
+ var LibFaust_default = LibFaust;
3389
+
3390
+ // src/WavEncoder.ts
3391
+ var WavEncoder = class {
3392
+ static encode(audioBuffer, options) {
3393
+ const numberOfChannels = audioBuffer.length;
3394
+ const length2 = audioBuffer[0].length;
3395
+ const { shared, float } = options;
3396
+ const bitDepth = float ? 32 : options.bitDepth | 0 || 16;
3397
+ const byteDepth = bitDepth >> 3;
3398
+ const byteLength = length2 * numberOfChannels * byteDepth;
3399
+ const AB = shared ? globalThis.SharedArrayBuffer || globalThis.ArrayBuffer : globalThis.ArrayBuffer;
3400
+ const ab = new AB((44 + byteLength) * Uint8Array.BYTES_PER_ELEMENT);
3401
+ const dataView = new DataView(ab);
3402
+ const writer = new Writer(dataView);
3403
+ const format = {
3404
+ formatId: float ? 3 : 1,
3405
+ float: !!float,
3406
+ numberOfChannels,
3407
+ sampleRate: options.sampleRate,
3408
+ symmetric: !!options.symmetric,
3409
+ length: length2,
3410
+ bitDepth,
3411
+ byteDepth
3412
+ };
3413
+ this.writeHeader(writer, format);
3414
+ this.writeData(writer, audioBuffer, format);
3415
+ return ab;
3416
+ }
3417
+ static writeHeader(writer, format) {
3418
+ const { formatId, sampleRate, bitDepth, numberOfChannels, length: length2, byteDepth } = format;
3419
+ writer.string("RIFF");
3420
+ writer.uint32(writer.dataView.byteLength - 8);
3421
+ writer.string("WAVE");
3422
+ writer.string("fmt ");
3423
+ writer.uint32(16);
3424
+ writer.uint16(formatId);
3425
+ writer.uint16(numberOfChannels);
3426
+ writer.uint32(sampleRate);
3427
+ writer.uint32(sampleRate * numberOfChannels * byteDepth);
3428
+ writer.uint16(numberOfChannels * byteDepth);
3429
+ writer.uint16(bitDepth);
3430
+ writer.string("data");
3431
+ writer.uint32(length2 * numberOfChannels * byteDepth);
3432
+ return writer.pos;
3433
+ }
3434
+ static writeData(writer, audioBuffer, format) {
3435
+ const { bitDepth, float, length: length2, numberOfChannels, symmetric } = format;
3436
+ if (bitDepth === 32 && float) {
3437
+ const { dataView, pos } = writer;
3438
+ const ab = dataView.buffer;
3439
+ const f32View = new Float32Array(ab, pos);
3440
+ if (numberOfChannels === 1) {
3441
+ f32View.set(audioBuffer[0]);
3442
+ return;
3443
+ }
3444
+ for (let ch = 0; ch < numberOfChannels; ch++) {
3445
+ const channel = audioBuffer[ch];
3446
+ for (let i = 0; i < length2; i++) {
3447
+ f32View[i * numberOfChannels + ch] = channel[i];
3448
+ }
3449
+ }
3450
+ return;
3451
+ }
3452
+ const encoderOption = float ? "f" : symmetric ? "s" : "";
3453
+ const methodName = "pcm" + bitDepth + encoderOption;
3454
+ if (!writer[methodName]) {
3455
+ throw new TypeError("Not supported bit depth: " + bitDepth);
3456
+ }
3457
+ const write = writer[methodName].bind(writer);
3458
+ for (let i = 0; i < length2; i++) {
3459
+ for (let j = 0; j < numberOfChannels; j++) {
3460
+ write(audioBuffer[j][i]);
3461
+ }
3462
+ }
3463
+ }
3464
+ };
3465
+ var Writer = class {
3466
+ constructor(dataView) {
3467
+ this.pos = 0;
3468
+ this.dataView = dataView;
3469
+ }
3470
+ int16(value) {
3471
+ this.dataView.setInt16(this.pos, value, true);
3472
+ this.pos += 2;
3473
+ }
3474
+ uint16(value) {
3475
+ this.dataView.setUint16(this.pos, value, true);
3476
+ this.pos += 2;
3477
+ }
3478
+ uint32(value) {
3479
+ this.dataView.setUint32(this.pos, value, true);
3480
+ this.pos += 4;
3481
+ }
3482
+ string(value) {
3483
+ for (let i = 0, imax = value.length; i < imax; i++) {
3484
+ this.dataView.setUint8(this.pos++, value.charCodeAt(i));
3485
+ }
3486
+ }
3487
+ pcm8(valueIn) {
3488
+ let value = valueIn;
3489
+ value = Math.max(-1, Math.min(value, 1));
3490
+ value = (value * 0.5 + 0.5) * 255;
3491
+ value = Math.round(value) | 0;
3492
+ this.dataView.setUint8(this.pos, value);
3493
+ this.pos += 1;
3494
+ }
3495
+ pcm8s(valueIn) {
3496
+ let value = valueIn;
3497
+ value = Math.round(value * 128) + 128;
3498
+ value = Math.max(0, Math.min(value, 255));
3499
+ this.dataView.setUint8(this.pos, value);
3500
+ this.pos += 1;
3501
+ }
3502
+ pcm16(valueIn) {
3503
+ let value = valueIn;
3504
+ value = Math.max(-1, Math.min(value, 1));
3505
+ value = value < 0 ? value * 32768 : value * 32767;
3506
+ value = Math.round(value) | 0;
3507
+ this.dataView.setInt16(this.pos, value, true);
3508
+ this.pos += 2;
3509
+ }
3510
+ pcm16s(valueIn) {
3511
+ let value = valueIn;
3512
+ value = Math.round(value * 32768);
3513
+ value = Math.max(-32768, Math.min(value, 32767));
3514
+ this.dataView.setInt16(this.pos, value, true);
3515
+ this.pos += 2;
3516
+ }
3517
+ pcm24(valueIn) {
3518
+ let value = valueIn;
3519
+ value = Math.max(-1, Math.min(value, 1));
3520
+ value = value < 0 ? 16777216 + value * 8388608 : value * 8388607;
3521
+ value = Math.round(value) | 0;
3522
+ const x0 = value >> 0 & 255;
3523
+ const x1 = value >> 8 & 255;
3524
+ const x2 = value >> 16 & 255;
3525
+ this.dataView.setUint8(this.pos + 0, x0);
3526
+ this.dataView.setUint8(this.pos + 1, x1);
3527
+ this.dataView.setUint8(this.pos + 2, x2);
3528
+ this.pos += 3;
3529
+ }
3530
+ pcm24s(valueIn) {
3531
+ let value = valueIn;
3532
+ value = Math.round(value * 8388608);
3533
+ value = Math.max(-8388608, Math.min(value, 8388607));
3534
+ const x0 = value >> 0 & 255;
3535
+ const x1 = value >> 8 & 255;
3536
+ const x2 = value >> 16 & 255;
3537
+ this.dataView.setUint8(this.pos + 0, x0);
3538
+ this.dataView.setUint8(this.pos + 1, x1);
3539
+ this.dataView.setUint8(this.pos + 2, x2);
3540
+ this.pos += 3;
3541
+ }
3542
+ pcm32(valueIn) {
3543
+ let value = valueIn;
3544
+ value = Math.max(-1, Math.min(value, 1));
3545
+ value = value < 0 ? value * 2147483648 : value * 2147483647;
3546
+ value = Math.round(value) | 0;
3547
+ this.dataView.setInt32(this.pos, value, true);
3548
+ this.pos += 4;
3549
+ }
3550
+ pcm32s(valueIn) {
3551
+ let value = valueIn;
3552
+ value = Math.round(value * 2147483648);
3553
+ value = Math.max(-2147483648, Math.min(value, 2147483647));
3554
+ this.dataView.setInt32(this.pos, value, true);
3555
+ this.pos += 4;
3556
+ }
3557
+ pcm32f(value) {
3558
+ this.dataView.setFloat32(this.pos, value, true);
3559
+ this.pos += 4;
3560
+ }
3561
+ };
3562
+ var WavEncoder_default = WavEncoder;
3563
+
3564
+ // src/WavDecoder.ts
3565
+ var WavDecoder = class {
3566
+ static decode(buffer, options) {
3567
+ const dataView = new DataView(buffer);
3568
+ const reader = new Reader(dataView);
3569
+ if (reader.string(4) !== "RIFF") {
3570
+ throw new TypeError("Invalid WAV file");
3571
+ }
3572
+ reader.uint32();
3573
+ if (reader.string(4) !== "WAVE") {
3574
+ throw new TypeError("Invalid WAV file");
3575
+ }
3576
+ let format = null;
3577
+ let audioData = null;
3578
+ do {
3579
+ const chunkType = reader.string(4);
3580
+ const chunkSize = reader.uint32();
3581
+ if (chunkType === "fmt ") {
3582
+ format = this.decodeFormat(reader, chunkSize);
3583
+ } else if (chunkType === "data") {
3584
+ audioData = this.decodeData(reader, chunkSize, format, options || {});
3585
+ } else {
3586
+ reader.skip(chunkSize);
3587
+ }
3588
+ } while (audioData === null);
3589
+ return audioData;
3590
+ }
3591
+ static decodeFormat(reader, chunkSize) {
3592
+ const formats = {
3593
+ 1: "lpcm",
3594
+ 3: "lpcm"
3595
+ };
3596
+ const formatId = reader.uint16();
3597
+ if (!formats.hasOwnProperty(formatId)) {
3598
+ throw new TypeError("Unsupported format in WAV file: 0x" + formatId.toString(16));
3599
+ }
3600
+ const format = {
3601
+ formatId,
3602
+ float: formatId === 3,
3603
+ numberOfChannels: reader.uint16(),
3604
+ sampleRate: reader.uint32(),
3605
+ byteRate: reader.uint32(),
3606
+ blockSize: reader.uint16(),
3607
+ bitDepth: reader.uint16()
3608
+ };
3609
+ reader.skip(chunkSize - 16);
3610
+ return format;
3611
+ }
3612
+ static decodeData(reader, chunkSizeIn, format, options) {
3613
+ const chunkSize = Math.min(chunkSizeIn, reader.remain());
3614
+ const length2 = Math.floor(chunkSize / format.blockSize);
3615
+ const numberOfChannels = format.numberOfChannels;
3616
+ const sampleRate = format.sampleRate;
3617
+ const channelData = new Array(numberOfChannels);
3618
+ for (let ch = 0; ch < numberOfChannels; ch++) {
3619
+ const AB = options.shared ? globalThis.SharedArrayBuffer || globalThis.ArrayBuffer : globalThis.ArrayBuffer;
3620
+ const ab = new AB(length2 * Float32Array.BYTES_PER_ELEMENT);
3621
+ channelData[ch] = new Float32Array(ab);
3622
+ }
3623
+ this.readPCM(reader, channelData, length2, format, options);
3624
+ return {
3625
+ numberOfChannels,
3626
+ length: length2,
3627
+ sampleRate,
3628
+ channelData
3629
+ };
3630
+ }
3631
+ static readPCM(reader, channelData, length2, format, options) {
3632
+ const bitDepth = format.bitDepth;
3633
+ const decoderOption = format.float ? "f" : options.symmetric ? "s" : "";
3634
+ const methodName = "pcm" + bitDepth + decoderOption;
3635
+ if (!reader[methodName]) {
3636
+ throw new TypeError("Not supported bit depth: " + format.bitDepth);
3637
+ }
3638
+ const read = reader[methodName].bind(reader);
3639
+ const numberOfChannels = format.numberOfChannels;
3640
+ for (let i = 0; i < length2; i++) {
3641
+ for (let ch = 0; ch < numberOfChannels; ch++) {
3642
+ channelData[ch][i] = read();
3643
+ }
3644
+ }
3645
+ }
3646
+ };
3647
+ var Reader = class {
3648
+ constructor(dataView) {
3649
+ this.pos = 0;
3650
+ this.dataView = dataView;
3651
+ }
3652
+ remain() {
3653
+ return this.dataView.byteLength - this.pos;
3654
+ }
3655
+ skip(n) {
3656
+ this.pos += n;
3657
+ }
3658
+ uint8() {
3659
+ const data = this.dataView.getUint8(this.pos);
3660
+ this.pos += 1;
3661
+ return data;
3662
+ }
3663
+ int16() {
3664
+ const data = this.dataView.getInt16(this.pos, true);
3665
+ this.pos += 2;
3666
+ return data;
3667
+ }
3668
+ uint16() {
3669
+ const data = this.dataView.getUint16(this.pos, true);
3670
+ this.pos += 2;
3671
+ return data;
3672
+ }
3673
+ uint32() {
3674
+ const data = this.dataView.getUint32(this.pos, true);
3675
+ this.pos += 4;
3676
+ return data;
3677
+ }
3678
+ string(n) {
3679
+ let data = "";
3680
+ for (let i = 0; i < n; i++) {
3681
+ data += String.fromCharCode(this.uint8());
3682
+ }
3683
+ return data;
3684
+ }
3685
+ pcm8() {
3686
+ const data = this.dataView.getUint8(this.pos) - 128;
3687
+ this.pos += 1;
3688
+ return data < 0 ? data / 128 : data / 127;
3689
+ }
3690
+ pcm8s() {
3691
+ const data = this.dataView.getUint8(this.pos) - 127.5;
3692
+ this.pos += 1;
3693
+ return data / 127.5;
3694
+ }
3695
+ pcm16() {
3696
+ const data = this.dataView.getInt16(this.pos, true);
3697
+ this.pos += 2;
3698
+ return data < 0 ? data / 32768 : data / 32767;
3699
+ }
3700
+ pcm16s() {
3701
+ const data = this.dataView.getInt16(this.pos, true);
3702
+ this.pos += 2;
3703
+ return data / 32768;
3704
+ }
3705
+ pcm24() {
3706
+ const x0 = this.dataView.getUint8(this.pos + 0);
3707
+ const x1 = this.dataView.getUint8(this.pos + 1);
3708
+ const x2 = this.dataView.getUint8(this.pos + 2);
3709
+ const xx = x0 + (x1 << 8) + (x2 << 16);
3710
+ const data = xx > 8388608 ? xx - 16777216 : xx;
3711
+ this.pos += 3;
3712
+ return data < 0 ? data / 8388608 : data / 8388607;
3713
+ }
3714
+ pcm24s() {
3715
+ const x0 = this.dataView.getUint8(this.pos + 0);
3716
+ const x1 = this.dataView.getUint8(this.pos + 1);
3717
+ const x2 = this.dataView.getUint8(this.pos + 2);
3718
+ const xx = x0 + (x1 << 8) + (x2 << 16);
3719
+ const data = xx > 8388608 ? xx - 16777216 : xx;
3720
+ this.pos += 3;
3721
+ return data / 8388608;
3722
+ }
3723
+ pcm32() {
3724
+ const data = this.dataView.getInt32(this.pos, true);
3725
+ this.pos += 4;
3726
+ return data < 0 ? data / 2147483648 : data / 2147483647;
3727
+ }
3728
+ pcm32s() {
3729
+ const data = this.dataView.getInt32(this.pos, true);
3730
+ this.pos += 4;
3731
+ return data / 2147483648;
3732
+ }
3733
+ pcm32f() {
3734
+ const data = this.dataView.getFloat32(this.pos, true);
3735
+ this.pos += 4;
3736
+ return data;
3737
+ }
3738
+ pcm64f() {
3739
+ const data = this.dataView.getFloat64(this.pos, true);
3740
+ this.pos += 8;
3741
+ return data;
3742
+ }
3743
+ };
3744
+ var WavDecoder_default = WavDecoder;
3745
+
3746
+ // src/FaustAudioWorkletNode.ts
3747
+ var FaustAudioWorkletNode = class extends (globalThis.AudioWorkletNode || null) {
3748
+ constructor(context, name, factory, options, nodeOptions = {}) {
3749
+ const JSONObj = JSON.parse(factory.json);
3750
+ super(context, name, {
3751
+ numberOfInputs: JSONObj.inputs > 0 ? 1 : 0,
3752
+ numberOfOutputs: JSONObj.outputs > 0 ? 1 : 0,
3753
+ channelCount: Math.max(1, JSONObj.inputs),
3754
+ outputChannelCount: [JSONObj.outputs],
3755
+ channelCountMode: "explicit",
3756
+ channelInterpretation: "speakers",
3757
+ processorOptions: options,
3758
+ ...nodeOptions
3759
+ });
3760
+ this.fJSONDsp = JSONObj;
3761
+ this.fJSON = factory.json;
3762
+ this.fOutputHandler = null;
3763
+ this.fComputeHandler = null;
3764
+ this.fPlotHandler = null;
3765
+ this.fDescriptor = [];
3766
+ this.fInputsItems = [];
3767
+ this.fUICallback = (item) => {
3768
+ if (item.type === "vslider" || item.type === "hslider" || item.type === "button" || item.type === "checkbox" || item.type === "nentry") {
3769
+ this.fInputsItems.push(item.address);
3770
+ this.fDescriptor.push(item);
3771
+ }
3772
+ };
3773
+ FaustBaseWebAudioDsp.parseUI(this.fJSONDsp.ui, this.fUICallback);
3774
+ this.port.onmessage = (e) => {
3775
+ if (e.data.type === "param" && this.fOutputHandler) {
3776
+ this.fOutputHandler(e.data.path, e.data.value);
3777
+ } else if (e.data.type === "plot" && this.fPlotHandler) {
3778
+ this.fPlotHandler(e.data.value, e.data.index, e.data.events);
3779
+ }
3780
+ };
3781
+ }
3782
+ setOutputParamHandler(handler) {
3783
+ this.fOutputHandler = handler;
3784
+ }
3785
+ getOutputParamHandler() {
3786
+ return this.fOutputHandler;
3787
+ }
3788
+ setComputeHandler(handler) {
3789
+ this.fComputeHandler = handler;
3790
+ }
3791
+ getComputeHandler() {
3792
+ return this.fComputeHandler;
3793
+ }
3794
+ setPlotHandler(handler) {
3795
+ this.fPlotHandler = handler;
3796
+ if (this.fPlotHandler) {
3797
+ this.port.postMessage({ type: "setPlotHandler", data: true });
3798
+ } else {
3799
+ this.port.postMessage({ type: "setPlotHandler", data: false });
3800
+ }
3801
+ }
3802
+ getPlotHandler() {
3803
+ return this.fPlotHandler;
3804
+ }
3805
+ getNumInputs() {
3806
+ return this.fJSONDsp.inputs;
3807
+ }
3808
+ getNumOutputs() {
3809
+ return this.fJSONDsp.outputs;
3810
+ }
3811
+ compute(inputs, outputs) {
3812
+ return false;
3813
+ }
3814
+ metadata(handler) {
3815
+ if (this.fJSONDsp.meta) {
3816
+ this.fJSONDsp.meta.forEach((meta) => handler(Object.keys(meta)[0], meta[Object.keys(meta)[0]]));
3817
+ }
3818
+ }
3819
+ midiMessage(data) {
3820
+ const cmd = data[0] >> 4;
3821
+ const channel = data[0] & 15;
3822
+ const data1 = data[1];
3823
+ const data2 = data[2];
3824
+ if (cmd === 11)
3825
+ this.ctrlChange(channel, data1, data2);
3826
+ else if (cmd === 14)
3827
+ this.pitchWheel(channel, data2 * 128 + data1);
3828
+ else
3829
+ this.port.postMessage({ type: "midi", data });
3830
+ }
3831
+ ctrlChange(channel, ctrl, value) {
3832
+ const e = { type: "ctrlChange", data: [channel, ctrl, value] };
3833
+ this.port.postMessage(e);
3834
+ }
3835
+ pitchWheel(channel, wheel) {
3836
+ const e = { type: "pitchWheel", data: [channel, wheel] };
3837
+ this.port.postMessage(e);
3838
+ }
3839
+ setParamValue(path, value) {
3840
+ const e = { type: "param", data: { path, value } };
3841
+ this.port.postMessage(e);
3842
+ const param = this.parameters.get(path);
3843
+ if (param)
3844
+ param.setValueAtTime(value, this.context.currentTime);
3845
+ }
3846
+ getParamValue(path) {
3847
+ const param = this.parameters.get(path);
3848
+ return param ? param.value : 0;
3849
+ }
3850
+ getParams() {
3851
+ return this.fInputsItems;
3852
+ }
3853
+ getMeta() {
3854
+ return this.fJSONDsp;
3855
+ }
3856
+ getJSON() {
3857
+ return JSON.stringify(this.getMeta());
3858
+ }
3859
+ getUI() {
3860
+ return this.fJSONDsp.ui;
3861
+ }
3862
+ getDescriptors() {
3863
+ return this.fDescriptor;
3864
+ }
3865
+ start() {
3866
+ this.port.postMessage({ type: "start" });
3867
+ }
3868
+ stop() {
3869
+ this.port.postMessage({ type: "stop" });
3870
+ }
3871
+ destroy() {
3872
+ this.port.postMessage({ type: "destroy" });
3873
+ this.port.close();
3874
+ }
3875
+ };
3876
+ var FaustMonoAudioWorkletNode = class extends FaustAudioWorkletNode {
3877
+ constructor(context, name, factory, sampleSize, nodeOptions = {}) {
3878
+ super(context, name, factory, { name, factory, sampleSize }, nodeOptions);
3879
+ this.onprocessorerror = (e) => {
3880
+ throw e;
3881
+ };
3882
+ }
3883
+ };
3884
+ var FaustPolyAudioWorkletNode = class extends FaustAudioWorkletNode {
3885
+ constructor(context, name, voiceFactory, mixerModule, voices, sampleSize, effectFactory, nodeOptions = {}) {
3886
+ super(
3887
+ context,
3888
+ name,
3889
+ voiceFactory,
3890
+ {
3891
+ name,
3892
+ voiceFactory,
3893
+ mixerModule,
3894
+ voices,
3895
+ sampleSize,
3896
+ effectFactory
3897
+ },
3898
+ nodeOptions
3899
+ );
3900
+ this.onprocessorerror = (e) => {
3901
+ throw e;
3902
+ };
3903
+ this.fJSONEffect = effectFactory ? JSON.parse(effectFactory.json) : null;
3904
+ if (this.fJSONEffect) {
3905
+ FaustBaseWebAudioDsp.parseUI(this.fJSONEffect.ui, this.fUICallback);
3906
+ }
3907
+ }
3908
+ keyOn(channel, pitch, velocity) {
3909
+ const e = { type: "keyOn", data: [channel, pitch, velocity] };
3910
+ this.port.postMessage(e);
3911
+ }
3912
+ keyOff(channel, pitch, velocity) {
3913
+ const e = { type: "keyOff", data: [channel, pitch, velocity] };
3914
+ this.port.postMessage(e);
3915
+ }
3916
+ allNotesOff(hard) {
3917
+ const e = { type: "ctrlChange", data: [0, 123, 0] };
3918
+ this.port.postMessage(e);
3919
+ }
3920
+ getMeta() {
3921
+ const o = this.fJSONDsp;
3922
+ const e = this.fJSONEffect;
3923
+ const r = { ...o };
3924
+ if (e) {
3925
+ r.ui = [{
3926
+ type: "tgroup",
3927
+ label: "Sequencer",
3928
+ items: [
3929
+ { type: "vgroup", label: "Instrument", items: o.ui },
3930
+ { type: "vgroup", label: "Effect", items: e.ui }
3931
+ ]
3932
+ }];
3933
+ } else {
3934
+ r.ui = [{
3935
+ type: "tgroup",
3936
+ label: "Polyphonic",
3937
+ items: [
3938
+ { type: "vgroup", label: "Voices", items: o.ui }
3939
+ ]
3940
+ }];
3941
+ }
3942
+ return r;
3943
+ }
3944
+ getJSON() {
3945
+ return JSON.stringify(this.getMeta());
3946
+ }
3947
+ getUI() {
3948
+ return this.getMeta().ui;
3949
+ }
3950
+ };
3951
+
3952
+ // src/FaustScriptProcessorNode.ts
3953
+ var FaustScriptProcessorNode = class extends (globalThis.ScriptProcessorNode || null) {
3954
+ init(instance) {
3955
+ this.fDSPCode = instance;
3956
+ this.fInputs = new Array(this.fDSPCode.getNumInputs());
3957
+ this.fOutputs = new Array(this.fDSPCode.getNumOutputs());
3958
+ this.onaudioprocess = (e) => {
3959
+ for (let chan = 0; chan < this.fDSPCode.getNumInputs(); chan++) {
3960
+ this.fInputs[chan] = e.inputBuffer.getChannelData(chan);
3961
+ }
3962
+ for (let chan = 0; chan < this.fDSPCode.getNumOutputs(); chan++) {
3963
+ this.fOutputs[chan] = e.outputBuffer.getChannelData(chan);
3964
+ }
3965
+ return this.fDSPCode.compute(this.fInputs, this.fOutputs);
3966
+ };
3967
+ this.start();
3968
+ }
3969
+ compute(input, output) {
3970
+ return this.fDSPCode.compute(input, output);
3971
+ }
3972
+ setOutputParamHandler(handler) {
3973
+ this.fDSPCode.setOutputParamHandler(handler);
3974
+ }
3975
+ getOutputParamHandler() {
3976
+ return this.fDSPCode.getOutputParamHandler();
3977
+ }
3978
+ setComputeHandler(handler) {
3979
+ this.fDSPCode.setComputeHandler(handler);
3980
+ }
3981
+ getComputeHandler() {
3982
+ return this.fDSPCode.getComputeHandler();
3983
+ }
3984
+ setPlotHandler(handler) {
3985
+ this.fDSPCode.setPlotHandler(handler);
3986
+ }
3987
+ getPlotHandler() {
3988
+ return this.fDSPCode.getPlotHandler();
3989
+ }
3990
+ getNumInputs() {
3991
+ return this.fDSPCode.getNumInputs();
3992
+ }
3993
+ getNumOutputs() {
3994
+ return this.fDSPCode.getNumOutputs();
3995
+ }
3996
+ metadata(handler) {
3997
+ }
3998
+ midiMessage(data) {
3999
+ this.fDSPCode.midiMessage(data);
4000
+ }
4001
+ ctrlChange(chan, ctrl, value) {
4002
+ this.fDSPCode.ctrlChange(chan, ctrl, value);
4003
+ }
4004
+ pitchWheel(chan, value) {
4005
+ this.fDSPCode.pitchWheel(chan, value);
4006
+ }
4007
+ setParamValue(path, value) {
4008
+ this.fDSPCode.setParamValue(path, value);
4009
+ }
4010
+ getParamValue(path) {
4011
+ return this.fDSPCode.getParamValue(path);
4012
+ }
4013
+ getParams() {
4014
+ return this.fDSPCode.getParams();
4015
+ }
4016
+ getMeta() {
4017
+ return this.fDSPCode.getMeta();
4018
+ }
4019
+ getJSON() {
4020
+ return this.fDSPCode.getJSON();
4021
+ }
4022
+ getDescriptors() {
4023
+ return this.fDSPCode.getDescriptors();
4024
+ }
4025
+ getUI() {
4026
+ return this.fDSPCode.getUI();
4027
+ }
4028
+ start() {
4029
+ this.fDSPCode.start();
4030
+ }
4031
+ stop() {
4032
+ this.fDSPCode.stop();
4033
+ }
4034
+ destroy() {
4035
+ this.fDSPCode.destroy();
4036
+ }
4037
+ };
4038
+ var FaustMonoScriptProcessorNode = class extends FaustScriptProcessorNode {
4039
+ };
4040
+ var FaustPolyScriptProcessorNode = class extends FaustScriptProcessorNode {
4041
+ keyOn(channel, pitch, velocity) {
4042
+ this.fDSPCode.keyOn(channel, pitch, velocity);
4043
+ }
4044
+ keyOff(channel, pitch, velocity) {
4045
+ this.fDSPCode.keyOff(channel, pitch, velocity);
4046
+ }
4047
+ allNotesOff(hard) {
4048
+ this.fDSPCode.allNotesOff(hard);
4049
+ }
4050
+ };
4051
+
4052
+ // src/FaustDspGenerator.ts
4053
+ var _FaustMonoDspGenerator = class {
4054
+ constructor() {
4055
+ this.factory = null;
4056
+ }
4057
+ async compile(compiler, name, code, args) {
4058
+ this.factory = await compiler.createMonoDSPFactory(name, code, args);
4059
+ if (this.factory) {
4060
+ this.name = name;
4061
+ return this;
4062
+ } else {
4063
+ return null;
4064
+ }
4065
+ }
4066
+ async createNode(context, name = this.name, factory = this.factory, sp = false, bufferSize = 1024, processorName = (factory == null ? void 0 : factory.shaKey) || name) {
4067
+ var _a, _b;
4068
+ if (!factory)
4069
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4070
+ const meta = JSON.parse(factory.json);
4071
+ const sampleSize = meta.compile_options.match("-double") ? 8 : 4;
4072
+ if (sp) {
4073
+ const instance = await FaustWasmInstantiator_default.createAsyncMonoDSPInstance(factory);
4074
+ const monoDsp = new FaustMonoWebAudioDsp(instance, context.sampleRate, sampleSize, bufferSize);
4075
+ await monoDsp.init(context);
4076
+ const sp2 = context.createScriptProcessor(bufferSize, monoDsp.getNumInputs(), monoDsp.getNumOutputs());
4077
+ Object.setPrototypeOf(sp2, FaustMonoScriptProcessorNode.prototype);
4078
+ sp2.init(monoDsp);
4079
+ return sp2;
4080
+ } else {
4081
+ if (!_FaustMonoDspGenerator.gWorkletProcessors.has(context))
4082
+ _FaustMonoDspGenerator.gWorkletProcessors.set(context, /* @__PURE__ */ new Set());
4083
+ if (!((_a = _FaustMonoDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _a.has(processorName))) {
4084
+ try {
4085
+ const processorCode = `
4086
+ // DSP name and JSON string for DSP are generated
4087
+ const faustData = ${JSON.stringify({
4088
+ processorName,
4089
+ dspName: name,
4090
+ dspMeta: meta,
4091
+ poly: false
4092
+ })};
4093
+ // Implementation needed classes of functions
4094
+ const ${FaustDspInstance.name} = ${FaustDspInstance.toString()}
4095
+ const ${FaustBaseWebAudioDsp.name} = ${FaustBaseWebAudioDsp.toString()}
4096
+ const ${FaustMonoWebAudioDsp.name} = ${FaustMonoWebAudioDsp.toString()}
4097
+ const ${FaustWasmInstantiator_default.name} = ${FaustWasmInstantiator_default.toString()}
4098
+ // Put them in dependencies
4099
+ const dependencies = {
4100
+ FaustBaseWebAudioDsp: ${FaustBaseWebAudioDsp.name},
4101
+ FaustMonoWebAudioDsp: ${FaustMonoWebAudioDsp.name},
4102
+ FaustWasmInstantiator: ${FaustWasmInstantiator_default.name}
4103
+ };
4104
+ // Generate the actual AudioWorkletProcessor code
4105
+ (${FaustAudioWorkletProcessor_default.toString()})(dependencies, faustData);
4106
+ `;
4107
+ const url = URL.createObjectURL(new Blob([processorCode], { type: "text/javascript" }));
4108
+ await context.audioWorklet.addModule(url);
4109
+ (_b = _FaustMonoDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _b.add(processorName);
4110
+ } catch (e) {
4111
+ throw e;
4112
+ }
4113
+ }
4114
+ const node = new FaustMonoAudioWorkletNode(context, processorName, factory, sampleSize);
4115
+ return node;
4116
+ }
4117
+ }
4118
+ async createFFTNode(context, fftUtils, name = this.name, factory = this.factory, fftOptions = {}, processorName = (factory == null ? void 0 : factory.shaKey) ? `${factory.shaKey}_fft` : name) {
4119
+ var _a, _b;
4120
+ if (!factory)
4121
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4122
+ const meta = JSON.parse(factory.json);
4123
+ const sampleSize = meta.compile_options.match("-double") ? 8 : 4;
4124
+ if (!_FaustMonoDspGenerator.gWorkletProcessors.has(context))
4125
+ _FaustMonoDspGenerator.gWorkletProcessors.set(context, /* @__PURE__ */ new Set());
4126
+ if (!((_a = _FaustMonoDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _a.has(processorName))) {
4127
+ try {
4128
+ const processorCode = `
4129
+ // DSP name and JSON string for DSP are generated
4130
+ const faustData = ${JSON.stringify({
4131
+ processorName,
4132
+ dspName: name,
4133
+ dspMeta: meta,
4134
+ fftOptions
4135
+ })};
4136
+ // Implementation needed classes of functions
4137
+ const ${FaustDspInstance.name} = ${FaustDspInstance.toString()}
4138
+ const ${FaustBaseWebAudioDsp.name} = ${FaustBaseWebAudioDsp.toString()}
4139
+ const ${FaustMonoWebAudioDsp.name} = ${FaustMonoWebAudioDsp.toString()}
4140
+ const ${FaustWasmInstantiator_default.name} = ${FaustWasmInstantiator_default.toString()}
4141
+ const FFTUtils = ${fftUtils.toString()}
4142
+ // Put them in dependencies
4143
+ const dependencies = {
4144
+ FaustBaseWebAudioDsp: ${FaustBaseWebAudioDsp.name},
4145
+ FaustMonoWebAudioDsp: ${FaustMonoWebAudioDsp.name},
4146
+ FaustWasmInstantiator: ${FaustWasmInstantiator_default.name},
4147
+ FFTUtils
4148
+ };
4149
+ // Generate the actual AudioWorkletProcessor code
4150
+ (${FaustFFTAudioWorkletProcessor_default.toString()})(dependencies, faustData);
4151
+ `;
4152
+ const url = URL.createObjectURL(new Blob([processorCode], { type: "text/javascript" }));
4153
+ await context.audioWorklet.addModule(url);
4154
+ (_b = _FaustMonoDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _b.add(processorName);
4155
+ } catch (e) {
4156
+ throw e;
4157
+ }
4158
+ }
4159
+ const node = new FaustMonoAudioWorkletNode(context, processorName, factory, sampleSize, { channelCount: Math.max(1, Math.ceil(meta.inputs / 3)), outputChannelCount: [Math.ceil(meta.outputs / 2)] });
4160
+ if (fftOptions.fftSize) {
4161
+ const param = node.parameters.get("fftSize");
4162
+ if (param)
4163
+ param.value = fftOptions.fftSize;
4164
+ }
4165
+ if (fftOptions.fftOverlap) {
4166
+ const param = node.parameters.get("fftOverlap");
4167
+ if (param)
4168
+ param.value = fftOptions.fftOverlap;
4169
+ }
4170
+ if (typeof fftOptions.defaultWindowFunction === "number") {
4171
+ const param = node.parameters.get("windowFunction");
4172
+ if (param)
4173
+ param.value = fftOptions.defaultWindowFunction + 1;
4174
+ }
4175
+ if (typeof fftOptions.noIFFT === "boolean") {
4176
+ const param = node.parameters.get("noIFFT");
4177
+ if (param)
4178
+ param.value = +fftOptions.noIFFT;
4179
+ }
4180
+ return node;
4181
+ }
4182
+ async createAudioWorkletProcessor(name = this.name, factory = this.factory, processorName = (factory == null ? void 0 : factory.shaKey) || name) {
4183
+ if (!factory)
4184
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4185
+ const meta = JSON.parse(factory.json);
4186
+ const dependencies = {
4187
+ FaustBaseWebAudioDsp,
4188
+ FaustMonoWebAudioDsp,
4189
+ FaustWasmInstantiator: FaustWasmInstantiator_default,
4190
+ FaustPolyWebAudioDsp: void 0,
4191
+ FaustWebAudioDspVoice: void 0
4192
+ };
4193
+ try {
4194
+ const faustData = {
4195
+ processorName,
4196
+ dspName: name,
4197
+ dspMeta: meta,
4198
+ poly: false
4199
+ };
4200
+ const Processor = FaustAudioWorkletProcessor_default(dependencies, faustData);
4201
+ return Processor;
4202
+ } catch (e) {
4203
+ throw e;
4204
+ }
4205
+ }
4206
+ async createOfflineProcessor(sampleRate, bufferSize, factory = this.factory) {
4207
+ if (!factory)
4208
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4209
+ const meta = JSON.parse(factory.json);
4210
+ const instance = await FaustWasmInstantiator_default.createAsyncMonoDSPInstance(factory);
4211
+ const sampleSize = meta.compile_options.match("-double") ? 8 : 4;
4212
+ const monoDsp = new FaustMonoWebAudioDsp(instance, sampleRate, sampleSize, bufferSize);
4213
+ await monoDsp.init(null);
4214
+ return new FaustMonoOfflineProcessor(monoDsp, bufferSize);
4215
+ }
4216
+ getMeta() {
4217
+ return JSON.parse(this.factory.json);
4218
+ }
4219
+ getJSON() {
4220
+ return JSON.stringify(this.getMeta());
4221
+ }
4222
+ getUI() {
4223
+ return this.getMeta().ui;
4224
+ }
4225
+ };
4226
+ var FaustMonoDspGenerator = _FaustMonoDspGenerator;
4227
+ FaustMonoDspGenerator.gWorkletProcessors = /* @__PURE__ */ new Map();
4228
+ var _FaustPolyDspGenerator = class {
4229
+ constructor() {
4230
+ this.voiceFactory = null;
4231
+ this.effectFactory = null;
4232
+ }
4233
+ async compile(compiler, name, dspCodeAux, args, effectCodeAux = `dsp_code = environment{
4234
+ ${dspCodeAux}
4235
+ };
4236
+ process = dsp_code.effect;`) {
4237
+ try {
4238
+ this.effectFactory = await compiler.createPolyDSPFactory(name, effectCodeAux, args);
4239
+ if (this.effectFactory) {
4240
+ const effectJSON = JSON.parse(this.effectFactory.json);
4241
+ const dspCode = `
4242
+ // Voice output is forced to 2, when DSP is stereo or effect has 2 ins or 2 outs,
4243
+ // so that the effect can process the 2 channels of the voice
4244
+ adaptOut(1,1,1) = _;
4245
+ adaptOut(1,1,2) = _ <: _,0; // The left channel only is kept
4246
+ adaptOut(1,2,1) = _ <: _,_;
4247
+ adaptOut(1,2,2) = _ <: _,_;
4248
+ adaptOut(2,1,1) = _,_;
4249
+ adaptOut(2,1,2) = _,_;
4250
+ adaptOut(2,2,1) = _,_;
4251
+ adaptOut(2,2,2) = _,_;
4252
+ adaptor(F) = adaptOut(outputs(F),${effectJSON.inputs},${effectJSON.outputs});
4253
+ dsp_code = environment{
4254
+ ${dspCodeAux}
4255
+ };
4256
+ process = dsp_code.process : adaptor(dsp_code.process);`;
4257
+ const effectCode = `
4258
+ // Inputs
4259
+ adaptIn(1,1,1) = _;
4260
+ adaptIn(1,1,2) = _,_ :> _;
4261
+ adaptIn(1,2,1) = _,_;
4262
+ adaptIn(1,2,2) = _,_;
4263
+ adaptIn(2,1,1) = _,_ :> _;
4264
+ adaptIn(2,1,2) = _,_ :> _;
4265
+ adaptIn(2,2,1) = _,_;
4266
+ adaptIn(2,2,2) = _,_;
4267
+ // Outputs
4268
+ adaptOut(1,1) = _ <: _,0; // The left channel only is kept
4269
+ adaptOut(1,2) = _,_;
4270
+ adaptOut(2,1) = _ <: _,0; // The left channel only is kept
4271
+ adaptOut(2,2) = _,_;
4272
+ adaptorIns(F) = adaptIn(outputs(F),${effectJSON.inputs},${effectJSON.outputs});
4273
+ adaptorOuts = adaptOut(${effectJSON.inputs},${effectJSON.outputs});
4274
+ dsp_code = environment{
4275
+ ${dspCodeAux}
4276
+ };
4277
+ process = adaptorIns(dsp_code.process) : dsp_code.effect : adaptorOuts;`;
4278
+ this.voiceFactory = await compiler.createPolyDSPFactory(name, dspCode, args);
4279
+ try {
4280
+ this.effectFactory = await compiler.createPolyDSPFactory(name, effectCode, args + " -inpl");
4281
+ } catch (e) {
4282
+ console.warn(e);
4283
+ }
4284
+ }
4285
+ } catch (e) {
4286
+ console.warn(e);
4287
+ this.voiceFactory = await compiler.createPolyDSPFactory(name, dspCodeAux, args);
4288
+ }
4289
+ if (this.voiceFactory) {
4290
+ this.name = name;
4291
+ const voiceMeta = JSON.parse(this.voiceFactory.json);
4292
+ const isDouble = voiceMeta.compile_options.match("-double");
4293
+ const { mixerBuffer, mixerModule } = await compiler.getAsyncInternalMixerModule(!!isDouble);
4294
+ this.mixerBuffer = mixerBuffer;
4295
+ this.mixerModule = mixerModule;
4296
+ return this;
4297
+ } else {
4298
+ return null;
4299
+ }
4300
+ }
4301
+ async createNode(context, voices, name = this.name, voiceFactory = this.voiceFactory, mixerModule = this.mixerModule, effectFactory = this.effectFactory, sp = false, bufferSize = 1024, processorName = ((voiceFactory == null ? void 0 : voiceFactory.shaKey) || "") + ((effectFactory == null ? void 0 : effectFactory.shaKey) || "") || `${name}_poly`) {
4302
+ var _a, _b;
4303
+ if (!voiceFactory)
4304
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4305
+ const voiceMeta = JSON.parse(voiceFactory.json);
4306
+ const effectMeta = effectFactory ? JSON.parse(effectFactory.json) : void 0;
4307
+ const sampleSize = voiceMeta.compile_options.match("-double") ? 8 : 4;
4308
+ if (sp) {
4309
+ const instance = await FaustWasmInstantiator_default.createAsyncPolyDSPInstance(voiceFactory, mixerModule, voices, effectFactory || void 0);
4310
+ const polyDsp = new FaustPolyWebAudioDsp(instance, context.sampleRate, sampleSize, bufferSize);
4311
+ await polyDsp.init(context);
4312
+ const sp2 = context.createScriptProcessor(bufferSize, polyDsp.getNumInputs(), polyDsp.getNumOutputs());
4313
+ Object.setPrototypeOf(sp2, FaustPolyScriptProcessorNode.prototype);
4314
+ sp2.init(polyDsp);
4315
+ return sp2;
4316
+ } else {
4317
+ if (!_FaustPolyDspGenerator.gWorkletProcessors.has(context))
4318
+ _FaustPolyDspGenerator.gWorkletProcessors.set(context, /* @__PURE__ */ new Set());
4319
+ if (!((_a = _FaustPolyDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _a.has(processorName))) {
4320
+ try {
4321
+ const processorCode = `
4322
+ // DSP name and JSON string for DSP are generated
4323
+ const faustData = ${JSON.stringify({
4324
+ processorName,
4325
+ dspName: name,
4326
+ dspMeta: voiceMeta,
4327
+ poly: true,
4328
+ effectMeta
4329
+ })};
4330
+ // Implementation needed classes of functions
4331
+ const ${FaustDspInstance.name} = ${FaustDspInstance.toString()}
4332
+ const ${FaustBaseWebAudioDsp.name} = ${FaustBaseWebAudioDsp.toString()}
4333
+ const ${FaustPolyWebAudioDsp.name} = ${FaustPolyWebAudioDsp.toString()}
4334
+ const ${FaustWebAudioDspVoice.name} = ${FaustWebAudioDspVoice.toString()}
4335
+ const ${FaustWasmInstantiator_default.name} = ${FaustWasmInstantiator_default.toString()}
4336
+ // Put them in dependencies
4337
+ const dependencies = {
4338
+ FaustBaseWebAudioDsp: ${FaustBaseWebAudioDsp.name},
4339
+ FaustPolyWebAudioDsp: ${FaustPolyWebAudioDsp.name},
4340
+ FaustWasmInstantiator: ${FaustWasmInstantiator_default.name}
4341
+ };
4342
+ // Generate the actual AudioWorkletProcessor code
4343
+ (${FaustAudioWorkletProcessor_default.toString()})(dependencies, faustData);
4344
+ `;
4345
+ const url = URL.createObjectURL(new Blob([processorCode], { type: "text/javascript" }));
4346
+ await context.audioWorklet.addModule(url);
4347
+ (_b = _FaustPolyDspGenerator.gWorkletProcessors.get(context)) == null ? void 0 : _b.add(processorName);
4348
+ } catch (e) {
4349
+ throw e;
4350
+ }
4351
+ }
4352
+ const node = new FaustPolyAudioWorkletNode(context, processorName, voiceFactory, mixerModule, voices, sampleSize, effectFactory || void 0);
4353
+ return node;
4354
+ }
4355
+ }
4356
+ async createAudioWorkletProcessor(name = this.name, voiceFactory = this.voiceFactory, effectFactory = this.effectFactory, processorName = ((voiceFactory == null ? void 0 : voiceFactory.shaKey) || "") + ((effectFactory == null ? void 0 : effectFactory.shaKey) || "") || `${name}_poly`) {
4357
+ if (!voiceFactory)
4358
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4359
+ const voiceMeta = JSON.parse(voiceFactory.json);
4360
+ const effectMeta = effectFactory ? JSON.parse(effectFactory.json) : void 0;
4361
+ const sampleSize = voiceMeta.compile_options.match("-double") ? 8 : 4;
4362
+ try {
4363
+ const dependencies = {
4364
+ FaustBaseWebAudioDsp,
4365
+ FaustMonoWebAudioDsp: void 0,
4366
+ FaustWasmInstantiator: FaustWasmInstantiator_default,
4367
+ FaustPolyWebAudioDsp,
4368
+ FaustWebAudioDspVoice
4369
+ };
4370
+ const faustData = {
4371
+ processorName,
4372
+ dspName: name,
4373
+ dspMeta: voiceMeta,
4374
+ poly: true,
4375
+ effectMeta
4376
+ };
4377
+ const Processor = FaustAudioWorkletProcessor_default(dependencies, faustData);
4378
+ return Processor;
4379
+ } catch (e) {
4380
+ throw e;
4381
+ }
4382
+ }
4383
+ async createOfflineProcessor(sampleRate, bufferSize, voices, voiceFactory = this.voiceFactory, mixerModule = this.mixerModule, effectFactory = this.effectFactory) {
4384
+ if (!voiceFactory)
4385
+ throw new Error("Code is not compiled, please define the factory or call `await this.compile()` first.");
4386
+ const voiceMeta = JSON.parse(voiceFactory.json);
4387
+ const effectMeta = effectFactory ? JSON.parse(effectFactory.json) : void 0;
4388
+ const instance = await FaustWasmInstantiator_default.createAsyncPolyDSPInstance(voiceFactory, mixerModule, voices, effectFactory || void 0);
4389
+ const sampleSize = voiceMeta.compile_options.match("-double") ? 8 : 4;
4390
+ const polyDsp = new FaustPolyWebAudioDsp(instance, sampleRate, sampleSize, bufferSize);
4391
+ return new FaustPolyOfflineProcessor(polyDsp, bufferSize);
4392
+ }
4393
+ getMeta() {
4394
+ const o = this.voiceFactory ? JSON.parse(this.voiceFactory.json) : null;
4395
+ const e = this.effectFactory ? JSON.parse(this.effectFactory.json) : null;
4396
+ const r = { ...o };
4397
+ if (e) {
4398
+ r.ui = [{
4399
+ type: "tgroup",
4400
+ label: "Sequencer",
4401
+ items: [
4402
+ { type: "vgroup", label: "Instrument", items: o.ui },
4403
+ { type: "vgroup", label: "Effect", items: e.ui }
4404
+ ]
4405
+ }];
4406
+ } else {
4407
+ r.ui = [{
4408
+ type: "tgroup",
4409
+ label: "Polyphonic",
4410
+ items: [
4411
+ { type: "vgroup", label: "Voices", items: o.ui }
4412
+ ]
4413
+ }];
4414
+ }
4415
+ return r;
4416
+ }
4417
+ getJSON() {
4418
+ return JSON.stringify(this.getMeta());
4419
+ }
4420
+ getUI() {
4421
+ return this.getMeta().ui;
4422
+ }
4423
+ };
4424
+ var FaustPolyDspGenerator = _FaustPolyDspGenerator;
4425
+ FaustPolyDspGenerator.gWorkletProcessors = /* @__PURE__ */ new Map();
4426
+ export {
4427
+ FaustAudioWorkletNode,
4428
+ FaustBaseWebAudioDsp,
4429
+ FaustCmajor_default as FaustCmajor,
4430
+ FaustCompiler_default as FaustCompiler,
4431
+ FaustDspInstance,
4432
+ FaustMonoAudioWorkletNode,
4433
+ FaustMonoDspGenerator,
4434
+ FaustMonoOfflineProcessor,
4435
+ FaustMonoScriptProcessorNode,
4436
+ FaustMonoWebAudioDsp,
4437
+ FaustOfflineProcessor_default as FaustOfflineProcessor,
4438
+ FaustPolyAudioWorkletNode,
4439
+ FaustPolyDspGenerator,
4440
+ FaustPolyOfflineProcessor,
4441
+ FaustPolyScriptProcessorNode,
4442
+ FaustPolyWebAudioDsp,
4443
+ FaustScriptProcessorNode,
4444
+ FaustSvgDiagrams_default as FaustSvgDiagrams,
4445
+ FaustWasmInstantiator_default as FaustWasmInstantiator,
4446
+ FaustWebAudioDspVoice,
4447
+ LibFaust_default as LibFaust,
4448
+ WavDecoder_default as WavDecoder,
4449
+ WavEncoder_default as WavEncoder,
4450
+ ab2str,
4451
+ FaustAudioWorkletProcessor_default as getFaustAudioWorkletProcessor,
4452
+ FaustFFTAudioWorkletProcessor_default as getFaustFFTAudioWorkletProcessor,
4453
+ instantiateFaustModuleFromFile_default as instantiateFaustModuleFromFile,
4454
+ str2ab
4455
+ };
4456
+ /*! *****************************************************************************
4457
+ Copyright (c) Microsoft Corporation.
4458
+
4459
+ Permission to use, copy, modify, and/or distribute this software for any
4460
+ purpose with or without fee is hereby granted.
4461
+
4462
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4463
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4464
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4465
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4466
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4467
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4468
+ PERFORMANCE OF THIS SOFTWARE.
4469
+ ***************************************************************************** */
4470
+ //# sourceMappingURL=index.js.map