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
@@ -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, 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,12 +379,26 @@ export class FrameSupply {
390
379
  (planar &&
391
380
  layer.kind === "video" &&
392
381
  this.#engine.hdrSource?.(need.sourceId) === true);
393
- const decoded = await this.#decodeCursor(keyForNeed(need, layer), () => pixelsFor(layer, Number(sourceTicks) / TICKS_PER_SECOND, {
382
+ const degraded = layer.kind === "video" &&
383
+ this.#contents.get(need.sourceId)?.degraded === true;
384
+ const software = !degraded &&
385
+ layer.kind === "video" &&
386
+ this.#contents.get(need.sourceId)?.softwareDecode === true;
387
+ const decoded = await this.#decodeCursor(software
388
+ ? `${keyForNeed(need, layer)}\u0000software`
389
+ : keyForNeed(need, layer), () => pixelsFor(layer, Number(sourceTicks) / TICKS_PER_SECOND, {
394
390
  preferVideoFrame: directVideo || enginesColor,
395
391
  consumerId: consumerOf(need),
396
392
  sourceId: need.sourceId,
393
+ ...(software ? { decode: "software" } : {}),
397
394
  }));
398
- 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);
399
402
  }
400
403
  catch (error) {
401
404
  failure = error;
@@ -414,13 +417,10 @@ export class FrameSupply {
414
417
  return decoded;
415
418
  }
416
419
  /**
417
- * Routes a decoded `VideoFrame` to the engine's own color conversion, from planes: an HDR frame,
418
- * every frame of a source whose project declares its color (`enginesColor`), which wins over
419
- * the frame's own as it does natively, and, unless the supply leaves SDR to the browser, every
420
- * other frame with a planar format. A source the engine must convert must decode to a
421
- * `VideoFrame`: an RGBA readback has been through the browser's conversion already. The planes
422
- * are copied out only at upload, after an earlier upload of the same picture had the chance to
423
- * 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.
424
424
  */
425
425
  #planarRoute(need, layer, source, enginesColor, declared, planar) {
426
426
  const isVideoFrame = source !== null && "kind" in source && source.kind === "video-frame";
@@ -446,35 +446,62 @@ export class FrameSupply {
446
446
  };
447
447
  }
448
448
  /**
449
- * 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.
450
450
  *
451
- * A frame whose planes the browser cannot read back (Chrome, now and then, for hardware-decoded
452
- * frames) is read again, then decoded again in software and copied from that decode: the codecs
453
- * define their decoding exactly, so the engine converts the planes it would have. With
454
- * `unreadableFrames: "present"`, a frame the engine need not convert resolves `undefined`
455
- * instead, left open for the browser's conversion. Rejects, the frame closed, when the copy
456
- * 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.
457
455
  */
458
456
  async #copyPlanar(need, layer, source, planar, pixelsFor) {
459
- let copied;
457
+ let intake;
460
458
  try {
461
- 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
+ });
462
468
  }
463
469
  catch (error) {
464
- if (!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)
465
485
  source.frame.close();
466
- throw error;
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);
467
491
  }
468
- this.#readback.unreadableFrames += 1;
469
- if (this.#unreadableFrames === "present" &&
470
- !planar.required &&
471
- takesPresentedFrames(this.#engine)) {
472
- this.#readback.presentedFrames += 1;
473
- return undefined;
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;
474
504
  }
475
- const timestamp = source.physicalTimeMicroseconds ?? source.frame.timestamp;
476
- source.frame.close();
477
- copied = await this.#redecodePlanar(need, layer, planar, timestamp, pixelsFor, error);
478
505
  }
479
506
  source.frame.close();
480
507
  this.#planarCopyFrames += 1;
@@ -482,30 +509,37 @@ export class FrameSupply {
482
509
  return copied;
483
510
  }
484
511
  /**
485
- * The frame's planes, read again up to {@link READBACK_RETRIES} times, a task apart, while the
486
- * browser fails to read them back. Leaves the frame open.
487
- */
488
- async #readPlanes(source, declared) {
489
- const color = declared === undefined ? null : JSON.parse(declared);
490
- for (let retry = 0;; retry += 1) {
491
- try {
492
- return await readPlanarYuvFrame(source.frame, color, planarIdentity(source), this.#planarCopies);
493
- }
494
- catch (error) {
495
- if (retry >= READBACK_RETRIES || !isUnreadableFrame(error))
496
- throw error;
497
- this.#readback.readbackRetries += 1;
498
- await nextTask();
499
- }
500
- }
501
- }
502
- /**
503
- * Decodes `need` again in software and copies that frame out planar. Rejects with `cause` when
504
- * the host cannot decode it in software, decodes another picture (another timestamp), or that
505
- * 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`.
506
517
  */
