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,18 +1,16 @@
1
1
  /**
2
- * Shape geometry for editors, answered in wasm by the code the engine draws shapes with: where a
3
- * shapes generator's items are, which paint is under a point, how long a path is, and paths cut,
4
- * resampled, or converted. A hit test or a trim here agrees with what a frame shows.
2
+ * Shape geometry queries for editors, computed in wasm by the engine's shape code so results match
3
+ * rendered frames.
5
4
  *
6
- * Positions are normalized as the project document's are, `(0, 0)` top-left to `(1, 1)`
7
- * bottom-right of a `width` by `height` picture; lengths and distances are in its pixels. Times
8
- * are ticks, as keyframe times are.
5
+ * Positions are normalized, `(0, 0)` top-left to `(1, 1)` bottom-right of a `width` by `height`
6
+ * picture. Lengths and distances are in pixels; times are in ticks.
9
7
  *
10
8
  * Every function throws an `INVALID_INPUT` error for a picture outside 1 to 16384 pixels a side, a
11
- * time that is not a whole number of ticks, or input the model rejects (a content tree or geometry
12
- * that is not valid, a path point or tangent that is not finite).
9
+ * non-integer tick time, or input the model rejects (invalid content tree or geometry, non-finite
10
+ * point or tangent).
13
11
  */
14
12
  import type { AnimatedPoint, Path, ShapeGeometry, ShapeItem, Ticks, Vec2 } from "./project.js";
