alpha2 0.4.6 → 0.5.1

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 (123) 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 +51 -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 +125 -176
  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 +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/frames.d.ts +23 -0
  55. package/dist/frames.js +34 -0
  56. package/dist/generated/project-schema.d.ts +712 -485
  57. package/dist/generated/project-schema.js +55 -2
  58. package/dist/generated/project-shape.js +276 -16
  59. package/dist/geometry.d.ts +28 -34
  60. package/dist/geometry.js +18 -23
  61. package/dist/gpu-recovery.d.ts +92 -0
  62. package/dist/gpu-recovery.js +135 -0
  63. package/dist/hdr-frames.d.ts +82 -67
  64. package/dist/hdr-frames.js +112 -49
  65. package/dist/index.d.ts +6 -0
  66. package/dist/index.js +6 -0
  67. package/dist/json-text.d.ts +13 -23
  68. package/dist/json-text.js +10 -20
  69. package/dist/layout-values.d.ts +14 -22
  70. package/dist/layout-values.js +18 -21
  71. package/dist/layout.d.ts +48 -63
  72. package/dist/layout.js +37 -37
  73. package/dist/loudness.d.ts +27 -32
  74. package/dist/loudness.js +19 -23
  75. package/dist/media.d.ts +85 -237
  76. package/dist/media.js +133 -287
  77. package/dist/mediabunny.d.ts +178 -246
  78. package/dist/mediabunny.js +781 -583
  79. package/dist/paint.d.ts +23 -0
  80. package/dist/paint.js +37 -0
  81. package/dist/physical-frames.d.ts +5 -17
  82. package/dist/physical-frames.js +4 -11
  83. package/dist/player.d.ts +56 -47
  84. package/dist/player.js +155 -40
  85. package/dist/presented-frames.d.ts +2 -7
  86. package/dist/presented-frames.js +3 -8
  87. package/dist/project.d.ts +74 -118
  88. package/dist/project.js +384 -445
  89. package/dist/rate-control.d.ts +9 -23
  90. package/dist/rate-control.js +7 -18
  91. package/dist/renderer-choice.d.ts +41 -0
  92. package/dist/renderer-choice.js +82 -0
  93. package/dist/repacked-bytes.d.ts +0 -2
  94. package/dist/repacked-bytes.js +2 -5
  95. package/dist/robustness.d.ts +25 -37
  96. package/dist/robustness.js +71 -54
  97. package/dist/sha256.d.ts +5 -13
  98. package/dist/sha256.js +9 -24
  99. package/dist/text.d.ts +97 -71
  100. package/dist/text.js +33 -70
  101. package/dist/video-frames.d.ts +7 -25
  102. package/dist/video-frames.js +12 -29
  103. package/dist/waveform.d.ts +5 -11
  104. package/dist/waveform.js +4 -9
  105. package/dist/worker-error.d.ts +5 -20
  106. package/dist/worker-error.js +8 -25
  107. package/dist/worker.d.ts +82 -95
  108. package/dist/worker.js +235 -143
  109. package/package.json +26 -2
  110. package/wasm/alpha2_audio_worklet.wasm +0 -0
  111. package/wasm/alpha2_extensions.d.ts +26 -47
  112. package/wasm/alpha2_extensions.js +26 -47
  113. package/wasm/alpha2_extensions_bg.wasm +0 -0
  114. package/wasm/alpha2_wasm.d.ts +501 -587
  115. package/wasm/alpha2_wasm.js +661 -616
  116. package/wasm/alpha2_wasm_bg.wasm +0 -0
  117. package/wasm/alpha2_wasm_bg.wasm.d.ts +22 -12
  118. package/wasm/rust-crate-licenses.md +2 -2
  119. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline1.js +1 -0
  120. package/wasm/snippets/alpha2-wasm-070d94113471ef0a/inline2.js +82 -0
  121. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  122. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline0.js +0 -0
  123. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline3.js +0 -0
package/dist/worker.js CHANGED
@@ -1,7 +1,11 @@
1
+ import { lossReportFromJson, } from "./gpu-recovery.js";
2
+ import { createGpuRenderer, createRenderer, gpuChoice, } from "./renderer-choice.js";
3
+ import { detectBrowserCapabilities, } from "./robustness.js";
1
4
  import { FrameGenerationRetainer, } from "./frame-supply.js";
5
+ import { intakeVideoFrame, readbackCounters, SoftwareDecodeRequiredError, } from "./frame-intake.js";
2
6
  import { videoFrameFromI420, videoFrameRepackedBytes } from "./video-frames.js";
3
7
  import { recordRepackedBytes } from "./repacked-bytes.js";