507
- async #redecodePlanar(need, layer, planar, timestamp, pixelsFor, cause) {
508
- const unrecovered = (reason, error = cause) => new Error(`the browser could not read back the frame of ${need.sourceId} at ${need.mediaTimeTicks}, and ${reason}`, { cause: error });
518
+ async #redecodePlanar(need, layer, planar, { timestamp, transfer }, pixelsFor, cause) {
519
+ const what = cause instanceof NonPlanarVideoFrameError
520
+ ? `the browser decoded the frame of ${need.sourceId} at ${need.mediaTimeTicks} to ${cause.format === null
521
+ ? "an opaque frame"
522
+ : `a ${cause.format} frame`} the engine must convert from planes (HDR, or color the project declares)`
523
+ : `the browser could not read back the frame of ${need.sourceId} at ${need.mediaTimeTicks}`;
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;
509
543
  let decoded;
510
544
  try {
511
545
  decoded = await this.#decodeCursor(`${keyForNeed(need, layer)}\u0000software`, () => pixelsFor(layer, Number(BigInt(need.mediaTimeTicks)) / TICKS_PER_SECOND, {
@@ -516,6 +550,10 @@ export class FrameSupply {
516
550
  }));
517
551
  }
518
552
  catch (error) {
553
+ if (nonPlanar &&
554
+ error?.code ===
555
+ "software_decode_unavailable")
556
+ throw refuse("none", error);
519
557
  throw unrecovered("decoding it again in software failed", error);
520
558
  }
521
559
  if (decoded === null ||
@@ -527,12 +565,21 @@ export class FrameSupply {
527
565
  const at = again.physicalTimeMicroseconds ?? again.frame.timestamp;
528
566
  if (at !== timestamp)
529
567
  throw unrecovered(`decoding it again in software gave the frame at ${at} us`);
530
- 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
+ }
531
577
  this.#readback.redecodedFrames += 1;
532
578
  return copied;
533
579
  }
534
580
  catch (error) {
535
- throw error instanceof Error && error.cause === cause
581
+ throw error instanceof PlanarDecodeUnavailableError ||
582
+ (error instanceof Error && error.cause === cause)
536
583
  ? error
537
584
  : unrecovered("the software decode's frame could not be copied either", error);
538
585
  }
@@ -540,7 +587,7 @@ export class FrameSupply {
540
587
  again.frame.close();
541
588
  }
542
589
  }
543
- /** The engine's presented RGBA uploads, called on the engine. */
590
+ /** The engine's presented RGBA upload methods, bound to it. */
544
591
  #presenter() {
545
592
  const engine = this.#engine;
546
593
  const required = (upload) => {
@@ -557,7 +604,7 @@ export class FrameSupply {
557
604
  : required(engine.uploadPresentedRgbaImage).call(engine, sourceId, raster.width, raster.height, raster.pixels, raster.alpha !== "straight", width, height),
558
605
  };
559
606
  }
560
- /** The engine, which must take presented `VideoFrame` uploads. */
607
+ /** The engine, asserted to take presented `VideoFrame` uploads. */
561
608
  #presentedEngine() {
562
609
  const engine = this.#engine;
563
610
  if (!takesPresentedFrames(engine))
@@ -607,9 +654,8 @@ export class FrameSupply {
607
654
  this.#decodeWaiters.shift()?.();
608
655
  }
609
656
  /**
610
- * Hands over receipts from {@link FrameSupply.supply} once the engine has rendered with them,
611
- * after the still uploads the supplies since the last call replaced or evicted. The oldest are
612
- * 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`.
613
659
  */
