alpha2 0.5.3 → 0.6.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 (82) hide show
  1. package/README.md +68 -3
  2. package/THIRD_PARTY_NOTICES.md +7 -3
  3. package/dist/apply-edit.d.ts +124 -0
  4. package/dist/apply-edit.js +15 -0
  5. package/dist/assets.d.ts +12 -0
  6. package/dist/audio-layout.js +6 -3
  7. package/dist/audio-worklet-processor.js +27 -33
  8. package/dist/audio.d.ts +5 -4
  9. package/dist/audio.js +8 -6
  10. package/dist/compose.d.ts +105 -0
  11. package/dist/compose.js +63 -0
  12. package/dist/decoder-fallback.d.ts +3 -2
  13. package/dist/decoder-fallback.js +11 -3
  14. package/dist/decoder-stall.d.ts +15 -0
  15. package/dist/decoder-stall.js +52 -0
  16. package/dist/edit-data.d.ts +24 -0
  17. package/dist/edit-data.js +224 -0
  18. package/dist/edit-keys.d.ts +16 -0
  19. package/dist/edit-keys.js +233 -0
  20. package/dist/edit.d.ts +41 -8
  21. package/dist/edit.js +123 -30
  22. package/dist/export-failure.d.ts +10 -2
  23. package/dist/export-failure.js +55 -4
  24. package/dist/export-retry.d.ts +6 -1
  25. package/dist/export-retry.js +12 -1
  26. package/dist/exporter.d.ts +11 -7
  27. package/dist/exporter.js +10 -9
  28. package/dist/extract.d.ts +65 -0
  29. package/dist/extract.js +291 -0
  30. package/dist/extractor.d.ts +151 -0
  31. package/dist/extractor.js +141 -0
  32. package/dist/float32.d.ts +2 -0
  33. package/dist/float32.js +10 -0
  34. package/dist/frame-intake.d.ts +5 -0
  35. package/dist/frame-intake.js +10 -3
  36. package/dist/generated/builtin-effects.d.ts +3 -0
  37. package/dist/generated/builtin-effects.js +1804 -0
  38. package/dist/generated/project-schema.d.ts +636 -37
  39. package/dist/generated/project-schema.js +55 -0
  40. package/dist/generated/project-shape.js +950 -381
  41. package/dist/index.d.ts +1 -0
  42. package/dist/index.js +1 -0
  43. package/dist/json-text.js +14 -2
  44. package/dist/layout-values.js +7 -1
  45. package/dist/layout.d.ts +12 -4
  46. package/dist/media.d.ts +43 -10
  47. package/dist/media.js +255 -66
  48. package/dist/mediabunny.d.ts +32 -12
  49. package/dist/mediabunny.js +276 -90
  50. package/dist/player.d.ts +9 -3
  51. package/dist/player.js +114 -18
  52. package/dist/plugins.d.ts +62 -0
  53. package/dist/plugins.js +506 -0
  54. package/dist/project-data.d.ts +56 -0
  55. package/dist/project-data.js +765 -0
  56. package/dist/project.d.ts +24 -1
  57. package/dist/project.js +456 -38
  58. package/dist/robustness.d.ts +6 -33
  59. package/dist/robustness.js +2 -63
  60. package/dist/sha256.d.ts +3 -2
  61. package/dist/sha256.js +14 -6
  62. package/dist/worker-error.d.ts +3 -2
  63. package/dist/worker-error.js +3 -1
  64. package/dist/worker.d.ts +13 -3
  65. package/dist/worker.js +36 -9
  66. package/package.json +26 -1
  67. package/wasm/alpha2_compose.d.ts +92 -0
  68. package/wasm/alpha2_compose.js +445 -0
  69. package/wasm/alpha2_compose_bg.wasm +0 -0
  70. package/wasm/alpha2_compose_bg.wasm.d.ts +17 -0
  71. package/wasm/alpha2_extensions_bg.wasm +0 -0
  72. package/wasm/alpha2_extensions_pdf_bg.wasm +0 -0
  73. package/wasm/alpha2_wasm.d.ts +151 -18
  74. package/wasm/alpha2_wasm.js +403 -59
  75. package/wasm/alpha2_wasm_bg.wasm +0 -0
  76. package/wasm/alpha2_wasm_bg.wasm.d.ts +21 -6
  77. package/wasm/rust-crate-licenses.md +5 -61
  78. package/wasm/snippets/alpha2-wasm-6749ed8b34a74067/inline3.js +7 -0
  79. /package/wasm/snippets/{alpha2-wasm-a6265983c9769e80/inline1.js → alpha2-wasm-6749ed8b34a74067/inline0.js} +0 -0
  80. /package/wasm/snippets/{alpha2-wasm-a6265983c9769e80/inline2.js → alpha2-wasm-6749ed8b34a74067/inline1.js} +0 -0
  81. /package/wasm/snippets/{alpha2-wasm-a6265983c9769e80/inline3.js → alpha2-wasm-6749ed8b34a74067/inline2.js} +0 -0
  82. /package/wasm/snippets/{alpha2-wasm-a6265983c9769e80/inline0.js → alpha2-wasm-6749ed8b34a74067/inline4.js} +0 -0