4
- import { copyPlanarYuvFrame, PlanarCopyPool, isHdrVideoFrame, isPlanarVideoFrame, uploadPlanarYuvFrame, } from "./hdr-frames.js";
8
+ import { decodeRefusalMessage, NonPlanarVideoFrameError, PlanarCopyPool, PlanarDecodeUnavailableError, isHdrVideoFrame, isPlanarVideoFrame, uploadPlanarYuvFrame, } from "./hdr-frames.js";
5
9
  import { Alpha2WasmError, serializeError, wasmTrapCode, } from "./worker-error.js";
6
10
  import { PhysicalFrameAliases, } from "./physical-frames.js";
7
11
  import { sendsBitmaps, uploadPresentedFrame } from "./presented-frames.js";
@@ -10,23 +14,18 @@ export { Alpha2WasmError } from "./worker-error.js";
10
14
  * Installs a serial request loop in the worker that owns the GPU device, replacing
11
15
  * `scope.onmessage`.
12
16
  *
13
- * `initialize` calls `createHost` with the transferred canvas; any other request but `dispose`
14
- * before it is answered with an error. Each answer is preceded by a `device-lost` message when the
15
- * host reports a lost device. A wasm trap is latched: every later error is reported as fatal,
16
- * because the module is no longer usable even when a later call fails with an ordinary-looking
17
- * error.
17
+ * Requests other than `dispose` fail until `initialize` has called `createHost`. After a wasm trap
18
+ * every later error is reported as fatal.
18
19
  */
