alpha2 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -88,6 +88,7 @@ For preview, `alpha2/audio-timeline` moves the mixed blocks to the audio thread
88
88
  | `alpha2/edit` | Editing operations on a project: split, trim, ripple, roll, slip, slide, retime, insert, overwrite, append, move. |
89
89
  | `alpha2/captions` | SRT and WebVTT import into caption tracks. |
90
90
  | `alpha2/geometry` | Shape geometry for editors, from the engine's own code: item bounds, hit tests, nearest points, path lengths, trims, resampling, convert to path, motion paths. |
91
+ | `alpha2/layout` | Layout generators: `measureLayout` (where every box lies and what overflows, laid out with the engine's fonts, pixels those of the project canvas) and a builder from CSS-like props, flexbox and grid. See [docs/layout.md](https://github.com/alpha2-sh/alpha2/blob/main/docs/layout.md). |
91
92
  | `alpha2/effects` | Effect definitions and the built-in catalog's types; `RuntimeEffectRegistry`, a typed wrapper for registering WGSL effects and effect resources at run time. |
92
93
  | `alpha2/extensions`, `alpha2/extensions-wasm` | SVG, animated image, Lottie, OpenEXR and image sequence sources, from their own WebAssembly module (`loadExtensions`). |
93
94
  | `alpha2/text` | Text rasterizers: `WasmTextRasterizer` (the engine's, the same pixels as a native export) and `OffscreenTextRasterizer` (the browser's). |
@@ -105,6 +105,13 @@ export interface FrameSupplyDecodeOptions {
105
105
  * own), so a host keys what it keeps per source by this, as `liveSourceIds` names sources.
106
106
  */
107
107
  readonly sourceId: string;
108
+ /**
109
+ * `"software"`: decode this frame on the CPU, on a cursor of its own beside `consumerId`'s, and
110
+ * resolve with a `VideoFrame`. The supply asks for it when the browser could not read a
111
+ * hardware-decoded frame back; a host that cannot decode the source in software rejects. Absent
112
+ * for every other request.
113
+ */
114
+ readonly decode?: "software";
108
115
  }
109
116
  /** Host callbacks and frame geometry for one `supply` call. */
110
117
  export interface FrameSupplyOptions {
@@ -159,6 +166,25 @@ export interface FrameSupplyConfig extends FrameRetentionOptions {
159
166
  * default), or the browser (`"browser"`); see {@link VideoConversion}.
160
167
  */
161
168
  readonly videoConversion?: VideoConversion;
169
+ /**
170
+ * What becomes of a frame whose planes the browser cannot read back, once reading them again
171
+ * has failed: `"redecode"` (the default) decodes it again in software, which decodes the same
172
+ * picture, and fails the supply if that fails too; `"present"` gives it to the browser's
173
+ * conversion instead, unless the engine must convert it (HDR, or color the project declares),
174
+ * for a preview, where a frame shown at once matters more than the engine's conversion.
175
+ */
176
+ readonly unreadableFrames?: "redecode" | "present";
177
+ }
178
+ /** How a {@link FrameSupply} recovered frames the browser could not read back; cumulative. */
179
+ export interface ReadbackRecoveryStats {
180
+ /** Frames whose planes the browser still could not read back after the repeated reads. */
181
+ readonly unreadableFrames: number;
182
+ /** Reads repeated on the same frame. */
183
+ readonly readbackRetries: number;
184
+ /** Frames decoded again in software and copied from that decode. */
185
+ readonly redecodedFrames: number;
186
+ /** Frames given to the browser's conversion (`unreadableFrames: "present"`). */
187
+ readonly presentedFrames: number;
162
188
  }
163
189
  /**
164
190
  * Keeps completed source upload generations resident within a byte budget, releasing the oldest
@@ -298,6 +324,8 @@ export declare class FrameSupply {
298
324
  * source-side cost, apart from any output readback.
299
325
  */
300
326
  get sourceTransfer(): SourceTransferStats;
