alpha2 0.4.6 → 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 +108 -177
  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/generated/project-schema.d.ts +701 -485
  55. package/dist/generated/project-schema.js +55 -2
  56. package/dist/generated/project-shape.js +261 -16
  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 +82 -67
  62. package/dist/hdr-frames.js +112 -49
  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 +48 -63
  70. package/dist/layout.js +37 -37
  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 +166 -245
  76. package/dist/mediabunny.js +741 -580
  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 +73 -117
  84. package/dist/project.js +384 -445
  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 +97 -71
  96. package/dist/text.js +33 -70
  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 -95
  104. package/dist/worker.js +235 -143
  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 +460 -567
  111. package/wasm/alpha2_wasm.js +594 -594
  112. package/wasm/alpha2_wasm_bg.wasm +0 -0
  113. package/wasm/alpha2_wasm_bg.wasm.d.ts +15 -8
  114. package/wasm/rust-crate-licenses.md +2 -2
  115. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
  116. package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
  117. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  118. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
  119. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
@@ -1,17 +1,16 @@
1
- // The engine's immutable project snapshot is the sole authority for frame keys. The host must not
2
- // derive them itself, for example by rounding (timelineSeconds - clip.start).
3
- import { isHdrVideoFrame, isPlanarVideoFrame, NonPlanarVideoFrameError, PlanarCopyPool, readPlanarYuvFrame, uploadPlanarYuvFrame, } from "./hdr-frames.js";
1
+ // Frame keys come only from the engine's project snapshot; hosts must not derive them (for example
2
+ // by rounding `timelineSeconds - clip.start`).
3
+ import { isHdrVideoFrame, isPlanarVideoFrame, decodeRefusalMessage, NonPlanarVideoFrameError, PlanarCopyPool, PlanarDecodeUnavailableError, uploadPlanarYuvFrame, } from "./hdr-frames.js";
4
4
  import { decoderConsumerId } from "./media.js";
5
5
  import { sendsBitmaps, uploadPresentedFrame, } from "./presented-frames.js";
6
6
  import { PhysicalFrameAliases, } from "./physical-frames.js";
7
- /** Tick rate shared by every engine timestamp. */
7
+ import { intakeVideoFrame, readbackCounters, readPlanesWithRetries, } from "./frame-intake.js";
8
8
  const TICKS_PER_SECOND = 120_000;
9
9
  const DEFAULT_MAX_RETIRED_FRAME_BYTES = 256 * 1024 * 1024;
10
10
  const DEFAULT_MAX_CACHED_IMAGE_BYTES = 256 * 1024 * 1024;
11
11
  const DEFAULT_MAX_DECODE_CONCURRENCY = 2;
12
12
  /**
13
- * Keeps completed source upload generations resident within a byte budget, releasing the oldest
14
- * through `release` when the budget is exceeded.
13
+ * Keeps rendered upload generations within a byte budget, releasing the oldest through `release`.
15
14
  *
16
15
  * The constructor throws `RangeError` when `maxRetiredBytes` is not a positive safe integer.
17
16
  */
@@ -26,12 +25,11 @@ export class FrameGenerationRetainer {
26
25
  this.#release = release;
27
26
  this.#maxRetiredBytes = maxRetiredBytes;
28
27
  }
29
- /** Bytes of the generations currently held. */
30
28
  get retainedBytes() {
31
29
  return this.#retiredBytes;
32
30
  }
33
31
  /**
34
- * Takes over generations whose rendering has completed, releasing older ones past the budget.
32
+ * Takes over rendered generations, releasing older ones past the budget.
35
33
  *
36
34
  * @throws RangeError for a receipt with a non-positive generation or byte count.
37
35
  */
@@ -40,8 +38,7 @@ export class FrameGenerationRetainer {
40
38
  validateUploadReceipt(upload);
41
39
  this.#retired.push(upload);
42
40
  this.#retiredBytes += upload.retainedBytes;
43
- // Keep the newest generation even when one texture exceeds the budget, so a large but valid
44
- // frame cannot block forward progress.
41
+ // Keep the newest generation even over budget so a large frame cannot block progress.
45
42
  while (this.#retired.length > 1 &&
46
43
  this.#retiredBytes > this.#maxRetiredBytes) {
47
44
  const retired = this.#retired.shift();
@@ -52,32 +49,25 @@ export class FrameGenerationRetainer {
52
49
  }
53
50
  }
54
51
  }