15
- /** The part of `alpha2/wasm` these functions use. */
13
+ /** The `alpha2/wasm` functions these wrappers use. */
16
14
  export interface GeometryBinding {
17
15
  shapeBounds(itemsJson: string, time: number, width: number, height: number): string;
18
16
  hitTest(itemsJson: string, time: number, width: number, height: number, x: number, y: number): string | undefined;
@@ -23,76 +21,72 @@ export interface GeometryBinding {
23
21
  toPath(geometryJson: string, time: number, width: number, height: number): string;
24
22
  motionPath(pointJson: string, width: number, height: number): string;
25
23
  }
26
- /** The size of the picture shapes are drawn on, in pixels. */
24
+ /** Picture size in pixels. */
27
25
  export interface PictureSize {
28
26
  readonly width: number;
29
27
  readonly height: number;
30
28
  }
31
- /** A normalized rectangle: `x0`, `y0` its top-left corner, `x1`, `y1` its bottom-right. */
29
+ /** Normalized rectangle from top-left (`x0`, `y0`) to bottom-right (`x1`, `y1`). */
32
30
  export interface Bounds {
33
31
  readonly x0: number;
34
32
  readonly y0: number;
35
33
  readonly x1: number;
36
34
  readonly y1: number;
37
35
  }
38
- /** An item's bounds, by its place in the tree (`items[0].items[2]`). */
36
+ /** An item's bounds; `at` is its tree path, such as `items[0].items[2]`. */
39
37
  export interface ItemBounds {
40
38
  readonly at: string;
41
- /** What it covers: geometry's outline, a paint's area; `null` for an item that shows nothing. */
39
+ /** `null` for an item that draws nothing. */
42
40
  readonly bounds: Bounds | null;
43
41
  }
44
- /** The point of a path nearest another. */
42
+ /** The closest point on a path to a query point. */
45
43
  export interface NearestPoint {
46
- /** The subpath. */
47
44
  readonly subpath: number;
48
- /** The segment within it: segment `i` runs from vertex `i` to the next. */
45
+ /** Segment `i` runs from vertex `i` to the next. */
49
46
  readonly segment: number;
50
- /** The parameter along the segment, in `0..=1`. */
47
+ /** Parameter along the segment, in `0..=1`. */
51
48
  readonly t: number;
52
- /** The point, normalized. */
49
+ /** Normalized position. */
53
50
  readonly point: Vec2;
54
- /** Its distance from the point asked about, in pixels. */
51
+ /** Distance from the query point, in pixels. */
55
52
  readonly distance: number;
56
53
  }
57
54
  /**
58
- * Each item's bounds at `time`, in document order: a group's are its items', a stroke's include
59
- * its width.
55
+ * Each item's bounds at `time`, in document order. Stroke bounds include the stroke width.
60
56
  *
61
57
  * @throws When `items` is not a valid content tree.
62
58
  */
63
59
  export declare function shapeBounds(binding: GeometryBinding, items: readonly ShapeItem[], time: Ticks, size: PictureSize): ItemBounds[];
64
60
  /**
65
- * The front-most fill or stroke at normalized `point` at `time`, by its fill rule (a stroke by
66
- * its outline): its place in the tree, or `undefined` where nothing is painted.
61
+ * Tree path of the front-most fill or stroke at normalized `point` at `time`, honoring fill rules,
62
+ * or `undefined` where nothing is painted.
67
63
  *
68
64
  * @throws When `items` is not a valid content tree.
69
65
  */
70
66
  export declare function hitTest(binding: GeometryBinding, items: readonly ShapeItem[], time: Ticks, size: PictureSize, point: Vec2): string | undefined;
71
- /** The point of `path` nearest normalized `point`, or `undefined` for an empty path. */
67
+ /** Closest point of `path` to normalized `point`, or `undefined` for an empty path. */
72
68
  export declare function nearestPoint(binding: GeometryBinding, path: Path, size: PictureSize, point: Vec2): NearestPoint | undefined;
73
69
  /** Each subpath's length, in pixels. */
74
70
  export declare function pathLength(binding: GeometryBinding, path: Path, size: PictureSize): number[];
75
71
  /**
76
- * The part of `path` a trim item keeps: from `start` to `end` (fractions of its pixel length, all
77
- * subpaths end to end, clamped to `0..=1`), shifted by `offset` turns. Nothing when `start` is not
78
- * before `end`.
72
+ * The part of `path` a trim item keeps. `start` and `end` are fractions of the total length of all
73
+ * subpaths, clamped to `0..=1`; `offset` is in turns. Empty when `start >= end`.
79
74
  */
80
75
  export declare function trimPath(binding: GeometryBinding, path: Path, size: PictureSize, start: number, end: number, offset?: number): Path;
81
76
  /**
82
- * `path` with `vertexCounts[i]` vertices on subpath `i`, evenly along its length, so two paths can
83
- * be given the same structure and their keyframes can morph. The engine never resamples on its
84
- * own. A subpath whose count is missing, below 2 (3 when closed), or that has no length is kept as
85
- * it is.
77
+ * Resamples subpath `i` to `vertexCounts[i]` evenly spaced vertices, so two paths can share a
78
+ * structure and morph between keyframes. Subpaths with a missing count, a count below 2 (3 when
79
+ * closed), or zero length are kept unchanged.
86
80
  *
87
81
  * @throws When a count is over `MAX_PATH_VERTICES`.
88
82
  */
89
83
  export declare function resamplePath(binding: GeometryBinding, path: Path, size: PictureSize, vertexCounts: readonly number[]): Path;
90
84
  /**
91
- * A rectangle, ellipse, or polystar at `time` as a path of the same outline, from the same start
92
- * point and in the same direction: "convert to path".
85
+ * Converts a rectangle, ellipse or polystar at `time` to a path with the same outline, start point
86
+ * and direction.
93
87
  *
94
88
  * @throws When `geometry` is not valid.
95
89
  */
96
90
  export declare function toPath(binding: GeometryBinding, geometry: ShapeGeometry, time: Ticks, size: PictureSize): Path;
97
- /** The polyline a position travels between its keyframes, along their spatial tangents. */
91
+ /** Polyline a position follows between keyframes, along their spatial tangents. */
98
92
  export declare function motionPath(binding: GeometryBinding, position: AnimatedPoint, size: PictureSize): Vec2[];
package/dist/geometry.js CHANGED
@@ -1,19 +1,16 @@
1
1
  /**
2
- * Shape geometry for editors, answered in wasm by the code the engine draws shapes with: where a
3
- * shapes generator's items are, which paint is under a point, how long a path is, and paths cut,
4
- * resampled, or converted. A hit test or a trim here agrees with what a frame shows.
2
+ * Shape geometry queries for editors, computed in wasm by the engine's shape code so results match
3
+ * rendered frames.
5
4
  *
6
- * Positions are normalized as the project document's are, `(0, 0)` top-left to `(1, 1)`
7
- * bottom-right of a `width` by `height` picture; lengths and distances are in its pixels. Times
8
- * are ticks, as keyframe times are.
5
+ * Positions are normalized, `(0, 0)` top-left to `(1, 1)` bottom-right of a `width` by `height`
6
+ * picture. Lengths and distances are in pixels; times are in ticks.
9
7
  *
10
8
  * Every function throws an `INVALID_INPUT` error for a picture outside 1 to 16384 pixels a side, a
11
- * time that is not a whole number of ticks, or input the model rejects (a content tree or geometry
12
- * that is not valid, a path point or tangent that is not finite).
9
+ * non-integer tick time, or input the model rejects (invalid content tree or geometry, non-finite
10
+ * point or tangent).
13
11
  */
14
12
  /**
15
- * Each item's bounds at `time`, in document order: a group's are its items', a stroke's include
16
- * its width.
13
+ * Each item's bounds at `time`, in document order. Stroke bounds include the stroke width.
17
14
  *
18
15
  * @throws When `items` is not a valid content tree.
19
16
  */
@@ -21,15 +18,15 @@ export function shapeBounds(binding, items, time, size) {
21
18
  return JSON.parse(binding.shapeBounds(JSON.stringify(items), time, size.width, size.height));
22
19
  }
23
20
  /**
24
- * The front-most fill or stroke at normalized `point` at `time`, by its fill rule (a stroke by
25
- * its outline): its place in the tree, or `undefined` where nothing is painted.
21
+ * Tree path of the front-most fill or stroke at normalized `point` at `time`, honoring fill rules,
22
+ * or `undefined` where nothing is painted.
26
23
  *
27
24
  * @throws When `items` is not a valid content tree.
28
25
  */
29
26
  export function hitTest(binding, items, time, size, point) {
30
27
  return (binding.hitTest(JSON.stringify(items), time, size.width, size.height, point.x, point.y) ?? undefined);
31
28
  }
32
- /** The point of `path` nearest normalized `point`, or `undefined` for an empty path. */
29
+ /** Closest point of `path` to normalized `point`, or `undefined` for an empty path. */
33
30
  export function nearestPoint(binding, path, size, point) {
34
31
  return (JSON.parse(binding.nearestPoint(JSON.stringify(path), size.width, size.height, point.x, point.y)) ?? undefined);
35
32
  }
@@ -38,18 +35,16 @@ export function pathLength(binding, path, size) {
38
35
  return JSON.parse(binding.pathLength(JSON.stringify(path), size.width, size.height));
39
36
  }
40
37
  /**
41
- * The part of `path` a trim item keeps: from `start` to `end` (fractions of its pixel length, all
42
- * subpaths end to end, clamped to `0..=1`), shifted by `offset` turns. Nothing when `start` is not
43
- * before `end`.
38
+ * The part of `path` a trim item keeps. `start` and `end` are fractions of the total length of all
39
+ * subpaths, clamped to `0..=1`; `offset` is in turns. Empty when `start >= end`.
44
40
  */
45
41
  export function trimPath(binding, path, size, start, end, offset = 0) {
46
42
  return JSON.parse(binding.trimPath(JSON.stringify(path), size.width, size.height, start, end, offset));
47
43
  }
48
44
  /**
49
- * `path` with `vertexCounts[i]` vertices on subpath `i`, evenly along its length, so two paths can
50
- * be given the same structure and their keyframes can morph. The engine never resamples on its
51
- * own. A subpath whose count is missing, below 2 (3 when closed), or that has no length is kept as
52
- * it is.
45
+ * Resamples subpath `i` to `vertexCounts[i]` evenly spaced vertices, so two paths can share a
46
+ * structure and morph between keyframes. Subpaths with a missing count, a count below 2 (3 when
47
+ * closed), or zero length are kept unchanged.
53
48
  *
54
49
  * @throws When a count is over `MAX_PATH_VERTICES`.
55
50
  */
@@ -57,15 +52,15 @@ export function resamplePath(binding, path, size, vertexCounts) {
57
52
  return JSON.parse(binding.resamplePath(JSON.stringify(path), size.width, size.height, Uint32Array.from(vertexCounts)));
58
53
  }
59
54
  /**
60
- * A rectangle, ellipse, or polystar at `time` as a path of the same outline, from the same start
61
- * point and in the same direction: "convert to path".
55
+ * Converts a rectangle, ellipse or polystar at `time` to a path with the same outline, start point
56
+ * and direction.
62
57
  *
63
58
  * @throws When `geometry` is not valid.
64
59
  */
65
60
  export function toPath(binding, geometry, time, size) {
66
61
  return JSON.parse(binding.toPath(JSON.stringify(geometry), time, size.width, size.height));
67
62
  }
68
- /** The polyline a position travels between its keyframes, along their spatial tangents. */
63
+ /** Polyline a position follows between keyframes, along their spatial tangents. */
69
64
  export function motionPath(binding, position, size) {
70
65
  return JSON.parse(binding.motionPath(JSON.stringify(position), size.width, size.height));
71
66
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Recovery decisions for a browser render host after a GPU loss.
3
+ *
4
+ * Browsers withdraw GPU access from a page after repeated GPU process resets: after the second,
5
+ * Chrome withholds WebGPU and page-canvas WebGL2 (`OffscreenCanvas` WebGL2 stays), and after the
6
+ * third nothing GPU-backed works. A loss caused by the page's own work recurs on the GPU. So the
7
+ * GPU is retried only for a first external loss; otherwise recovery moves to the CPU renderer on a
8
+ * fresh surface. Each rung is tried once per loss.
9
+ */
10
+ /** GPU loss details, read before the lost renderer is freed. */
11
+ export interface GpuLossReport {
12
+ /**
13
+ * The longest recent submission ran for at least half the GPU watchdog, so the loss was most
14
+ * likely caused by this work and would recur.
15
+ */
16
+ readonly hung: boolean;
17
+ /** Export frame index of the longest submission, when known. */
18
+ readonly frameIndex: number | null;
19
+ /** Timeline time of the longest submission, when known. */
20
+ readonly timeTicks: bigint | null;
21
+ /** GPU time of the longest recent submission. */
22
+ readonly gpuMs: number | null;
23
+ /** One-line message for the user. */
24
+ readonly message: string;
25
+ }
26
+ /** Renderer and surface to use after a loss. */
27
+ export interface RecoveryStep {
28
+ /** `gpu` uses WebGPU, else WebGL2, as the browser now offers. */
29
+ readonly renderer: "gpu" | "cpu";
30
+ /**
31
+ * `"same"` reuses the lost renderer's canvas, possible only for a WebGPU canvas while an adapter
32
+ * is still offered. `"fresh"` needs a new canvas, since a canvas keeps its first context kind.
33
+ */
34
+ readonly surface: "same" | "fresh";
35
+ /** Diagnostic reason. */
36
+ readonly reason: string;
37
+ }
38
+ /** State of the lost renderer's surface after the loss. */
39
+ export interface SurfaceProbe {
40
+ /** Context kind the surface is bound to; `"none"` when no renderer held it. */
41
+ readonly kind: "webgpu" | "webgl2" | "cpu" | "none";
42
+ /** Whether `navigator.gpu.requestAdapter()` now returns an adapter in the host's context. */
43
+ readonly webgpuAdapter: boolean;
44
+ }
45
+ /** See {@link pageGpuLosses}. */
46
+ export interface PageGpuLosses {
47
+ /** Losses counted in this JavaScript realm so far. */
48
+ count(): number;
49
+ add(): void;
50
+ }
51
+ /**
52
+ * GPU losses in this JavaScript realm, stored on `globalThis` so duplicate copies of the package
53
+ * share it. {@link GpuRecoveryLadder.onLoss} counts its own losses; code that handles a loss
54
+ * outside a ladder should call `add()` and pass `count()` as the retry policy's `pageGpuLosses`.
55
+ * Losses in other tabs or realms are not counted.
56
+ */
57
+ export declare const pageGpuLosses: PageGpuLosses;
58
+ /**
59
+ * Decides recovery after each GPU loss of one host. Once it moves to the CPU it stays there, as
60
+ * reported by {@link GpuRecoveryLadder.renderer}.
61
+ */
62
+ export declare class GpuRecoveryLadder {
63
+ #private;
64
+ /**
65
+ * @param options.maxGpuLosses Page losses after which the GPU is not tried again. Default 2,
66
+ * since the browser withdraws GPU access at the next reset.
67
+ * @param options.losses Loss counter to use. Default {@link pageGpuLosses}.
68
+ * @throws RangeError When `maxGpuLosses` is not a positive integer.
69
+ */
70
+ constructor(options?: {
71
+ readonly maxGpuLosses?: number;
72
+ readonly losses?: PageGpuLosses;
73
+ });
74
+ /** Current renderer; `"cpu"` is permanent once reached. */
75
+ get renderer(): "gpu" | "cpu";
76
+ /**
77
+ * Counts the loss and decides the first step. Moves to the CPU when the loss was `hung`, recurred
78
+ * at the previous loss's time, or the page reached `maxGpuLosses`. Otherwise retries the GPU, on
79
+ * the same surface when it is WebGPU-bound and an adapter is still offered.
80
+ */
81
+ onLoss(report: GpuLossReport, surface: SurfaceProbe): RecoveryStep;
82
+ /**
83
+ * Next step after `step` failed: GPU on the same surface, GPU on a fresh one, then CPU on a fresh
84
+ * one, skipping rungs already tried for this loss. `"terminal"` after the CPU.
85
+ */
86
+ onRecoveryFailed(step: RecoveryStep, error: unknown): RecoveryStep | "terminal";
87
+ }
88
+ /**
89
+ * Parses a wasm renderer's `lossReport` JSON, or returns a plain lost-device report with
90
+ * `fallbackMessage` when there is none.
91
+ */
92
+ export declare function lossReportFromJson(json: string | undefined, fallbackMessage?: string): GpuLossReport;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Recovery decisions for a browser render host after a GPU loss.
3
+ *
4
+ * Browsers withdraw GPU access from a page after repeated GPU process resets: after the second,
5
+ * Chrome withholds WebGPU and page-canvas WebGL2 (`OffscreenCanvas` WebGL2 stays), and after the
6
+ * third nothing GPU-backed works. A loss caused by the page's own work recurs on the GPU. So the
7
+ * GPU is retried only for a first external loss; otherwise recovery moves to the CPU renderer on a
8
+ * fresh surface. Each rung is tried once per loss.
9
+ */
10
+ const LOSSES = Symbol.for("alpha2.pageGpuLosses");
11
+ /**
12
+ * GPU losses in this JavaScript realm, stored on `globalThis` so duplicate copies of the package
13
+ * share it. {@link GpuRecoveryLadder.onLoss} counts its own losses; code that handles a loss
14
+ * outside a ladder should call `add()` and pass `count()` as the retry policy's `pageGpuLosses`.
15
+ * Losses in other tabs or realms are not counted.
16
+ */
17
+ export const pageGpuLosses = Object.freeze({
18
+ count() {
19
+ const holder = globalThis;
20
+ return holder[LOSSES] ?? 0;
21
+ },
22
+ add() {
23
+ const holder = globalThis;
24
+ holder[LOSSES] = (holder[LOSSES] ?? 0) + 1;
25
+ },
26
+ });
27
+ /** Recovery rungs in order; recovery never moves back up. */
28
+ const RUNGS = ["gpu", "gpu", "cpu"];
29
+ const RUNG_SURFACES = [
30
+ "same",
31
+ "fresh",
32
+ "fresh",
33
+ ];
34
+ /**
35
+ * Decides recovery after each GPU loss of one host. Once it moves to the CPU it stays there, as
36
+ * reported by {@link GpuRecoveryLadder.renderer}.
37
+ */
38
+ export class GpuRecoveryLadder {
39
+ #maxGpuLosses;
40
+ #losses;
41
+ /** Indices into `RUNGS` tried since the last loss. */
42
+ #tried = new Set();
43
+ #lastLossTicks = null;
44
+ #renderer = "gpu";
45
+ /**
46
+ * @param options.maxGpuLosses Page losses after which the GPU is not tried again. Default 2,
47
+ * since the browser withdraws GPU access at the next reset.
48
+ * @param options.losses Loss counter to use. Default {@link pageGpuLosses}.
49
+ * @throws RangeError When `maxGpuLosses` is not a positive integer.
50
+ */
51
+ constructor(options = {}) {
52
+ const max = options.maxGpuLosses ?? 2;
53
+ if (!Number.isSafeInteger(max) || max < 1)
54
+ throw new RangeError("maxGpuLosses must be a positive integer");
55
+ this.#maxGpuLosses = max;
56
+ this.#losses = options.losses ?? pageGpuLosses;
57
+ }
58
+ /** Current renderer; `"cpu"` is permanent once reached. */
59
+ get renderer() {
60
+ return this.#renderer;
61
+ }
62
+ /**
63
+ * Counts the loss and decides the first step. Moves to the CPU when the loss was `hung`, recurred
64
+ * at the previous loss's time, or the page reached `maxGpuLosses`. Otherwise retries the GPU, on
65
+ * the same surface when it is WebGPU-bound and an adapter is still offered.
66
+ */
67
+ onLoss(report, surface) {
68
+ this.#losses.add();
69
+ this.#tried = new Set();
70
+ const recurred = report.timeTicks !== null && report.timeTicks === this.#lastLossTicks;
71
+ this.#lastLossTicks = report.timeTicks;
72
+ if (this.#renderer === "cpu")
73
+ return this.#take(2, "recovery already moved to the CPU renderer");
74
+ if (report.hung)
75
+ return this.#take(2, `the GPU was lost while this work ran ${report.gpuMs ?? "?"} ms in one submission; the same work on the GPU would stop it again`);
76
+ if (recurred)
77
+ return this.#take(2, "the GPU was lost again at the same frame");
78
+ if (this.#losses.count() >= this.#maxGpuLosses)
79
+ return this.#take(2, `the page has lost the GPU ${this.#losses.count()} times; the browser withdraws GPU access after another reset`);
80
+ if (surface.kind === "webgpu" && surface.webgpuAdapter)
81
+ return this.#take(0, "a first GPU loss: the WebGPU canvas takes a new device");
82
+ return this.#take(1, surface.kind === "webgpu"
83
+ ? "a first GPU loss, and the browser gives no WebGPU adapter now: a fresh canvas takes WebGL2"
84
+ : "a first GPU loss: a WebGL2 canvas keeps its lost context, so a fresh canvas takes the GPU");
85
+ }
86
+ /**
87
+ * Next step after `step` failed: GPU on the same surface, GPU on a fresh one, then CPU on a fresh
88
+ * one, skipping rungs already tried for this loss. `"terminal"` after the CPU.
89
+ */
90
+ onRecoveryFailed(step, error) {
91
+ const failed = RUNGS.findIndex((renderer, index) => renderer === step.renderer && RUNG_SURFACES[index] === step.surface);
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ for (let next = failed + 1; next < RUNGS.length; next += 1) {
94
+ if (this.#tried.has(next))
95
+ continue;
96
+ return this.#take(next, `the ${step.renderer} renderer on the ${step.surface} surface failed (${message})`);
97
+ }
98
+ return "terminal";
99
+ }
100
+ #take(index, reason) {
101
+ this.#tried.add(index);
102
+ for (let below = 0; below < index; below += 1)
103
+ this.#tried.add(below);
104
+ const renderer = RUNGS[index];
105
+ if (renderer === "cpu")
106
+ this.#renderer = "cpu";
107
+ return Object.freeze({ renderer, surface: RUNG_SURFACES[index], reason });
108
+ }
109
+ }
110
+ /**
111
+ * Parses a wasm renderer's `lossReport` JSON, or returns a plain lost-device report with
112
+ * `fallbackMessage` when there is none.
113
+ */
114
+ export function lossReportFromJson(json, fallbackMessage = "the GPU device was lost") {
115
+ if (json === undefined)
116
+ return {
117
+ hung: false,
118
+ frameIndex: null,
119
+ timeTicks: null,
120
+ gpuMs: null,
121
+ message: fallbackMessage,
122
+ };
123
+ const value = JSON.parse(json);
124
+ const hung = value.hung === true;
125
+ const gpuMs = typeof value.gpuMs === "number" ? value.gpuMs : null;
126
+ return {
127
+ hung,
128
+ frameIndex: typeof value.frameIndex === "number" ? value.frameIndex : null,
129
+ timeTicks: typeof value.timeTicks === "string" ? BigInt(value.timeTicks) : null,
130
+ gpuMs,
131
+ message: hung
132
+ ? `the GPU device hung: one submission ran ${gpuMs} ms against a ${value.watchdogMs} ms watchdog`
133
+ : fallbackMessage,
134
+ };
135
+ }