327
+ /** Frames the browser could not read back, and how they were recovered; cumulative. */
328
+ get readbackRecovery(): ReadbackRecoveryStats;
301
329
  /**
302
330
  * Uploads every source the engine asks for at one timestamp. Browser video stays as a
303
331
  * `VideoFrame` until the WebGPU external-image copy consumes it.
@@ -1,6 +1,6 @@
1
1
  // The engine's immutable project snapshot is the sole authority for frame keys. The host must not
2
2
  // derive them itself, for example by rounding (timelineSeconds - clip.start).
3
- import { copyPlanarYuvFrame, isHdrVideoFrame, isPlanarVideoFrame, PlanarCopyPool, uploadPlanarYuvFrame, } from "./hdr-frames.js";
3
+ import { isHdrVideoFrame, isPlanarVideoFrame, PlanarCopyPool, readPlanarYuvFrame, 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";
@@ -91,8 +91,15 @@ export class FrameSupply {
91
91
  #decodeWaiters = [];
92
92
  #cachedImageBytes = 0;
93
93
  #videoConversion;
94
+ #unreadableFrames;
94
95
  #planarCopyFrames = 0;
95
96
  #planarCopyBytes = 0;
97
+ #readback = {
98
+ unreadableFrames: 0,
99
+ readbackRetries: 0,
100
+ redecodedFrames: 0,
101
+ presentedFrames: 0,
102
+ };
96
103
  /** Buffers the planar copies reuse; each is given back once its upload has taken it. */
97
104
  #planarCopies = new PlanarCopyPool();
98
105
  #imageUse = 0n;
@@ -123,6 +130,10 @@ export class FrameSupply {
123
130
  if (videoConversion !== "engine" && videoConversion !== "browser")
124
131
  throw new RangeError('videoConversion must be "engine" or "browser"');
125
132
  this.#videoConversion = videoConversion;
133
+ const unreadableFrames = options.unreadableFrames ?? "redecode";
134
+ if (unreadableFrames !== "redecode" && unreadableFrames !== "present")
135
+ throw new RangeError('unreadableFrames must be "redecode" or "present"');
136
+ this.#unreadableFrames = unreadableFrames;
126
137
  this.#retainer = new FrameGenerationRetainer((generation) => this.#engine.releaseFrameGeneration(generation), options);
127
138
  }
128
139
  /** Bytes of rendered source textures kept resident; see {@link FrameRetentionOptions}. */
@@ -144,6 +155,10 @@ export class FrameSupply {
144
155
  planarCopyBytes: this.#planarCopyBytes,
145
156
  };
146
157
  }