614
660
  retire(uploads) {
615
661
  const replaced = this.#replacedStills;
@@ -626,7 +672,7 @@ export class FrameSupply {
626
672
  return;
627
673
  this.#replacedStills.push(image.upload);
628
674
  }
629
- /** 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. */
630
676
  #forgetImage(id, image) {
631
677
  if (!this.#images.delete(id))
632
678
  return false;
@@ -659,10 +705,8 @@ export class FrameSupply {
659
705
  this.#cachedImageBytes += upload.retainedBytes;
660
706
  }
661
707
  /**
662
- * Uploads again each still this timestamp shows that the engine no longer holds. The engine drops
663
- * stills by its own byte budget and count limit, oldest upload first, without telling the page,
664
- * so a still cached here since long ago is the first to go, before this supply or during it. One
665
- * 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.
666
710
  */
667
711
  #keepStillsHeld(stills, width, height) {
668
712
  for (let pass = 0; pass <= stills.size; pass += 1) {
@@ -682,9 +726,8 @@ export class FrameSupply {
682
726
  }
683
727
  }
684
728
  /**
685
- * The number naming the content of `id` this supply uploads, in physical-frame identities. When
686
- * `contentOf` says the source changed, what was uploaded for it goes, here and in the engine;
687
- * 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.
688
731
  */
689
732
  #contentEpoch(id, contentOf) {
690
733
  const content = contentOf?.(id);
@@ -717,11 +760,10 @@ export class FrameSupply {
717
760
  }
718
761
  }
719
762
  /**
720
- * Supplies one timestamp and presents it, retiring the uploads afterwards.
763
+ * Supplies one timestamp, presents it, and retires the uploads.
721
764
  *
722
765
  * Resolves with `null` when `isCurrent` turned false before presenting. Rejects as
723
- * {@link FrameSupply.supply} does, and with an `Error` naming the missing frames when the engine
724
- * still reports missing sources after the supply.
766
+ * {@link FrameSupply.supply} does, or when the engine still reports missing sources.
725
767
  */
726
768
  async render(timeTicks, options) {
727
769
  const supplied = await this.supply(timeTicks, options);
@@ -732,8 +774,7 @@ export class FrameSupply {
732
774
  if (!options.isCurrent())
733
775
  return null;
734
776
  const playback = JSON.parse(this.#engine.renderAt(timeTicks));
735
- // Do not await GPU completion here: it adds latency and does not fix flicker. Export reads
736
- // pixels back offscreen instead.
777
+ // Do not await GPU completion: it adds latency without fixing flicker.
737
778
  if (playback.missingSources.length) {
738
779
  const missing = needs.filter((need) => playback.missingSources.includes(need.sourceId));
739
780
  throw new Error(`missing frames at timeline ${timeTicks}: ${missing
@@ -797,12 +838,11 @@ function rgbaIdentity(sourceId, contentGeneration, source, outputWidth, outputHe
797
838
  };
798
839
  }
799
840
  /**
800
- * Whether two stills are one picture: the same RGBA8 array, or provider rasters of the same
801
- * identity (its first source time and duration, size, precision, and alpha). A source whose content
802
- * 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.
803
843
  */
804
844
  function sameStill(cached, still) {
805
- // 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.
806
846
  if (!("kind" in cached) || !("kind" in still))
807
847
  return cached === still;
808
848
  return (cached.width === still.width &&
@@ -834,20 +874,13 @@ function validatePositiveInteger(value, name) {
834
874
  throw new RangeError(`${name} must be a positive safe integer`);
835
875
  }
836
876
  }
837
- /** Reads repeated on a frame whose planes the browser could not read back, before decoding again. */
838
- const READBACK_RETRIES = 2;
839
- /**
840
- * Whether a planar copy failed because the browser could not read a GPU-backed frame back: Chrome
841
- * rejects `copyTo` with `InvalidStateError` ("Failed to read VideoFrame data."), now and then, for
842
- * hardware-decoded frames. A closed frame rejects with the same name, but the supply owns the
843
- * frames it copies and has not closed them.
844
- */
845
- function isUnreadableFrame(error) {
846
- return (typeof DOMException !== "undefined" &&
847
- error instanceof DOMException &&
848
- 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);
849
883
  }
850
- /** What a planar copy of `source` carries beyond the frame (see `PlanarFrameIdentity`). */
851
884
  function planarIdentity(source) {
852
885
  return {
853
886
  ...(source.physicalTimeMicroseconds === undefined
@@ -860,11 +893,7 @@ function planarIdentity(source) {
860
893
  : { chromaSiting: source.chromaSiting }),
861
894
  };
862
895
  }
863
- /** Resolves once the browser has run other tasks, such as the GPU process's replies. */
864
- function nextTask() {
865
- return new Promise((resolve) => setTimeout(resolve, 0));
866
- }
867
- /** Whether `engine` takes presented `VideoFrame` uploads (`uploadPresentedVideoFrame`). */
896
+ /** Whether `engine` has `uploadPresentedVideoFrame`. */
868
897
  function takesPresentedFrames(engine) {
869
898
  return typeof engine.uploadPresentedVideoFrame === "function";
870
899
  }
@@ -881,8 +910,8 @@ function keyForNeed(need, layer) {
881
910
  : decoderCursorKey(need.sourceId, consumerOf(need));
882
911
  }
883
912
  /**
884
- * Who reads a source sequentially: the clip, or one of its composition's steps. Two steps reading
885
- * 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.
886
915
  */
887
916
  function consumerOf(need) {
888
917
  return decoderConsumerId(need.clipId ?? need.sourceId, need.readerId);