alpha2 0.4.5 → 0.5.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.
Files changed (119) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +28 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +109 -173
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +98 -157
  53. package/dist/frame-supply.js +191 -162
  54. package/dist/generated/project-schema.d.ts +742 -464
  55. package/dist/generated/project-schema.js +63 -2
  56. package/dist/generated/project-shape.js +663 -118
  57. package/dist/geometry.d.ts +28 -34
  58. package/dist/geometry.js +18 -23
  59. package/dist/gpu-recovery.d.ts +92 -0
  60. package/dist/gpu-recovery.js +135 -0
  61. package/dist/hdr-frames.d.ts +88 -62
  62. package/dist/hdr-frames.js +123 -46
  63. package/dist/index.d.ts +4 -0
  64. package/dist/index.js +4 -0
  65. package/dist/json-text.d.ts +13 -23
  66. package/dist/json-text.js +10 -20
  67. package/dist/layout-values.d.ts +14 -22
  68. package/dist/layout-values.js +18 -21
  69. package/dist/layout.d.ts +55 -55
  70. package/dist/layout.js +37 -36
  71. package/dist/loudness.d.ts +27 -32
  72. package/dist/loudness.js +19 -23
  73. package/dist/media.d.ts +85 -237
  74. package/dist/media.js +133 -287
  75. package/dist/mediabunny.d.ts +173 -237
  76. package/dist/mediabunny.js +943 -518
  77. package/dist/physical-frames.d.ts +5 -17
  78. package/dist/physical-frames.js +4 -11
  79. package/dist/player.d.ts +56 -47
  80. package/dist/player.js +155 -40
  81. package/dist/presented-frames.d.ts +2 -7
  82. package/dist/presented-frames.js +3 -8
  83. package/dist/project.d.ts +83 -110
  84. package/dist/project.js +421 -447
  85. package/dist/rate-control.d.ts +9 -23
  86. package/dist/rate-control.js +7 -18
  87. package/dist/renderer-choice.d.ts +41 -0
  88. package/dist/renderer-choice.js +82 -0
  89. package/dist/repacked-bytes.d.ts +0 -2
  90. package/dist/repacked-bytes.js +2 -5
  91. package/dist/robustness.d.ts +25 -37
  92. package/dist/robustness.js +71 -54
  93. package/dist/sha256.d.ts +5 -13
  94. package/dist/sha256.js +9 -24
  95. package/dist/text.d.ts +106 -63
  96. package/dist/text.js +44 -69
  97. package/dist/video-frames.d.ts +7 -25
  98. package/dist/video-frames.js +12 -29
  99. package/dist/waveform.d.ts +5 -11
  100. package/dist/waveform.js +4 -9
  101. package/dist/worker-error.d.ts +5 -20
  102. package/dist/worker-error.js +8 -25
  103. package/dist/worker.d.ts +82 -92
  104. package/dist/worker.js +239 -144
  105. package/package.json +26 -2
  106. package/wasm/alpha2_audio_worklet.wasm +0 -0
  107. package/wasm/alpha2_extensions.d.ts +26 -47
  108. package/wasm/alpha2_extensions.js +26 -47
  109. package/wasm/alpha2_extensions_bg.wasm +0 -0
  110. package/wasm/alpha2_wasm.d.ts +487 -543
  111. package/wasm/alpha2_wasm.js +669 -572
  112. package/wasm/alpha2_wasm_bg.wasm +0 -0
  113. package/wasm/alpha2_wasm_bg.wasm.d.ts +20 -8
  114. package/wasm/rust-crate-licenses.md +2 -2
  115. package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
  116. package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
  117. package/wasm/snippets/alpha2-wasm-57b04ecc6db57e1f/inline2.js +0 -52
  118. /package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
  119. /package/wasm/snippets/{alpha2-wasm-57b04ecc6db57e1f → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
@@ -2,23 +2,17 @@ import { TICKS_PER_SECOND } from "./project.js";
2
2
  /**
3
3
  * Browser plumbing for engine-mixed timeline audio.
4
4
  *
5
- * The engine mixes blocks inside the worker that owns the wasm module. Those
6
- * blocks reach the audio thread through {@link AudioRingBuffer}, a lock-free
7
- * single-producer/single-consumer ring in shared memory, so the worklet never
8
- * waits on a message and the mixer never runs on the audio thread.
5
+ * The engine mixes in the wasm worker, and blocks reach the audio thread through
6
+ * {@link AudioRingBuffer}, a lock-free SPSC ring in shared memory, so neither side waits on the
7
+ * other.
9
8
  *
10
- * `SharedArrayBuffer` requires a cross-origin-isolated document
11
- * (`Cross-Origin-Opener-Policy: same-origin` and
12
- * `Cross-Origin-Embedder-Policy: require-corp`). Call
13
- * {@link canShareAudioMemory} before choosing this path.
9
+ * `SharedArrayBuffer` requires a cross-origin-isolated document; check
10
+ * {@link canShareAudioMemory} first.
14
11
  */
15
12
  /**
16
- * Control slots held in the ring's shared `Int32Array` header.
17
- *
18
- * Each slot has one writing side, which keeps the ring single-producer/single-consumer: the reader
19
- * owns `READ_INDEX` and `CLEARED_EPOCH`; the writer owns `WRITE_INDEX`, `CLEAR_TO`, and
20
- * `CLEAR_EPOCH`. A clear is a request (`CLEAR_TO`, then a new `CLEAR_EPOCH`) that the reader
21
- * carries out at its next read.
13
+ * Control slots in the ring's shared header. Each slot has a single writer: the reader owns
14
+ * `READ_INDEX` and `CLEARED_EPOCH`, the writer the rest. A clear is a request (`CLEAR_TO`, then a
15
+ * new `CLEAR_EPOCH`) that the reader carries out at its next read.
22
16
  */
23
17
  const READ_INDEX = 0;
24
18
  const WRITE_INDEX = 1;
@@ -28,23 +22,18 @@ const CLEARED_EPOCH = 4;
28
22
  const HEADER_SLOTS = 5;
29
23
  /** Byte length of an {@link AudioRingTransfer}'s `control` buffer. */
30
24
  export const AUDIO_RING_CONTROL_BYTES = HEADER_SLOTS * Int32Array.BYTES_PER_ELEMENT;
31
- /**
32
- * Whether shared memory is usable for the audio ring: `SharedArrayBuffer` exists and the document
33
- * is cross-origin isolated.
34
- */
25
+ /** Whether `SharedArrayBuffer` exists and the document is cross-origin isolated. */
35
26
  export function canShareAudioMemory() {
36
27
  return (typeof SharedArrayBuffer === "function" &&
37
28
  globalThis.crossOriginIsolated ===
38
29
  true);
39
30
  }
40
31
  /**
41
- * A lock-free planar audio ring shared by one writer and one reader.
32
+ * A lock-free planar audio ring for exactly one writer and one reader.
42
33
  *
43
- * Indices are monotonic sample counts that wrap at 2^32. The capacity is a power of two, so it
44
- * divides 2^32 and an index keeps its slot across the wrap. Each side publishes its index with a
45
- * sequentially consistent `Atomics.store` after writing or reading the samples, and the other side
46
- * loads it with `Atomics.load`, so neither side blocks and neither sees samples before they are
47
- * written. This holds only for one writer and one reader.
34
+ * Indices are sample counts wrapping at 2^32; a power-of-two capacity keeps slots stable across
35
+ * the wrap. Each side publishes its index with `Atomics.store` after touching the samples, so the
36
+ * other side never sees samples before they are written.
48
37
  */
49
38
  export class AudioRingBuffer {
50
39
  #control;
@@ -68,11 +57,10 @@ export class AudioRingBuffer {
68
57
  this.#planes = planes;
69
58
  }
70
59
  /**
71
- * Allocates a ring holding at least `capacity` samples per channel, rounded up to a power of two.
60
+ * Allocates a ring of at least `capacity` samples per channel, rounded up to a power of two.
72
61
  *
73
62
  * @param channels 1 or 2.
74
- * @param capacity From 2 to 2^30. A fraction is rounded up with the rest, so a ring sized from
75
- * an odd sample rate (`sampleRate / 2` at 11 025 Hz) holds at least that much.
63
+ * @param capacity From 2 to 2^30; fractions round up.
76
64
  * @throws RangeError for a channel count or capacity out of range.
77
65
  * @throws Error when shared memory is unavailable ({@link canShareAudioMemory} is false).
78
66
  */
@@ -95,14 +83,14 @@ export class AudioRingBuffer {
95
83
  });
96
84
  }