158
+ /** Frames the browser could not read back, and how they were recovered; cumulative. */
159
+ get readbackRecovery() {
160
+ return { ...this.#readback };
161
+ }
147
162
  #trace(sourceId, mediaTimeTicks, pixels) {
148
163
  if (!this.onUpload)
149
164
  return;
@@ -267,18 +282,24 @@ export class FrameSupply {
267
282
  }
268
283
  let upload;
269
284
  if (planar !== undefined) {
270
- // The copy takes the frame over and closes it, failed or not.
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"`).
271
287
  decoded[decodedIndex] = { need, layer, source: null };
272
- const copied = await this.#copyPlanar(videoFrame, planar.declared);
273
- try {
274
- upload = uploadPlanarYuvFrame(this.#planarEngine(), need.sourceId, sourceTicks, copied, width, height);
288
+ const copied = await this.#copyPlanar(need, layer, videoFrame, planar, pixelsFor);
289
+ if (copied === undefined) {
290
+ decoded[decodedIndex] = { need, layer, source: videoFrame };
275
291
  }
276
- finally {
277
- // The upload copied the planes into the engine before it returned.
278
- this.#planarCopies.release(copied.data);
292
+ else {
293
+ try {
294
+ upload = uploadPlanarYuvFrame(this.#planarEngine(), need.sourceId, sourceTicks, copied, width, height);
295
+ }
296
+ finally {
297
+ // The upload copied the planes into the engine before it returned.
298
+ this.#planarCopies.release(copied.data);
299
+ }
279
300
  }
280
301
  }
281
- else {
302
+ if (upload === undefined) {
282
303
  const engine = this.#presentedEngine();
283
304
  const presented = [
284
305
  need.sourceId,
@@ -414,24 +435,111 @@ export class FrameSupply {
414
435
  isHdrVideoFrame(source.frame) ||
415
436
  (this.#videoConversion === "engine" && isPlanarVideoFrame(source.frame))))
416
437
  return { need, layer, source };
417
- return { need, layer, source, planar: { declared } };
418
- }
419
- /** Copies a frame out planar for the engine to convert; the copy closes the frame. */
420
- async #copyPlanar(source, declared) {
421
- const copied = await copyPlanarYuvFrame(source.frame, declared === undefined ? null : JSON.parse(declared), {
422
- ...(source.physicalTimeMicroseconds === undefined
423
- ? {}
424
- : { physicalTimeMicroseconds: source.physicalTimeMicroseconds }),
425
- ...(source.rotation === undefined ? {} : { rotation: source.rotation }),
426
- ...(source.mirror === undefined ? {} : { mirror: source.mirror }),
427
- ...(source.chromaSiting === undefined
428
- ? {}
429
- : { chromaSiting: source.chromaSiting }),
430
- }, this.#planarCopies);
438
+ return {
439
+ need,
440
+ layer,
441
+ source,
442
+ planar: {
443
+ declared,
444
+ required: enginesColor || isHdrVideoFrame(source.frame),
445
+ },
446
+ };
447
+ }
448
+ /**
449
+ * Copies a frame out planar for the engine to convert, and closes it.
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.
457
+ */
458
+ async #copyPlanar(need, layer, source, planar, pixelsFor) {
459
+ let copied;
460
+ try {
461
+ copied = await this.#readPlanes(source, planar.declared);
462
+ }
463
+ catch (error) {
464
+ if (!isUnreadableFrame(error)) {
465
+ source.frame.close();
466
+ throw error;
467
+ }
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;
474
+ }
475
+ const timestamp = source.physicalTimeMicroseconds ?? source.frame.timestamp;
476
+ source.frame.close();
477
+ copied = await this.#redecodePlanar(need, layer, planar, timestamp, pixelsFor, error);
478
+ }
479
+ source.frame.close();
431
480
  this.#planarCopyFrames += 1;
432
481
  this.#planarCopyBytes += copied.data.byteLength;
433
482
  return copied;
434
483
  }
484
+ /**
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.
506
+ */
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 });
509
+ let decoded;
510
+ try {
511
+ decoded = await this.#decodeCursor(`${keyForNeed(need, layer)}\u0000software`, () => pixelsFor(layer, Number(BigInt(need.mediaTimeTicks)) / TICKS_PER_SECOND, {
512
+ preferVideoFrame: true,
513
+ consumerId: consumerOf(need),
514
+ sourceId: need.sourceId,
515
+ decode: "software",
516
+ }));
517
+ }
518
+ catch (error) {
519
+ throw unrecovered("decoding it again in software failed", error);
520
+ }
521
+ if (decoded === null ||
522
+ !("kind" in decoded) ||
523
+ decoded.kind !== "video-frame")
524
+ throw unrecovered("decoding it again in software gave no VideoFrame");
525
+ const again = decoded;
526
+ try {
527
+ const at = again.physicalTimeMicroseconds ?? again.frame.timestamp;
528
+ if (at !== timestamp)
529
+ throw unrecovered(`decoding it again in software gave the frame at ${at} us`);
530
+ const copied = await this.#readPlanes(again, planar.declared);
531
+ this.#readback.redecodedFrames += 1;
532
+ return copied;
533
+ }
534
+ catch (error) {
535
+ throw error instanceof Error && error.cause === cause
536
+ ? error
537
+ : unrecovered("the software decode's frame could not be copied either", error);
538
+ }
539
+ finally {
540
+ again.frame.close();
541
+ }
542
+ }
435
543
  /** The engine's presented RGBA uploads, called on the engine. */
436
544
  #presenter() {
437
545
  const engine = this.#engine;
@@ -726,6 +834,36 @@ function validatePositiveInteger(value, name) {
726
834
  throw new RangeError(`${name} must be a positive safe integer`);
727
835
  }
728
836
  }
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");
849
+ }
850
+ /** What a planar copy of `source` carries beyond the frame (see `PlanarFrameIdentity`). */
851
+ function planarIdentity(source) {
852
+ return {
853
+ ...(source.physicalTimeMicroseconds === undefined
854
+ ? {}
855
+ : { physicalTimeMicroseconds: source.physicalTimeMicroseconds }),
856
+ ...(source.rotation === undefined ? {} : { rotation: source.rotation }),
857
+ ...(source.mirror === undefined ? {} : { mirror: source.mirror }),
858
+ ...(source.chromaSiting === undefined
859
+ ? {}
860
+ : { chromaSiting: source.chromaSiting }),
861
+ };
862
+ }
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
+ }
729
867
  /** Whether `engine` takes presented `VideoFrame` uploads (`uploadPresentedVideoFrame`). */
730
868
  function takesPresentedFrames(engine) {
731
869
  return typeof engine.uploadPresentedVideoFrame === "function";