alpha2 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -146,50 +146,58 @@ export class PlanarCopyPool {
146
146
  */
147
147
  export async function copyPlanarYuvFrame(frame, declared, identity = {}, pool) {
148
148
  try {
149
- const format = frame.format;
150
- if (format === null || !isPlanarVideoFrame(frame)) {
151
- throw new Error(`frame has no planar YUV format the engine reads (${format ?? "opaque"}); decode HDR sources, and sources whose color the project declares, in software`);
152
- }
153
- const visible = frame.visibleRect;
154
- if (!visible)
155
- throw new Error("frame has no visible rectangle");
156
- // copyTo copies the visible rectangle by default, so the copy is exactly the picture.
157
- const size = frame.allocationSize();
158
- const data = pool?.acquire(size) ?? new Uint8Array(size);
159
- let planes;
160
- try {
161
- planes = await frame.copyTo(data);
162
- }
163
- catch (error) {
164
- pool?.release(data);
165
- throw error;
166
- }
167
- return {
168
- kind: "yuv-frame",
169
- format,
170
- codedWidth: visible.width,
171
- codedHeight: visible.height,
172
- data,
173
- layout: planes.flatMap((plane) => [plane.offset, plane.stride]),
174
- visibleRect: [0, 0, visible.width, visible.height],
175
- color: declared ?? colorMetadataFromVideoColorSpace(frame.colorSpace),
176
- chromaSiting: identity.chromaSiting ?? "unspecified",
177
- displayWidth: frame.displayWidth,
178
- displayHeight: frame.displayHeight,
179
- physicalTimeMicroseconds: identity.physicalTimeMicroseconds ?? frame.timestamp,
180
- ...(frame.duration === null
181
- ? {}
182
- : { durationMicroseconds: frame.duration }),
183
- ...(identity.rotation === undefined
184
- ? {}
185
- : { rotation: identity.rotation }),
186
- ...(identity.mirror === undefined ? {} : { mirror: identity.mirror }),
187
- };
149
+ return await readPlanarYuvFrame(frame, declared, identity, pool);
188
150
  }
189
151
  finally {
190
152
  frame.close();
191
153
  }
192
154
  }
155
+ /**
156
+ * {@link copyPlanarYuvFrame} without closing `frame`: the caller owns it whether the copy succeeds
157
+ * or not, so a frame whose planes the browser could not read back can be read again. Rejects as
158
+ * {@link copyPlanarYuvFrame} does; with `pool`, a failed copy gives its buffer back.
159
+ *
160
+ * @internal For `FrameSupply`.
161
+ */
162
+ export async function readPlanarYuvFrame(frame, declared, identity = {}, pool) {
163
+ const format = frame.format;
164
+ if (format === null || !isPlanarVideoFrame(frame)) {
165
+ throw new Error(`frame has no planar YUV format the engine reads (${format ?? "opaque"}); decode HDR sources, and sources whose color the project declares, in software`);
166
+ }
167
+ const visible = frame.visibleRect;
168
+ if (!visible)
169
+ throw new Error("frame has no visible rectangle");
170
+ // copyTo copies the visible rectangle by default, so the copy is exactly the picture.
171
+ const size = frame.allocationSize();
172
+ const data = pool?.acquire(size) ?? new Uint8Array(size);
173
+ let planes;
174
+ try {
175
+ planes = await frame.copyTo(data);
176
+ }
177
+ catch (error) {
178
+ pool?.release(data);
179
+ throw error;
180
+ }
181
+ return {
182
+ kind: "yuv-frame",
183
+ format,
184
+ codedWidth: visible.width,
185
+ codedHeight: visible.height,
186
+ data,
187
+ layout: planes.flatMap((plane) => [plane.offset, plane.stride]),
188
+ visibleRect: [0, 0, visible.width, visible.height],
189
+ color: declared ?? colorMetadataFromVideoColorSpace(frame.colorSpace),
190
+ chromaSiting: identity.chromaSiting ?? "unspecified",
191
+ displayWidth: frame.displayWidth,
192
+ displayHeight: frame.displayHeight,
193
+ physicalTimeMicroseconds: identity.physicalTimeMicroseconds ?? frame.timestamp,
194
+ ...(frame.duration === null
195
+ ? {}
196
+ : { durationMicroseconds: frame.duration }),
197
+ ...(identity.rotation === undefined ? {} : { rotation: identity.rotation }),
198
+ ...(identity.mirror === undefined ? {} : { mirror: identity.mirror }),
199
+ };
200
+ }
193
201
  /**
194
202
  * Uploads a planar frame for the engine to convert and present at
195
203
  * `outputWidth` x `outputHeight`, the size it is shown upright at. Throws what
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The CSS value forms a layout reads, parsed as `alpha2_model::layout_values` parses them, with
3
+ * the same messages: lengths (a number, `"<n>px"`, `"<n>%"`), the four-side shorthand, grid track
4
+ * lists and grid lines, and CSS hex colors. Internal: `validateProject` and the layout builder use
5
+ * it.
6
+ */
7
+ /** A parsed value, or why the text is not one. */
8
+ export type Parsed<T> = {
9
+ readonly ok: true;
10
+ readonly value: T;
11
+ } | {
12
+ readonly ok: false;
13
+ readonly error: string;
14
+ };
15
+ /** A length's unit: a fraction of the shorter side, canvas pixels, or a percent. */
16
+ export type LengthUnit = "fraction" | "px" | "percent";
17
+ /** A length as the engine reads it: its unit and its 32-bit value. */
18
+ export interface Length {
19
+ readonly unit: LengthUnit;
20
+ readonly value: number;
21
+ }
22
+ /**
23
+ * A CSS number without an exponent, read as a JSON number is: through 64 bits to the nearest
24
+ * 32-bit float. `undefined` when it is not one or is not finite.
25
+ */
26
+ export declare function parseNumber(text: string): number | undefined;
27
+ /** A length that may not be a percent (`LayoutSize`), from its string form. */
28
+ export declare function parseSize(text: string): Parsed<Length>;
29
+ /** A length that may be a percent (`LayoutLength`), from its string form. */
30
+ export declare function parseLength(text: string): Parsed<Length>;
31
+ /** Padding or margin sides (`Insets`), top first, from the shorthand string. */
32
+ export declare function parseInsets(text: string): Parsed<readonly [Length, Length, Length, Length]>;
33
+ /** A translation (`LayoutOffset`) from the CSS `translate` string: x, then y (0 when missing). */
34
+ export declare function parseOffset(text: string): Parsed<{
35
+ readonly x: Length;
36
+ readonly y: Length;
37
+ }>;
38
+ /** One side of a track's size. */
39
+ export type TrackBreadth = {
40
+ readonly kind: "length";
41
+ readonly length: Length;
42
+ } | {
43
+ readonly kind: "fr";
44
+ readonly share: number;
45
+ } | {
46
+ readonly kind: "auto" | "min-content" | "max-content";
47
+ };
48
+ /** One track's size. */
49
+ export type TrackSize = {
50
+ readonly kind: "breadth";
51
+ readonly breadth: TrackBreadth;
52
+ } | {
53
+ readonly kind: "minmax";
54
+ readonly min: TrackBreadth;
55
+ readonly max: TrackBreadth;
56
+ } | {
57
+ readonly kind: "fit-content";
58
+ readonly limit: Length;
59
+ };
60
+ /** How often `repeat()` repeats: a count, `auto-fill`, or `auto-fit`. */
61
+ export type RepeatCount = number | "auto-fill" | "auto-fit";
62
+ /** One entry of a track list. */
63
+ export type TrackComponent = {
64
+ readonly kind: "single";
65
+ readonly size: TrackSize;
66
+ } | {
67
+ readonly kind: "repeat";
68
+ readonly count: RepeatCount;
69
+ readonly tracks: readonly TrackSize[];
70
+ };
71
+ /** A grid track list (`TrackList`), from its CSS string. */
72
+ export declare function parseTrackList(text: string): Parsed<TrackComponent[]>;
73
+ /** One edge of a grid placement: `auto`, a line, or a span. */
74
+ export type GridEdge = {
75
+ readonly kind: "auto";
76
+ } | {
77
+ readonly kind: "line";
78
+ readonly line: number;
79
+ } | {
80
+ readonly kind: "span";
81
+ readonly count: number;
82
+ };
83
+ /** Where a grid item lies on one axis (`GridPlacement`), from a line number or its CSS string. */
84
+ export declare function parsePlacement(value: number | string): Parsed<{
85
+ readonly start: GridEdge;
86
+ readonly end: GridEdge;
87
+ }>;
88
+ /** A straight sRGB color with alpha, each component in `0..=1`. */
89
+ export interface Color {
90
+ readonly red: number;
91
+ readonly green: number;
92
+ readonly blue: number;
93
+ readonly alpha: number;
94
+ }
95
+ /** The color a CSS hex string names (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), as 32-bit floats. */
96
+ export declare function parseHex(text: string): Parsed<Color>;
@@ -0,0 +1,370 @@
1
+ /**
2
+ * The CSS value forms a layout reads, parsed as `alpha2_model::layout_values` parses them, with
3
+ * the same messages: lengths (a number, `"<n>px"`, `"<n>%"`), the four-side shorthand, grid track
4
+ * lists and grid lines, and CSS hex colors. Internal: `validateProject` and the layout builder use
5
+ * it.
6
+ */
7
+ const ok = (value) => ({ ok: true, value });
8
+ const refused = (error) => ({ ok: false, error });
9
+ const NUMBER = /^-?(\d+\.?\d*|\.\d+)$/;
10
+ /**
11
+ * A CSS number without an exponent, read as a JSON number is: through 64 bits to the nearest
12
+ * 32-bit float. `undefined` when it is not one or is not finite.
13
+ */
14
+ export function parseNumber(text) {
15
+ if (!NUMBER.test(text))
16
+ return undefined;
17
+ const value = Math.fround(Number(text));
18
+ return Number.isFinite(value) ? value : undefined;
19
+ }
20
+ /** The tokens of a CSS value: runs of characters between ASCII spaces. */
21
+ function tokens(text) {
22
+ return text.split(" ").filter((token) => token.length > 0);
23
+ }
24
+ /** Strips ASCII spaces from both ends, as Rust's `trim_matches(' ')` does. */
25
+ function trimSpaces(text) {
26
+ return text.replace(/^ +| +$/g, "");
27
+ }
28
+ function invalidLength(token, percent) {
29
+ const hint = token.includes(" ")
30
+ ? ` (write ${token.replaceAll(" ", "")})`
31
+ : token.endsWith("em")
32
+ ? " (em and rem are not supported: write px or a number)"
33
+ : "";
34
+ const forms = percent
35
+ ? 'a number, "<n>px", or "<n>%"'
36
+ : 'a number or "<n>px"';
37
+ return `invalid length "${token}"${hint}: write ${forms}`;
38
+ }
39
+ /** One token: a number or `<n>px`; `percent` says whether the field takes a percent. */
40
+ function parseSizeToken(token, percent) {
41
+ if (token.endsWith("px")) {
42
+ const value = parseNumber(token.slice(0, -2));
43
+ return value === undefined
44
+ ? refused(invalidLength(token, percent))
45
+ : ok({ unit: "px", value });
46
+ }
47
+ if (!percent &&
48
+ token.endsWith("%") &&
49
+ parseNumber(token.slice(0, -1)) !== undefined) {
50
+ return refused(`percent is not allowed here: "${token}"`);
51
+ }
52
+ const value = parseNumber(token);
53
+ return value === undefined
54
+ ? refused(invalidLength(token, percent))
55
+ : ok({ unit: "fraction", value });
56
+ }
57
+ /** A length that may not be a percent (`LayoutSize`), from its string form. */
58
+ export function parseSize(text) {
59
+ return parseSizeToken(trimSpaces(text), false);
60
+ }
61
+ /** A length that may be a percent (`LayoutLength`), from its string form. */
62
+ export function parseLength(text) {
63
+ const trimmed = trimSpaces(text);
64
+ if (trimmed.endsWith("%")) {
65
+ const value = parseNumber(trimmed.slice(0, -1));
66
+ return value === undefined
67
+ ? refused(invalidLength(text, true))
68
+ : ok({ unit: "percent", value });
69
+ }
70
+ const size = parseSizeToken(trimmed, true);
71
+ return size.ok ? size : refused(invalidLength(text, true));
72
+ }
73
+ /** The four sides of a CSS shorthand of one to four values, top first. */
74
+ function shorthand(values) {
75
+ const [a, b, c, d] = values;
76
+ switch (values.length) {
77
+ case 1:
78
+ return ok([a, a, a, a]);
79
+ case 2:
80
+ return ok([a, b, a, b]);
81
+ case 3:
82
+ return ok([a, b, c, b]);
83
+ case 4:
84
+ return ok([a, b, c, d]);
85
+ default:
86
+ return refused(`expected 1 to 4 lengths, got ${values.length}`);
87
+ }
88
+ }
89
+ /** Padding or margin sides (`Insets`), top first, from the shorthand string. */
90
+ export function parseInsets(text) {
91
+ const sides = [];
92
+ for (const token of tokens(text)) {
93
+ const side = parseSizeToken(token, false);
94
+ if (!side.ok)
95
+ return side;
96
+ sides.push(side.value);
97
+ }
98
+ return shorthand(sides);
99
+ }
100
+ /** A translation (`LayoutOffset`) from the CSS `translate` string: x, then y (0 when missing). */
101
+ export function parseOffset(text) {
102
+ const values = [];
103
+ for (const token of tokens(text)) {
104
+ const value = parseSizeToken(token, false);
105
+ if (!value.ok)
106
+ return value;
107
+ values.push(value.value);
108
+ }
109
+ if (values.length === 1)
110
+ return ok({ x: values[0], y: { unit: "fraction", value: 0 } });
111
+ if (values.length === 2)
112
+ return ok({ x: values[0], y: values[1] });
113
+ return refused(`expected 1 or 2 lengths, got ${values.length}`);
114
+ }
115
+ function unknownTrack(token) {
116
+ const hints = {
117
+ min_content: "min-content",
118
+ max_content: "max-content",
119
+ auto_fill: "auto-fill",
120
+ auto_fit: "auto-fit",
121
+ };
122
+ if (!(token in hints) && token.startsWith("[")) {
123
+ return `named grid lines are not supported: "${token}"`;
124
+ }
125
+ const hint = hints[token] ?? (token.includes(" ") ? token.replaceAll(" ", "") : "");
126
+ return hint
127
+ ? `unknown track "${token}" (write ${hint})`
128
+ : `unknown track "${token}"`;
129
+ }
130
+ function parseBreadth(token, max) {
131
+ if (token === "auto" || token === "min-content" || token === "max-content")
132
+ return ok({ kind: token });
133
+ if (token.endsWith("fr")) {
134
+ const share = parseNumber(token.slice(0, -2));
135
+ if (share !== undefined) {
136
+ return max
137
+ ? ok({ kind: "fr", share })
138
+ : refused(`a minimum size cannot be fr: "${token}"`);
139
+ }
140
+ }
141
+ const length = parseLength(token);
142
+ return length.ok
143
+ ? ok({ kind: "length", length: length.value })
144
+ : refused(unknownTrack(token));
145
+ }
146
+ /** Reads a track list left to right, as `TrackParser` does. */
147
+ class TrackParser {
148
+ text;
149
+ at = 0;
150
+ constructor(text) {
151
+ this.text = text;
152
+ }
153
+ rest() {
154
+ return this.text.slice(this.at);
155
+ }
156
+ /** Skips spaces; whether anything is left. */
157
+ skipSpaces() {
158
+ while (this.rest().startsWith(" "))
159
+ this.at += 1;
160
+ return this.rest().length > 0;
161
+ }
162
+ /** The next token: up to a space, a comma or a parenthesis. */
163
+ token() {
164
+ const rest = this.rest();
165
+ const match = /[ ,()]/.exec(rest);
166
+ const end = match ? match.index : rest.length;
167
+ this.at += end;
168
+ return rest.slice(0, end);
169
+ }
170
+ expect(expected) {
171
+ this.skipSpaces();
172
+ if (this.rest().startsWith(expected)) {
173
+ this.at += 1;
174
+ return ok(null);
175
+ }
176
+ return refused(`expected "${expected}" in "${this.text}"`);
177
+ }
178
+ breadth(max) {
179
+ this.skipSpaces();
180
+ const token = this.token();
181
+ if (token.length === 0)
182
+ return refused(`expected a track size in "${this.text}"`);
183
+ return parseBreadth(token, max);
184
+ }
185
+ track() {
186
+ const start = this.at;
187
+ const token = this.token();
188
+ if ((token === "minmax" || token === "fit-content") &&
189
+ this.rest().startsWith("(")) {
190
+ this.at += 1;
191
+ if (token === "fit-content") {
192
+ const limit = this.breadth(false);
193
+ if (!limit.ok)
194
+ return limit;
195
+ const close = this.expect(")");
196
+ if (!close.ok)
197
+ return close;
198
+ return limit.value.kind === "length"
199
+ ? ok({ kind: "fit-content", limit: limit.value.length })
200
+ : refused(`fit-content takes a length: "${this.text.slice(start, this.at)}"`);
201
+ }
202
+ const min = this.breadth(false);
203
+ if (!min.ok)
204
+ return min;
205
+ const comma = this.expect(",");
206
+ if (!comma.ok)
207
+ return comma;
208
+ const max = this.breadth(true);
209
+ if (!max.ok)
210
+ return max;
211
+ const close = this.expect(")");
212
+ if (!close.ok)
213
+ return close;
214
+ return ok({ kind: "minmax", min: min.value, max: max.value });
215
+ }
216
+ if (token === "")
217
+ return refused(`expected a track in "${this.text}"`);
218
+ if (token === "fit_content" || token === "min_max") {
219
+ const hint = token.replaceAll("_", "-").replace("min-max", "minmax");
220
+ return refused(`unknown track "${token}" (write ${hint})`);
221
+ }
222
+ // A unit standing apart from its number: "1 fr".
223
+ const after = this.at;
224
+ if (parseNumber(token) !== undefined && this.skipSpaces()) {
225
+ const unit = this.token();
226
+ if (unit === "fr" || unit === "px" || unit === "%") {
227
+ return refused(unknownTrack(this.text.slice(start, this.at)));
228
+ }
229
+ }
230
+ this.at = after;
231
+ const breadth = parseBreadth(token, true);
232
+ return breadth.ok
233
+ ? ok({ kind: "breadth", breadth: breadth.value })
234
+ : breadth;
235
+ }
236
+ repeat() {
237
+ this.skipSpaces();
238
+ const token = this.token();
239
+ let count;
240
+ if (token === "auto-fill" || token === "auto-fit")
241
+ count = token;
242
+ else if (token === "auto_fill" || token === "auto_fit") {
243
+ return refused(`unknown repeat count "${token}" (write ${token.replace("_", "-")})`);
244
+ }
245
+ else if (/^\d+$/.test(token) && Number(token) <= 65535) {
246
+ count = Number(token);
247
+ }
248
+ else
249
+ return refused(`unknown repeat count "${token}"`);
250
+ const comma = this.expect(",");
251
+ if (!comma.ok)
252
+ return comma;
253
+ const tracks = [];
254
+ for (;;) {
255
+ if (!this.skipSpaces())
256
+ return refused(`expected ")" in "${this.text}"`);
257
+ if (this.rest().startsWith(")")) {
258
+ this.at += 1;
259
+ break;
260
+ }
261
+ if (this.rest().startsWith("repeat("))
262
+ return refused("repeat() cannot hold repeat()");
263
+ const track = this.track();
264
+ if (!track.ok)
265
+ return track;
266
+ tracks.push(track.value);
267
+ }
268
+ if (tracks.length === 0)
269
+ return refused("repeat() needs at least one track");
270
+ return ok({ kind: "repeat", count, tracks });
271
+ }
272
+ }
273
+ /** A grid track list (`TrackList`), from its CSS string. */
274
+ export function parseTrackList(text) {
275
+ const parser = new TrackParser(text);
276
+ const components = [];
277
+ while (parser.skipSpaces()) {
278
+ if (parser.rest().startsWith("repeat(")) {
279
+ parser.at += "repeat(".length;
280
+ const repeat = parser.repeat();
281
+ if (!repeat.ok)
282
+ return repeat;
283
+ components.push(repeat.value);
284
+ }
285
+ else {
286
+ const track = parser.track();
287
+ if (!track.ok)
288
+ return track;
289
+ components.push({ kind: "single", size: track.value });
290
+ }
291
+ }
292
+ return components.length === 0
293
+ ? refused("expected at least one track")
294
+ : ok(components);
295
+ }
296
+ function invalidLine(text) {
297
+ const trimmed = trimSpaces(text);
298
+ const named = trimmed
299
+ .split(/[ /]/)
300
+ .filter((word) => word.length > 0)
301
+ .some((word) => word !== "span" && word !== "auto" && /^[A-Za-z]/.test(word));
302
+ return named
303
+ ? `named grid lines are not supported: "${trimmed}"`
304
+ : `invalid grid line "${trimmed}": write a line number, "span <n>", or "auto"`;
305
+ }
306
+ /** An i16, as a CSS integer: digits with an optional minus. */
307
+ function gridInteger(word) {
308
+ if (!/^-?\d+$/.test(word))
309
+ return undefined;
310
+ const value = Number(word);
311
+ return value >= -32768 && value <= 32767 ? value : undefined;
312
+ }
313
+ function parseEdge(text) {
314
+ const words = tokens(text);
315
+ if (words.length === 1 && words[0] === "auto")
316
+ return { kind: "auto" };
317
+ if (words.length === 2 && words[0] === "span") {
318
+ const count = gridInteger(words[1]);
319
+ return count !== undefined && count >= 0
320
+ ? { kind: "span", count }
321
+ : undefined;
322
+ }
323
+ if (words.length === 1) {
324
+ const line = gridInteger(words[0]);
325
+ return line === undefined ? undefined : { kind: "line", line };
326
+ }
327
+ return undefined;
328
+ }
329
+ /** Where a grid item lies on one axis (`GridPlacement`), from a line number or its CSS string. */
330
+ export function parsePlacement(value) {
331
+ if (typeof value === "number") {
332
+ return Number.isInteger(value) && value >= -32768 && value <= 32767
333
+ ? ok({ start: { kind: "line", line: value }, end: { kind: "auto" } })
334
+ : refused(invalidLine(String(value)));
335
+ }
336
+ const split = value.indexOf("/");
337
+ const [start, end] = split < 0
338
+ ? [value, undefined]
339
+ : [value.slice(0, split), value.slice(split + 1)];
340
+ if (end?.includes("/"))
341
+ return refused(invalidLine(value));
342
+ const first = parseEdge(start);
343
+ if (first === undefined)
344
+ return refused(invalidLine(start));
345
+ if (end === undefined)
346
+ return ok({ start: first, end: { kind: "auto" } });
347
+ const second = parseEdge(end);
348
+ return second === undefined
349
+ ? refused(invalidLine(end))
350
+ : ok({ start: first, end: second });
351
+ }
352
+ /** The color a CSS hex string names (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), as 32-bit floats. */
353
+ export function parseHex(text) {
354
+ const digits = text.startsWith("#") ? text.slice(1) : undefined;
355
+ if (digits === undefined ||
356
+ ![3, 4, 6, 8].includes(digits.length) ||
357
+ !/^[0-9a-fA-F]*$/.test(digits)) {
358
+ return refused(`invalid color "${text}": write #rgb, #rgba, #rrggbb, or #rrggbbaa`);
359
+ }
360
+ const short = digits.length <= 4;
361
+ const channels = Array.from({ length: short ? digits.length : digits.length / 2 }, (_, index) => Math.fround((short
362
+ ? parseInt(digits[index], 16) * 17
363
+ : parseInt(digits.slice(index * 2, index * 2 + 2), 16)) / 255));
364
+ return ok({
365
+ red: channels[0],
366
+ green: channels[1],
367
+ blue: channels[2],
368
+ alpha: channels[3] ?? 1,
369
+ });
370
+ }