55
- /**
56
- * Forgets every held generation without releasing it, for when the owning engine has dropped its
57
- * whole frame store.
58
- */
52
+ /** Forgets held generations without releasing them, after the engine dropped its frame store. */
59
53
  discardAll() {
60
54
  this.#retired = [];
61
55
  this.#retiredBytes = 0;
62
56
  }
63
57
  }
64
58
  /**
65
- * Keys the decoder cursor of one clip reading one asset.
66
- *
67
- * Two clips sharing a source must not share a cursor: a single sequential decoder would seek
68
- * backwards and forwards on every output frame.
59
+ * Keys the decoder cursor of one clip reading one asset. Clips sharing a source need separate
60
+ * cursors, or one decoder would seek back and forth every frame.
69
61
  */
70
62
  export function decoderCursorKey(assetId, consumerId) {
71
63
  return `${assetId}\u0000${consumerId}`;
72
64
  }
73
65
  /**
74
- * Reference host-side consumer of the engine's `frameNeeds` contract.
66
+ * Reference host-side consumer of the engine's `frameNeeds` contract. It decodes each needed frame
67
+ * through a clip-scoped cursor, uploads it, and bounds retention. Needs resolving to the same
68
+ * decoded frame share one upload.
75
69
  *
76
- * It asks the engine which source frames one timestamp requires, decodes each through a
77
- * clip-scoped cursor, uploads them, and bounds upload retention. Requests whose frames resolve to
78
- * one decoded frame share one upload.
79
- *
80
- * The constructor throws `RangeError` for a limit in `options` that is not a positive safe integer.
70
+ * The constructor throws `RangeError` for a limit that is not a positive safe integer.
81
71
  */