97
85
  /**
98
- * Attaches to a ring described by a transferred handle, sharing its memory.
86
+ * Attaches to a transferred ring, sharing its memory.
99
87
  *
100
88
  * @throws RangeError when the capacity is not a power of two or the control buffer is too small.
101
89
  */
102
90
  static attach(transfer) {
103
91
  return new AudioRingBuffer(transfer);
104
92
  }
105
- /** The handle to post to the other thread; posting it shares, not copies, the ring. */
93
+ /** Handle to post to the other thread; the memory is shared, not copied. */
106
94
  get transfer() {
107
95
  return {
108
96
  control: this.#control.buffer,
@@ -117,10 +105,7 @@ export class AudioRingBuffer {
117
105
  get capacity() {
118
106
  return this.#capacity;
119
107
  }
120
- /**
121
- * Samples per channel the reader will still play: everything written since the last clear, even
122
- * before the reader has carried that clear out.
123
- */
108
+ /** Samples per channel written since the last clear, even if the reader has not applied it. */
124
109
  get available() {
125
110
  const write = Atomics.load(this.#control, WRITE_INDEX) >>> 0;
126
111
  const from = this.#clearPending()
@@ -130,10 +115,8 @@ export class AudioRingBuffer {
130
115
  return available <= this.#capacity ? available : 0;
131
116
  }
132
117
  /**
133
- * Samples per channel the writer may still push.
134
- *
135
- * Audio a pending clear discards still occupies its slots until the reader moves past it, so it
136
- * counts against the space here.
118
+ * Samples per channel the writer may still push. Audio a pending clear discards still occupies
119
+ * its slots until the reader applies the clear.
137
120
  */
138
121
  get writable() {
139
122
  const write = Atomics.load(this.#control, WRITE_INDEX) >>> 0;
@@ -146,11 +129,8 @@ export class AudioRingBuffer {
146
129
  Atomics.load(this.#control, CLEARED_EPOCH));
147
130
  }
148
131
  /**
149
- * Writes the first `frames` samples of each plane. Writer side only.
150
- *
151
- * A channel with no plane of its own takes `planes[0]`; a non-finite sample is written as 0.
152
- * Returns how many samples per channel were accepted, which is less than `frames` when the reader
153
- * has not drained enough.
132
+ * Writer side: writes up to `frames` samples per channel and returns how many were accepted.
133
+ * Missing planes take `planes[0]`; non-finite samples become 0.
154
134
  *
155
135
  * @throws RangeError when `frames` is not a non-negative whole number, before any index moves.
156
136
  */
@@ -176,13 +156,9 @@ export class AudioRingBuffer {
176
156
  return accepted;
177
157
  }
178
158
  /**
179
- * Reads `frames` samples per channel into caller-owned planes, carrying out a pending clear
180
- * first. Reader side only.
181
- *
182
- * Returns how many samples per channel were produced; the rest of each plane is filled with
183
- * silence, so an underrun is heard as a gap rather than as stale audio. Channels are mixed as
184
- * WebAudio's speaker rules mix them: a plane past the ring's channel count receives channel 0,
185
- * and a single plane read from a stereo ring receives the average of both.
159
+ * Reader side: applies a pending clear, then reads up to `frames` samples per channel and returns
160
+ * how many were produced. The rest is filled with silence. Channels fold as WebAudio's speaker
161
+ * rules do: extra planes take channel 0, and a mono read of a stereo ring averages both.
186
162
  *
187
163
  * @throws RangeError when `frames` is not a non-negative whole number, before any index moves.
188
164
  */
@@ -212,11 +188,8 @@ export class AudioRingBuffer {
212
188
  return produced;
213
189
  }
214
190
  /**
215
- * Reader side: carries out a pending clear and returns the read index.
216
- *
217
- * The read index only moves forward, to where the writer stood when it asked, so the writer's
218
- * view of free space is never too large. The worklet processor's reader repeats this logic, so a
219
- * change here must be made there too.
191
+ * Reader side: applies a pending clear and returns the read index. The index only moves forward,
192
+ * so the writer never overestimates free space. Keep in sync with the worklet processor's reader.
220
193
  */
221
194
  #applyClear() {
222
195
  let read = Atomics.load(this.#control, READ_INDEX) >>> 0;
@@ -231,8 +204,8 @@ export class AudioRingBuffer {
231
204
  return read;
232
205
  }
233
206
  /**
234
- * Writer side: discards everything written so far, as a seek needs. The reader carries it out at
235
- * its next read, so the writer may keep writing the new position's audio at once.
207
+ * Writer side: discards everything written so far. The reader applies it at its next read, so the
208
+ * writer may immediately write audio for the new position.
236
209
  */
237
210
  clear() {
238
211
  const write = Atomics.load(this.#control, WRITE_INDEX);
@@ -240,13 +213,12 @@ export class AudioRingBuffer {
240
213
  Atomics.add(this.#control, CLEAR_EPOCH, 1);
241
214
  }
242
215
  }
243
- /** A frame count a ring can move by: a whole number, never NaN, which would reset an index. */
216
+ /** Rejects non-integer counts; NaN would corrupt an index. */
244
217
  function checkFrames(frames) {
245
218
  if (!Number.isSafeInteger(frames) || frames < 0) {
246
219
  throw new RangeError("audio frame count must be a non-negative whole number");
247
220
  }
248
221
  }
249
- /** A pump option that sizes blocks or fill, both counted in whole samples. */
250
222
  function positiveFrames(value, name) {
251
223
  if (!Number.isSafeInteger(value) || value < 1) {
252
224
  throw new RangeError(`audio pump ${name} must be a positive whole number of samples`);
@@ -257,13 +229,11 @@ function isPowerOfTwo(value) {
257
229
  return Number.isInteger(value) && value >= 2 && (value & (value - 1)) === 0;
258
230
  }
259
231
  /**
260
- * Keeps an {@link AudioRingBuffer} ahead of the audio thread.
232
+ * Keeps an {@link AudioRingBuffer} ahead of the audio thread. The host drives it from its own
233
+ * scheduler; this package owns no clock.
261
234
  *
262
- * The pump is driven by the host's own scheduler (a timer, a message, or the
263
- * worklet's own fill notifications) so this package never owns a clock.
264
- *
265
- * The constructor throws `RangeError` when `startSample` is not a non-negative integer, or a
266
- * `blockFrames` or `targetFrames` option is not a positive one.
235
+ * The constructor throws `RangeError` when `startSample` is not a non-negative integer, or
236
+ * `blockFrames` or `targetFrames` is not a positive one.
267
237
  */
268
238
  export class AudioPump {
269
239
  #source;
@@ -274,8 +244,7 @@ export class AudioPump {
274
244
  #nextSample;
275
245
  #startSample;
276
246
  #running = false;
277
- // Replaced by every seek and aborted with it, so a mix asked for before the seek is known stale
278
- // when it settles, and its source may stop working on it.
247
+ // Aborted and replaced on every seek, marking in-flight mixes stale.
279
248
  #position = new AbortController();
280
249
  constructor(source, ring, startSample = 0, options = {}) {
281
250
  if (!Number.isInteger(startSample) || startSample < 0) {
@@ -289,7 +258,7 @@ export class AudioPump {
289
258
  this.#targetFrames = positiveFrames(options.targetFrames ?? Math.floor(ring.capacity / 2), "targetFrames");
290
259
  this.#onRefill = options.onRefill;
291
260
  }
292
- /** The rate the pump mixes at: its source's, the project's. */
261
+ /** The project sample rate. */
293
262
  get sampleRate() {
294
263
  return this.#source.sampleRate;
295
264
  }
@@ -302,11 +271,8 @@ export class AudioPump {
302
271
  return this.#startSample;
303
272
  }
304
273
  /**
305
- * Moves the pump to `startSample` and clears buffered audio, as a seek needs.
306
- *
307
- * A mix still running for the old position is aborted, and what it returns is dropped: a fill
308
- * in progress goes on from `startSample`, so the first sample written after a seek is always
309
- * the target's.
274
+ * Moves the pump to `startSample` and clears buffered audio. An in-flight mix is aborted and
275
+ * dropped; a running fill continues from the new position.
310
276
  *
311
277
  * @throws RangeError when `startSample` is not a non-negative integer.
312
278
  */
@@ -321,12 +287,9 @@ export class AudioPump {
321
287
  this.#ring.clear();
322
288
  }
323
289
  /**
324
- * Mixes until the ring holds its target fill or the engine needs media.
325
- *
326
- * Resolves with the number of samples per channel written. A call made while another is running
327
- * resolves with 0 at once, so a host may call this from several events; after a seek, the
328
- * running call carries on from the new position. Rejects when the source's `mix` or `onRefill`
329
- * rejects, except for a mix that a seek made stale.
290
+ * Mixes until the ring reaches its target fill or the engine needs media, resolving with the
291
+ * samples per channel written. A concurrent call resolves with 0 immediately. Rejects when `mix`
292
+ * or `onRefill` rejects, unless a seek made the mix stale.
330
293
  */
331
294
  async fill() {
332
295
  if (this.#running)
@@ -348,12 +311,12 @@ export class AudioPump {
348
311
  continue;
349
312
  throw error;
350
313
  }
351
- // Mixed for a position the pump has left: its audio would play before the target's.
314
+ // Stale mix from before a seek.
352
315
  if (position.signal.aborted)
353
316
  continue;
354
317
  if (step.kind === "waiting") {
355
318
  await this.#onRefill?.(step.missingSources);
356
- // A seek made while the host supplied media: the target may need none.
319
+ // A seek happened meanwhile; the new position may need no media.
357
320
  if (position.signal.aborted)
358
321
  continue;
359
322
  break;
@@ -372,34 +335,25 @@ export class AudioPump {
372
335
  }
373
336
  }
374
337
  /**
375
- * The timeline position a listener is hearing now, for presenting video against the audio (closed
376
- * loop).
338
+ * The timeline position being heard now, for presenting video against the audio clock.
377
339
  *
378
- * `Alpha2Player.present(time)` shows whatever time the host passes. Deriving that time from a wall
379
- * clock (`performance.now()`) is open loop: the audio device runs on its own crystal, so video and
380
- * sound drift apart by the difference of the two clocks (tens of milliseconds over ten minutes at
381
- * 50 ppm), and every audio underrun or seek adds a step. This clock instead counts what the audio
382
- * thread has taken from the ring (everything the pump mixed, less what is still buffered) and
383
- * subtracts the output's latency, so a host that presents `timelineTicks` on each animation frame
384
- * shows the picture that belongs to the sound being heard, without drift.
340
+ * A wall clock drifts from the audio device's crystal and ignores underruns. This clock counts
341
+ * samples the audio thread has consumed from the ring and subtracts output latency and the manual
342
+ * offset, so presenting `timelineTicks` each animation frame stays in sync without drift.
385
343
  *
386
- * Before playback reaches the speaker, the position holds at the start or seek target instead of
387
- * going earlier. Positions are the pump's samples, at the project's rate; the output's latency is
388
- * converted from seconds and `processing` from the output's samples, so a context at another rate
389
- * (whose worklet converts the ring to it) keeps time. The constructor throws `RangeError` for an
390
- * output or pump sample rate that is not positive.
344
+ * The position never goes before the start or seek target. Positions are at the project rate;
345
+ * latency is converted from seconds and `processing` from output-rate samples, so a resampling
346
+ * context keeps time.
347
+ *
348
+ * The constructor throws `RangeError` for a non-positive sample rate or a non-finite offset.
391
349
  */
392
350
  export class AudioPlaybackClock {
393
351
  #pump;
394
352
  #ring;
395
353
  #output;
396
354
  #processing;
397
- /**
398
- * `processing` is the delay of what plays the ring before the output, read at every query: for a
399
- * worklet that runs the master itself, `Alpha2AudioWorkletHost.latency(node)` (its compressors'
400
- * lookahead). An engine-mixed node delays nothing.
401
- */
402
- constructor(pump, ring, output, processing) {
355
+ #offset;
356
+ constructor(pump, ring, output, { processing, latencyOffsetSeconds = 0 } = {}) {
403
357
  if (!(output.sampleRate > 0) || !(pump.sampleRate > 0)) {
404
358
  throw new RangeError("audio clock needs a positive sample rate");
405
359
  }
@@ -407,12 +361,44 @@ export class AudioPlaybackClock {
407
361
  this.#ring = ring;
408
362
  this.#output = output;
409
363
  this.#processing = processing;
364
+ this.#offset = checkedOffset(latencyOffsetSeconds);
410
365
  }
411
- /** Absolute sample index being heard now, at the pump's (the project's) rate. */
366
+ /** Manual offset in seconds; a non-finite value throws `RangeError`. */
367
+ get latencyOffsetSeconds() {
368
+ return this.#offset;
369
+ }
370
+ set latencyOffsetSeconds(seconds) {
371
+ this.#offset = checkedOffset(seconds);
372
+ }
373
+ #latency() {
374
+ const output = this.#output;
375
+ const base = output.baseLatency ?? 0;
376
+ const reported = output.outputLatency ?? 0;
377
+ if (reported > 0)
378
+ return { seconds: reported + base, source: "output-latency" };
379
+ const stamp = output.getOutputTimestamp?.();
380
+ if (stamp?.contextTime !== undefined &&
381
+ stamp.performanceTime !== undefined &&
382
+ output.currentTime !== undefined) {
383
+ // Difference between the next render time and the time heard now is the full output delay.
384
+ const heard = stamp.contextTime + (performance.now() - stamp.performanceTime) / 1000;
385
+ const seconds = output.currentTime - heard;
386
+ if (seconds > 0)
387
+ return { seconds, source: "output-timestamp" };
388
+ }
389
+ return { seconds: base, source: "base-only" };
390
+ }
391
+ get latencySource() {
392
+ return this.#latency().source;
393
+ }
394
+ /** Output latency in seconds, excluding the manual offset. */
395
+ get latencySeconds() {
396
+ return this.#latency().seconds;
397
+ }
398
+ /** Absolute sample being heard now, at the project rate. */
412
399
  get sample() {
413
400
  const rate = this.#pump.sampleRate;
414
- const latency = ((this.#output.outputLatency ?? 0) + (this.#output.baseLatency ?? 0)) *
415
- rate +
401
+ const latency = (this.#latency().seconds + this.#offset) * rate +
416
402
  ((this.#processing?.latencySamples ?? 0) * rate) /
417
403
  this.#output.sampleRate;
418
404
  const handedOver = this.#pump.position - this.#ring.available;
@@ -424,7 +410,12 @@ export class AudioPlaybackClock {
424
410
  BigInt(Math.round(this.#pump.sampleRate)));
425
411
  }
426
412
  }
427
- /** Record version and effect node identifiers of the worklet's master-chain record. */
413
+ function checkedOffset(seconds) {
414
+ if (!Number.isFinite(seconds))
415
+ throw new RangeError("audio latency offset must be a finite number of seconds");
416
+ return seconds;
417
+ }
418
+ /** Worklet master-chain record version and effect node ids. Must match the DSP module. */
428
419
  const EFFECT_EQ_BAND = 0;
429
420
  const EFFECT_COMPRESSOR = 1;
430
421
  const EFFECT_REVERB = 2;
@@ -434,24 +425,17 @@ const BAND_KINDS = {
434
425
  low_pass: 1,
435
426
  high_pass: 2,
436
427
  };
437
- /** The limiter a master bus without a `limiter` field has (the schema default). */
428
+ /** Schema default limiter. */
438
429
  const DEFAULT_LIMITER = { threshold: 1, release_ms: 50 };
439
430
  /**
440
- * Encodes a project master bus into the worklet's fixed-width record.
441
- *
442
- * The worklet carries no JSON parser, so the host writes this record into the module's
443
- * configuration region and calls `alpha2_worklet_configure`. The layout is little-endian and
444
- * versioned (version u32, gain f32, limiter flag u8, limiter threshold f32, limiter release f32,
445
- * node count u32, then the nodes); the module rejects anything it cannot read without disturbing
446
- * the chain it is already running.
431
+ * Encodes a master bus into the worklet's binary record, since the worklet has no JSON parser.
447
432
  *
448
- * Fields the master leaves out take the project schema's defaults, as the engine reads them: unity
449
- * gain and the 0 dBFS, 50 ms limiter. Only `limiter: null` removes the limiter. An EQ effect
450
- * becomes one node per band.
433
+ * Little-endian layout: version u32, gain f32, limiter flag u8, limiter threshold f32, limiter
434
+ * release f32, node count u32, then the nodes. Missing fields take schema defaults (unity gain,
435
+ * 0 dBFS 50 ms limiter); only `limiter: null` removes the limiter. Each EQ band becomes one node.
451
436
  *
452
- * @throws RangeError for a keyframed master gain, which the record's one static gain cannot play.
453
- * Preview such a master through engine-mixed audio (`configureEngineMixedAudio`), which applies
454
- * it as the export does, or pass the gain evaluated at the time being heard.
437
+ * @throws RangeError for a keyframed master gain. Use `configureEngineMixedAudio`, or pass the gain
438
+ * evaluated at the time being heard.
455
439
  */
456
440
  export function encodeMasterAudio(master) {
457
441
  const gain = master?.gain ?? {
@@ -1,8 +1,8 @@
1
1
  import type { BrowserAudioBlockSink, OfflineAudioRenderer } from "./audio.js";
2
2
  import { type SerializedAlpha2Error } from "./worker-error.js";
3
3
  /**
4
- * A message to {@link AudioWorkerHost.handle}: render `totalFrames` frames in
5
- * blocks cycling through `blockSizes`, or cancel the render with request `id`.
4
+ * A request to {@link AudioWorkerHost.handle}. `render-audio` renders `totalFrames` frames in
5
+ * blocks cycling through `blockSizes`; `cancel-audio` cancels the render with that `id`.
6
6
  */
7
7
  export type AudioWorkerRequest = {
8
8
  readonly type: "render-audio";
@@ -13,46 +13,37 @@ export type AudioWorkerRequest = {
13
13
  readonly type: "cancel-audio";
14
14
  readonly id: number;
15
15
  };
16
- /** The answer to a `render-audio` request; a `cancel-audio` request has none. */
16
+ /** The response to a `render-audio` request (`cancel-audio` has none). */
17
17
  export type AudioWorkerResponse = {
18
18
  readonly type: "audio-complete";
19
19
  readonly id: number;
20
20
  } | {
21
21
  readonly type: "audio-error";
22
22
  readonly id: number;
23
- /**
24
- * The failure as the render worker reports one: its code, name, fatality, and classified
25
- * `failure`. `new Alpha2WasmError(error)` (`alpha2/worker`) rebuilds it for
26
- * `classifyBrowserFailure`.
27
- */
23
+ /** Rebuild with `new Alpha2WasmError(error)` from `alpha2/worker`. */
28
24
  readonly error: SerializedAlpha2Error;
29
25
  /** Whether the render failed because a `cancel-audio` request aborted it. */
30
26
  readonly cancelled: boolean;
31
27
  };
32
- /** What {@link AudioWorkerHost} asks for when a `render-audio` request starts. */
28
+ /** Creates the sink for each `render-audio` request. */
33
29
  export type AudioWorkerSinkFactory = (request: {
34
30
  readonly id: number;
35
31
  readonly totalFrames: bigint;
36
32
  }) => BrowserAudioBlockSink | Promise<BrowserAudioBlockSink>;
37
33
  /**
38
- * The worker side of the offline audio protocol: runs {@link renderOfflineAudio} per request, one
39
- * at a time, each into a sink of its own, and cancels by request id.
34
+ * Worker side of the offline audio protocol. Runs {@link renderOfflineAudio} per request into its
35
+ * own sink, one request at a time, and cancels by request id.
40
36
  *
41
- * Renders never overlap. A cancelled render still finishes the block it is writing and aborts its
42
- * sink, so a request made meanwhile (the usual cancel-then-export-again) waits for that, then gets
43
- * a fresh sink from `sinkFor`: no block of one render reaches another's sink, and no late `abort`
44
- * reaches a sink after it finished.
37
+ * A request made while a cancelled render is still winding down waits for that render to abort
38
+ * its sink, so no block or late `abort` reaches the wrong sink.
45
39
  */
46
40
  export declare class AudioWorkerHost {
47
41
  #private;
48
42
  constructor(render: OfflineAudioRenderer, sinkFor: AudioWorkerSinkFactory);
49
43
  /**
50
- * Handles one request. A render resolves with its response once its sink has finished or
51
- * aborted; it never rejects, since a failure is answered with `audio-error`. It starts after the
52
- * renders asked for before it have settled, and a cancel that arrives first answers it as
53
- * cancelled without opening a sink. A render whose id is still rendering or waiting is refused
54
- * with `audio-error`, leaving the first one as it was. A cancel resolves with `undefined` at
55
- * once, and cancelling an id that is not rendering or waiting does nothing.
44
+ * Handles one request. A render resolves with its response after its sink has finished or
45
+ * aborted and never rejects; failures become `audio-error`, including reuse of an id that is still
46
+ * active. A cancel resolves with `undefined` immediately; unknown ids are ignored.
56
47
  */
57
48
  handle(request: AudioWorkerRequest): Promise<AudioWorkerResponse | undefined>;
58
49
  }
@@ -1,31 +1,26 @@
1
1
  import { renderOfflineAudio } from "./audio.js";
2
2
  import { serializeError } from "./worker-error.js";
3
3
  /**
4
- * The worker side of the offline audio protocol: runs {@link renderOfflineAudio} per request, one
5
- * at a time, each into a sink of its own, and cancels by request id.
4
+ * Worker side of the offline audio protocol. Runs {@link renderOfflineAudio} per request into its
5
+ * own sink, one request at a time, and cancels by request id.
6
6
  *
7
- * Renders never overlap. A cancelled render still finishes the block it is writing and aborts its
8
- * sink, so a request made meanwhile (the usual cancel-then-export-again) waits for that, then gets
9
- * a fresh sink from `sinkFor`: no block of one render reaches another's sink, and no late `abort`
10
- * reaches a sink after it finished.
7
+ * A request made while a cancelled render is still winding down waits for that render to abort
8
+ * its sink, so no block or late `abort` reaches the wrong sink.
11
9
  */
12
10
  export class AudioWorkerHost {
13
11
  #render;
14
12
  #sinkFor;
15
13
  #controllers = new Map();
16
- // Settles when the last render asked for has finished or aborted its sink.
14
+ // Settles when the last queued render has finished or aborted its sink.
17
15
  #queue = Promise.resolve();
18
16
  constructor(render, sinkFor) {
19
17
  this.#render = render;
20
18
  this.#sinkFor = sinkFor;
21
19
  }
22
20
  /**
23
- * Handles one request. A render resolves with its response once its sink has finished or
24
- * aborted; it never rejects, since a failure is answered with `audio-error`. It starts after the
25
- * renders asked for before it have settled, and a cancel that arrives first answers it as
26
- * cancelled without opening a sink. A render whose id is still rendering or waiting is refused
27
- * with `audio-error`, leaving the first one as it was. A cancel resolves with `undefined` at
28
- * once, and cancelling an id that is not rendering or waiting does nothing.
21
+ * Handles one request. A render resolves with its response after its sink has finished or
22
+ * aborted and never rejects; failures become `audio-error`, including reuse of an id that is still
23
+ * active. A cancel resolves with `undefined` immediately; unknown ids are ignored.
29
24
  */
30
25
  async handle(request) {
31
26
  if (request.type === "cancel-audio") {