@onda-lang/webaudio 0.8.39 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -1,3 +1,12 @@
1
+ import {
2
+ ONDA_RUNTIME_ERROR, RUNTIME_ERROR_MESSAGES, STATUS_OPERATIONS,
3
+ } from "./runtime-status.js";
4
+ import {
5
+ createExecutionStatusRing, openExecutionStatusRing, drainExecutionStatusRing,
6
+ STATUS_WAKE, wakeExecutionStatusRing, MAX_IN_FLIGHT_REQUESTS,
7
+ } from "./execution-status-ring.js";
8
+ export { ONDA_RUNTIME_ERROR } from "./runtime-status.js";
9
+
1
10
  import { paramAddress, paramElementAddress, paramSmoothingSamples } from "./param-metadata.js";
2
11
  import {
3
12
  PayloadPlan,
@@ -47,6 +56,15 @@ export class OndaExecutionError extends Error {
47
56
  }
48
57
  }
49
58
 
59
+ export class OndaRuntimeError extends Error {
60
+ constructor(operation, code) {
61
+ super(`${operation}: ${RUNTIME_ERROR_MESSAGES[code] ?? "unknown runtime error"}`);
62
+ this.name = "OndaRuntimeError";
63
+ this.operation = operation;
64
+ this.code = code;
65
+ }
66
+ }
67
+
50
68
  const registrationByContext = new WeakMap();
51
69
  const DEFAULT_DELEGATE_CAPACITY_BYTES = 64 * 1024;
52
70
  const DEFAULT_PRINT_CAPACITY_BYTES = 64 * 1024;