@@ -3,9 +3,10 @@ import { type TrackDecodeFacts } from "./hdr-frames.js";
3
3
  export declare function isDecoderFailure(error: unknown): boolean;
4
4
  /**
5
5
  * Runs `decodeOnce`; on a decoder failure, if `reopenSoftware` is given, reopens in software and
6
- * runs it once more.
6
+ * runs it once more. When that attempt fails in its decoder too, `restore` runs before the
7
+ * rejection, so the next request starts from the original choice.
7
8
  */
8
- export declare function withSoftwareFallback<T>(decodeOnce: () => Promise<T>, reopenSoftware: ((cause: DOMException) => Promise<void>) | undefined): Promise<T>;
9
+ export declare function withSoftwareFallback<T>(decodeOnce: () => Promise<T>, reopenSoftware: ((cause: DOMException) => Promise<void>) | undefined, restore?: () => Promise<void>): Promise<T>;
9
10
  /**
10
11
  * Turns a decoder failure into {@link DecodeUnavailableError} when no frame of the track was ever
11
12
  * decoded. Other errors are returned unchanged.
@@ -8,9 +8,10 @@ export function isDecoderFailure(error) {
8
8
  }
9
9
  /**
10
10
  * Runs `decodeOnce`; on a decoder failure, if `reopenSoftware` is given, reopens in software and
11
- * runs it once more.
11
+ * runs it once more. When that attempt fails in its decoder too, `restore` runs before the
12
+ * rejection, so the next request starts from the original choice.
12
13
  */
