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
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,47 +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;
55
+ addFontFile(family: string, bytes: Uint8Array): void;
68
56
  rasterize(requestJson: string, contentVersion: bigint): {
69
57
  readonly descriptor: string;
58
+ takeBackground?(): Uint8Array;
70
59
  takePixels(): Uint8Array;
71
60
  free?(): void;
72
61
  };
@@ -75,7 +64,6 @@ export interface WasmTextRasterizerHandle {
75
64
  readonly cacheSize: number;
76
65
  free?(): void;
77
66
  }
78
- /** The part of the `alpha2/wasm` module `WasmTextRasterizer` needs. */
79
67
  export interface WasmTextBinding {
80
68
  readonly WasmTextRasterizer: new () => WasmTextRasterizerHandle;
81
69
  }
@@ -87,72 +75,129 @@ export interface WasmTextRequest {
87
75
  readonly fontSize: number;
88
76
  /** Layout width; zero or absent disables wrapping. */
89
77
  readonly maxWidth?: number;
90
- /** Baseline-to-baseline distance in font-size multiples (default 1.2). */
78
+ /** Line height in font-size multiples (default 1.2). */
91
79
  readonly lineHeight?: number;
80
+ /**
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.
83
+ */
84
+ readonly letterSpacing?: number;
85
+ /**
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.
88
+ */
89
+ readonly fontWeight?: number;
92
90
  readonly align?: "start" | "center" | "end";
93
- /** Straight (not premultiplied), sRGB-encoded RGBA, each in `0..=255`. */
94
- 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;
95
93
  /**
96
- * How emoji are drawn (default `color`): a font's color glyphs (COLR, CBDT, sbix) in their own
97
- * colors, an emoji trying the color fonts first; `monochrome` draws every glyph as an outline in
98
- * `color`, an emoji trying the other fonts first; `replace` draws each emoji grapheme as one
99
- * 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.
100
96
  */
101
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;
102
131
  }
132
+ /** See {@link WasmClusterState}. */
133
+ export interface WasmColorMix {
134
+ readonly keep: number;
135
+ readonly add: readonly [number, number, number, number];
136
+ }
137
+ /** Straight (not premultiplied), sRGB-encoded RGBA, each in `0..=255`. */
138
+ export type WasmTextColor = readonly [number, number, number, number];
139
+ /**
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
+ };
103
164
  /**
104
- * The engine's portable text host (`alpha2-text`: Unicode bidirectional
105
- * layout and line breaking, rustybuzz shaping, `ab_glyph_rasterizer`
106
- * outlines, COLR paintings and CBDT or sbix bitmaps) running in wasm.
107
- *
108
- * It is the same code a native host rasterizes with, so with the same font bytes a browser preview
109
- * and a native export draw identical text; the platform's own rasterizer, {@link
110
- * OffscreenTextRasterizer}, does not. Fonts are caller-supplied bytes in fallback order; system
111
- * fonts are not reachable. Color emoji are drawn in color from the fonts given, as outlines, or
112
- * replaced (`emojiPolicy`).
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.
113
168
  */
114
169
  export declare class WasmTextRasterizer {
115
170
  #private;
116
- /** Creates a rasterizer with no fonts from an initialized `alpha2/wasm`. */
117
171
  constructor(binding: WasmTextBinding);
172
+ /** Appends an OpenType font to the fallback stack and drops every cached result. */
173
+ addFont(family: string, bytes: ArrayBuffer | Uint8Array, faceIndex?: number): void;
118
174
  /**
119
- * Appends an OpenType font to the fallback stack. Every cached result is dropped, since fonts
120
- * change what a request draws.
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.
121
177
  */
122
- addFont(family: string, bytes: ArrayBuffer | Uint8Array, faceIndex?: number): void;
178
+ addFontFile(family: string, bytes: ArrayBuffer | Uint8Array): void;
123
179
  /**
124
- * Shapes and rasterizes `request`, cached by content version: the rasterizer keeps up to 64 MiB
125
- * of results, dropping the least recently used past it.
180
+ * Shapes and rasterizes `request`, cached by content version (LRU, up to 64 MiB).
126
181
  *
127
182
  * @throws RangeError when `contentVersion` is not positive; the engine throws for an invalid
128
183
  * style, such as a font size over {@link MAX_TEXT_FONT_SIZE}.
129
184
  */
130
185
  rasterize(request: WasmTextRequest): BrowserTextTexture;
131
- /** Drops the cached texture for `contentVersion`, if any. */
132
186
  invalidate(contentVersion: bigint): void;
133
187
  /** Drops every cached texture; fonts stay loaded. */
134
188
  clear(): void;
135
- /** Releases the wasm-side rasterizer and its fonts. */
136
189
  close(): void;
137
- /** Number of cached textures. */
138
190
  get cacheSize(): number;
139
191
  }