82
72
  export class FrameSupply {
83
73
  #engine;
@@ -92,30 +82,22 @@ export class FrameSupply {
92
82
  #cachedImageBytes = 0;
93
83
  #videoConversion;
94
84
  #unreadableFrames;
85
+ #presentsDegraded;
95
86
  #planarCopyFrames = 0;
96
87
  #planarCopyBytes = 0;
97
- #readback = {
98
- unreadableFrames: 0,
99
- readbackRetries: 0,
100
- redecodedFrames: 0,
101
- presentedFrames: 0,
102
- };
103
- /** Buffers the planar copies reuse; each is given back once its upload has taken it. */
88
+ #readback = readbackCounters();
104
89
  #planarCopies = new PlanarCopyPool();
105
90
  #imageUse = 0n;
106
91
  #contents = new Map();
107
92
  #nextEpoch = 0;
108
93
  /**
109
- * Still uploads a supply replaced or evicted, for the next {@link FrameSupply.retire}. Retiring
110
- * them at once could release, past the retired budget, a generation that a request of the same
111
- * frame was just served from by alias, before the engine renders that frame.
94
+ * Replaced or evicted still uploads, retired at the next {@link FrameSupply.retire}. Retiring
95
+ * immediately could release a generation that an alias just served before the engine renders it.
112
96
  */
113
97
  #replacedStills = [];
114
98
  /**
115
- * Optional upload trace, for diagnosing a clip that renders another clip's picture. Every RGBA
116
- * upload then reports which source received which pixels. Two sources sharing a checksum means
117
- * the host decoded the wrong asset, which is a host bug; distinct checksums move the search into
118
- * the engine.
99
+ * Optional RGBA upload trace for diagnosing a clip that shows another clip's picture. Two sources
100
+ * with the same checksum point to a host decoding bug; distinct checksums point to the engine.
119
101
  */
120
102
  onUpload = null;
121
103
  constructor(engine, options = {}) {
@@ -134,28 +116,30 @@ export class FrameSupply {
134
116
  if (unreadableFrames !== "redecode" && unreadableFrames !== "present")
135
117
  throw new RangeError('unreadableFrames must be "redecode" or "present"');
136
118
  this.#unreadableFrames = unreadableFrames;
119
+ const opaqueEngineFrames = options.opaqueEngineFrames ?? "refuse";
120
+ if (opaqueEngineFrames !== "refuse" &&
121
+ opaqueEngineFrames !== "present-degraded")
122
+ throw new RangeError('opaqueEngineFrames must be "refuse" or "present-degraded"');
123
+ this.#presentsDegraded =
124
+ opaqueEngineFrames === "present-degraded" &&
125
+ typeof engine.uploadDegradedVideoFrame === "function";
137
126
  this.#retainer = new FrameGenerationRetainer((generation) => this.#engine.releaseFrameGeneration(generation), options);
138
127
  }
139
- /** Bytes of rendered source textures kept resident; see {@link FrameRetentionOptions}. */
128
+ /** See {@link FrameRetentionOptions}. */
140
129
  get retiredBytes() {
141
130
  return this.#retainer.retainedBytes;
142
131
  }
143
- /** Bytes of uploaded stills currently cached. */
144
132
  get cachedImageBytes() {
145
133
  return this.#cachedImageBytes;
146
134
  }
147
- /**
148
- * Raw source video this supply copied through script memory, cumulative. Frames are copied out
149
- * planar so the engine converts them, as natively (see {@link VideoConversion}); that copy is a
150
- * source-side cost, apart from any output readback.
151
- */
135
+ /** Planar copies made for engine conversion (see {@link VideoConversion}). */
152
136
  get sourceTransfer() {
153
137
  return {
154
138
  planarCopyFrames: this.#planarCopyFrames,
155
139
  planarCopyBytes: this.#planarCopyBytes,
156
140
  };
157
141
  }
158
- /** Frames the browser could not read back, and how they were recovered; cumulative. */
142
+ /** Cumulative readback failures and how they were recovered. */
159
143
  get readbackRecovery() {
160
144
  return { ...this.#readback };
161
145
  }
@@ -171,24 +155,20 @@ export class FrameSupply {
171
155
  this.onUpload({ sourceId, mediaTimeTicks, checksum });
172
156
  }
173
157
  /**
174
- * Uploads every source the engine asks for at one timestamp. Browser video stays as a
175
- * `VideoFrame` until the WebGPU external-image copy consumes it.
158
+ * Uploads every source the engine needs at one timestamp.
176
159
  *
177
- * Resolves with receipts for the textures this call uploaded, or `null` when `isCurrent` turned
178
- * false mid-decode (decoded frames are then closed). The caller retires the receipts with
179
- * {@link FrameSupply.retire} once the engine has consumed them, so this call does not; the still
180
- * uploads it replaced or evicted are retired then too.
160
+ * Resolves with upload receipts for the caller to pass to {@link FrameSupply.retire} after
161
+ * rendering, or `null` when `isCurrent` turned false mid-decode (decoded frames are closed).
181
162
  *
182
- * Rejects with a fatal `GPU_DEVICE_LOST` error when the engine's device is lost, and with an
183
- * `Error` when a source is unavailable, decodes to nothing or to the wrong kind of frame, or an
184
- * upload fails. Uploads made before the failure are retired and remaining frames closed.
163
+ * Rejects with a fatal `GPU_DEVICE_LOST` error when the device is lost, and with an `Error` when
164
+ * a source is unavailable, decodes to nothing or the wrong kind of frame, or an upload fails.
165
+ * Earlier uploads are then retired and remaining frames closed.
185
166
  */
186
167
  async supply(timeTicks, { width, height, contentOf, liveSourceIds, getLayer, pixelsFor, retainVideoConsumers, isCurrent, }) {
187
168
  if (!isCurrent())
188
169
  return null;
189
170
  if (this.#engine.deviceLost) {
190
- // Coded as the binding codes a loss, so an owner can tell it from a failed frame and make the
191
- // renderer again.
171
+ // Same code the binding uses, so the owner recreates the renderer.
192
172
  const error = new Error("GPU device was lost; make the renderer again");
193
173
  error.name = "Alpha2Error";
194
174
  error.code = "GPU_DEVICE_LOST";
@@ -227,6 +207,7 @@ export class FrameSupply {
227
207
  if (entry === undefined)
228
208
  continue;
229
209
  const { need, layer, source, planar } = entry;
210
+ let degraded = entry.degraded === true;
230
211
  const sourceTicks = BigInt(need.mediaTimeTicks);
231
212
  const content = epochs.get(need.sourceId) ?? 0;
232
213
  let videoFrame = null;
@@ -281,24 +262,32 @@ export class FrameSupply {
281
262
  continue;
282
263
  }
283
264
  let upload;
284
- if (planar !== undefined) {
285
- // The copy takes the frame over and closes it, unless it hands it back for the
286
- // browser's own upload below (`unreadableFrames: "present"`).
265
+ if (planar !== undefined && !degraded) {
266
+ // The copy owns and closes the frame unless it hands it back for a browser upload.
287
267
  decoded[decodedIndex] = { need, layer, source: null };
288
268
  const copied = await this.#copyPlanar(need, layer, videoFrame, planar, pixelsFor);
289
- if (copied === undefined) {
269
+ if (copied === undefined || copied === DEGRADED) {
290
270
  decoded[decodedIndex] = { need, layer, source: videoFrame };
271
+ degraded = copied === DEGRADED;
291
272
  }
292
273
  else {
293
274
  try {
294
275
  upload = uploadPlanarYuvFrame(this.#planarEngine(), need.sourceId, sourceTicks, copied, width, height);
295
276
  }
296
277
  finally {
297
- // The upload copied the planes into the engine before it returned.
278
+ // The upload has already copied the planes into the engine.
298
279
  this.#planarCopies.release(copied.data);
299
280
  }
300
281
  }
301
282
  }
283
+ if (upload === undefined && degraded) {
284
+ const engine = this.#engine;
285
+ if (engine.uploadDegradedVideoFrame === undefined)
286
+ throw new Error("engine cannot present degraded frames");
287
+ // The engine owns and closes the frame whether or not the upload succeeds.
288
+ decoded[decodedIndex] = { need, layer, source: null };
289
+ upload = engine.uploadDegradedVideoFrame(need.sourceId, sourceTicks, videoFrame.frame, width, height, videoFrame.rotation ?? 0, videoFrame.mirror ?? false);
290
+ }
302
291
  if (upload === undefined) {
303
292
  const engine = this.#presentedEngine();
304
293
  const presented = [
@@ -310,7 +299,6 @@ export class FrameSupply {
310
299
  videoFrame.rotation ?? 0,
311
300
  videoFrame.mirror ?? false,
312
301
  ];
313
- // A frame the engine takes directly still uploads synchronously.
314
302
  upload = sendsBitmaps(engine)
315
303
  ? await uploadPresentedFrame(engine, ...presented)
316
304
  : engine.uploadPresentedVideoFrame(...presented);
@@ -376,13 +364,14 @@ export class FrameSupply {
376
364
  if (group === undefined)
377
365
  return;
378
366
  for (const { index, need, layer } of group) {
379
- // A request a seek or an edit replaced starts no further decodes: the next request waits
380
- // only for those already running.
367
+ // A replaced request starts no further decodes.
381
368
  if (failed || !isCurrent())
382
369
  return;
383
370
  try {
371
+ const refused = this.#contents.get(need.sourceId)?.refused;
372
+ if (refused !== undefined)
373
+ throw refused;
384
374
  const sourceTicks = BigInt(need.mediaTimeTicks);
385
- // Declared or HDR color is converted by the engine from planes.
386
375
  const declared = planar && layer.kind === "video"
387
376
  ? this.#engine.sourceColorMetadata?.(need.sourceId)
388
377
  : undefined;
@@ -390,7 +379,10 @@ export class FrameSupply {
390
379
  (planar &&
391
380
  layer.kind === "video" &&
392
381
  this.#engine.hdrSource?.(need.sourceId) === true);
393
- const software = layer.kind === "video" &&
382
+ const degraded = layer.kind === "video" &&
383
+ this.#contents.get(need.sourceId)?.degraded === true;
384
+ const software = !degraded &&
385
+ layer.kind === "video" &&
394
386
  this.#contents.get(need.sourceId)?.softwareDecode === true;
395
387
  const decoded = await this.#decodeCursor(software
396
388
  ? `${keyForNeed(need, layer)}\u0000software`
@@ -400,7 +392,13 @@ export class FrameSupply {
400
392
  sourceId: need.sourceId,
401
393
  ...(software ? { decode: "software" } : {}),
402
394
  }));
403
- results[index] = this.#planarRoute(need, layer, decoded, enginesColor, declared, planar);
395
+ results[index] =
396
+ degraded &&
397
+ decoded !== null &&
398
+ "kind" in decoded &&
399
+ decoded.kind === "video-frame"
400
+ ? { need, layer, source: decoded, degraded: true }
401
+ : this.#planarRoute(need, layer, decoded, enginesColor, declared, planar);
404
402
  }
405
403
  catch (error) {
406
404
  failure = error;
@@ -419,13 +417,10 @@ export class FrameSupply {
419
417
  return decoded;
420
418
  }
421
419
  /**
422
- * Routes a decoded `VideoFrame` to the engine's own color conversion, from planes: an HDR frame,
423
- * every frame of a source whose project declares its color (`enginesColor`), which wins over
424
- * the frame's own as it does natively, and, unless the supply leaves SDR to the browser, every
425
- * other frame with a planar format. A source the engine must convert must decode to a
426
- * `VideoFrame`: an RGBA readback has been through the browser's conversion already. The planes
427
- * are copied out only at upload, after an earlier upload of the same picture had the chance to
428
- * serve it.
420
+ * Routes a decoded `VideoFrame` to the engine's planar conversion: HDR frames, sources with
421
+ * declared color (`enginesColor`), and other planar frames unless SDR is left to the browser.
422
+ * Such sources must decode to a `VideoFrame`; an RGBA readback is browser-converted.
423
+ * Planes are copied only at upload, in case an earlier upload serves the picture.
429
424
  */
430
425
  #planarRoute(need, layer, source, enginesColor, declared, planar) {
431
426
  const isVideoFrame = source !== null && "kind" in source && source.kind === "video-frame";
@@ -451,44 +446,62 @@ export class FrameSupply {
451
446
  };
452
447
  }
453
448
  /**
454
- * Copies a frame out planar for the engine to convert, and closes it.
449
+ * Copies a frame out planar for the engine and closes it.
455
450
  *
456
- * A frame whose planes the browser cannot read back (Chrome, now and then, for hardware-decoded
457
- * frames) is read again, then decoded again in software and copied from that decode: the codecs
458
- * define their decoding exactly, so the engine converts the planes it would have. With
459
- * `unreadableFrames: "present"`, a frame the engine need not convert resolves `undefined`
460
- * instead, left open for the browser's conversion. A frame with no planar format the engine
461
- * reads (an opaque hardware frame, routed here only when the engine must convert it) is decoded
462
- * again in software at once, as every later frame of its source is. Rejects, the frame closed,
463
- * when the copy fails otherwise or the software decode cannot serve it.
451
+ * Unreadable frames are retried, then decoded again in software (decoding is exact, so the planes
452
+ * match). With `unreadableFrames: "present"`, a frame the engine need not convert resolves
453
+ * `undefined` and stays open for the browser. Non-planar frames go straight to software, as do
454
+ * later frames of the source. Rejects, closing the frame, when the copy or software decode fails.
464
455
  */
465
456
  async #copyPlanar(need, layer, source, planar, pixelsFor) {
466
- let copied;
457
+ let intake;
467
458
  try {
468
- copied = await this.#readPlanes(source, planar.declared);
459
+ intake = await intakeVideoFrame(source.frame, {
460
+ required: planar.required,
461
+ declared: parseDeclared(planar.declared),
462
+ identity: planarIdentity(source),
463
+ pool: this.#planarCopies,
464
+ counters: this.#readback,
465
+ unreadable: this.#unreadableFrames,
466
+ takesPresented: takesPresentedFrames(this.#engine),
467
+ });
469
468
  }
470
469
  catch (error) {
471
- const nonPlanar = error instanceof NonPlanarVideoFrameError;
472
- if (!nonPlanar && !isUnreadableFrame(error)) {
470
+ source.frame.close();
471
+ throw error;
472
+ }
473
+ if (intake.kind === "present")
474
+ return undefined;
475
+ let copied;
476
+ if (intake.kind === "planar")
477
+ copied = intake.planar;
478
+ else {
479
+ const timestamp = source.physicalTimeMicroseconds ?? source.frame.timestamp;
480
+ const transfer = source.frame.colorSpace?.transfer ?? null;
481
+ const nonPlanar = intake.cause instanceof NonPlanarVideoFrameError;
482
+ // Keep the frame open in case it is presented degraded.
483
+ const keep = nonPlanar && this.#presentsDegraded;
484
+ if (!keep)
473
485
  source.frame.close();
474
- throw error;
475
- }
476
- this.#readback.unreadableFrames += 1;
477
- if (!nonPlanar &&
478
- this.#unreadableFrames === "present" &&
479
- !planar.required &&
480
- takesPresentedFrames(this.#engine)) {
481
- this.#readback.presentedFrames += 1;
482
- return undefined;
486
+ const content = this.#contents.get(need.sourceId);
487
+ if (nonPlanar && content !== undefined)
488
+ content.softwareDecode = true;
489
+ try {
490
+ copied = await this.#redecodePlanar(need, layer, planar, { timestamp, transfer }, pixelsFor, intake.cause);
483
491
  }
484
- const timestamp = source.physicalTimeMicroseconds ?? source.frame.timestamp;
485
- source.frame.close();
486
- if (nonPlanar) {
487
- const content = this.#contents.get(need.sourceId);
488
- if (content !== undefined)
489
- content.softwareDecode = true;
492
+ catch (error) {
493
+ if (keep && error instanceof PlanarDecodeUnavailableError) {
494
+ if (content !== undefined) {
495
+ content.refused = undefined;
496
+ content.softwareDecode = undefined;
497
+ content.degraded = true;
498
+ }
499
+ return DEGRADED;
500
+ }
501
+ if (keep)
502
+ source.frame.close();
503
+ throw error;
490
504
  }
491
- copied = await this.#redecodePlanar(need, layer, planar, timestamp, pixelsFor, error);
492
505
  }
493
506
  source.frame.close();
494
507
  this.#planarCopyFrames += 1;
@@ -496,35 +509,37 @@ export class FrameSupply {
496
509
  return copied;
497
510
  }
498
511
  /**
499
- * The frame's planes, read again up to {@link READBACK_RETRIES} times, a task apart, while the
500
- * browser fails to read them back. Leaves the frame open.
501
- */
502
- async #readPlanes(source, declared) {
503
- const color = declared === undefined ? null : JSON.parse(declared);
504
- for (let retry = 0;; retry += 1) {
505
- try {
506
- return await readPlanarYuvFrame(source.frame, color, planarIdentity(source), this.#planarCopies);
507
- }
508
- catch (error) {
509
- if (retry >= READBACK_RETRIES || !isUnreadableFrame(error))
510
- throw error;
511
- this.#readback.readbackRetries += 1;
512
- await nextTask();
513
- }
514
- }
515
- }
516
- /**
517
- * Decodes `need` again in software and copies that frame out planar. Rejects with `cause` when
518
- * the host cannot decode it in software, decodes another picture (another timestamp), or that
519
- * copy fails too.
512
+ * Decodes `need` again in software and copies it out planar.
513
+ *
514
+ * When `cause` is a {@link NonPlanarVideoFrameError} and software decode is unavailable or also
515
+ * non-planar, rejects with {@link PlanarDecodeUnavailableError} and fails later frames of the
516
+ * source at once. Other failures reject with `FRAME_SUPPLY_FAILED`.
520
517
  */
521
- async #redecodePlanar(need, layer, planar, timestamp, pixelsFor, cause) {
518
+ async #redecodePlanar(need, layer, planar, { timestamp, transfer }, pixelsFor, cause) {
522
519
  const what = cause instanceof NonPlanarVideoFrameError
523
520
  ? `the browser decoded the frame of ${need.sourceId} at ${need.mediaTimeTicks} to ${cause.format === null
524
521
  ? "an opaque frame"
525
522
  : `a ${cause.format} frame`} the engine must convert from planes (HDR, or color the project declares)`
526
523
  : `the browser could not read back the frame of ${need.sourceId} at ${need.mediaTimeTicks}`;
527
- const unrecovered = (reason, error = cause) => new Error(`${what}, and ${reason}`, { cause: error });
524
+ const unrecovered = (reason, error = cause) => Object.assign(new Error(`${what}, and ${reason}`, { cause: error }), {
525
+ code: "FRAME_SUPPLY_FAILED",
526
+ });
527
+ const refuse = (softwareDecoder, error) => {
528
+ const facts = {
529
+ kind: "video",
530
+ codec: null,
531
+ transfer,
532
+ frameFormat: cause instanceof NonPlanarVideoFrameError ? cause.format : null,
533
+ softwareDecoder,
534
+ browserError: error instanceof Error ? error.message : String(error),
535
+ };
536
+ const refusal = new PlanarDecodeUnavailableError(decodeRefusalMessage(need.sourceId, facts), facts, { cause: error });
537
+ const content = this.#contents.get(need.sourceId);
538
+ if (content !== undefined)
539
+ content.refused = refusal;
540
+ return refusal;
541
+ };
542
+ const nonPlanar = cause instanceof NonPlanarVideoFrameError;
528
543
  let decoded;
529
544
  try {
530
545
  decoded = await this.#decodeCursor(`${keyForNeed(need, layer)}\u0000software`, () => pixelsFor(layer, Number(BigInt(need.mediaTimeTicks)) / TICKS_PER_SECOND, {
@@ -535,6 +550,10 @@ export class FrameSupply {
535
550
  }));
536
551
  }
537
552
  catch (error) {
553
+ if (nonPlanar &&
554
+ error?.code ===
555
+ "software_decode_unavailable")
556
+ throw refuse("none", error);
538
557
  throw unrecovered("decoding it again in software failed", error);
539
558
  }
540
559
  if (decoded === null ||
@@ -546,12 +565,21 @@ export class FrameSupply {
546
565
  const at = again.physicalTimeMicroseconds ?? again.frame.timestamp;
547
566
  if (at !== timestamp)
548
567
  throw unrecovered(`decoding it again in software gave the frame at ${at} us`);
549
- const copied = await this.#readPlanes(again, planar.declared);
568
+ let copied;
569
+ try {
570
+ copied = await readPlanesWithRetries(again.frame, parseDeclared(planar.declared), planarIdentity(again), this.#planarCopies, this.#readback);
571
+ }
572
+ catch (error) {
573
+ if (nonPlanar && error instanceof NonPlanarVideoFrameError)
574
+ throw refuse("opaque", error);
575
+ throw error;
576
+ }
550
577
  this.#readback.redecodedFrames += 1;
551
578
  return copied;
552
579
  }
553
580
  catch (error) {
554
- throw error instanceof Error && error.cause === cause
581
+ throw error instanceof PlanarDecodeUnavailableError ||
582
+ (error instanceof Error && error.cause === cause)
555
583
  ? error
556
584
  : unrecovered("the software decode's frame could not be copied either", error);
557
585
  }
@@ -559,7 +587,7 @@ export class FrameSupply {
559
587
  again.frame.close();
560
588
  }
561
589
  }
562
- /** The engine's presented RGBA uploads, called on the engine. */
590
+ /** The engine's presented RGBA upload methods, bound to it. */
563
591
  #presenter() {
564
592
  const engine = this.#engine;
565
593
  const required = (upload) => {
@@ -576,7 +604,7 @@ export class FrameSupply {
576
604
  : required(engine.uploadPresentedRgbaImage).call(engine, sourceId, raster.width, raster.height, raster.pixels, raster.alpha !== "straight", width, height),
577
605
  };
578
606
  }
579
- /** The engine, which must take presented `VideoFrame` uploads. */
607
+ /** The engine, asserted to take presented `VideoFrame` uploads. */
580
608
  #presentedEngine() {
581
609
  const engine = this.#engine;
582
610
  if (!takesPresentedFrames(engine))
@@ -626,9 +654,8 @@ export class FrameSupply {
626
654
  this.#decodeWaiters.shift()?.();
627
655
  }
628
656
  /**
629
- * Hands over receipts from {@link FrameSupply.supply} once the engine has rendered with them,
630
- * after the still uploads the supplies since the last call replaced or evicted. The oldest are
631
- * released past `maxRetiredBytes`.
657
+ * Retires receipts from {@link FrameSupply.supply} after rendering, along with replaced or
658
+ * evicted stills. The oldest are released past `maxRetiredBytes`.
632
659
  */
633
660
  retire(uploads) {
634
661
  const replaced = this.#replacedStills;
@@ -645,7 +672,7 @@ export class FrameSupply {
645
672
  return;
646
673
  this.#replacedStills.push(image.upload);
647
674
  }
648
- /** Drops a cache entry whose upload the engine no longer holds, so there is nothing to retire. */
675
+ /** Drops a cache entry whose upload the engine already evicted. */
649
676
  #forgetImage(id, image) {
650
677
  if (!this.#images.delete(id))
651
678
  return false;
@@ -678,10 +705,8 @@ export class FrameSupply {
678
705
  this.#cachedImageBytes += upload.retainedBytes;
679
706
  }
680
707
  /**
681
- * Uploads again each still this timestamp shows that the engine no longer holds. The engine drops
682
- * stills by its own byte budget and count limit, oldest upload first, without telling the page,
683
- * so a still cached here since long ago is the first to go, before this supply or during it. One
684
- * upload can drop another still this timestamp shows, so this repeats while it makes progress.
708
+ * Re-uploads stills this timestamp shows that the engine silently evicted (oldest first, by its
709
+ * own budget). One upload can evict another, so this repeats while it makes progress.
685
710
  */
686
711
  #keepStillsHeld(stills, width, height) {
687
712
  for (let pass = 0; pass <= stills.size; pass += 1) {
@@ -701,9 +726,8 @@ export class FrameSupply {
701
726
  }
702
727
  }
703
728
  /**
704
- * The number naming the content of `id` this supply uploads, in physical-frame identities. When
705
- * `contentOf` says the source changed, what was uploaded for it goes, here and in the engine;
706
- * other sources keep theirs.
729
+ * Content epoch of `id` used in physical-frame identities. When `contentOf` reports a change, the
730
+ * source's uploads are dropped here and in the engine.
707
731
  */
708
732
  #contentEpoch(id, contentOf) {
709
733
  const content = contentOf?.(id);
@@ -736,11 +760,10 @@ export class FrameSupply {
736
760
  }
737
761
  }
738
762
  /**
739
- * Supplies one timestamp and presents it, retiring the uploads afterwards.
763
+ * Supplies one timestamp, presents it, and retires the uploads.
740
764
  *
741
765
  * Resolves with `null` when `isCurrent` turned false before presenting. Rejects as
742
- * {@link FrameSupply.supply} does, and with an `Error` naming the missing frames when the engine
743
- * still reports missing sources after the supply.
766
+ * {@link FrameSupply.supply} does, or when the engine still reports missing sources.
744
767
  */
745
768
  async render(timeTicks, options) {
746
769
  const supplied = await this.supply(timeTicks, options);
@@ -751,8 +774,7 @@ export class FrameSupply {
751
774
  if (!options.isCurrent())
752
775
  return null;
753
776
  const playback = JSON.parse(this.#engine.renderAt(timeTicks));
754
- // Do not await GPU completion here: it adds latency and does not fix flicker. Export reads
755
- // pixels back offscreen instead.
777
+ // Do not await GPU completion: it adds latency without fixing flicker.
756
778
  if (playback.missingSources.length) {
757
779
  const missing = needs.filter((need) => playback.missingSources.includes(need.sourceId));
758
780
  throw new Error(`missing frames at timeline ${timeTicks}: ${missing
@@ -816,12 +838,11 @@ function rgbaIdentity(sourceId, contentGeneration, source, outputWidth, outputHe
816
838
  };
817
839
  }
818
840
  /**
819
- * Whether two stills are one picture: the same RGBA8 array, or provider rasters of the same
820
- * identity (its first source time and duration, size, precision, and alpha). A source whose content
821
- * changes loses its cached still through `contentOf` first.
841
+ * Whether two stills are the same picture: the same RGBA8 array, or provider rasters with equal
842
+ * time, duration, size, precision and alpha.
822
843
  */
823
844
  function sameStill(cached, still) {
824
- // Told apart by shape, not by class: a host's pixels can be a typed array of another realm.
845
+ // Check shape, not class, since host pixels may come from another realm.
825
846
  if (!("kind" in cached) || !("kind" in still))
826
847
  return cached === still;
827
848
  return (cached.width === still.width &&
@@ -853,20 +874,13 @@ function validatePositiveInteger(value, name) {
853
874
  throw new RangeError(`${name} must be a positive safe integer`);
854
875
  }
855
876
  }
856
- /** Reads repeated on a frame whose planes the browser could not read back, before decoding again. */
857
- const READBACK_RETRIES = 2;
858
- /**
859
- * Whether a planar copy failed because the browser could not read a GPU-backed frame back: Chrome
860
- * rejects `copyTo` with `InvalidStateError` ("Failed to read VideoFrame data."), now and then, for
861
- * hardware-decoded frames. A closed frame rejects with the same name, but the supply owns the
862
- * frames it copies and has not closed them.
863
- */
864
- function isUnreadableFrame(error) {
865
- return (typeof DOMException !== "undefined" &&
866
- error instanceof DOMException &&
867
- error.name === "InvalidStateError");
877
+ /** `#copyPlanar` result for a frame to present degraded. */
878
+ const DEGRADED = Symbol("degraded");
879
+ function parseDeclared(declared) {
880
+ return declared === undefined
881
+ ? null
882
+ : JSON.parse(declared);
868
883
  }
869
- /** What a planar copy of `source` carries beyond the frame (see `PlanarFrameIdentity`). */
870
884
  function planarIdentity(source) {
871
885
  return {
872
886
  ...(source.physicalTimeMicroseconds === undefined
@@ -879,11 +893,7 @@ function planarIdentity(source) {
879
893
  : { chromaSiting: source.chromaSiting }),
880
894
  };
881
895
  }
882
- /** Resolves once the browser has run other tasks, such as the GPU process's replies. */
883
- function nextTask() {
884
- return new Promise((resolve) => setTimeout(resolve, 0));
885
- }
886
- /** Whether `engine` takes presented `VideoFrame` uploads (`uploadPresentedVideoFrame`). */
896
+ /** Whether `engine` has `uploadPresentedVideoFrame`. */
887
897
  function takesPresentedFrames(engine) {
888
898
  return typeof engine.uploadPresentedVideoFrame === "function";
889
899
  }
@@ -900,8 +910,8 @@ function keyForNeed(need, layer) {
900
910
  : decoderCursorKey(need.sourceId, consumerOf(need));
901
911
  }
902
912
  /**
903
- * Who reads a source sequentially: the clip, or one of its composition's steps. Two steps reading
904
- * one source at different times must not share a cursor, or each read makes the decoder seek.
913
+ * The sequential reader of a source: the clip or a composition step. Readers at different times
914
+ * need separate cursors to avoid constant seeking.
905
915
  */
906
916
  function consumerOf(need) {
907
917
  return decoderConsumerId(need.clipId ?? need.sourceId, need.readerId);