13
- export async function withSoftwareFallback(decodeOnce, reopenSoftware) {
14
+ export async function withSoftwareFallback(decodeOnce, reopenSoftware, restore) {
14
15
  try {
15
16
  return await decodeOnce();
16
17
  }
@@ -18,7 +19,14 @@ export async function withSoftwareFallback(decodeOnce, reopenSoftware) {
18
19
  if (reopenSoftware === undefined || !isDecoderFailure(error))
19
20
  throw error;
20
21
  await reopenSoftware(error);
21
- return decodeOnce();
22
+ try {
23
+ return await decodeOnce();
24
+ }
25
+ catch (retry) {
26
+ if (restore !== undefined && isDecoderFailure(retry))
27
+ await restore();
28
+ throw retry;
29
+ }
22
30
  }
23
31
  }
24
32
  /**
@@ -0,0 +1,15 @@
1
+ /** A `DECODE_STALLED` error, classed as a GPU timeout in the decode phase. */
2
+ export declare function decoderStalled(message: string, stage: string): Error;
3
+ /**
4
+ * The iterator's next sample, raced against `stallMs` of active time (a frozen page does not
5
+ * count) and `signal`. On a stall (`DECODE_STALLED`) or an abort (the signal's reason) the
6
+ * iterator is ended and a sample that arrives late is closed.
7
+ */
8
+ export declare function nextSampleOrStall<T extends {
9
+ close(): void;
10
+ }>(iterator: AsyncIterator<T>, { stallMs, signal, sourceId, kind, }: {
11
+ readonly stallMs: number;
12
+ readonly signal?: AbortSignal | undefined;
13
+ readonly sourceId: string;
14
+ readonly kind: "video" | "audio";
15
+ }): Promise<IteratorResult<T>>;
@@ -0,0 +1,52 @@
1
+ // Stall limits shared by the video and audio decoder adapters.
2
+ import { activeTimeout } from "./active-clock.js";
3
+ /** A `DECODE_STALLED` error, classed as a GPU timeout in the decode phase. */
4
+ export function decoderStalled(message, stage) {
5
+ return Object.assign(new Error(message), {
6
+ code: "DECODE_STALLED",
7
+ failure: {
8
+ code: "GPU_TIMEOUT",
9
+ phase: "decode",
10
+ stage,
11
+ resource: "unknown",
12
+ },
13
+ });
14
+ }
15
+ /**
16
+ * The iterator's next sample, raced against `stallMs` of active time (a frozen page does not
17
+ * count) and `signal`. On a stall (`DECODE_STALLED`) or an abort (the signal's reason) the
18
+ * iterator is ended and a sample that arrives late is closed.
19
+ */
20
+ export async function nextSampleOrStall(iterator, { stallMs, signal, sourceId, kind, }) {
21
+ const pending = iterator.next();
22
+ const settled = new AbortController();
23
+ let abort;
24
+ const interrupted = new Promise((_, reject) => {
25
+ void activeTimeout(stallMs, settled.signal).then(() => reject(decoderStalled(`${kind} decoder ${sourceId} stalled: no ${kind === "video" ? "frame" : "samples"} for ${stallMs} ms`, `${kind}-decoder-stalled`)));
26
+ if (signal === undefined)
27
+ return;
28
+ abort = () => reject(signal.reason instanceof Error
29
+ ? signal.reason
30
+ : new DOMException("Aborted", "AbortError"));
31
+ if (signal.aborted)
32
+ abort();
33
+ else
34
+ signal.addEventListener("abort", abort, { once: true });
35
+ });
36
+ try {
37
+ return await Promise.race([pending, interrupted]);
38
+ }
39
+ catch (error) {
40
+ void pending.then((late) => {
41
+ if (!late.done)
42
+ late.value.close();
43
+ }, () => { });
44
+ void iterator.return?.()?.catch(() => { });
45
+ throw error;
46
+ }
47
+ finally {
48
+ settled.abort();
49
+ if (abort !== undefined)
50
+ signal?.removeEventListener("abort", abort);
51
+ }
52
+ }
@@ -0,0 +1,24 @@
1
+ import type { DataSet, Project } from "./generated/project-schema.js";
2
+ /** Sorted, disjoint, non-empty `[start, end)` tick ranges. */
3
+ type Removal = readonly (readonly [number, number])[];
4
+ /**
5
+ * A timeline-anchored set with `removal` cut out and later times moved left; a sample set keeps
6
+ * the value read just after each cut, and a linear one also the value just before it (mirrors
7
+ * `split::cut_data`).
8
+ */
9
+ export declare function cutData(set: DataSet, removal: Removal): DataSet;
10
+ /**
11
+ * Opens `delta > 0` ticks at `pivot` in a timeline-anchored set. Later times move right, an item
12
+ * across `pivot` lengthens, and a sample set holds the value read at `pivot` on both sides of the
13
+ * opening, so every moment outside it reads as before.
14
+ */
15
+ export declare function openData(set: DataSet, pivot: number, delta: number): DataSet;
16
+ /**
17
+ * Edits `project`'s timeline-anchored data sets as a ripple of `delta` at `pivot` edits the
18
+ * timeline. A negative `delta` removes `[pivot + delta, pivot)` and a positive one opens that much
19
+ * time at `pivot`. Source-anchored sets never change.
20
+ */
21
+ export declare function rippleTimelineData(project: Project, pivot: number, delta: number): Project;
22
+ /** `value` with every data binding that reads through clip `from` reading through `to`. */
23
+ export declare function renameVia<T>(value: T, from: string, to: string): T;
24
+ export {};
@@ -0,0 +1,224 @@
1
+ // Timeline-anchored data and `via` under timeline edits, mirroring `alpha2_eval::edit`.
2
+ import { shortestFloat32 } from "./float32.js";
3
+ const F32_MAX = 3.4028234663852886e38;
4
+ /** The removed length before `tick` (mirrors `shift_of`). */
5
+ function shiftOf(tick, removal) {
6
+ let shift = 0;
7
+ for (const [from, to] of removal)
8
+ shift += to <= tick ? to - from : from < tick ? tick - from : 0;
9
+ return shift;
10
+ }
11
+ /** A kept tick's new position, `undefined` for a removed one (mirrors `new_time`). */
12
+ function newTime(tick, removal) {
13
+ if (removal.some(([from, to]) => from <= tick && tick < to))
14
+ return undefined;
15
+ return tick - shiftOf(tick, removal);
16
+ }
17
+ /** Mirrors `kept_windows_ticks`. */
18
+ function keptWindows(start, end, removal) {
19
+ const windows = [];
20
+ let cursor = start;
21
+ for (const [from, to] of removal) {
22
+ if (to <= cursor || from >= end)
23
+ continue;
24
+ if (from > cursor)
25
+ windows.push([cursor, from]);
26
+ cursor = Math.max(cursor, to);
27
+ }
28
+ if (cursor < end)
29
+ windows.push([cursor, end]);
30
+ return windows;
31
+ }
32
+ function arityOf(set) {
33
+ return set.kind === "points" ? 2 : set.kind === "similarity" ? 4 : 1;
34
+ }
35
+ function channelCount(set) {
36
+ return Math.max("channels" in set ? set.channels.length : 0, 1);
37
+ }
38
+ /**
39
+ * The 32-bit value of `channel` at `time`, or `undefined` when the channel has no known value
40
+ * (mirrors `sample_channel`).
41
+ */
42
+ function sampleChannel(set, channel, arity, time) {
43
+ const width = channelCount(set) * arity;
44
+ const { times, values } = set;
45
+ const known = (sample) => {
46
+ const start = sample * width + channel * arity;
47
+ return sample < times.length && values[start] !== null
48
+ ? values.slice(start, start + arity).map((v) => Math.fround(v ?? 0))
49
+ : undefined;
50
+ };
51
+ let next = 0;
52
+ for (let high = times.length; next < high;) {
53
+ const middle = (next + high) >> 1;
54
+ if (times[middle] <= time)
55
+ next = middle + 1;
56
+ else
57
+ high = middle;
58
+ }
59
+ const first = (from, to, step) => {
60
+ for (let sample = from; sample !== to; sample += step) {
61
+ const value = known(sample);
62
+ if (value)
63
+ return value;
64
+ }
65
+ return undefined;
66
+ };
67
+ const current = next - 1;
68
+ if (current < 0)
69
+ return first(0, times.length, 1);
70
+ const left = known(current);
71
+ if (left) {
72
+ const right = set.interpolation === "linear" && times[current] < time
73
+ ? known(next)
74
+ : undefined;
75
+ if (!right)
76
+ return left;
77
+ const amount = (time - times[current]) / (times[next] - times[current]);
78
+ return left.map((from, index) => Math.fround(Math.min(F32_MAX, Math.max(-F32_MAX, from + (right[index] - from) * amount))));
79
+ }
80
+ return first(current - 1, -1, -1) ?? first(next, times.length, 1);
81
+ }
82
+ /** The values each channel reads at `time`, written as the engine writes 32-bit floats. */
83
+ function heldAt(set, time) {
84
+ const arity = arityOf(set);
85
+ const held = [];
86
+ for (let channel = 0; channel < channelCount(set); channel++) {
87
+ const value = sampleChannel(set, channel, arity, time);
88
+ held.push(...(value
89
+ ? value.map(shortestFloat32)
90
+ : new Array(arity).fill(null)));
91
+ }
92
+ return held;
93
+ }
94
+ /** `set` with samples `entries` as `[tick, values]`, sorted by tick. */
95
+ function withSamples(set, entries) {
96
+ entries.sort((a, b) => a[0] - b[0]);
97
+ return {
98
+ ...set,
99
+ times: entries.map(([tick]) => tick),
100
+ values: entries.flatMap(([, values]) => values),
101
+ };
102
+ }
103
+ function samplesOf(set, time) {
104
+ const width = channelCount(set) * arityOf(set);
105
+ const entries = [];
106
+ set.times.forEach((tick, index) => {
107
+ const moved = time(tick);
108
+ if (moved !== undefined)
109
+ entries.push([
110
+ moved,
111
+ set.values.slice(index * width, (index + 1) * width),
112
+ ]);
113
+ });
114
+ return entries;
115
+ }
116
+ /** An item's new edges past removed ranges, `undefined` when none stays (mirrors `cut_item`). */
117
+ function cutItem(start, end, removal, instants) {
118
+ const windows = keptWindows(start, Math.max(end, start + 1), removal);
119
+ if (!windows.length)
120
+ return undefined;
121
+ const from = windows[0][0] - shiftOf(windows[0][0], removal);
122
+ const last = windows[windows.length - 1][1] - 1;
123
+ const to = end === start ? from : last - shiftOf(last, removal) + 1;
124
+ return instants || from < to ? [from, to] : undefined;
125
+ }
126
+ function byEdges(items) {
127
+ return items.sort((a, b) => a.start - b.start || a.end - b.end);
128
+ }
129
+ /**
130
+ * A timeline-anchored set with `removal` cut out and later times moved left; a sample set keeps
131
+ * the value read just after each cut, and a linear one also the value just before it (mirrors
132
+ * `split::cut_data`).
133
+ */
134
+ export function cutData(set, removal) {
135
+ if (set.kind === "words" || set.kind === "intervals") {
136
+ const instants = set.kind === "intervals";
137
+ const cut = (items) => byEdges(items.flatMap((item) => {
138
+ const edges = cutItem(item.start, item.end, removal, instants);
139
+ return edges ? [{ ...item, start: edges[0], end: edges[1] }] : [];
140
+ }));
141
+ return set.kind === "words"
142
+ ? { ...set, words: cut(set.words) }
143
+ : { ...set, intervals: cut(set.intervals) };
144
+ }
145
+ if (!set.times.length)
146
+ return set;
147
+ const entries = samplesOf(set, (tick) => newTime(tick, removal));
148
+ const ticks = new Set(entries.map(([tick]) => tick));
149
+ const linear = set.interpolation === "linear";
150
+ for (const [from, to] of removal) {
151
+ const reads = linear && from - 1 >= set.times[0] ? [from - 1, to] : [to];
152
+ for (const read of reads) {
153
+ const at = newTime(read, removal);
154
+ if (at === undefined || ticks.has(at))
155
+ continue;
156
+ ticks.add(at);
157
+ entries.push([at, heldAt(set, read)]);
158
+ }
159
+ }
160
+ return withSamples(set, entries);
161
+ }
162
+ /**
163
+ * Opens `delta > 0` ticks at `pivot` in a timeline-anchored set. Later times move right, an item
164
+ * across `pivot` lengthens, and a sample set holds the value read at `pivot` on both sides of the
165
+ * opening, so every moment outside it reads as before.
166
+ */
167
+ export function openData(set, pivot, delta) {
168
+ if (set.kind === "words" || set.kind === "intervals") {
169
+ const open = (items) => byEdges(items.map((item) => item.start >= pivot
170
+ ? { ...item, start: item.start + delta, end: item.end + delta }
171
+ : item.end > pivot
172
+ ? { ...item, end: item.end + delta }
173
+ : item));
174
+ return set.kind === "words"
175
+ ? { ...set, words: open(set.words) }
176
+ : { ...set, intervals: open(set.intervals) };
177
+ }
178
+ const entries = samplesOf(set, (tick) => tick >= pivot ? tick + delta : tick);
179
+ if (set.times.some((t) => t < pivot) && set.times.some((t) => t >= pivot)) {
180
+ const held = heldAt(set, pivot);
181
+ const ticks = new Set(entries.map(([tick]) => tick));
182
+ for (const at of [pivot, pivot + delta])
183
+ if (!ticks.has(at))
184
+ entries.push([at, held]);
185
+ }
186
+ return withSamples(set, entries);
187
+ }
188
+ /**
189
+ * Edits `project`'s timeline-anchored data sets as a ripple of `delta` at `pivot` edits the
190
+ * timeline. A negative `delta` removes `[pivot + delta, pivot)` and a positive one opens that much
191
+ * time at `pivot`. Source-anchored sets never change.
192
+ */
193
+ export function rippleTimelineData(project, pivot, delta) {
194
+ if (!delta || !project.data?.some((set) => set.anchor.type === "timeline"))
195
+ return project;
196
+ const removal = [[pivot + delta, pivot]];
197
+ return {
198
+ ...project,
199
+ data: project.data.map((set) => set.anchor.type !== "timeline"
200
+ ? set
201
+ : delta < 0
202
+ ? cutData(set, removal)
203
+ : openData(set, pivot, delta)),
204
+ };
205
+ }
206
+ /** `value` with every data binding that reads through clip `from` reading through `to`. */
207
+ export function renameVia(value, from, to) {
208
+ if (Array.isArray(value))
209
+ return value.map((item) => renameVia(item, from, to));
210
+ if (typeof value !== "object" || value === null)
211
+ return value;
212
+ const record = value;
213
+ if (record.mode === "data") {
214
+ const via = record.via;
215
+ return via?.clip === from ? { ...record, via: { clip: to } } : value;
216
+ }
217
+ let changed = false;
218
+ const next = {};
219
+ for (const [key, field] of Object.entries(record)) {
220
+ next[key] = renameVia(field, from, to);
221
+ changed ||= next[key] !== field;
222
+ }
223
+ return changed ? next : value;
224
+ }
@@ -0,0 +1,16 @@
1
+ import type { Animated } from "./generated/project-schema.js";
2
+ /** Sorted, disjoint, non-empty `[start, end)` tick ranges. */
3
+ type Removal = readonly (readonly [number, number])[];
4
+ /**
5
+ * Bus keyframes after `removal` leaves a rippled timeline: keys inside go, the rest move, the
6
+ * value at each cut is keyed on both sides, and every key takes the part of the old curve up to
7
+ * the next key (mirrors `shift_keys`).
8
+ */
9
+ export declare function closeKeys(animation: Animated<number> | undefined, removal: Removal): Animated<number> | undefined;
10
+ /**
11
+ * Bus keyframes after `length` ticks open at `pivot`: keys at or after it move right, and when
12
+ * keys lie on both sides the value at `pivot` is held across the opening, so every moment outside
13
+ * it reads as before.
14
+ */
15
+ export declare function openKeys(animation: Animated<number> | undefined, pivot: number, length: number): Animated<number> | undefined;
16
+ export {};
@@ -0,0 +1,233 @@
1
+ // Bus automation under timeline edits, mirroring `shift_keys` in `alpha2_eval::edit` and
2
+ // `CubicBezier::between` in `alpha2_model`.
3
+ import { shortestFloat32 } from "./float32.js";
4
+ const NEWTON_STEPS = 8;
5
+ const BISECTION_STEPS = 64;
6
+ const TOLERANCE = 1e-12;
7
+ const MIN_SLOPE = 1e-9;
8
+ const F32_MAX = 3.4028234663852886e38;
9
+ function component(t, p1, p2) {
10
+ const c = 3 * p1;
11
+ const b = 3 * (p2 - p1) - c;
12
+ const a = 1 - c - b;
13
+ return ((a * t + b) * t + c) * t;
14
+ }
15
+ function slope(t, p1, p2) {
16
+ const c = 3 * p1;
17
+ const b = 3 * (p2 - p1) - c;
18
+ const a = 1 - c - b;
19
+ return (3 * a * t + 2 * b) * t + c;
20
+ }
21
+ /** The Bezier parameter whose `x` is `x` in `(0, 1)` (mirrors `CubicBezier::parameter_at`). */
22
+ function parameterAt(x, x1, x2) {
23
+ let parameter = x;
24
+ for (let step = 0; step < NEWTON_STEPS; step += 1) {
25
+ const error = component(parameter, x1, x2) - x;
26
+ if (Math.abs(error) < TOLERANCE) {
27
+ if (parameter >= 0 && parameter <= 1)
28
+ return parameter;
29
+ break;
30
+ }
31
+ const steepness = slope(parameter, x1, x2);
32
+ if (Math.abs(steepness) < MIN_SLOPE)
33
+ break;
34
+ parameter -= error / steepness;
35
+ }
36
+ let low = 0;
37
+ let high = 1;
38
+ parameter = x;
39
+ for (let step = 0; step < BISECTION_STEPS; step += 1) {
40
+ const value = component(parameter, x1, x2);
41
+ if (Math.abs(value - x) < TOLERANCE)
42
+ break;
43
+ if (value < x)
44
+ low = parameter;
45
+ else
46
+ high = parameter;
47
+ parameter = low + (high - low) * 0.5;
48
+ }
49
+ return parameter;
50
+ }
51
+ /** Mirrors `CubicBezier::apply`. */
52
+ function apply(curve, progress) {
53
+ const x = Math.min(1, Math.max(0, progress));
54
+ if (x <= 0)
55
+ return 0;
56
+ if (x >= 1)
57
+ return 1;
58
+ const parameter = parameterAt(x, Math.fround(curve.x1), Math.fround(curve.x2));
59
+ return component(parameter, Math.fround(curve.y1), Math.fround(curve.y2));
60
+ }
61
+ function blossom(points, u, v, w) {
62
+ const lerp = (a, b, t) => a + (b - a) * t;
63
+ const first = [
64
+ lerp(points[0], points[1], u),
65
+ lerp(points[1], points[2], u),
66
+ lerp(points[2], points[3], u),
67
+ ];
68
+ return lerp(lerp(first[0], first[1], v), lerp(first[1], first[2], v), w);
69
+ }
70
+ /** The part of `curve` between linear progress `from` and `to`, rescaled (mirrors `between`). */
71
+ function between(curve, from, to) {
72
+ const x1 = Math.fround(curve.x1);
73
+ const x2 = Math.fround(curve.x2);
74
+ const at = (progress) => progress <= 0 ? 0 : progress >= 1 ? 1 : parameterAt(progress, x1, x2);
75
+ const [u, v] = [at(from), at(to)];
76
+ const part = (p1, p2) => {
77
+ const points = [0, p1, p2, 1];
78
+ return [
79
+ blossom(points, u, u, u),
80
+ blossom(points, u, u, v),
81
+ blossom(points, u, v, v),
82
+ blossom(points, v, v, v),
83
+ ];
84
+ };
85
+ const x = part(x1, x2);
86
+ const y = part(Math.fround(curve.y1), Math.fround(curve.y2));
87
+ const width = x[3] - x[0];
88
+ const height = y[3] - y[0];
89
+ if (!(width > 0) || height === 0)
90
+ return undefined;
91
+ const unit = (value) => Math.min(1, Math.max(0, value));
92
+ const result = {
93
+ type: "cubic_bezier",
94
+ x1: shortestFloat32(unit((x[1] - x[0]) / width)),
95
+ y1: shortestFloat32((y[1] - y[0]) / height),
96
+ x2: shortestFloat32(unit((x[2] - x[0]) / width)),
97
+ y2: shortestFloat32((y[2] - y[0]) / height),
98
+ };
99
+ return [result.x1, result.y1, result.x2, result.y2].every(Number.isFinite)
100
+ ? result
101
+ : undefined;
102
+ }
103
+ /** The value of keyframes `keys` at `tick` (mirrors the scalar keyframe sampler). */
104
+ function valueAt(keys, tick) {
105
+ let next = 0;
106
+ for (let high = keys.length; next < high;) {
107
+ const middle = (next + high) >> 1;
108
+ if (keys[middle].time <= tick)
109
+ next = middle + 1;
110
+ else
111
+ high = middle;
112
+ }
113
+ if (next === 0)
114
+ return Math.fround(keys[0].value);
115
+ const left = keys[next - 1];
116
+ const right = keys[next];
117
+ if (!right || tick === left.time)
118
+ return Math.fround(left.value);
119
+ const progress = (tick - left.time) / (right.time - left.time);
120
+ const interpolation = left.interpolation;
121
+ const amount = interpolation.type === "hold"
122
+ ? undefined
123
+ : interpolation.type === "linear"
124
+ ? Math.min(1, Math.max(0, progress))
125
+ : apply(interpolation, progress);
126
+ if (amount === undefined)
127
+ return Math.fround(left.value);
128
+ const start = Math.fround(left.value);
129
+ const end = Math.fround(right.value);
130
+ return Math.fround(Math.min(F32_MAX, Math.max(-F32_MAX, start + (end - start) * amount)));
131
+ }
132
+ /** The interpolation showing the old curve from `from` to `to` (mirrors `part_of_curve`). */
133
+ function partOfCurve(keys, from, to) {
134
+ let next = 0;
135
+ while (next < keys.length && keys[next].time <= from)
136
+ next += 1;
137
+ const start = keys[next - 1];
138
+ const end = keys[next];
139
+ if (!start || !end)
140
+ return undefined;
141
+ const interpolation = start.interpolation;
142
+ if (interpolation.type !== "cubic_bezier")
143
+ return interpolation;
144
+ if (from === start.time && to === end.time)
145
+ return interpolation;
146
+ const span = end.time - start.time;
147
+ return (between(interpolation, (from - start.time) / span, (to - start.time) / span) ?? {
148
+ type: "linear",
149
+ });
150
+ }
151
+ function shiftOf(tick, removal) {
152
+ let shift = 0;
153
+ for (const [from, to] of removal)
154
+ shift += to <= tick ? to - from : from < tick ? tick - from : 0;
155
+ return shift;
156
+ }
157
+ /**
158
+ * Bus keyframes after `removal` leaves a rippled timeline: keys inside go, the rest move, the
159
+ * value at each cut is keyed on both sides, and every key takes the part of the old curve up to
160
+ * the next key (mirrors `shift_keys`).
161
+ */
162
+ export function closeKeys(animation, removal) {
163
+ if (animation?.mode !== "keyframes" || !removal.length)
164
+ return animation;
165
+ const old = animation.keyframes;
166
+ const removed = (tick) => removal.some(([from, to]) => from <= tick && tick < to);
167
+ const at = [];
168
+ old.forEach((key, index) => {
169
+ if (!removed(key.time))
170
+ at.push([key.time, index]);
171
+ });
172
+ for (const [from, to] of removal) {
173
+ if (from - 1 - shiftOf(from - 1, removal) >= 0)
174
+ at.push([from - 1, undefined]);
175
+ at.push([to, undefined]);
176
+ }
177
+ at.sort((a, b) => a[0] - b[0] || Number(a[1] === undefined) - Number(b[1] === undefined));
178
+ const unique = at.filter((entry, index) => index === 0 || at[index - 1][0] !== entry[0]);
179
+ const keyframes = unique.map(([tick, kept], position) => {
180
+ const next = unique[position + 1]?.[0];
181
+ const own = kept === undefined ? undefined : old[kept].interpolation;
182
+ const interpolation = next === undefined
183
+ ? (own ?? { type: "linear" })
184
+ : removal.some(([from, to]) => tick < from && to <= next)
185
+ ? { type: "hold" }
186
+ : (partOfCurve(old, tick, next) ?? own ?? { type: "linear" });
187
+ return {
188
+ time: tick - shiftOf(tick, removal),
189
+ value: kept === undefined
190
+ ? shortestFloat32(valueAt(old, tick))
191
+ : old[kept].value,
192
+ interpolation,
193
+ };
194
+ });
195
+ return { ...animation, keyframes };
196
+ }
197
+ /**
198
+ * Bus keyframes after `length` ticks open at `pivot`: keys at or after it move right, and when
199
+ * keys lie on both sides the value at `pivot` is held across the opening, so every moment outside
200
+ * it reads as before.
201
+ */
202
+ export function openKeys(animation, pivot, length) {
203
+ if (animation?.mode !== "keyframes" || !length)
204
+ return animation;
205
+ const old = animation.keyframes;
206
+ const before = old.filter((key) => key.time < pivot);
207
+ const after = old.filter((key) => key.time >= pivot);
208
+ const moved = after.map((key) => ({ ...key, time: key.time + length }));
209
+ if (!before.length || !after.length)
210
+ return { ...animation, keyframes: [...before, ...moved] };
211
+ const held = shortestFloat32(valueAt(old, pivot));
212
+ const last = before[before.length - 1];
213
+ const head = before.slice(0, -1);
214
+ const keyframes = [
215
+ ...head,
216
+ {
217
+ ...last,
218
+ interpolation: partOfCurve(old, last.time, pivot) ?? last.interpolation,
219
+ },
220
+ { time: pivot, value: held, interpolation: { type: "hold" } },
221
+ ];
222
+ if (after[0].time === pivot)
223
+ keyframes.push(...moved);
224
+ else
225
+ keyframes.push({
226
+ time: pivot + length,
227
+ value: held,
228
+ interpolation: partOfCurve(old, pivot, after[0].time) ?? {
229
+ type: "linear",
230
+ },
231
+ }, ...moved);
232
+ return { ...animation, keyframes };
233
+ }