alpha2 0.4.6 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +51 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +125 -176
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/frames.d.ts +23 -0
  55. package/dist/frames.js +34 -0
  56. package/dist/generated/project-schema.d.ts +712 -485
  57. package/dist/generated/project-schema.js +55 -2
  58. package/dist/generated/project-shape.js +276 -16
  59. package/dist/geometry.d.ts +28 -34
  60. package/dist/geometry.js +18 -23
  61. package/dist/gpu-recovery.d.ts +92 -0
  62. package/dist/gpu-recovery.js +135 -0
  63. package/dist/hdr-frames.d.ts +82 -67
  64. package/dist/hdr-frames.js +112 -49
  65. package/dist/index.d.ts +6 -0
  66. package/dist/index.js +6 -0
  67. package/dist/json-text.d.ts +13 -23
  68. package/dist/json-text.js +10 -20
  69. package/dist/layout-values.d.ts +14 -22
  70. package/dist/layout-values.js +18 -21
  71. package/dist/layout.d.ts +48 -63
  72. package/dist/layout.js +37 -37
  73. package/dist/loudness.d.ts +27 -32
  74. package/dist/loudness.js +19 -23
  75. package/dist/media.d.ts +85 -237
  76. package/dist/media.js +133 -287
  77. package/dist/mediabunny.d.ts +178 -246
  78. package/dist/mediabunny.js +781 -583
  79. package/dist/paint.d.ts +23 -0
  80. package/dist/paint.js +37 -0
  81. package/dist/physical-frames.d.ts +5 -17
  82. package/dist/physical-frames.js +4 -11
  83. package/dist/player.d.ts +56 -47
  84. package/dist/player.js +155 -40
  85. package/dist/presented-frames.d.ts +2 -7
  86. package/dist/presented-frames.js +3 -8
  87. package/dist/project.d.ts +74 -118
  88. package/dist/project.js +384 -445
  89. package/dist/rate-control.d.ts +9 -23
  90. package/dist/rate-control.js +7 -18
  91. package/dist/renderer-choice.d.ts +41 -0
  92. package/dist/renderer-choice.js +82 -0
  93. package/dist/repacked-bytes.d.ts +0 -2
  94. package/dist/repacked-bytes.js +2 -5
  95. package/dist/robustness.d.ts +25 -37
  96. package/dist/robustness.js +71 -54
  97. package/dist/sha256.d.ts +5 -13
  98. package/dist/sha256.js +9 -24
  99. package/dist/text.d.ts +97 -71
  100. package/dist/text.js +33 -70
  101. package/dist/video-frames.d.ts +7 -25
  102. package/dist/video-frames.js +12 -29
  103. package/dist/waveform.d.ts +5 -11
  104. package/dist/waveform.js +4 -9
  105. package/dist/worker-error.d.ts +5 -20
  106. package/dist/worker-error.js +8 -25
  107. package/dist/worker.d.ts +82 -95
  108. package/dist/worker.js +235 -143
  109. package/package.json +26 -2
  110. package/wasm/alpha2_audio_worklet.wasm +0 -0
  111. package/wasm/alpha2_extensions.d.ts +26 -47
  112. package/wasm/alpha2_extensions.js +26 -47
  113. package/wasm/alpha2_extensions_bg.wasm +0 -0
  114. package/wasm/alpha2_wasm.d.ts +501 -587
  115. package/wasm/alpha2_wasm.js +661 -616
  116. package/wasm/alpha2_wasm_bg.wasm +0 -0
  117. package/wasm/alpha2_wasm_bg.wasm.d.ts +22 -12
  118. package/wasm/rust-crate-licenses.md +2 -2
  119. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline1.js +1 -0
  120. package/wasm/snippets/alpha2-wasm-070d94113471ef0a/inline2.js +82 -0
  121. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  122. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline0.js +0 -0
  123. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-070d94113471ef0a}/inline3.js +0 -0