140
192
  /**
141
- * OffscreenCanvas/FontFace text host with explicit version invalidation.
142
- *
143
- * It draws with the browser's own shaper and rasterizer, which reach system
144
- * fonts and color emoji; its glyphs differ from a native host's. Use
145
- * {@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.
146
195
  */
147
196
  export declare class OffscreenTextRasterizer {
148
197
  #private;
149
198
  /**
150
- * Loads a caller-supplied font and adds it to the global's `FontFaceSet` (the worker's `fonts`
151
- * or `document.fonts`) until {@link close}. No stylesheet is touched. Rejects when the font data
152
- * cannot be loaded.
153
- *
154
- * Cached textures are not invalidated; bump `contentVersion` or call {@link clear} for text that
155
- * 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}.
156
201
  */
157
202
  loadFont(family: string, source: ArrayBuffer, descriptors?: FontFaceDescriptors): Promise<FontFace>;
158
203
  /**
@@ -163,18 +208,16 @@ export declare class OffscreenTextRasterizer {
163
208
  * @throws Error when no OffscreenCanvas 2D context is available.
164
209
  */
165
210
  rasterize(request: BrowserTextRequest): BrowserTextTexture;
166
- /** Drops the cached texture for `contentVersion`, if any. */
167
211
  invalidate(contentVersion: bigint): void;
168
212
  /** Drops every cached texture; loaded fonts stay registered. */
169
213
  clear(): void;
170
214
  /** Removes the fonts this rasterizer loaded from the global `FontFaceSet` and drops the cache. */
171
215
  close(): void;
172
- /** Number of cached textures. */
173
216
  get cacheSize(): number;
174
217
  }
175
218
  /** The largest font size, in pixels, either text host draws. */
176
219
  export declare const MAX_TEXT_FONT_SIZE = 2048;
177
- /** 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. */
178
221
  export declare const MAX_TEXT_DIMENSION = 16384;
179
222
  /** The longest text either text host draws, in UTF-8 bytes. */
180
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,33 +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
- * Shapes and rasterizes `request`, cached by content version: the rasterizer keeps up to 64 MiB
62
- * of results, dropping the least recently used past it.
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.
46
+ */
47
+ addFontFile(family, bytes) {
48
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
49
+ this.#handle.addFontFile(family, view);
50
+ }
51
+ /**
52
+ * Shapes and rasterizes `request`, cached by content version (LRU, up to 64 MiB).
63
53
  *
64
54
  * @throws RangeError when `contentVersion` is not positive; the engine throws for an invalid
65
55
  * style, such as a font size over {@link MAX_TEXT_FONT_SIZE}.
@@ -72,8 +62,10 @@ export class WasmTextRasterizer {
72
62
  const raster = this.#handle.rasterize(JSON.stringify(style), contentVersion);
73
63
  let descriptor;
74
64
  let pixels;
65
+ let background;
75
66
  try {
76
67
  descriptor = JSON.parse(raster.descriptor);
68
+ background = raster.takeBackground?.();
77
69
  pixels = raster.takePixels();
78
70
  }
79
71
  finally {
@@ -96,9 +88,13 @@ export class WasmTextRasterizer {
96
88
  descent: descriptor.descent,
97
89
  lineCount: descriptor.lineCount,
98
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
+ : {}),
99
96
  };
100
97
  }
101
- /** Drops the cached texture for `contentVersion`, if any. */
102
98
  invalidate(contentVersion) {
103
99
  this.#handle.invalidate(contentVersion);
104
100
  }
@@ -106,32 +102,23 @@ export class WasmTextRasterizer {
106
102
  clear() {
107
103
  this.#handle.clear();
108
104
  }
109
- /** Releases the wasm-side rasterizer and its fonts. */
110
105
  close() {
111
106
  this.#handle.free?.();
112
107
  }
113
- /** Number of cached textures. */
114
108
  get cacheSize() {
115
109
  return this.#handle.cacheSize;
116
110
  }
117
111
  }
118
112
  /**
119
- * OffscreenCanvas/FontFace text host with explicit version invalidation.
120
- *
121
- * It draws with the browser's own shaper and rasterizer, which reach system
122
- * fonts and color emoji; its glyphs differ from a native host's. Use
123
- * {@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.
124
115
  */