@@ -144,6 +162,7 @@ function audioWorkletNodeOptionsFromValidated(
144
162
  delegateCapacityBytes,
145
163
  printCapacityBytes,
146
164
  executionOutputRing,
165
+ executionStatusRing: createExecutionStatusRing(),
147
166
  printCollectionEnabled: options.onPrint !== undefined,
148
167
  printSubscriptionId: options.onPrint === undefined ? 0 : 1,
149
168
  initialize: options.initialize === true,
@@ -299,6 +318,7 @@ async function createOndaAudioProcessorImpl(context, artifact, options, initiali
299
318
  validated.metadata,
300
319
  options.onPrint,
301
320
  nodeOptions.processorOptions.executionOutputRing,
321
+ nodeOptions.processorOptions.executionStatusRing,
302
322
  );
303
323
  if (!initialize) return processor;
304
324
  try {
@@ -340,6 +360,7 @@ export class OndaAudioProcessor {
340
360
  metadata = null,
341
361
  initialPrintListener = undefined,
342
362
  executionOutputRing = null,
363
+ executionStatusRing = null,
343
364
  ) {
344
365
  if (
345
366
  initialPrintListener !== undefined
@@ -353,6 +374,16 @@ export class OndaAudioProcessor {
353
374
  this.eventPlans = new WeakMap();
354
375
  this.paramControls = new WeakMap();
355
376
  this.paramElements = new WeakMap();
377
+ this.executionStatusRing = executionStatusRing === null
378
+ ? null : openExecutionStatusRing(executionStatusRing);
379
+ this.statusPoll = null;
380
+ this.statusDrainActive = false;
381
+ this.statusNeedsWake = this.executionStatusRing !== null
382
+ && typeof Atomics.waitAsync !== "function";
383
+ this.requestQueue = [];
384
+ this.inFlightRequests = new Set();
385
+ this.sendingRequests = false;
386
+ this.requestPumpScheduled = false;
356
387
  this.nextRequestId = 1;
357
388
  this.pending = new Map();
358
389
  this.executionErrorListeners = new Set();
@@ -373,26 +404,24 @@ export class OndaAudioProcessor {
373
404
  this.executionOutputWaitGeneration = 0;
374
405
  this.executionOutputPoll = null;
375
406
  this.executionOutputDrainActive = false;
407
+ this.executionOutputReading = false;
376
408
  this.closed = false;
377
409
  this.closeReason = null;
378
410
  this.handleMessage = (event) => {
379
411
  const message = event.data ?? {};
380
- const error = message.type === "onda-error"
381
- ? Number.isInteger(message.status)
382
- ? new OndaExecutionError(message.error, message.operation, message.status)
383
- : new Error(message.error)
384
- : null;
385
- if (message.requestId === undefined) {
386
- if (error instanceof OndaExecutionError) {
387
- this.notifyListeners(this.executionErrorListeners, error);
388
- }
412
+ if (message.type === "onda-status-ready") {
413
+ this.drainExecutionStatus();
414
+ return;
415
+ }
416
+ if (message.type === "onda-status") {
417
+ this.consumeExecutionStatus(message.requestId, message.operation, message.status);
389
418
  return;
390
419
  }
391
420
  const pending = this.pending.get(message.requestId);
392
421
  if (!pending) return;
393
422
  this.pending.delete(message.requestId);
394
- if (error) pending.reject(error);
395
- else pending.resolve(message);
423
+ pending.resolve(message);
424
+ this.finishRequest(message.requestId);
396
425
  };
397
426
  this.handleProcessorError = (event) => {
398
427
  const error = event.error instanceof Error
@@ -405,6 +434,105 @@ export class OndaAudioProcessor {
405
434
  node.port.addEventListener("message", this.handleMessage);
406
435
  node.port.start?.();
407
436
  if (this.printListeners.size !== 0) this.startExecutionOutputDrain();
437
+ this.startExecutionStatusDrain();
438
+ }
439
+
440
+ startExecutionStatusDrain() {
441
+ const ring = this.executionStatusRing;
442
+ if (!ring) return;
443
+ if (typeof Atomics.waitAsync !== "function") {
444
+ this.statusPoll = setInterval(() => this.drainExecutionStatus(), 16);
445
+ this.statusPoll.unref?.();
446
+ return;
447
+ }
448
+ const wait = async () => {
449
+ while (!this.closed) {
450
+ const expected = Atomics.load(ring, STATUS_WAKE);
451
+ this.drainExecutionStatus();
452
+ if (this.closed) return;
453
+ const result = Atomics.waitAsync(ring, STATUS_WAKE, expected);
454
+ if (result.async) await result.value;
455
+ }
456
+ };
457
+ void wait().catch((error) => this.close(error));
458
+ }
459
+
460
+ drainExecutionStatus() {
461
+ if (!this.executionStatusRing || this.closed || this.statusDrainActive) return 0;
462
+ this.statusDrainActive = true;
463
+ try {
464
+ return drainExecutionStatusRing(this.executionStatusRing,
465
+ (id, operation, status) => this.consumeExecutionStatus(id, operation, status));
466
+ } finally {
467
+ this.statusDrainActive = false;
468
+ if (this.requestQueue.length !== 0) this.scheduleRequests();
469
+ }
470
+ }
471
+
472
+ consumeExecutionStatus(requestId, operation, status) {
473
+ // Preserve diagnostic delivery before resolving/rejecting its execution call.
474
+ this.drainExecutionOutput();
475
+ const name = STATUS_OPERATIONS[operation] ?? "unknown";
476
+ const error = status < 0
477
+ ? new OndaRuntimeError(name, status)
478
+ : status > 0
479
+ ? new OndaExecutionError(
480
+ `${name} failed with Onda execution status ${status}`, name, status)
481
+ : null;
482
+ if (status === ONDA_RUNTIME_ERROR.TRANSPORT_OVERFLOW) {
483
+ this.notifyListeners(this.executionErrorListeners, error);
484
+ this.close(error);
485
+ return;
486
+ }
487
+ if (!requestId) {
488
+ if (error) this.notifyListeners(this.executionErrorListeners, error);
489
+ return;
490
+ }
491
+ const pending = this.pending.get(requestId);
492
+ if (!pending) return;
493
+ this.pending.delete(requestId);
494
+ if (error) pending.reject(error);
495
+ else pending.resolve({ type: "onda-ok", operation: name, requestId });
496
+ this.finishRequest(requestId);
497
+ }
498
+
499
+ finishRequest(requestId) {
500
+ if (this.inFlightRequests.delete(requestId)) this.scheduleRequests();
501
+ }
502
+
503
+ scheduleRequests() {
504
+ if (this.closed || this.requestPumpScheduled) return;
505
+ this.requestPumpScheduled = true;
506
+ queueMicrotask(() => {
507
+ this.requestPumpScheduled = false;
508
+ this.sendQueuedRequests();
509
+ });
510
+ }
511
+
512
+ sendQueuedRequests() {
513
+ if (this.closed || this.sendingRequests || this.statusDrainActive
514
+ || this.requestQueue.length === 0
515
+ || this.inFlightRequests.size >= MAX_IN_FLIGHT_REQUESTS) return;
516
+ this.sendingRequests = true;
517
+ try {
518
+ // Consume asynchronous failures before reusing credits, including when a
519
+ // data reply on the port (rather than a ring status) released the credit.
520
+ this.drainExecutionStatus();
521
+ while (!this.closed && this.requestQueue.length !== 0
522
+ && this.inFlightRequests.size < MAX_IN_FLIGHT_REQUESTS) {
523
+ const { message, transfer } = this.requestQueue.shift();
524
+ this.inFlightRequests.add(message.requestId);
525
+ try {
526
+ this.node.port.postMessage(message, transfer);
527
+ } catch (error) {
528
+ this.pending.get(message.requestId)?.reject(error);
529
+ this.pending.delete(message.requestId);
530
+ this.finishRequest(message.requestId);
531
+ }
532
+ }
533
+ } finally {
534
+ this.sendingRequests = false;
535
+ }
408
536
  }
409
537
 
410
538
  startExecutionOutputDrain() {
@@ -474,17 +602,19 @@ export class OndaAudioProcessor {
474
602
  }
475
603
 
476
604
  drainExecutionOutput() {
477
- if (!this.executionOutputRing) return 0;
478
- return drainExecutionOutputRing(
479
- this.executionOutputRing,
480
- (entry) => {
605
+ if (!this.executionOutputRing || this.executionOutputReading) return 0;
606
+ this.executionOutputReading = true;
607
+ try {
608
+ return drainExecutionOutputRing(this.executionOutputRing, (entry) => {
481
609
  try {
482
610
  this.consumeExecutionOutput(entry);
483
611
  } catch (error) {
484
612
  this.reportListenerError(error);
485
613
  }
486
- },
487
- );
614
+ });
615
+ } finally {
616
+ this.executionOutputReading = false;
617
+ }
488
618
  }
489
619
 
490
620
  consumeExecutionOutput(entry) {
@@ -641,15 +771,18 @@ export class OndaAudioProcessor {
641
771
  if (this.closed) {
642
772
  return Promise.reject(this.closeReason);
643
773
  }
644
- const requestId = this.nextRequestId++;
774
+ // IDs travel as u32; never reuse an ID that still belongs to queued work.
775
+ let requestId;
776
+ do {
777
+ requestId = this.nextRequestId;
778
+ this.nextRequestId = (this.nextRequestId + 1) >>> 0 || 1;
779
+ } while (this.pending.has(requestId));
645
780
  return new Promise((resolve, reject) => {
646
781
  this.pending.set(requestId, { resolve, reject });
647
- try {
648
- this.node.port.postMessage({ type, ...fields, requestId }, transfer);
649
- } catch (error) {
650
- this.pending.delete(requestId);
651
- reject(error);
652
- }
782
+ this.requestQueue.push({
783
+ message: { ...fields, type, requestId, notifyStatus: this.statusNeedsWake }, transfer,
784
+ });
785
+ this.sendQueuedRequests();
653
786
  });
654
787
  }
655
788
 
@@ -876,10 +1009,18 @@ export class OndaAudioProcessor {
876
1009
  }
877
1010
 
878
1011
  restoreSnapshot(snapshot) {
879
- const bytes = snapshot instanceof Uint8Array
880
- ? snapshot.slice()
881
- : new Uint8Array(snapshot.slice(0));
882
- return this.request("restore-snapshot", { snapshot: bytes }, [bytes.buffer]);
1012
+ try {
1013
+ this.assertOpen();
1014
+ if (!(snapshot instanceof Uint8Array) && !(snapshot instanceof ArrayBuffer)) {
1015
+ throw new OndaRuntimeError("restore-snapshot", ONDA_RUNTIME_ERROR.INVALID_SNAPSHOT);
1016
+ }
1017
+ const bytes = snapshot instanceof Uint8Array
1018
+ ? snapshot.slice()
1019
+ : new Uint8Array(snapshot.slice(0));
1020
+ return this.request("restore-snapshot", { snapshot: bytes }, [bytes.buffer]);
1021
+ } catch (error) {
1022
+ return Promise.reject(error);
1023
+ }
883
1024
  }
884
1025
 
885
1026
  async readControlOutputs() {
@@ -919,6 +1060,10 @@ export class OndaAudioProcessor {
919
1060
  this.node.port.removeEventListener("message", this.handleMessage);
920
1061
  this.node.removeEventListener("processorerror", this.handleProcessorError);
921
1062
  this.stopExecutionOutputDrain();
1063
+ if (this.statusPoll !== null) clearInterval(this.statusPoll);
1064
+ if (this.executionStatusRing) wakeExecutionStatusRing(this.executionStatusRing);
1065
+ this.requestQueue.length = 0;
1066
+ this.inFlightRequests.clear();
922
1067
  for (const pending of this.pending.values()) pending.reject(this.closeReason);
923
1068
  this.pending.clear();
924
1069
  this.executionErrorListeners.clear();
@@ -0,0 +1,48 @@
1
+ // Numeric worklet failures. Only the main-thread adapter formats these as errors.
2
+ export const ONDA_RUNTIME_ERROR = Object.freeze({
3
+ UNINITIALIZED: -1,
4
+ INVALID_INIT_MODE: -2,
5
+ UNKNOWN_EVENT: -3,
6
+ INVALID_PAYLOAD: -4,
7
+ PAYLOAD_CAPACITY: -5,
8
+ INVALID_SNAPSHOT: -6,
9
+ UNKNOWN_OPERATION: -7,
10
+ INVALID_PARAMETER: -8,
11
+ INVALID_SMOOTHING: -9,
12
+ INVALID_AUDIO_SHAPE: -10,
13
+ INVALID_OUTPUT: -11,
14
+ UNEXPECTED_FAILURE: -12,
15
+ TRANSPORT_OVERFLOW: -13,
16
+ INVALID_STORAGE: -14,
17
+ UNKNOWN_BUFFER: -15,
18
+ });
19
+
20
+ export const RUNTIME_ERROR_MESSAGES = Object.freeze({
21
+ [-1]: "full initialization is required",
22
+ [-2]: "invalid Onda init mode",
23
+ [-3]: "unknown Onda event",
24
+ [-4]: "event payload must be encoded bytes",
25
+ [-5]: "event payload exceeds configured capacity",
26
+ [-6]: "snapshot storage has an invalid type or size",
27
+ [-7]: "unknown Onda worklet operation",
28
+ [-8]: "invalid parameter selector, element, value, or storage",
29
+ [-9]: "invalid parameter smoothing duration",
30
+ [-10]: "AudioWorklet channels have missing or inconsistent frame counts",
31
+ [-11]: "processor returned invalid execution-output storage",
32
+ [-12]: "unexpected processor failure; full initialization is required",
33
+ [-13]: "execution-status transport overflowed; recreate the processor",
34
+ [-14]: "invalid processor storage",
35
+ [-15]: "unknown Onda buffer",
36
+ });
37
+
38
+ export const STATUS_OPERATIONS = Object.freeze([
39
+ "unknown", "process", "init", "event", "set-param", "set-param-smoothing",
40
+ "reset-params", "restore-snapshot", "snapshot", "read-control-outputs",
41
+ "read-buffer", "delegate-subscription", "print-subscription",
42
+ ]);
43
+
44
+ export function failureStatus(error) {
45
+ return Number.isInteger(error) && (error > 0 || RUNTIME_ERROR_MESSAGES[error])
46
+ ? error
47
+ : ONDA_RUNTIME_ERROR.UNEXPECTED_FAILURE;
48
+ }