19
20
  export function installRenderWorker(scope, createHost) {
20
21
  let host;
21
22
  let serial = Promise.resolve();
22
- // Latch traps: later calls may report the same plain error as recoverable re-entrancy, so only
23
- // the original trap reliably marks the module unusable.
23
+ // Later calls after a trap can fail with ordinary-looking errors, so the trap is latched.
24
24
  let trapped = false;
25
- // Posted before the answer that found the loss, because a host checks isDeviceLost() as soon as
26
- // its request settles.
25
+ // Posted before the answer because the caller checks isDeviceLost() as soon as it settles.
27
26
  const reportDeviceLoss = () => {
28
27
  if (host !== undefined && isLost(host))
29
- scope.postMessage({ type: "device-lost" });
28
+ scope.postMessage({ type: "device-lost", report: lossReportOf(host) });
30
29
  };
31
30
  scope.onmessage = (event) => {
32
31
  serial = serial.then(async () => {
@@ -39,7 +38,7 @@ export function installRenderWorker(scope, createHost) {
39
38
  result = host.rendererChoice;
40
39
  break;
41
40
  case "upload-video-frame":
42
- // The frame was transferred here; with no host to take it over, it is closed here.
41
+ // The frame was transferred here and has no host to take it.
43
42
  if (host === undefined)
44
43
  request.frame.close();
45
44
  await requiredHost(host).uploadVideoFrame({
@@ -53,6 +52,9 @@ export function installRenderWorker(scope, createHost) {
53
52
  ...(request.chromaSiting === undefined
54
53
  ? {}
55
54
  : { chromaSiting: request.chromaSiting }),
55
+ ...(request.decode === undefined
56
+ ? {}
57
+ : { decode: request.decode }),
56
58
  });
57
59
  break;
58
60
  case "present":
@@ -62,7 +64,7 @@ export function installRenderWorker(scope, createHost) {
62
64
  await requiredHost(host).reset();
63
65
  break;
64
66
  case "begin-export-frame": {
65
- const ticket = requiredHost(host).beginExport(request.timeTicks, request.codec, request.outputTimeTicks);
67
+ const ticket = requiredHost(host).beginExport(request.timeTicks, request.codec, request.outputTimeTicks, request.pixels);
66
68
  reportDeviceLoss();
67
69
  if (ticket.kind === "waiting") {
68
70
  scope.postMessage({
@@ -118,13 +120,27 @@ export function installRenderWorker(scope, createHost) {
118
120
  return;
119
121
  }
120
122
  case "recover": {
121
- // A recovery asked for twice, or after another made the renderer again, has nothing to
122
- // replace: making it again would drop every upload and recompile every pipeline.
123
+ // A duplicate recovery would drop every upload and recompile every pipeline for
124
+ // nothing, so skip it unless a fresh surface was transferred.
123
125
  const lost = requiredHost(host);
124
- if (isLost(lost))
125
- await lost.recover();
126
+ if (isLost(lost) || request.canvas !== undefined)
127
+ await lost.recover(request.step, request.canvas);
128
+ result = lost.rendererChoice;
129
+ break;
130
+ }
131
+ case "probe-surface": {
132
+ const current = requiredHost(host);
133
+ result =
134
+ (await current.probeSurface?.()) ??
135
+ {
136
+ kind: current.rendererChoice?.backend ?? "none",
137
+ webgpuAdapter: false,
138
+ };
126
139
  break;
127
140
  }
141
+ case "detect-capabilities":
142
+ result = await detectBrowserCapabilities();
143
+ break;
128
144
  case "dispose":
129
145
  host?.dispose();
130
146
  host = undefined;
@@ -147,17 +163,12 @@ export function installRenderWorker(scope, createHost) {
147
163
  };
148
164
  }
149
165
  /**
150
- * Returns the `createHost` callback for {@link installRenderWorker}, backed by the alpha2 wasm
151
- * binding. The callback makes a canvas renderer, registers `options`' effects, resources and
152
- * fonts, then loads `projectJson`.
153
- *
154
- * The renderer is the one `options.renderer` picks (see {@link WasmRenderWorkerHostOptions}); the
155
- * host's `rendererChoice` says which, and `initialize` answers it.
166
+ * Returns a `createHost` callback for {@link installRenderWorker} backed by the wasm binding. It
167
+ * creates the renderer `options.renderer` picks, registers effects, resources and fonts, then
168
+ * loads `projectJson`; `recover` repeats the same registration.
156
169
  *
157
- * The callback rejects when the binding lacks the constructor the renderer needs
158
- * (`createForCanvas`, or `createCpu` for `"cpu"`), or when making the renderer, compiling an
159
- * effect or loading the project fails. After a device loss, `recover()` repeats the same
160
- * registration on a new renderer of the same kind.
170
+ * The callback rejects when the binding lacks the needed constructor, or when creating the
171
+ * renderer, compiling an effect or loading the project fails.
161
172
  */
162
173
  export function createWasmRenderWorkerHost(binding, projectJson, options = {}) {
163
174
  const effects = options.effects ?? [];
@@ -168,13 +179,17 @@ export function createWasmRenderWorkerHost(binding, projectJson, options = {}) {
168
179
  const renderer = options.renderer ?? "auto";
169
180
  if (renderer !== "auto" && renderer !== "gpu" && renderer !== "cpu")
170
181
  throw new RangeError('renderer must be "auto", "gpu" or "cpu"');
182
+ const unreadableFrames = options.unreadableFrames ?? "redecode";
183
+ if (unreadableFrames !== "redecode" && unreadableFrames !== "present")
184
+ throw new RangeError('unreadableFrames must be "redecode" or "present"');
171
185
  return async (canvas) => {
172
- return WasmRenderWorkerHost.create(binding, canvas, projectJson, effects, resources, options.fonts ?? [], options.uploadRetention, videoConversion, renderer);
186
+ return WasmRenderWorkerHost.create(binding, canvas, projectJson, effects, resources, options.fonts ?? [], options.uploadRetention, videoConversion, renderer, unreadableFrames);
173
187
  };
174
188
  }
175
189
  class WasmRenderWorkerHost {
176
190
  #binding;
177
191
  #canvas;
192
+ #mode;
178
193
  #projectJson;
179
194
  #effects;
180
195
  #resources;
@@ -183,20 +198,24 @@ class WasmRenderWorkerHost {
183
198
  #uploadedFrames;
184
199
  #physicalFrames = new PhysicalFrameAliases();
185
200
  #videoConversion;
201
+ #unreadableFrames;
202
+ #readback = readbackCounters();
203
+ #planarCopyFrames = 0;
204
+ #planarCopyBytes = 0;
186
205
  rendererChoice;
187
206
  #pendingUploads = [];
188
- /** Buffers the planar copies reuse; each is given back once its upload has taken it. */
189
207
  #planarCopies = new PlanarCopyPool();
190
- /** `undefined` while recovery has freed the lost binding and not yet made another. */
208
+ // `undefined` between freeing the lost binding and making a new one.
191
209
  #registry;
192
- /** The live binding; with none, every call fails as the lost device it is. */
193
210
  get #wasm() {
194
211
  if (this.#registry === undefined)
195
212
  throw lostRenderer();
196
213
  return this.#registry;
197
214
  }
198
- constructor(binding, canvas, projectJson, effects, resources, fonts, wasm, uploadRetention, videoConversion, rendererChoice) {
215
+ constructor(binding, canvas, projectJson, effects, resources, fonts, wasm, uploadRetention, videoConversion, rendererChoice, unreadableFrames, mode) {
199
216
  this.#binding = binding;
217
+ this.#mode = mode;
218
+ this.#unreadableFrames = unreadableFrames;
200
219
  this.rendererChoice = rendererChoice;
201
220
  this.#canvas = canvas;
202
221
  this.#projectJson = projectJson;
@@ -211,13 +230,22 @@ class WasmRenderWorkerHost {
211
230
  this.#registry?.releaseFrameGeneration(generation);
212
231
  }, uploadRetention);
213
232
  }
214
- static async create(binding, canvas, projectJson, effects, resources, fonts, uploadRetention, videoConversion, mode) {
215
- const { wasm, choice } = await makeRenderer(binding, canvas, mode);
233
+ static async create(binding, canvas, projectJson, effects, resources, fonts, uploadRetention, videoConversion, mode, unreadableFrames) {
234
+ const { wasm, choice } = await createRenderer(binding, canvas, mode);
216
235
  await registerEffects(wasm, effects);
217
236
  registerResources(wasm, resources);
218
237
  registerFonts(wasm, fonts);
219
238
  wasm.loadProject(projectJson);
220
- return new WasmRenderWorkerHost(binding, canvas, projectJson, effects, resources, fonts, wasm, uploadRetention, videoConversion, choice);
239
+ return new WasmRenderWorkerHost(binding, canvas, projectJson, effects, resources, fonts, wasm, uploadRetention, videoConversion, choice, unreadableFrames, mode);
240
+ }
241
+ get sourceTransfer() {
242
+ return {
243
+ planarCopyFrames: this.#planarCopyFrames,
244
+ planarCopyBytes: this.#planarCopyBytes,
245
+ };
246
+ }
247
+ get readbackRecovery() {
248
+ return { ...this.#readback };
221
249
  }
222
250
  async uploadVideoFrame(frame) {
223
251
  const rotation = frame.rotationDegrees ?? 0;
@@ -228,44 +256,75 @@ class WasmRenderWorkerHost {
228
256
  mediaTimeTicks: frame.requestedTimeTicks,
229
257
  };
230
258
  let declared;
259
+ let required;
231
260
  let convert;
232
261
  try {
233
262
  if (this.#physicalFrames.alias(identity, exact, (existing, requested) => this.#wasm.aliasVideoFrame(requested.sourceId, existing.mediaTimeTicks, requested.mediaTimeTicks))) {
234
263
  frame.frame.close();
235
264
  return;
236
265
  }
237
- // A project-declared color wins over the frame's own, so such frames, and all HDR ones, are
238
- // converted by the engine; other planar frames too unless the host leaves SDR to the browser.
266
+ // Project-declared color and HDR frames always need the engine's conversion.
239
267
  declared = this.#wasm.sourceColorMetadata(frame.sourceId);
240
- convert =
268
+ required =
241
269
  declared !== undefined ||
242
270
  this.#wasm.hdrSource(frame.sourceId) ||
243
- isHdrVideoFrame(frame.frame) ||
271
+ isHdrVideoFrame(frame.frame);
272
+ convert =
273
+ required ||
244
274
  (this.#videoConversion === "engine" && isPlanarVideoFrame(frame.frame));
245
275
  }
246
276
  catch (error) {
247
- // The frame is this host's from the start: a binding that refuses it before an upload takes
248
- // it over (a lost renderer, a trap) must not leave it holding a decoder surface.
277
+ // Close the frame so a refused upload does not hold a decoder surface.
249
278
  frame.frame.close();
250
279
  throw error;
251
280
  }
252
281
  if (convert) {
253
- const planar = await copyPlanarYuvFrame(frame.frame, declared === undefined ? null : JSON.parse(declared), {
254
- rotation,
255
- mirror,
256
- ...(frame.chromaSiting === undefined
257
- ? {}
258
- : { chromaSiting: frame.chromaSiting }),
259
- }, this.#planarCopies);
282
+ let intake;
260
283
  try {
261
- this.#pendingUploads.push(uploadPlanarYuvFrame(this.#wasm, frame.sourceId, frame.requestedTimeTicks, planar, this.#outputSize.width, this.#outputSize.height));
284
+ intake = await intakeVideoFrame(frame.frame, {
285
+ required,
286
+ declared: declared === undefined
287
+ ? null
288
+ : JSON.parse(declared),
289
+ identity: {
290
+ rotation,
291
+ mirror,
292
+ ...(frame.chromaSiting === undefined
293
+ ? {}
294
+ : { chromaSiting: frame.chromaSiting }),
295
+ },
296
+ pool: this.#planarCopies,
297
+ counters: this.#readback,
298
+ unreadable: this.#unreadableFrames,
299
+ takesPresented: true,
300
+ });
301
+ }
302
+ catch (error) {
303
+ frame.frame.close();
304
+ throw error;
262
305
  }
263
- finally {
264
- // The upload copied the planes into the engine before it returned.
265
- this.#planarCopies.release(planar.data);
306
+ if (intake.kind === "redecode") {
307
+ const transfer = frame.frame.colorSpace?.transfer ?? null;
308
+ frame.frame.close();
309
+ throw redecodeRequest(frame, intake.cause, transfer);
310
+ }
311
+ if (intake.kind === "planar") {
312
+ frame.frame.close();
313
+ const planar = intake.planar;
314
+ if (frame.decode === "software")
315
+ this.#readback.redecodedFrames += 1;
316
+ this.#planarCopyFrames += 1;
317
+ this.#planarCopyBytes += planar.data.byteLength;
318
+ try {
319
+ this.#pendingUploads.push(uploadPlanarYuvFrame(this.#wasm, frame.sourceId, frame.requestedTimeTicks, planar, this.#outputSize.width, this.#outputSize.height));
320
+ }
321
+ finally {
322
+ // The upload copied the planes into the engine before it returned.
323
+ this.#planarCopies.release(planar.data);
324
+ }
325
+ this.#physicalFrames.record(identity, exact);
326
+ return;
266
327
  }
267
- this.#physicalFrames.record(identity, exact);
268
- return;
269
328
  }
270
329
  const upload = [
271
330
  frame.sourceId,
@@ -282,8 +341,7 @@ class WasmRenderWorkerHost {
282
341
  : this.#wasm.uploadPresentedVideoFrame(...upload));
283
342
  this.#physicalFrames.record(identity, exact);
284
343
  }
285
- // The backend contract is asynchronous because a worker-side implementation
286
- // must be; this in-process one answers without awaiting anything.
344
+ // Async to match the worker contract, though this in-process host never awaits.
287
345
  // eslint-disable-next-line @typescript-eslint/require-await
288
346
  async present(timeTicks) {
289
347
  const result = JSON.parse(this.#wasm.renderAt(timeTicks));
@@ -300,8 +358,8 @@ class WasmRenderWorkerHost {
300
358
  unchanged: result.unchanged,
301
359
  };
302
360
  }
303
- beginExport(timeTicks, codec, outputTimeTicks) {
304
- const ticket = this.#wasm.beginExportAt(timeTicks, codec);
361
+ beginExport(timeTicks, codec, outputTimeTicks, pixels) {
362
+ const ticket = this.#wasm.beginExportAt(timeTicks, codec, pixels);
305
363
  if (ticket.kind === "waiting")
306
364
  return {
307
365
  kind: "waiting",
@@ -310,11 +368,11 @@ class WasmRenderWorkerHost {
310
368
  };
311
369
  this.#retirePendingUploads();
312
370
  const readback = ticket.readback.then((result) => videoFrameFromI420(result.pixels, {
313
- format: "I420",
371
+ // The 10-bit formats are newer than this package's DOM types.
372
+ format: (result.format ?? "I420"),
314
373
  codedWidth: result.width,
315
374
  codedHeight: result.height,
316
- // The output's time, as `ExportedFrame.timeTicks` counts it, not the timeline's: a host
317
- // that encodes the frame as it arrives starts its file at 0.
375
+ // Output time, not timeline time, so a host encoding frames as they arrive starts at 0.
318
376
  timestamp: Number((outputTimeTicks * 1000000n) / 120000n),
319
377
  layout: [...result.layout],
320
378
  colorSpace: result.colorSpace,
@@ -333,21 +391,43 @@ class WasmRenderWorkerHost {
333
391
  isDeviceLost() {
334
392
  return this.#registry?.deviceLost ?? true;
335
393
  }
394
+ lossReport() {
395
+ const wasm = this.#registry;
396
+ if (wasm === undefined || !wasm.deviceLost)
397
+ return undefined;
398
+ return lossReportFromJson(wasm.lossReport);
399
+ }
400
+ async probeSurface() {
401
+ return {
402
+ kind: this.#registry === undefined ? "none" : this.rendererChoice.backend,
403
+ webgpuAdapter: await webgpuAdapterAvailable(),
404
+ };
405
+ }
336
406
  /**
337
- * Makes the binding again on the same canvas. The lost one is freed first and never used again:
338
- * when making the new one fails (a WebGL context the browser did not restore), this host stays
339
- * lost and the next recovery tries again.
407
+ * Frees the lost binding and makes the one `step` names. On failure the host stays lost and the
408
+ * next step tries. A GPU step refuses software adapters unless the host was asked for `"gpu"`.
340
409
  */
341
- async recover() {
410
+ async recover(step, canvas) {
342
411
  this.#discardUploadedFrames();
343
412
  const lost = this.#registry;
344
413
  this.#registry = undefined;
345
414
  lost?.free?.();
346
- // Only a GPU renderer is ever lost; the CPU one has no device.
347
- if (this.#binding.createForCanvas === undefined) {
348
- throw new Error("createForCanvas is unavailable");
415
+ const surface = canvas ?? this.#canvas;
416
+ this.#canvas = surface;
417
+ let wasm;
418
+ let choice;
419
+ if (step.renderer === "cpu") {
420
+ const made = await createRenderer(this.#binding, surface, "cpu");
421
+ wasm = made.wasm;
422
+ choice = {
423
+ ...made.choice,
424
+ rendererReason: `the GPU was lost: ${step.reason}`,
425
+ };
426
+ }
427
+ else {
428
+ wasm = await createGpuRenderer(this.#binding, surface, this.#mode === "gpu" ? "allow" : "refuse");
429
+ choice = gpuChoice(wasm);
349
430
  }
350
- const wasm = await this.#binding.createForCanvas(this.#canvas);
351
431
  try {
352
432
  await registerEffects(wasm, this.#effects);
353
433
  registerResources(wasm, this.#resources);
@@ -359,6 +439,7 @@ class WasmRenderWorkerHost {
359
439
  throw error;
360
440
  }
361
441
  this.#registry = wasm;
442
+ this.rendererChoice = choice;
362
443
  }
363
444
  dispose() {
364
445
  this.#discardUploadedFrames();
@@ -375,51 +456,25 @@ class WasmRenderWorkerHost {
375
456
  this.#physicalFrames.clear();
376
457
  }
377
458
  }
378
- /**
379
- * Makes the renderer `mode` asks for on `canvas` and says which it is. `"auto"` falls back to the
380
- * CPU only when the GPU renderer could not be made for want of a GPU (`GPU_INIT_FAILED`, or a
381
- * canvas that takes no GPU surface: `INVALID_INPUT`); a canvas whose failed WebGL2 request left it
382
- * without a context still takes the CPU renderer's 2D one.
383
- */
384
- async function makeRenderer(binding, canvas, mode) {
385
- const cpu = (rendererReason) => {
386
- if (binding.createCpu === undefined)
387
- throw new Error("wasm binding does not expose createCpu");
388
- return {
389
- wasm: binding.createCpu(canvas),
390
- choice: { renderer: "cpu", rendererReason },
391
- };
392
- };
393
- if (mode === "cpu")
394
- return cpu('the CPU renderer was asked for (renderer "cpu")');
395
- if (binding.createForCanvas === undefined) {
396
- if (mode === "auto" && binding.createCpu !== undefined)
397
- return cpu("the wasm binding has no GPU renderer");
398
- throw new Error("wasm binding does not expose createForCanvas");
459
+ async function webgpuAdapterAvailable() {
460
+ const gpu = globalThis.navigator?.gpu;
461
+ if (gpu === undefined)
462
+ return false;
463
+ try {
464
+ return (await gpu.requestAdapter()) != null;
465
+ }
466
+ catch {
467
+ return false;
399
468
  }
469
+ }
470
+ function lossReportOf(host) {
400
471
  try {
401
- return {
402
- wasm: await binding.createForCanvas(canvas),
403
- choice: { renderer: "gpu", rendererReason: null },
404
- };
472
+ return host.lossReport?.();
405
473
  }
406
- catch (error) {
407
- const code = error?.code;
408
- if (mode !== "auto" ||
409
- binding.createCpu === undefined ||
410
- (code !== "GPU_INIT_FAILED" && code !== "INVALID_INPUT"))
411
- throw error;
412
- const message = error instanceof Error ? error.message : String(error);
413
- try {
414
- return cpu(`the browser offers no WebGPU adapter and no WebGL2 context (${message})`);
415
- }
416
- catch {
417
- // The GPU's failure is the one to report: it says why there is no renderer at all.
418
- throw error;
419
- }
474
+ catch {
475
+ return undefined;
420
476
  }
421
477
  }
422
- /** The engine's name for a missing frame, with its source time as a tick count. */
423
478
  function missingFrame(frame) {
424
479
  return {
425
480
  clipId: frame.clipId,
@@ -442,6 +497,31 @@ function workerFrameIdentity(source, outputWidth, outputHeight, rotation, mirror
442
497
  mirror,
443
498
  };
444
499
  }
500
+ /**
501
+ * Requests a software decode, or refuses a frame that already is one: still without planes means
502
+ * `PlanarDecodeUnavailableError`, still unreadable means `FRAME_SUPPLY_FAILED`.
503
+ */
504
+ function redecodeRequest(frame, cause, transfer) {
505
+ const nonPlanar = cause instanceof NonPlanarVideoFrameError;
506
+ if (frame.decode !== "software")
507
+ return new SoftwareDecodeRequiredError({
508
+ sourceId: frame.sourceId,
509
+ mediaTimeTicks: frame.requestedTimeTicks.toString(),
510
+ reason: nonPlanar ? "non-planar" : "unreadable",
511
+ }, { cause });
512
+ if (nonPlanar) {
513
+ const facts = {
514
+ kind: "video",
515
+ codec: null,
516
+ transfer,
517
+ frameFormat: cause.format,
518
+ softwareDecoder: "opaque",
519
+ browserError: cause.message,
520
+ };
521
+ return new PlanarDecodeUnavailableError(decodeRefusalMessage(frame.sourceId, facts), facts, { cause });
522
+ }
523
+ return Object.assign(new Error(`the browser could not read back the frame of ${frame.sourceId} at ${frame.requestedTimeTicks}, decoded again in software`, { cause }), { code: "FRAME_SUPPLY_FAILED" });
524
+ }
445
525
  function registerFonts(wasm, fonts) {
446
526
  for (const font of fonts) {
447
527
  if (font.faceIndex === undefined)
@@ -459,7 +539,6 @@ function registerResources(wasm, resources) {
459
539
  for (const resource of resources)
460
540
  wasm.registerLut3d(resource.id, resource.data);
461
541
  }
462
- /** Whether `host` lost its device; one whose check throws is taken to have lost it. */
463
542
  function isLost(host) {
464
543
  try {
465
544
  return host.isDeviceLost();
@@ -474,13 +553,11 @@ function requiredHost(host) {
474
553
  return host;
475
554
  }
476
555
  /**
477
- * A `RenderBackend` that forwards every call to a worker running {@link installRenderWorker}, which
478
- * exclusively owns the wasm and GPU state.
556
+ * A `RenderBackend` that forwards every call to a worker running {@link installRenderWorker}.
479
557
  *
480
- * Calls reject with `Alpha2WasmError` for an error the worker reports, and with a plain `Error`
481
- * after {@link WorkerRenderBackend.dispose}. Once the worker raises an uncaught error, every
482
- * pending and later call rejects with a fatal `RENDER_WORKER_FAILED` and the worker must be
483
- * replaced.
558
+ * Calls reject with `Alpha2WasmError` for worker errors, and with a plain `Error` after
559
+ * {@link WorkerRenderBackend.dispose}. After an uncaught worker error, every pending and later call
560
+ * rejects with a fatal `RENDER_WORKER_FAILED` and the worker must be replaced.
484
561
  */
485
562
  export class WorkerRenderBackend {
486
563
  #worker;
@@ -489,18 +566,15 @@ export class WorkerRenderBackend {
489
566
  #nextId = 1;
490
567
  #rendererChoice;
491
568
  #deviceLost = false;
569
+ #lossReport;
492
570
  #disposed = false;
493
- /** Set once the worker raised an uncaught error; see `#onWorkerError`. */
494
571
  #failure;
495
572
  constructor(worker) {
496
573
  this.#worker = worker;
497
574
  worker.addEventListener("message", this.#onMessage);
498
575
  worker.addEventListener("error", this.#onWorkerError);
499
576
  }
500
- /**
501
- * The renderer the worker's host draws with, once {@link WorkerRenderBackend.initialize} has
502
- * resolved; `undefined` before, or for a host that does not say.
503
- */
577
+ /** Set by {@link WorkerRenderBackend.initialize} and each recovery; `undefined` before. */
504
578
  get rendererChoice() {
505
579
  return this.#rendererChoice;
506
580
  }
@@ -511,10 +585,7 @@ export class WorkerRenderBackend {
511
585
  ]);
512
586
  this.#rendererChoice = choice;
513
587
  }
514
- /**
515
- * Transfers `frame.frame` to the worker; it is closed here if it cannot be posted, including
516
- * after {@link WorkerRenderBackend.dispose} or a worker failure.
517
- */
588
+ /** Transfers `frame.frame` to the worker, closing it here if it cannot be posted. */
518
589
  async uploadVideoFrame(frame) {
519
590
  await this.#request({
520
591
  type: "upload-video-frame",
@@ -526,6 +597,7 @@ export class WorkerRenderBackend {
526
597
  rotationDegrees: frame.rotationDegrees,
527
598
  mirror: frame.mirror,
528
599
  chromaSiting: frame.chromaSiting,
600
+ ...(frame.decode === undefined ? {} : { decode: frame.decode }),
529
601
  }, [frame.frame], () => frame.frame.close());
530
602
  }
531
603
  async present(timeTicks) {
@@ -538,11 +610,10 @@ export class WorkerRenderBackend {
538
610
  await this.#request({ type: "reset" });
539
611
  }
540
612
  /**
541
- * Renders timeline time `timeTicks` offscreen for an export to `codec`, which decides where its
542
- * chroma is packed, stamping the frame at `outputTimeTicks`, its time in the output. A `rendered`
543
- * ticket's `readback` settles when the worker posts the frame.
613
+ * Renders `timeTicks` for export with chroma sited for `codec`, stamped at `outputTimeTicks`. A
614
+ * `rendered` ticket's `readback` settles when the worker posts the frame.
544
615
  */
545
- beginExport(timeTicks, codec, outputTimeTicks) {
616
+ beginExport(timeTicks, codec, outputTimeTicks, pixels) {
546
617
  if (this.#disposed) {
547
618
  return Promise.reject(new Error("render backend disposed"));
548
619
  }
@@ -569,6 +640,7 @@ export class WorkerRenderBackend {
569
640
  timeTicks,
570
641
  codec,
571
642
  outputTimeTicks,
643
+ ...(pixels === undefined ? {} : { pixels }),
572
644
  });
573
645
  }
574
646
  catch (error) {
@@ -600,9 +672,27 @@ export class WorkerRenderBackend {
600
672
  isDeviceLost() {
601
673
  return this.#deviceLost;
602
674
  }
603
- async recover() {
604
- await this.#request({ type: "recover" });
675
+ /** Cleared by a recovery. */
676
+ lossReport() {
677
+ return this.#lossReport;
678
+ }
679
+ async probeSurface() {
680
+ return (await this.#request({ type: "probe-surface" }));
681
+ }
682
+ /** Resolves to the renderer the worker made. On rejection the backend stays lost. */
683
+ async recover(step, canvas) {
684
+ const choice = (await this.#request({ type: "recover", step, ...(canvas === undefined ? {} : { canvas }) }, canvas === undefined ? [] : [canvas]));
605
685
  this.#deviceLost = false;
686
+ this.#lossReport = undefined;
687
+ if (choice !== undefined)
688
+ this.#rendererChoice = choice;
689
+ return choice;
690
+ }
691
+ /** Capabilities probed inside the worker, which can differ from the page's. */
692
+ async detectCapabilities() {
693
+ return (await this.#request({
694
+ type: "detect-capabilities",
695
+ }));
606
696
  }
607
697
  /** Terminates the worker and rejects every pending call. Idempotent. */
608
698
  dispose() {
@@ -627,6 +717,8 @@ export class WorkerRenderBackend {
627
717
  if ("type" in message) {
628
718
  if (message.type === "device-lost") {
629
719
  this.#deviceLost = true;
720
+ if (message.report !== undefined)
721
+ this.#lossReport = message.report;
630
722
  return;
631
723
  }
632
724
  const readback = this.#pendingExportReadbacks.get(message.id);
@@ -653,12 +745,8 @@ export class WorkerRenderBackend {
653
745
  else
654
746
  request.reject(new Alpha2WasmError(message.error));
655
747
  };
656
- /**
657
- * An uncaught error in the worker is a failure outside any request, such as a wasm trap in a
658
- * future the module drove itself. The worker's serial queue may now wait forever on the call that
659
- * trapped, so a request posted after it would never be answered: the backend stays failed,
660
- * rejecting what is pending and everything later as fatal, and the host must replace the worker.
661
- */
748
+ // An uncaught worker error (such as a trap in a wasm-driven future) can leave the serial queue
749
+ // waiting forever, so the backend fails every pending and later call.
662
750
  #onWorkerError = (event) => {
663
751
  const error = new Alpha2WasmError({
664
752
  code: "RENDER_WORKER_FAILED",
@@ -675,7 +763,6 @@ export class WorkerRenderBackend {
675
763
  this.#pendingExportReadbacks.clear();
676
764
  };
677
765
  #request(request, transfer = [], onPostFailure) {
678
- // A request refused before posting releases its transfers as a failed post would.
679
766
  if (this.#disposed) {
680
767
  onPostFailure?.();
681
768
  return Promise.reject(new Error("render backend disposed"));
@@ -706,11 +793,10 @@ export class WorkerRenderBackend {
706
793
  }
707
794
  }
708
795
  }
709
- /** What a worker host without a live binding answers until a recovery makes one. */
710
796
  function lostRenderer() {
711
797
  return new Alpha2WasmError({
712
798
  code: "GPU_DEVICE_LOST",
713
- message: "the GPU device was lost and no renderer has been made again yet; recover() makes one",
799
+ message: "the GPU device was lost and no renderer has been made again yet; recover(step) makes one",
714
800
  fatal: true,
715
801
  });
716
802
  }
@@ -721,16 +807,22 @@ function lostRenderer() {
721
807
  export class WorkerExportBackend {
722
808
  #renderer;
723
809
  #codec;
810
+ #pixels;
724
811
  #aborted;
725
- /** Exports through `renderer`, packing frames for the `codec` the sink encodes. */
726
- constructor(renderer, codec) {
812
+ /**
813
+ * `pixels` is `resolvePixels(...).format` from `alpha2/containers` (I420 when absent). Pictures
814
+ * with alpha are drawn without the project background.
815
+ */
816
+ constructor(renderer, codec, pixels) {
727
817
  this.#renderer = renderer;
728
818
  this.#codec = codec;
819
+ if (pixels !== undefined && pixels !== "yuv420p")
820
+ this.#pixels = pixels;
729
821
  }
730
822
  async begin(timeTicks, outputTimeTicks) {
731
823
  if (this.#aborted !== undefined)
732
824
  throw this.#aborted;
733
- return this.#renderer.beginExport(timeTicks, this.#codec, outputTimeTicks);
825
+ return this.#renderer.beginExport(timeTicks, this.#codec, outputTimeTicks, this.#pixels);
734
826
  }
735
827
  isDeviceLost() {
736
828
  return this.#renderer.isDeviceLost();