package/dist/sha256.js CHANGED
@@ -1,5 +1,4 @@
1
- // Incremental SHA-256: Web Crypto hashes only a whole buffer, and a media file can be gigabytes, so
2
- // memory stays bounded by one chunk.
1
+ // Incremental SHA-256, because Web Crypto hashes only a whole buffer and media files can be huge.
3
2
  const K = new Uint32Array([
4
3
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
5
4
  0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
@@ -46,10 +45,7 @@ export class Sha256 {
46
45
  this.#buffered = bytes.length - offset;
47
46
  return this;
48
47
  }
49
- /**
50
- * Finishes the message and returns its hash as 64 lowercase hex digits.
51
- * The hash can be finished once; a second call throws.
52
- */
48
+ /** Returns the hash as 64 lowercase hex digits. Throws if called twice. */
53
49
  hex() {
54
50
  if (this.#done)
55
51
  throw new Error("the hash is already finished");
@@ -124,17 +120,11 @@ export class Sha256 {
124
120
  s[7] = (s[7] + h) | 0;
125
121
  }
126
122
  }
127
- /** How long hashing holds the thread before it lets other tasks run, in milliseconds. */
128
123
  const HASH_SLICE_MS = 8;
129
- /** The most bytes hashed between two looks at the clock: about 5 ms of hashing. */
124
+ // About 5 ms of hashing between clock checks.
130
125
  const HASH_PIECE_BYTES = 1 << 20;
131
- /**
132
- * Resolves in a task of its own, once the event loop has had its turn: a frame, input, timers, an
133
- * abort. Posts a channel message, which a timer's minimum delay does not slow down.
134
- *
135
- * Not `scheduler.yield()`: Chrome runs its continuation ahead of timers and of the next frame, so a
136
- * hash yielding through it draws about 10 frames a second and runs no timer until it ends.
137
- */
126
+ // A channel message avoids the timer minimum delay. `scheduler.yield()` is not used because Chrome
127
+ // runs its continuation ahead of timers and the next frame, which starves rendering.
138
128
  function yieldToEventLoop() {
139
129
  if (typeof MessageChannel === "function") {
140
130
  return new Promise((resolve) => {
@@ -149,17 +139,12 @@ function yieldToEventLoop() {
149
139
  return new Promise((resolve) => setTimeout(resolve, 0));
150
140
  }
151
141
  /**
152
- * The SHA-256 of a blob's bytes, read as a stream, as 64 lowercase hex digits.
153
- *
154
- * `onProgress` receives the bytes hashed so far after each piece of at most 1 MiB. Memory stays
155
- * bounded by one chunk of the blob's stream.
142
+ * Streams a blob through SHA-256 and returns 64 lowercase hex digits.
156
143
  *
157
- * A blob whose chunks are already read (a cached local file) resolves each read without a task in
158
- * between, so hashing yields to the event loop about every 8 ms: the page keeps painting and
159
- * handling input, and `signal` can abort it partway.
144
+ * `onProgress` receives the bytes hashed so far after each piece of at most 1 MiB. Hashing yields
145
+ * to the event loop about every 8 ms so the page stays responsive and `signal` can abort it.
160
146
  *
161
- * Rejects with `signal.reason` when `signal` aborts, and with the stream's error when the blob
162
- * cannot be read.
147
+ * Rejects with `signal.reason` on abort, or with the stream's error when the blob cannot be read.
163
148
  */
164
149
  export async function sha256Blob(blob, options = {}) {
165
150
  const hash = new Sha256();
package/dist/text.d.ts CHANGED
@@ -10,12 +10,9 @@ export interface HostTextureDescriptor {
10
10
  /** Layout facts retained beside a generic host texture. */
11
11
  export interface BrowserTextTexture {
12
12
  readonly texture: HostTextureDescriptor;
13
- /**
14
- * Where the layout box's left edge lies in the texture: the margin, the same on both sides, that
15
- * holds ink and decorations past the box.
16
- */
13
+ /** The layout box's left edge in the texture; equal side margins hold overhanging ink. */
17
14
  readonly layoutX: number;
18
- /** Where the layout box's top edge lies in the texture, with the same margin below it. */
15
+ /** The layout box's top edge in the texture, with the same margin below it. */
19
16
  readonly layoutY: number;
20
17
  readonly layoutWidth: number;
21
18
  readonly layoutHeight: number;
@@ -26,48 +23,39 @@ export interface BrowserTextTexture {
26
23
  readonly lineCount: number;
27
24
  /** Tightly packed, premultiplied RGBA8 rows for renderer upload. */
28
25
  readonly rgba8: Uint8ClampedArray;
26
+ /** The background boxes alone when `splitBackground` was set; `rgba8` then excludes them. */
27
+ readonly background?: Uint8ClampedArray;
29
28
  }
30
29
  /** Browser-owned text layout and raster style. */
31
30
  export interface BrowserTextRequest {
32
31
  /** The text to draw, at most {@link MAX_TEXT_BYTES} as UTF-8; `\n` starts a new paragraph. */
33
32
  readonly text: string;
34
- /** Positive cache key: a request with a cached version returns the cached texture unchanged. */
33
+ /** Positive cache key; a cached version returns the cached texture unchanged. */
35
34
  readonly contentVersion: bigint;
36
- /**
37
- * Font families in fallback order, at least one. CSS generic family names are passed as keywords,
38
- * every other name as a quoted family name.
39
- */
35
+ /** Font families in fallback order, at least one. CSS generic family names stay keywords. */
40
36
  readonly fontFamilies: readonly string[];
41
37
  /** Font size in pixels, above zero and at most {@link MAX_TEXT_FONT_SIZE}. */
42
38
  readonly fontSize: number;
43
39
  /** Wrap width in pixels, at most {@link MAX_TEXT_DIMENSION}; zero or absent disables wrapping. */
44
40
  readonly maxWidth?: number;
45
- /**
46
- * Baseline-to-baseline distance in font-size multiples (default 1.2), above zero and at most
47
- * {@link MAX_TEXT_LINE_HEIGHT}.
48
- */
41
+ /** Line height in font-size multiples (default 1.2), up to {@link MAX_TEXT_LINE_HEIGHT}. */
49
42
  readonly lineHeight?: number;
50
- /**
51
- * Where lines sit in the layout box, as canvas `textAlign` names it; text runs left to right, so
52
- * `start` is `left`.
53
- */
43
+ /** Canvas `textAlign`; text runs left to right, so `start` is `left`. */
54
44
  readonly align?: CanvasTextAlign;
55
45
  /** A CSS color (default opaque white). */
56
46
  readonly color?: string;
57
47
  /**
58
- * How emoji are drawn (default `color`): in the platform's color font, as text presentation
59
- * where there is one (`monochrome`), or as one U+FFFD per grapheme shown as an emoji
60
- * (`replace`), as the portable host replaces them. Symbols shown as text by default, such as
61
- * (c), stay.
48
+ * Emoji drawing (default `color`). `monochrome` uses text presentation where one exists;
49
+ * `replace` draws one U+FFFD per emoji grapheme, as the portable host does.
62
50
  */
63
51
  readonly emojiPolicy?: "color" | "monochrome" | "replace";
64
52
  }
65
- /** The `WasmTextRasterizer` class that `alpha2/wasm` exports. */
66
53
  export interface WasmTextRasterizerHandle {
67
54
  addFont(family: string, bytes: Uint8Array, faceIndex: number): void;
68
55
  addFontFile(family: string, bytes: Uint8Array): void;
69
56
  rasterize(requestJson: string, contentVersion: bigint): {
70
57
  readonly descriptor: string;
58
+ takeBackground?(): Uint8Array;
71
59
  takePixels(): Uint8Array;
72
60
  free?(): void;
73
61
  };
@@ -76,7 +64,6 @@ export interface WasmTextRasterizerHandle {
76
64
  readonly cacheSize: number;
77
65
  free?(): void;
78
66
  }
79
- /** The part of the `alpha2/wasm` module `WasmTextRasterizer` needs. */
80
67
  export interface WasmTextBinding {
81
68
  readonly WasmTextRasterizer: new () => WasmTextRasterizerHandle;
82
69
  }
@@ -88,88 +75,129 @@ export interface WasmTextRequest {
88
75
  readonly fontSize: number;
89
76
  /** Layout width; zero or absent disables wrapping. */
90
77
  readonly maxWidth?: number;
91
- /** Baseline-to-baseline distance in font-size multiples (default 1.2). */
78
+ /** Line height in font-size multiples (default 1.2). */
92
79
  readonly lineHeight?: number;
93
80
  /**
94
- * Space after each character in pixels (default 0), as CSS `letter-spacing` adds it: none after
95
- * a line's last character or a character of a cursive script. Within -0.5 to 1 font sizes.
81
+ * CSS-style letter spacing in pixels (default 0), within -0.5 to 1 font sizes. None is added
82
+ * after a line's last character or within cursive scripts.
96
83
  */
97
84
  readonly letterSpacing?: number;
98
85
  /**
99
- * The weight a family's faces are matched by, 1 to 1000 (default 400), as CSS matches
100
- * `font-weight`; a variable face draws at it, held to its `wght` axis. No face is emboldened.
86
+ * Weight for face matching, 1 to 1000 (default 400), as CSS `font-weight`. Variable faces follow
87
+ * their `wght` axis; no face is synthetically emboldened.
101
88
  */
102
89
  readonly fontWeight?: number;
103
90
  readonly align?: "start" | "center" | "end";
104
- /** Straight (not premultiplied), sRGB-encoded RGBA, each in `0..=255`. */
105
- readonly color: readonly [number, number, number, number];
91
+ /** A solid color or a gradient over the layout box; also fills color glyphs' text parts. */
92
+ readonly fill: WasmTextColor | WasmTextGradient;
106
93
  /**
107
- * How emoji are drawn (default `color`): a font's color glyphs (COLR, CBDT, sbix) in their own
108
- * colors, an emoji trying the color fonts first; `monochrome` draws every glyph as an outline in
109
- * `color`, an emoji trying the other fonts first; `replace` draws each emoji grapheme as one
110
- * U+FFFD.
94
+ * Emoji drawing (default `color`). `color` uses color glyphs (COLR, CBDT, sbix), `monochrome`
95
+ * draws outlines in the fill, `replace` draws one U+FFFD per emoji grapheme.
111
96
  */
112
97
  readonly emojiPolicy?: "color" | "monochrome" | "replace";
98
+ /** Outline bands, innermost first: at most 4, with widths summing to at most 64 pixels. */
99
+ readonly strokes?: readonly {
100
+ readonly color: WasmTextColor;
101
+ readonly width: number;
102
+ }[];
103
+ /** A box behind each line, grown by `padding` pixels (at most 256). */
104
+ readonly background?: {
105
+ readonly color: WasmTextColor;
106
+ readonly padding: number;
107
+ };
108
+ /**
109
+ * Returns the boxes as their own plane ({@link BrowserTextTexture.background}) so the page can
110
+ * draw a shadow between them and the glyphs.
111
+ */
112
+ readonly splitBackground?: boolean;
113
+ /** One animation state applied to every cluster. Tracking never re-wraps lines. */
114
+ readonly clusterState?: WasmClusterState;
115
+ /** One animation state per cluster, in logical order. */
116
+ readonly clusterStates?: readonly WasmClusterState[];
117
+ }
118
+ /**
119
+ * Per-cluster animation; omitted fields are identity. Offset and tracking are pixels, rotation is
120
+ * clockwise radians, opacity is `0..=1`. A color mix computes `color * keep + add` in premultiplied
121
+ * linear light.
122
+ */
123
+ export interface WasmClusterState {
124
+ readonly offset?: readonly [number, number];
125
+ readonly scale?: readonly [number, number];
126
+ readonly rotation?: number;
127
+ readonly opacity?: number;
128
+ readonly fill?: WasmColorMix;
129
+ readonly stroke?: WasmColorMix;
130
+ readonly tracking?: number;
131
+ }
132
+ /** See {@link WasmClusterState}. */
133
+ export interface WasmColorMix {
134
+ readonly keep: number;
135
+ readonly add: readonly [number, number, number, number];
113
136
  }
137
+ /** Straight (not premultiplied), sRGB-encoded RGBA, each in `0..=255`. */
138
+ export type WasmTextColor = readonly [number, number, number, number];
114
139
  /**
115
- * The engine's portable text host (`alpha2-text`: Unicode bidirectional
116
- * layout and line breaking, rustybuzz shaping, `ab_glyph_rasterizer`
117
- * outlines, COLR paintings and CBDT or sbix bitmaps) running in wasm.
118
- *
119
- * It is the same code a native host rasterizes with, so with the same font bytes a browser preview
120
- * and a native export draw identical text; the platform's own rasterizer, {@link
121
- * OffscreenTextRasterizer}, does not. Fonts are caller-supplied bytes in fallback order; system
122
- * fonts are not reachable. Color emoji are drawn in color from the fonts given, as outlines, or
123
- * replaced (`emojiPolicy`).
140
+ * A gradient over the layout box. Points are box fractions (`[0, 0]` top-left), the radius is a
141
+ * fraction of the shorter side, the conic angle is radians clockwise from up. 2 to 16 stops with
142
+ * straight sRGB colors in `0..=1`, interpolated in linear light.
143
+ */
144
+ export type WasmTextGradient = ({
145
+ readonly type: "linear";
146
+ readonly start: readonly [number, number];
147
+ readonly end: readonly [number, number];
148
+ readonly spread?: "pad" | "repeat" | "reflect";
149
+ } | {
150
+ readonly type: "radial";
151
+ readonly center: readonly [number, number];
152
+ readonly radius: number;
153
+ readonly spread?: "pad" | "repeat" | "reflect";
154
+ } | {
155
+ readonly type: "conic";
156
+ readonly center: readonly [number, number];
157
+ readonly angle?: number;
158
+ }) & {
159
+ readonly stops: readonly {
160
+ readonly offset: number;
161
+ readonly color: readonly [number, number, number, number];
162
+ }[];
163
+ };
164
+ /**
165
+ * The engine's portable text host (`alpha2-text`) in wasm. Given the same font bytes it draws text
166
+ * identical to a native export, unlike {@link OffscreenTextRasterizer}. Fonts are caller-supplied
167
+ * bytes in fallback order; system fonts are not reachable.
124
168
  */
125
169
  export declare class WasmTextRasterizer {
126
170
  #private;
127
- /** Creates a rasterizer with no fonts from an initialized `alpha2/wasm`. */
128
171
  constructor(binding: WasmTextBinding);
129
- /**
130
- * Appends an OpenType font to the fallback stack. Every cached result is dropped, since fonts
131
- * change what a request draws.
132
- */
172
+ /** Appends an OpenType font to the fallback stack and drops every cached result. */
133
173
  addFont(family: string, bytes: ArrayBuffer | Uint8Array, faceIndex?: number): void;
134
174
  /**
135
- * Appends every face of an OpenType font file to the fallback stack, in the file's order: each
136
- * weight of a collection (`.ttc`), so a style's `font_weight` can pick it. The export host
137
- * registers a font file the same way. Every cached result is dropped.
175
+ * Appends every face of a font file (each weight of a `.ttc`) to the fallback stack, as the
176
+ * export host does, and drops every cached result.
138
177
  */
139
178
  addFontFile(family: string, bytes: ArrayBuffer | Uint8Array): void;
140
179
  /**
141
- * Shapes and rasterizes `request`, cached by content version: the rasterizer keeps up to 64 MiB
142
- * of results, dropping the least recently used past it.
180
+ * Shapes and rasterizes `request`, cached by content version (LRU, up to 64 MiB).
143
181
  *
144
182
  * @throws RangeError when `contentVersion` is not positive; the engine throws for an invalid
145
183
  * style, such as a font size over {@link MAX_TEXT_FONT_SIZE}.
146
184
  */
147
185
  rasterize(request: WasmTextRequest): BrowserTextTexture;
148
- /** Drops the cached texture for `contentVersion`, if any. */
149
186
  invalidate(contentVersion: bigint): void;
150
187
  /** Drops every cached texture; fonts stay loaded. */
151
188
  clear(): void;
152
- /** Releases the wasm-side rasterizer and its fonts. */
153
189
  close(): void;
154
- /** Number of cached textures. */
155
190
  get cacheSize(): number;
156
191
  }
157
192
  /**
158
- * OffscreenCanvas/FontFace text host with explicit version invalidation.
159
- *
160
- * It draws with the browser's own shaper and rasterizer, which reach system
161
- * fonts and color emoji; its glyphs differ from a native host's. Use
162
- * {@link WasmTextRasterizer} where preview and export must match.
193
+ * OffscreenCanvas/FontFace text host. It uses the browser's shaper and system fonts, so its glyphs
194
+ * differ from a native host's; use {@link WasmTextRasterizer} where preview and export must match.
163
195
  */
164
196
  export declare class OffscreenTextRasterizer {
165
197
  #private;
166
198
  /**
167
- * Loads a caller-supplied font and adds it to the global's `FontFaceSet` (the worker's `fonts`
168
- * or `document.fonts`) until {@link close}. No stylesheet is touched. Rejects when the font data
169
- * cannot be loaded.
170
- *
171
- * Cached textures are not invalidated; bump `contentVersion` or call {@link clear} for text that
172
- * should pick up the new font.
199
+ * Loads a font into the global `FontFaceSet` until {@link close}. Rejects when the font data
200
+ * cannot be loaded. Cached textures are kept; bump `contentVersion` or call {@link clear}.
173
201
  */
174
202
  loadFont(family: string, source: ArrayBuffer, descriptors?: FontFaceDescriptors): Promise<FontFace>;
175
203
  /**
@@ -180,18 +208,16 @@ export declare class OffscreenTextRasterizer {
180
208
  * @throws Error when no OffscreenCanvas 2D context is available.
181
209
  */
182
210
  rasterize(request: BrowserTextRequest): BrowserTextTexture;
183
- /** Drops the cached texture for `contentVersion`, if any. */
184
211
  invalidate(contentVersion: bigint): void;
185
212
  /** Drops every cached texture; loaded fonts stay registered. */
186
213
  clear(): void;
187
214
  /** Removes the fonts this rasterizer loaded from the global `FontFaceSet` and drops the cache. */
188
215
  close(): void;
189
- /** Number of cached textures. */
190
216
  get cacheSize(): number;
191
217
  }
192
218
  /** The largest font size, in pixels, either text host draws. */
193
219
  export declare const MAX_TEXT_FONT_SIZE = 2048;
194
- /** The widest and tallest text texture, in pixels, and so the widest wrap width. */
220
+ /** The largest text texture side and wrap width, in pixels. */
195
221
  export declare const MAX_TEXT_DIMENSION = 16384;
196
222
  /** The longest text either text host draws, in UTF-8 bytes. */
197
223
  export declare const MAX_TEXT_BYTES: number;
package/dist/text.js CHANGED
@@ -1,7 +1,4 @@
1
- /**
2
- * The CSS generic families: keywords, which a quoted name would turn into a family of that literal
3
- * name.
4
- */
1
+ // Quoting these would turn them into literal family names.
5
2
  const GENERIC_FAMILIES = new Set([
6
3
  "serif",
7
4
  "sans-serif",
@@ -17,10 +14,6 @@ const GENERIC_FAMILIES = new Set([
17
14
  "emoji",
18
15
  "fangsong",
19
16
  ]);
20
- /**
21
- * `families` as a CSS font-family list: generic families as keywords, every other name a quoted CSS
22
- * string.
23
- */
24
17
  function cssFontFamilies(families) {
25
18
  return families
26
19
  .map((name) => {
@@ -33,42 +26,30 @@ function cssFontFamilies(families) {
33
26
  }
34
27
  const TEXT_ALIGNS = new Set(["start", "end", "left", "right", "center"]);
35
28
  /**
36
- * The engine's portable text host (`alpha2-text`: Unicode bidirectional
37
- * layout and line breaking, rustybuzz shaping, `ab_glyph_rasterizer`
38
- * outlines, COLR paintings and CBDT or sbix bitmaps) running in wasm.
39
- *
40
- * It is the same code a native host rasterizes with, so with the same font bytes a browser preview
41
- * and a native export draw identical text; the platform's own rasterizer, {@link
42
- * OffscreenTextRasterizer}, does not. Fonts are caller-supplied bytes in fallback order; system
43
- * fonts are not reachable. Color emoji are drawn in color from the fonts given, as outlines, or
44
- * replaced (`emojiPolicy`).
29
+ * The engine's portable text host (`alpha2-text`) in wasm. Given the same font bytes it draws text
30
+ * identical to a native export, unlike {@link OffscreenTextRasterizer}. Fonts are caller-supplied
31
+ * bytes in fallback order; system fonts are not reachable.
45
32
  */
46
33
  export class WasmTextRasterizer {
47
34
  #handle;
48
- /** Creates a rasterizer with no fonts from an initialized `alpha2/wasm`. */
49
35
  constructor(binding) {
50
36
  this.#handle = new binding.WasmTextRasterizer();
51
37
  }
52
- /**
53
- * Appends an OpenType font to the fallback stack. Every cached result is dropped, since fonts
54
- * change what a request draws.
55
- */
38
+ /** Appends an OpenType font to the fallback stack and drops every cached result. */
56
39
  addFont(family, bytes, faceIndex = 0) {
57
40
  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
58
41
  this.#handle.addFont(family, view, faceIndex);
59
42
  }
60
43
  /**
61
- * Appends every face of an OpenType font file to the fallback stack, in the file's order: each
62
- * weight of a collection (`.ttc`), so a style's `font_weight` can pick it. The export host
63
- * registers a font file the same way. Every cached result is dropped.
44
+ * Appends every face of a font file (each weight of a `.ttc`) to the fallback stack, as the
45
+ * export host does, and drops every cached result.
64
46
  */
65
47
  addFontFile(family, bytes) {
66
48
  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
67
49
  this.#handle.addFontFile(family, view);
68
50
  }
69
51
  /**
70
- * Shapes and rasterizes `request`, cached by content version: the rasterizer keeps up to 64 MiB
71
- * of results, dropping the least recently used past it.
52
+ * Shapes and rasterizes `request`, cached by content version (LRU, up to 64 MiB).
72
53
  *
73
54
  * @throws RangeError when `contentVersion` is not positive; the engine throws for an invalid
74
55
  * style, such as a font size over {@link MAX_TEXT_FONT_SIZE}.
@@ -81,8 +62,10 @@ export class WasmTextRasterizer {
81
62
  const raster = this.#handle.rasterize(JSON.stringify(style), contentVersion);
82
63
  let descriptor;
83
64
  let pixels;
65
+ let background;
84
66
  try {
85
67
  descriptor = JSON.parse(raster.descriptor);
68
+ background = raster.takeBackground?.();
86
69
  pixels = raster.takePixels();
87
70
  }
88
71
  finally {
@@ -105,9 +88,13 @@ export class WasmTextRasterizer {
105
88
  descent: descriptor.descent,
106
89
  lineCount: descriptor.lineCount,
107
90
  rgba8: new Uint8ClampedArray(pixels.buffer, pixels.byteOffset, pixels.byteLength),
91
+ ...(background !== undefined && background.byteLength > 0
92
+ ? {
93
+ background: new Uint8ClampedArray(background.buffer, background.byteOffset, background.byteLength),
94
+ }
95
+ : {}),
108
96
  };
109
97
  }
110
- /** Drops the cached texture for `contentVersion`, if any. */
111
98
  invalidate(contentVersion) {
112
99
  this.#handle.invalidate(contentVersion);
113
100
  }
@@ -115,32 +102,23 @@ export class WasmTextRasterizer {
115
102
  clear() {
116
103
  this.#handle.clear();
117
104
  }
118
- /** Releases the wasm-side rasterizer and its fonts. */
119
105
  close() {
120
106
  this.#handle.free?.();
121
107
  }
122
- /** Number of cached textures. */
123
108
  get cacheSize() {
124
109
  return this.#handle.cacheSize;
125
110
  }
126
111
  }
127
112
  /**
128
- * OffscreenCanvas/FontFace text host with explicit version invalidation.
129
- *
130
- * It draws with the browser's own shaper and rasterizer, which reach system
131
- * fonts and color emoji; its glyphs differ from a native host's. Use
132
- * {@link WasmTextRasterizer} where preview and export must match.
113
+ * OffscreenCanvas/FontFace text host. It uses the browser's shaper and system fonts, so its glyphs
114
+ * differ from a native host's; use {@link WasmTextRasterizer} where preview and export must match.
133
115
  */
134
116
  export class OffscreenTextRasterizer {
135
117
  #cache = new Map();
136
118
  #fonts = new Set();
137
119
  /**
138
- * Loads a caller-supplied font and adds it to the global's `FontFaceSet` (the worker's `fonts`
139
- * or `document.fonts`) until {@link close}. No stylesheet is touched. Rejects when the font data
140
- * cannot be loaded.
141
- *
142
- * Cached textures are not invalidated; bump `contentVersion` or call {@link clear} for text that
143
- * should pick up the new font.
120
+ * Loads a font into the global `FontFaceSet` until {@link close}. Rejects when the font data
121
+ * cannot be loaded. Cached textures are kept; bump `contentVersion` or call {@link clear}.
144
122
  */
145
123
  async loadFont(family, source, descriptors = {}) {
146
124
  const face = await new FontFace(family, source, descriptors).load();
@@ -179,9 +157,8 @@ export class OffscreenTextRasterizer {
179
157
  const measured = lines.map((line) => probe.measureText(line));
180
158
  const textWidth = measured.reduce((maximum, metrics) => Math.max(maximum, metrics.width), 0);
181
159
  const layoutWidth = Math.max(1, request.maxWidth && request.maxWidth > 0 ? request.maxWidth : textWidth);
182
- // The box holds every line's nominal em at fixed baselines, each em centred in its line when
183
- // lines are more than an em apart; ink past it goes in an equal margin on both sides so the box
184
- // stays centered.
160
+ // The box holds each line's nominal em, centered in its line; overhanging ink goes in an equal
161
+ // margin on both sides so the box stays centered.
185
162
  const halfLeading = Math.max(0, lineAdvance - fontSize) / 2;
186
163
  const nominalAscent = fontSize * 0.8;
187
164
  const firstBaseline = halfLeading + nominalAscent;
@@ -240,7 +217,6 @@ export class OffscreenTextRasterizer {
240
217
  this.#cache.set(request.contentVersion, result);
241
218
  return result;
242
219
  }
243
- /** Drops the cached texture for `contentVersion`, if any. */
244
220
  invalidate(contentVersion) {
245
221
  this.#cache.delete(contentVersion);
246
222
  }
@@ -257,27 +233,24 @@ export class OffscreenTextRasterizer {
257
233
  this.#fonts.clear();
258
234
  this.#cache.clear();
259
235
  }
260
- /** Number of cached textures. */
261
236
  get cacheSize() {
262
237
  return this.#cache.size;
263
238
  }
264
239
  }
265
240
  /** The largest font size, in pixels, either text host draws. */
266
241
  export const MAX_TEXT_FONT_SIZE = 2_048;
267
- /** The widest and tallest text texture, in pixels, and so the widest wrap width. */
242
+ /** The largest text texture side and wrap width, in pixels. */
268
243
  export const MAX_TEXT_DIMENSION = 16_384;
269
244
  /** The longest text either text host draws, in UTF-8 bytes. */
270
245
  export const MAX_TEXT_BYTES = 64 * 1024;
271
246
  /** The largest line height either text host draws, in font-size multiples. */
272
247
  export const MAX_TEXT_LINE_HEIGHT = 10;
273
- /**
274
- * `text`'s UTF-8 length is at most {@link MAX_TEXT_BYTES}; never shorter than its UTF-16 length.
275
- */
248
+ // UTF-8 is never shorter than UTF-16 code units, so the cheap check runs first.
276
249
  function textWithinLimit(text) {
277
250
  return (text.length <= MAX_TEXT_BYTES &&
278
251
  new TextEncoder().encode(text).length <= MAX_TEXT_BYTES);
279
252
  }
280
- /** Refuses what the portable host (`alpha2-text`) refuses, before any text is measured. */
253
+ // Refuses what the portable host refuses, before any text is measured.
281
254
  function validateRequest(request) {
282
255
  if (request.contentVersion <= 0n ||
283
256
  typeof request.text !== "string" ||
@@ -298,13 +271,9 @@ function validateRequest(request) {
298
271
  }
299
272
  }
300
273
  /**
301
- * `text` in lines no wider than `maxWidth` (none when it is not positive): a line breaks before the
302
- * word that would overflow it, and a word wider than the whole width breaks between graphemes, as
303
- * the portable host breaks it between glyphs; spaces hang past the end.
304
- *
305
- * Each word and each grapheme of an overflowing word is measured once and a line's width is their
306
- * sum, as the portable host sums cluster advances, so the cost is linear in the text. The ink of
307
- * each drawn line is measured whole afterwards, so a kerning difference is never cut off.
274
+ * Breaks before an overflowing word, and inside a word wider than the line between graphemes, as
275
+ * the portable host does; trailing spaces hang. Line widths sum per-word measurements, as the
276
+ * portable host sums cluster advances, which keeps the cost linear.
308
277
  */
309
278
  function wrapLines(context, text, maxWidth) {
310
279
  const output = [];
@@ -314,7 +283,7 @@ function wrapLines(context, text, maxWidth) {
314
283
  output.push(paragraph);
315
284
  continue;
316
285
  }
317
- // The line so far, its width, and its width without the spaces it ends in.
286
+ // `inkWidth` excludes trailing spaces.
318
287
  let line = "";
319
288
  let lineWidth = 0;
320
289
  let inkWidth = 0;
@@ -362,7 +331,7 @@ function wrapLines(context, text, maxWidth) {
362
331
  }
363
332
  return output.length === 0 ? [""] : output;
364
333
  }
365
- /** `text`'s user-perceived characters, or its code points where `Intl.Segmenter` is missing. */
334
+ // Falls back to code points where `Intl.Segmenter` is missing.
366
335
  function graphemes(text) {
367
336
  const Segmenter = Intl.Segmenter;
368
337
  if (Segmenter === undefined)
@@ -386,12 +355,8 @@ function premultiplyInPlace(pixels) {
386
355
  pixels[index + 2] = Math.round(((pixels[index + 2] ?? 0) * alpha) / 255);
387
356
  }
388
357
  }
389
- /**
390
- * Whether a grapheme is shown as an emoji (UTS #51), as the portable host (`alpha2-text`) reads one
391
- * too: unless U+FE0E asks for text, one holding an `Emoji_Presentation` character (regional
392
- * indicators and skin tones included), or U+FE0F with a pictograph or a keycap. A symbol shown as
393
- * text by default, such as (c) or a sun, is not one: a text font draws it.
394
- */
358
+ // UTS #51 emoji presentation, matching the portable host. Text-default symbols such as (c) are not
359
+ // emoji.
395
360
  function isEmoji(grapheme) {
396
361
  if (grapheme.includes("\ufe0e"))
397
362
  return false;
@@ -399,7 +364,7 @@ function isEmoji(grapheme) {
399
364
  (grapheme.includes("\ufe0f") &&
400
365
  /\p{Extended_Pictographic}|\u20e3/u.test(grapheme)));
401
366
  }
402
- /** A lone pictograph, with or without a presentation selector: what U+FE0E can make text. */
367
+ // Only a lone pictograph can take text presentation (U+FE0E).
403
368
  const LONE_PICTOGRAPH = /^(\p{Extended_Pictographic})\ufe0f?$/u;
404
369
  function normalizeEmoji(text, policy) {
405
370
  if (policy === "color")
@@ -407,12 +372,10 @@ function normalizeEmoji(text, policy) {
407
372
  let normalized = "";
408
373
  for (const segment of graphemes(text)) {
409
374
  if (policy === "replace") {
410
- // Each emoji grapheme, sequence or flag, becomes one replacement character.
411
375
  normalized += isEmoji(segment) ? "\ufffd" : segment;
412
376
  continue;
413
377
  }
414
- // Text presentation exists only for a lone pictograph; a skin tone, a ZWJ sequence, a flag, or
415
- // a keycap has none, and a selector inside one would split it.
378
+ // A selector inside a sequence (skin tone, ZWJ, flag, keycap) would split it.
416
379
  const lone = LONE_PICTOGRAPH.exec(segment);
417
380
  normalized += lone ? `${lone[1]}\ufe0e` : segment;
418
381
  }
@@ -1,32 +1,14 @@
1
1
  /**
2
- * `VideoFrame`s built from buffers whose planes carry their own layout.
3
- *
4
- * The engine hands export frames over as I420 with rows padded to the GPU's copy alignment, and
5
- * passes `layout` so the frame reads the planes where they are instead of script repacking them.
6
- * Safari (measured on 26.6.2) ignores `layout` in the buffer constructor and reads the planes as if
7
- * packed tightly from offset 0, so every width whose rows are padded (640 and 1920 among them)
8
- * encodes a sheared, miscoloured picture. Chrome honours it. Which one this browser is gets
9
- * measured once, on a tiny frame, rather than guessed from the user agent; where `layout` is
10
- * ignored the planes are copied tight first.
11
- */
12
- /**
13
- * Whether this browser's `VideoFrame` buffer constructor reads planes through `layout`.
14
- *
15
- * Builds a 2x2 I420 frame whose luma rows are padded, copies it back out, and compares. A browser
16
- * that ignores `layout` returns the padding as picture.
2
+ * Export frames arrive as I420 with rows padded to the GPU copy alignment, read through `layout`.
3
+ * Safari ignores `layout` in the buffer constructor and reads the planes as tightly packed, which
4
+ * shears the picture, so support is probed once and the planes are repacked where it is missing.
17
5
  */
6
+ /** Whether this browser's `VideoFrame` buffer constructor reads planes through `layout`. */
18
7
  export declare function videoFrameHonoursLayout(): Promise<boolean>;
19
8
  /**
20
- * An I420 frame over `pixels`, read through `init.layout`.
21
- *
22
- * `pixels` is owned by the caller and handed over: where the browser can take the buffer without
23
- * copying it, it does. Where the browser ignores `layout`, and the layout is not already the tight
24
- * one, the planes are copied tight into a new buffer first; {@link videoFrameRepackedBytes} reports
25
- * that copy.
9
+ * Builds an I420 frame over `pixels`, transferring the buffer where possible. Repacks the planes
10
+ * where the browser ignores `layout`; {@link videoFrameRepackedBytes} reports that copy.
26
11
  */
27
12
  export declare function videoFrameFromI420(pixels: Uint8Array, init: VideoFrameBufferInit): Promise<VideoFrame>;
28
- /**
29
- * Bytes script copied to build `frame` because the browser ignores `layout`; 0 for any other frame.
30
- * A frame the SDK's render worker built and posted reports the worker's copy.
31
- */
13
+ /** Bytes copied to build `frame` because the browser ignores `layout`, or 0. */
32
14
  export declare function videoFrameRepackedBytes(frame: VideoFrame): number;