125
116
  export class OffscreenTextRasterizer {
126
117
  #cache = new Map();
127
118
  #fonts = new Set();
128
119
  /**
129
- * Loads a caller-supplied font and adds it to the global's `FontFaceSet` (the worker's `fonts`
130
- * or `document.fonts`) until {@link close}. No stylesheet is touched. Rejects when the font data
131
- * cannot be loaded.
132
- *
133
- * Cached textures are not invalidated; bump `contentVersion` or call {@link clear} for text that
134
- * 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}.
135
122
  */
136
123
  async loadFont(family, source, descriptors = {}) {
137
124
  const face = await new FontFace(family, source, descriptors).load();
@@ -170,9 +157,11 @@ export class OffscreenTextRasterizer {
170
157
  const measured = lines.map((line) => probe.measureText(line));
171
158
  const textWidth = measured.reduce((maximum, metrics) => Math.max(maximum, metrics.width), 0);
172
159
  const layoutWidth = Math.max(1, request.maxWidth && request.maxWidth > 0 ? request.maxWidth : textWidth);
173
- // The box holds every line's nominal em at fixed baselines; ink past it goes in an equal margin
174
- // on both sides so the box 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.
162
+ const halfLeading = Math.max(0, lineAdvance - fontSize) / 2;
175
163
  const nominalAscent = fontSize * 0.8;
164
+ const firstBaseline = halfLeading + nominalAscent;
176
165
  const layoutHeight = Math.max(1, (lines.length - 1) * lineAdvance + Math.max(lineAdvance, fontSize));
177
166
  const boxWidth = checkedDimension(layoutWidth);
178
167
  const boxHeight = checkedDimension(layoutHeight);
@@ -186,7 +175,7 @@ export class OffscreenTextRasterizer {
186
175
  let ascent = nominalAscent;
187
176
  let descent = fontSize * 0.2;
188
177
  measured.forEach((metrics, index) => {
189
- const baseline = nominalAscent + index * lineAdvance;
178
+ const baseline = firstBaseline + index * lineAdvance;
190
179
  overflowX = Math.max(overflowX, metrics.actualBoundingBoxLeft - x, x + metrics.actualBoundingBoxRight - boxWidth);
191
180
  overflowY = Math.max(overflowY, metrics.actualBoundingBoxAscent - baseline, baseline + metrics.actualBoundingBoxDescent - boxHeight);
192
181
  ascent = Math.max(ascent, metrics.actualBoundingBoxAscent);
@@ -204,7 +193,7 @@ export class OffscreenTextRasterizer {
204
193
  context.textBaseline = "alphabetic";
205
194
  context.textAlign = request.align ?? "start";
206
195
  context.fillStyle = request.color ?? "#ffffffff";
207
- lines.forEach((line, index) => context.fillText(line, marginX + x, marginY + nominalAscent + index * lineAdvance));
196
+ lines.forEach((line, index) => context.fillText(line, marginX + x, marginY + firstBaseline + index * lineAdvance));
208
197
  const image = context.getImageData(0, 0, width, height);
209
198
  premultiplyInPlace(image.data);
210
199
  const result = {
@@ -219,7 +208,7 @@ export class OffscreenTextRasterizer {
219
208
  layoutY: marginY,
220
209
  layoutWidth,
221
210
  layoutHeight,
222
- firstBaseline: nominalAscent,
211
+ firstBaseline,
223
212
  ascent,
224
213
  descent,
225
214
  lineCount: lines.length,
@@ -228,7 +217,6 @@ export class OffscreenTextRasterizer {
228
217
  this.#cache.set(request.contentVersion, result);
229
218
  return result;
230
219
  }
231
- /** Drops the cached texture for `contentVersion`, if any. */
232
220
  invalidate(contentVersion) {
233
221
  this.#cache.delete(contentVersion);
234
222
  }
@@ -245,27 +233,24 @@ export class OffscreenTextRasterizer {
245
233
  this.#fonts.clear();
246
234
  this.#cache.clear();
247
235
  }
248
- /** Number of cached textures. */
249
236
  get cacheSize() {
250
237
  return this.#cache.size;
251
238
  }
252
239
  }
253
240
  /** The largest font size, in pixels, either text host draws. */
254
241
  export const MAX_TEXT_FONT_SIZE = 2_048;
255
- /** 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. */
256
243
  export const MAX_TEXT_DIMENSION = 16_384;
257
244
  /** The longest text either text host draws, in UTF-8 bytes. */
258
245
  export const MAX_TEXT_BYTES = 64 * 1024;
259
246
  /** The largest line height either text host draws, in font-size multiples. */
260
247
  export const MAX_TEXT_LINE_HEIGHT = 10;
261
- /**
262
- * `text`'s UTF-8 length is at most {@link MAX_TEXT_BYTES}; never shorter than its UTF-16 length.
263
- */
248
+ // UTF-8 is never shorter than UTF-16 code units, so the cheap check runs first.
264
249
  function textWithinLimit(text) {
265
250
  return (text.length <= MAX_TEXT_BYTES &&
266
251
  new TextEncoder().encode(text).length <= MAX_TEXT_BYTES);
267
252
  }
268
- /** 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.
269
254
  function validateRequest(request) {
270
255
  if (request.contentVersion <= 0n ||
271
256
  typeof request.text !== "string" ||
@@ -286,13 +271,9 @@ function validateRequest(request) {
286
271
  }
287
272
  }
288
273
  /**
289
- * `text` in lines no wider than `maxWidth` (none when it is not positive): a line breaks before the
290
- * word that would overflow it, and a word wider than the whole width breaks between graphemes, as
291
- * the portable host breaks it between glyphs; spaces hang past the end.
292
- *
293
- * Each word and each grapheme of an overflowing word is measured once and a line's width is their
294
- * sum, as the portable host sums cluster advances, so the cost is linear in the text. The ink of
295
- * 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.
296
277
  */
297
278
  function wrapLines(context, text, maxWidth) {
298
279
  const output = [];
@@ -302,7 +283,7 @@ function wrapLines(context, text, maxWidth) {
302
283
  output.push(paragraph);
303
284
  continue;
304
285
  }
305
- // The line so far, its width, and its width without the spaces it ends in.
286
+ // `inkWidth` excludes trailing spaces.
306
287
  let line = "";
307
288
  let lineWidth = 0;
308
289
  let inkWidth = 0;
@@ -350,7 +331,7 @@ function wrapLines(context, text, maxWidth) {
350
331
  }
351
332
  return output.length === 0 ? [""] : output;
352
333
  }
353
- /** `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.
354
335
  function graphemes(text) {
355
336
  const Segmenter = Intl.Segmenter;
356
337
  if (Segmenter === undefined)
@@ -374,12 +355,8 @@ function premultiplyInPlace(pixels) {
374
355
  pixels[index + 2] = Math.round(((pixels[index + 2] ?? 0) * alpha) / 255);
375
356
  }
376
357
  }
377
- /**
378
- * Whether a grapheme is shown as an emoji (UTS #51), as the portable host (`alpha2-text`) reads one
379
- * too: unless U+FE0E asks for text, one holding an `Emoji_Presentation` character (regional
380
- * indicators and skin tones included), or U+FE0F with a pictograph or a keycap. A symbol shown as
381
- * text by default, such as (c) or a sun, is not one: a text font draws it.
382
- */
358
+ // UTS #51 emoji presentation, matching the portable host. Text-default symbols such as (c) are not
359
+ // emoji.
383
360
  function isEmoji(grapheme) {
384
361
  if (grapheme.includes("\ufe0e"))
385
362
  return false;
@@ -387,7 +364,7 @@ function isEmoji(grapheme) {
387
364
  (grapheme.includes("\ufe0f") &&
388
365
  /\p{Extended_Pictographic}|\u20e3/u.test(grapheme)));
389
366
  }
390
- /** 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).
391
368
  const LONE_PICTOGRAPH = /^(\p{Extended_Pictographic})\ufe0f?$/u;
392
369
  function normalizeEmoji(text, policy) {
393
370
  if (policy === "color")
@@ -395,12 +372,10 @@ function normalizeEmoji(text, policy) {
395
372
  let normalized = "";
396
373
  for (const segment of graphemes(text)) {
397
374
  if (policy === "replace") {
398
- // Each emoji grapheme, sequence or flag, becomes one replacement character.
399
375
  normalized += isEmoji(segment) ? "\ufffd" : segment;
400
376
  continue;
401
377
  }
402
- // Text presentation exists only for a lone pictograph; a skin tone, a ZWJ sequence, a flag, or
403
- // 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.
404
379
  const lone = LONE_PICTOGRAPH.exec(segment);
405
380
  normalized += lone ? `${lone[1]}\ufe0e` : segment;
406
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;