@serimo/player 0.1.0 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,58 +1,294 @@
1
1
  "use client";
2
- import { validateComposition } from "@serimo/core/composition";
2
+ import { getAudioMixGain, getAudioTracks, validateComposition } from "@serimo/core/composition";
3
3
  import { createTimelineRegistry } from "@serimo/core/timeline-registry";
4
4
  import { createContext, createElement, forwardRef, isValidElement, useContext, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
5
5
  import { getFrameState } from "@serimo/core/clock";
6
6
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
- //#region src/player-session.ts
7
+ // src/composition-timing.ts
8
+ const CompositionFps = createContext(null);
9
+ // src/player-audio.ts
10
+ const MAX_PCM_BYTES = 268435456;
11
+ function inspectPCM(bytes, required) {
12
+ const invalid = () => /* @__PURE__ */ new Error("E_ASSET: prepared audio must be sufficient PCM16 48 kHz mono or stereo WAV");
13
+ if (bytes.byteLength < 44 || bytes.byteLength > MAX_PCM_BYTES) throw invalid();
14
+ const view = new DataView(bytes);
15
+ const text = (offset) => String.fromCharCode(...new Uint8Array(bytes, offset, 4));
16
+ if (text(0) !== "RIFF" || text(8) !== "WAVE" || view.getUint32(4, true) + 8 !== bytes.byteLength) throw invalid();
17
+ let channels = 0;
18
+ let dataBytes = 0;
19
+ for (let offset = 12; offset + 8 <= bytes.byteLength;) {
20
+ const size = view.getUint32(offset + 4, true);
21
+ if (offset + 8 + size > bytes.byteLength) throw invalid();
22
+ if (text(offset) === "fmt ") {
23
+ if (channels || size < 16 || view.getUint16(offset + 8, true) !== 1 || view.getUint32(offset + 12, true) !== 48e3 || view.getUint16(offset + 22, true) !== 16) throw invalid();
24
+ channels = view.getUint16(offset + 10, true);
25
+ if (channels !== 1 && channels !== 2 || view.getUint16(offset + 20, true) !== channels * 2 || view.getUint32(offset + 16, true) !== 48e3 * channels * 2) throw invalid();
26
+ }
27
+ if (text(offset) === "data") {
28
+ if (dataBytes) throw invalid();
29
+ dataBytes = size;
30
+ }
31
+ offset += 8 + size + size % 2;
32
+ }
33
+ const samples = dataBytes / (channels * 2);
34
+ if (!channels || !Number.isSafeInteger(samples) || samples < required) throw invalid();
35
+ return {
36
+ channels,
37
+ samples
38
+ };
39
+ }
40
+ async function readPCM(src, signal) {
41
+ const response = await fetch(src, {
42
+ signal,
43
+ credentials: "omit"
44
+ });
45
+ if (!response.ok || !response.body || Number(response.headers.get("content-length") ?? 0) > MAX_PCM_BYTES) throw new Error("E_ASSET: prepared PCM audio unavailable or too large");
46
+ const native = response.clone();
47
+ const reader = response.body.getReader();
48
+ let size = 0;
49
+ try {
50
+ while (true) {
51
+ signal.throwIfAborted();
52
+ const { done, value } = await reader.read();
53
+ if (done) break;
54
+ size += value.byteLength;
55
+ if (size > MAX_PCM_BYTES) throw new Error("E_ASSET: prepared PCM audio exceeds its size limit");
56
+ }
57
+ } catch (error) {
58
+ await Promise.allSettled([reader.cancel(), native.body?.cancel()]);
59
+ throw error;
60
+ } finally {
61
+ reader.releaseLock();
62
+ }
63
+ const bytes = await native.arrayBuffer();
64
+ if (bytes.byteLength !== size) throw new Error("E_ASSET: prepared PCM byte count changed");
65
+ return bytes;
66
+ }
67
+ function createPlayerAudio(composition, signal) {
68
+ const tracks = getAudioTracks(composition.audio);
69
+ if (!tracks.length) throw new Error("E_ASSET: audio declaration missing");
70
+ const context = new AudioContext({ sampleRate: 48e3 });
71
+ const controller = new AbortController();
72
+ const activeSignal = AbortSignal.any([signal, controller.signal]);
73
+ const gains = tracks.map((track) => {
74
+ const gain = context.createGain();
75
+ gain.gain.value = track.volume;
76
+ return gain;
77
+ });
78
+ const master = context.createGain();
79
+ master.gain.value = getAudioMixGain(tracks);
80
+ master.channelCountMode = "explicit";
81
+ master.channelInterpretation = "speakers";
82
+ master.connect(context.destination);
83
+ for (const gain of gains) gain.connect(master);
84
+ const sources = /* @__PURE__ */ new Set();
85
+ const buffers = /* @__PURE__ */ new Map();
86
+ let version = 0;
87
+ let disposed = false;
88
+ let closing;
89
+ const pause = () => {
90
+ version++;
91
+ for (const source of sources) {
92
+ source.stop();
93
+ source.disconnect();
94
+ }
95
+ sources.clear();
96
+ };
97
+ activeSignal.addEventListener("abort", pause, { once: true });
98
+ const dispose = () => {
99
+ if (closing) return closing;
100
+ pause();
101
+ disposed = true;
102
+ controller.abort();
103
+ for (const gain of gains) gain.disconnect();
104
+ master.disconnect();
105
+ buffers.clear();
106
+ activeSignal.removeEventListener("abort", pause);
107
+ return closing = context.state === "closed" ? Promise.resolve() : context.close();
108
+ };
109
+ return {
110
+ ready: (async () => {
111
+ activeSignal.throwIfAborted();
112
+ let bytesTotal = 0;
113
+ let channels = 1;
114
+ for (const track of tracks) {
115
+ const required = Math.ceil(track.durationInFrames * 48e3 / composition.fps);
116
+ let decoded = buffers.get(track.src);
117
+ if (!decoded) {
118
+ const bytes = await readPCM(track.src, activeSignal);
119
+ bytesTotal += bytes.byteLength;
120
+ if (bytesTotal > MAX_PCM_BYTES * 2) throw new Error("E_ASSET: prepared PCM audio exceeds its session size limit");
121
+ const pcm = inspectPCM(bytes, required);
122
+ decoded = await context.decodeAudioData(bytes);
123
+ activeSignal.throwIfAborted();
124
+ if (decoded.sampleRate !== 48e3 || decoded.numberOfChannels !== pcm.channels || decoded.length !== pcm.samples) throw new Error("E_ASSET: decoded PCM audio does not match its prepared samples");
125
+ buffers.set(track.src, decoded);
126
+ }
127
+ if (decoded.length < required) throw new Error("E_ASSET: prepared PCM audio is shorter than its declared track");
128
+ channels = Math.max(channels, decoded.numberOfChannels);
129
+ }
130
+ master.channelCount = channels;
131
+ })().catch(async (error) => {
132
+ await dispose();
133
+ if (error instanceof Error && error.message.startsWith("E_ASSET:")) throw error;
134
+ throw new Error("E_ASSET: prepared PCM audio failed to load or decode", { cause: error });
135
+ }),
136
+ pause,
137
+ dispose,
138
+ play(frame) {
139
+ try {
140
+ getFrameState({
141
+ ...composition,
142
+ audio: void 0
143
+ }, frame);
144
+ activeSignal.throwIfAborted();
145
+ if (disposed || tracks.some((track) => !buffers.has(track.src))) throw new Error("E_ASSET: audio is not ready");
146
+ } catch (error) {
147
+ return Promise.reject(error);
148
+ }
149
+ pause();
150
+ const generation = version;
151
+ const resume = context.resume();
152
+ return (async () => {
153
+ let timer;
154
+ const check = () => {
155
+ if (generation !== version || disposed || activeSignal.aborted) throw new DOMException("Stale audio playback", "AbortError");
156
+ };
157
+ try {
158
+ const stamp = await Promise.race([resume.then(async () => {
159
+ while (true) {
160
+ check();
161
+ const stamp = context.getOutputTimestamp();
162
+ if (Number.isFinite(stamp.contextTime) && Number.isFinite(stamp.performanceTime) && stamp.contextTime > 0 && stamp.performanceTime > 0) return stamp;
163
+ await new Promise((resolve) => setTimeout(resolve, 10));
164
+ }
165
+ }), new Promise((_resolve, reject) => {
166
+ timer = setTimeout(() => {
167
+ if (generation === version) pause();
168
+ reject(/* @__PURE__ */ new Error("E_ASSET: audio activation blocked or output clock unavailable"));
169
+ }, 1e3);
170
+ })]);
171
+ check();
172
+ const start = context.currentTime + .05;
173
+ const seconds = frame / composition.fps;
174
+ for (const [index, track] of tracks.entries()) {
175
+ const offset = Math.max(0, seconds - track.startFrame / composition.fps);
176
+ const remaining = track.durationInFrames / composition.fps - offset;
177
+ if (remaining > 0) {
178
+ const source = context.createBufferSource();
179
+ source.buffer = buffers.get(track.src) ?? null;
180
+ const gain = gains[index];
181
+ if (!gain) throw new Error("E_ASSET: audio gain unavailable");
182
+ source.connect(gain);
183
+ source.onended = () => {
184
+ if (sources.delete(source)) source.disconnect();
185
+ };
186
+ try {
187
+ source.start(start + Math.max(0, track.startFrame / composition.fps - seconds), offset, remaining);
188
+ sources.add(source);
189
+ } catch (error) {
190
+ source.disconnect();
191
+ throw error;
192
+ }
193
+ }
194
+ }
195
+ return { originTimeMs: performance.timeOrigin + stamp.performanceTime + (start - stamp.contextTime) * 1e3 };
196
+ } catch (error) {
197
+ if (generation === version) pause();
198
+ throw error;
199
+ } finally {
200
+ clearTimeout(timer);
201
+ }
202
+ })();
203
+ }
204
+ };
205
+ }
206
+ // src/player-session.ts
8
207
  function createPlayerSession(composition, registry) {
9
208
  let current;
209
+ const stop = () => {
210
+ const active = current;
211
+ current = void 0;
212
+ active?.controller.abort(new DOMException("Player unmounted", "AbortError"));
213
+ return active?.audio?.dispose() ?? Promise.resolve();
214
+ };
10
215
  const handle = {
11
216
  whenReady() {
12
217
  return current?.ready ?? Promise.reject(/* @__PURE__ */ new Error("Player is not mounted"));
13
218
  },
14
219
  async seek(frame) {
15
220
  getFrameState(composition, frame);
221
+ const active = current;
16
222
  await handle.whenReady();
17
- if (!current) throw new Error("Player is not mounted");
223
+ if (!active || current !== active) throw new Error("Player is not mounted");
224
+ active.controller.signal.throwIfAborted();
18
225
  registry.seek(frame);
19
226
  },
20
227
  getComposition() {
21
- const { id, width, height, fps, durationInFrames } = composition;
228
+ const { id, width, height, fps, durationInFrames, audio } = composition;
22
229
  return {
23
230
  id,
24
231
  width,
25
232
  height,
26
233
  fps,
27
- durationInFrames
234
+ durationInFrames,
235
+ ...audio ? { audio: Array.isArray(audio) ? audio.map((track) => ({ ...track })) : { ...audio } } : {}
28
236
  };
29
- }
237
+ },
238
+ ...composition.audio ? { audio: {
239
+ play(frame) {
240
+ if (!current || current.controller.signal.aborted) return Promise.reject(/* @__PURE__ */ new Error("Player is not mounted"));
241
+ if (!current.audio) return Promise.reject(/* @__PURE__ */ new Error("E_ASSET: audio is not ready"));
242
+ return current.audio.play(frame);
243
+ },
244
+ pause() {
245
+ current?.audio?.pause();
246
+ }
247
+ } } : {}
30
248
  };
31
249
  return {
32
250
  ...handle,
33
251
  start() {
34
252
  const controller = new AbortController();
253
+ stop().catch((error) => controller.abort(error));
254
+ const active = {
255
+ controller,
256
+ ready: Promise.resolve()
257
+ };
258
+ current = active;
35
259
  const timeout = setTimeout(() => {
36
260
  controller.abort(/* @__PURE__ */ new Error("Player timelines were not ready within 10000ms"));
37
261
  }, 1e4);
38
- const ready = registry.whenReady({ signal: controller.signal }).then(() => {
262
+ const abortReady = () => rejectReady(controller.signal.reason);
263
+ let rejectReady = () => {};
264
+ const cancelled = new Promise((_resolve, reject) => {
265
+ rejectReady = reject;
266
+ });
267
+ controller.signal.addEventListener("abort", abortReady, { once: true });
268
+ const ready = Promise.race([cancelled, Promise.all([registry.whenReady({ signal: controller.signal }), Promise.resolve().then(() => {
269
+ controller.signal.throwIfAborted();
270
+ if (composition.audio) {
271
+ active.audio = createPlayerAudio(composition, controller.signal);
272
+ return active.audio.ready;
273
+ }
274
+ })])]).then(() => {
39
275
  controller.signal.throwIfAborted();
40
276
  registry.seek(0);
41
- }).finally(() => clearTimeout(timeout));
42
- current = {
43
- controller,
44
- ready
45
- };
277
+ }).catch(async (error) => {
278
+ controller.abort(error);
279
+ await active.audio?.dispose();
280
+ throw error;
281
+ }).finally(() => {
282
+ clearTimeout(timeout);
283
+ controller.signal.removeEventListener("abort", abortReady);
284
+ });
285
+ active.ready = ready;
46
286
  return ready;
47
287
  },
48
- stop() {
49
- current?.controller.abort(new DOMException("Player unmounted", "AbortError"));
50
- current = void 0;
51
- }
288
+ stop
52
289
  };
53
290
  }
54
- //#endregion
55
- //#region ../../node_modules/clsx/dist/clsx.mjs
291
+ // ../../node_modules/clsx/dist/clsx.mjs
56
292
  function r(e) {
57
293
  var t, f, n = "";
58
294
  if ("string" == typeof e || "number" == typeof e) n += e;
@@ -66,8 +302,7 @@ function clsx() {
66
302
  for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
67
303
  return n;
68
304
  }
69
- //#endregion
70
- //#region ../../node_modules/class-variance-authority/dist/index.mjs
305
+ // ../../node_modules/class-variance-authority/dist/index.mjs
71
306
  /**
72
307
  * Copyright 2022 Joe Bell. All rights reserved.
73
308
  *
@@ -120,8 +355,7 @@ const cva = (base, config) => (props) => {
120
355
  }, []);
121
356
  return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
122
357
  };
123
- //#endregion
124
- //#region ../../node_modules/cn/dist/tables.js
358
+ // ../../node_modules/cn/dist/tables.js
125
359
  const P = 48;
126
360
  const U = (s, o = 0) => {
127
361
  const out = new Int32Array(s.length);
@@ -183,20 +417,20 @@ const nodeVlist = (() => {
183
417
  for (let i = 0; i < A.length; i++) out[A[i]] = V[i];
184
418
  return out;
185
419
  })();
186
- const SETS = "container |break-after- all auto avoid avoid-page column left page right|break-before- all auto avoid avoid-page column left page right|break-inside-a uto void void-column void-page|box-decoration- clone slice|box- border content| contents flow-root hidden table table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group| not-sr-only sr-only|float- end left none right start|clear- both end left none right start|isolat e ion-auto|overflow- auto clip hidden scroll visible|overflow-x- auto clip hidden scroll visible|overflow-y- auto clip hidden scroll visible|overscroll- auto contain none|overscroll-x- auto contain none|overscroll-y- auto contain none| absolute fixed relative static sticky| collapse invisible visible|justify- around baseline between center center-safe end end-safe evenly normal start stretch|justify-items- center center-safe end end-safe normal start stretch|justify-self- auto center center-safe end end-safe start stretch|items- baseline baseline-last center center-safe end end-safe start stretch|self- auto baseline baseline-last center center-safe end end-safe start stretch|place-content- around baseline between center center-safe end end-safe evenly start stretch|place-items- baseline center center-safe end end-safe start stretch|place-self- auto center center-safe end end-safe start stretch| antialiased subpixel-antialiased| italic not-italic|normal-nums |ordinal |slashed-zero | lining-nums oldstyle-nums| proportional-nums tabular-nums| diagonal-fractions stacked-fractions| no-underline overline| capitalize lowercase normal-case uppercase|truncate |whitespace- break-spaces normal nowrap pre pre-line pre-wrap|break- all keep normal words|wrap- anywhere break-word normal|hyphens- auto manual none|mix-blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay plus-darker plus-lighter saturation screen soft-light|table- auto fixed|caption- bottom top|backface- hidden visible|appearance- auto none|scheme- dark light light-dark normal only-dark only-light|field-sizing- content fixed|pointer-events- auto none|resize -none -x -y|snap- align-none center end start|snap- always normal|snap- both none x y|snap- mandatory proximity|touch- auto manipulation none|touch-pan- left right x|touch-pan- down up y|touch-pinch-zoom |select- all auto none text|forced-color-adjust- auto none| normal size| baseline bottom middle sub super text-bottom text-top top| bounce none ping pulse spin| auto square video| auto fr max min px|none | auto full px| fixed local scroll|clip- border content padding text|origin- border content padding| bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| no-repeat repeat repeat-round repeat-space repeat-x repeat-y| auto contain cover| gradient-to-b gradient-to-bl gradient-to-br gradient-to-l gradient-to-r gradient-to-t gradient-to-tl gradient-to-tr none|blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay saturation screen soft-light|to- b bl br l r t tl tr| auto dvh fit full lh lvh max min px screen svh| dashed dotted double hidden none solid| collapse separate|px |auto |full | content none strict| inline-size size|layout |paint |style | around baseline between center center-safe end end-safe evenly normal start stretch| alias all-scroll auto cell col-resize context-menu copy crosshair default e-resize ew-resize grab grabbing help move n-resize ne-resize nesw-resize no-drop none not-allowed ns-resize nw-resize nwse-resize pointer progress row-resize s-resize se-resize sw-resize text vertical-text w-resize wait zoom-in zoom-out| dashed dotted double solid wavy| auto from-font|reverse |initial | in in-out initial linear out| col col-reverse row row-reverse| nowrap wrap wrap-reverse| auto initial none| black bold extrabold extralight light medium normal semibold thin| condensed expanded extra-condensed extra-expanded normal semi-condensed semi-expanded ultra-condensed ultra-expanded|flow- col col-dense dense row row-dense| none subgrid| auto dvh dvw fit full lh lvh lvw max min px screen svh svw| block flex grid table| auto dvw fit full lvw max min px screen svw| loose none normal px relaxed snug tight|through |item | inside outside| decimal disc none| auto px| clip-border clip-content clip-fill clip-padding clip-stroke clip-view no-clip| add exclude intersect subtract| alpha luminance match|origin- border content fill padding stroke view|type- alpha luminance| circle ellipse| closest-corner closest-side farthest-corner farthest-side|at- bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| dvh fit full lh lvh max min none px screen svh| auto dvh dvw fit full lh lvh lvw max min none px screen svh svw| dvw fit full lvw max min none px screen svw| auto dvh dvw fit full lvh lvw max min none prose px svh svw| auto dvh dvw fit full lvh lvw max min none px screen svh svw| contain cover fill none scale-down| first last none| distant dramatic midrange near none normal|inset | full none|3d | auto smooth|gutter- auto both stable| auto none thin| inner none| auto dvh dvw fit full lvh lvw max min px svh svw|base | center end justify left right start| clip ellipsis| balance nowrap pretty wrap| normal tight tighter wide wider widest| cpu gpu none| 3d flat| all colors none opacity shadow transform| discrete normal| full px| auto dvh dvw fit full lvh lvw max min px screen svh svw| auto contents scroll transform".split("|").map((s) => {
420
+ const SETS = "container |break-after- all auto avoid avoid-page column left page right|break-before- all auto avoid avoid-page column left page right|break-inside-a uto void void-column void-page|box-decoration- clone slice|box- border content| contents flow-root hidden table table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group| not-sr-only sr-only|float- end left none right start|clear- both end left none right start|isolat e ion-auto|overflow- auto clip hidden scroll visible|overflow-x- auto clip hidden scroll visible|overflow-y- auto clip hidden scroll visible|overscroll- auto contain none|overscroll-x- auto contain none|overscroll-y- auto contain none| absolute fixed relative static sticky| collapse invisible visible|justify- around baseline between center center-safe end end-safe evenly normal start stretch|justify-items- center center-safe end end-safe normal start stretch|justify-self- auto center center-safe end end-safe start stretch|items- baseline baseline-last center center-safe end end-safe start stretch|self- auto baseline baseline-last center center-safe end end-safe start stretch|place-content- around baseline between center center-safe end end-safe evenly start stretch|place-items- baseline center center-safe end end-safe start stretch|place-self- auto center center-safe end end-safe start stretch| antialiased subpixel-antialiased| italic not-italic|normal-nums |ordinal |slashed-zero | lining-nums oldstyle-nums| proportional-nums tabular-nums| diagonal-fractions stacked-fractions| no-underline overline| capitalize lowercase normal-case uppercase|truncate |whitespace- break-spaces normal nowrap pre pre-line pre-wrap|break- all keep normal words|wrap- anywhere break-word normal|hyphens- auto manual none|mix-blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay plus-darker plus-lighter saturation screen soft-light|table- auto fixed|caption- bottom top|backface- hidden visible|appearance- auto none|scheme- dark light light-dark normal only-dark only-light|field-sizing- content fixed|pointer-events- auto none|resize -none -x -y|snap- align-none center end start|snap- always normal|snap- both none x y|snap- mandatory proximity|touch- auto manipulation none|touch-pan- left right x|touch-pan- down up y|touch-pinch-zoom |select- all auto none text|forced-color-adjust- auto none| normal size| baseline bottom middle sub super text-bottom text-top top| bounce none ping pulse spin| auto square video| auto fr max min px|none | auto full px| fixed local scroll|clip- border content padding text|origin- border content padding| bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| no-repeat repeat repeat-round repeat-space repeat-x repeat-y| auto contain cover|blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay saturation screen soft-light|to- b bl br l r t tl tr| auto dvh fit full lh lvh max min px screen svh| dashed dotted double hidden none solid| collapse separate|px |auto |full | content none strict| inline-size size|layout |paint |style | around baseline between center center-safe end end-safe evenly normal start stretch| alias all-scroll auto cell col-resize context-menu copy crosshair default e-resize ew-resize grab grabbing help move n-resize ne-resize nesw-resize no-drop none not-allowed ns-resize nw-resize nwse-resize pointer progress row-resize s-resize se-resize sw-resize text vertical-text w-resize wait zoom-in zoom-out| dashed dotted double solid wavy| auto from-font|reverse |initial | in in-out initial linear out| col col-reverse row row-reverse| nowrap wrap wrap-reverse| auto initial none| black bold extrabold extralight light medium normal semibold thin| condensed expanded extra-condensed extra-expanded normal semi-condensed semi-expanded ultra-condensed ultra-expanded|flow- col col-dense dense row row-dense| none subgrid| auto dvh dvw fit full lh lvh lvw max min px screen svh svw| block flex grid table| auto dvw fit full lvw max min px screen svw| loose none normal px relaxed snug tight|through |item | inside outside| decimal disc none| auto px| clip-border clip-content clip-fill clip-padding clip-stroke clip-view no-clip| add exclude intersect subtract| alpha luminance match|origin- border content fill padding stroke view|type- alpha luminance| circle ellipse| closest-corner closest-side farthest-corner farthest-side|at- bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| dvh fit full lh lvh max min none px screen svh| auto dvh dvw fit full lh lvh lvw max min none px screen svh svw| dvw fit full lvw max min none px screen svw| auto dvh dvw fit full lvh lvw max min none prose px svh svw| auto dvh dvw fit full lvh lvw max min none px screen svh svw| contain cover fill none scale-down| first last none| distant dramatic midrange near none normal|inset | full none|3d | auto smooth|gutter- auto both stable| auto none thin| inner none| auto dvh dvw fit full lvh lvw max min px svh svw|base | center end justify left right start| clip ellipsis| balance nowrap pretty wrap| normal tight tighter wide wider widest| cpu gpu none| 3d flat| all colors none opacity shadow transform| discrete normal| full px| auto dvh dvw fit full lvh lvw max min px screen svh svw| auto contents scroll transform".split("|").map((s) => {
187
421
  const tails = s.split(" ");
188
422
  const prefix = tails.shift();
189
423
  for (let i = 0; i < tails.length; i++) tails[i] = prefix + tails[i];
190
424
  return tails;
191
425
  });
192
426
  const AA = DZ("0000000000000000000000000000000000000000000000000000000000000262242:6@200000006:240B428:4422400002046044222426220026642642462026224222824220022400000000\\00N222422242222222224062242222222422226264222422222222222222442804222422222222222222222222220<4<0204260002444020204224422");
193
- const AG = DZ("ɠ222222222222222222222222222222222222222222222222222222222222˕4222226>ʶ22ʷʺʷ2ʸʷ42ʴ2ʓ22>621422ɶ222ɹɼɷɺɷɺ22ɱ42222ɨ2ɧ26622ɘɓ244ƸƵ222]d24242ǖǓƚÄȫ2263ȨȥȨ2222222ǣ222222222222222222ǂƽ2ƾƵ2222222422222ƜƑ22222222222222222222144Ŧţ22Ţş222222222222222222222ĸ2ı68ĦģĦɡŰ4Ġ«®ĝ822ĔđĔ2ē2222622");
194
- const AS = DZ("02222222222222222222222222222222222222222222222222222222222222222202022222222222EH2200IL021042222Y\\222IL0cf2e10j2222U00X202[^2y0000120|{~‚22…ˆ‡:22|22222222222G000q†OVI00000}š2›>40000ŒB00000I¨©000¬00000000000000021M®­00°“000000000000000000000–222›HGHa1º222¿2À2222ÉÌ000­°2±");
195
- const litAnchor = /* @__PURE__ */ new Int32Array(995);
196
- const litGroup = /* @__PURE__ */ new Int32Array(995);
197
- const litPool = /* @__PURE__ */ new Int32Array(995);
427
+ const AG = DZ("ɠ222222222222222222222222222222222222222222222222222222222222˕4222226>6ʰ22ʷʺʷʺʷ42ʴ2ʓ22>621422ɶ222ɹɼɷɺɷɺ22ɱ42222ɨ2ɧ26622ɘɓ244ƸƵ222]d24242ǖǓƚÄȫ2263ȨȥȨ2222222ǣ222222222222222222ǂƽ2ƾƵ2222222422222ƜƑ22222222222222222222144Ŧţ22Ţş222222222222222222222ĸ2ı68ĦģĦɡŰ4Ġ«®ĝ822ĔđĔ2ē2222622");
428
+ const AS = DZ("02222222222222222222222222222222222222222222222222222222222222222202021422222222CF2200GJ021042222WZ222IL0ad2c10h2222U00X202[^2w0000120zy|}€22ƒ†…:22z22222222222G000q†OVI00000{˜2™<40000Œ›@00000G¦§000ª00000000000000021K¬«00®“000000000000000000000–222›HGH_1¸222½2¾2222ÇÊ000­°2±");
429
+ const litAnchor = /* @__PURE__ */ new Int32Array(987);
430
+ const litGroup = /* @__PURE__ */ new Int32Array(987);
431
+ const litPool = /* @__PURE__ */ new Int32Array(987);
198
432
  let poolText = "";
199
- const poolOffsets = /* @__PURE__ */ new Int32Array(1038);
433
+ const poolOffsets = /* @__PURE__ */ new Int32Array(1022);
200
434
  {
201
435
  const tailRef = /* @__PURE__ */ new Map();
202
436
  let nextRef = 0;
@@ -248,8 +482,7 @@ var tables_generated_default = {
248
482
  postfixLookupGroups,
249
483
  orderSensitiveModifiers: "* ** after backdrop before details-content file first-letter first-line marker placeholder selection"
250
484
  };
251
- //#endregion
252
- //#region ../../node_modules/cn/dist/engine.js
485
+ // ../../node_modules/cn/dist/engine.js
253
486
  const IS_JSC = "line" in /* @__PURE__ */ new Error();
254
487
  const EXTERNAL = -1;
255
488
  const DEAD = -1;
@@ -1276,8 +1509,7 @@ const wrapClsx = (mergeString, fresh) => {
1276
1509
  return resolveArgs(vals, true);
1277
1510
  };
1278
1511
  };
1279
- //#endregion
1280
- //#region ../../node_modules/cn/dist/index.js
1512
+ // ../../node_modules/cn/dist/index.js
1281
1513
  const instance = /* @__PURE__ */ createEngine(tables_generated_default);
1282
1514
  /**
1283
1515
  * Merge Tailwind CSS classes with clsx-style arguments (strings, arrays,
@@ -1285,8 +1517,7 @@ const instance = /* @__PURE__ */ createEngine(tables_generated_default);
1285
1517
  */
1286
1518
  const cn = /* @__PURE__ */ wrapClsx(instance.mergeString, instance);
1287
1519
  instance.merge;
1288
- //#endregion
1289
- //#region ../ui/src/components/alert.tsx
1520
+ // ../ui/src/components/alert.tsx
1290
1521
  const alertVariants = cva("group/alert relative grid w-full gap-0.5 rounded-lg border px-2.5 py-2 text-start text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pe-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4", {
1291
1522
  variants: { variant: {
1292
1523
  default: "bg-card text-card-foreground",
@@ -1316,19 +1547,17 @@ function AlertDescription({ className, ...props }) {
1316
1547
  ...props
1317
1548
  });
1318
1549
  }
1319
- //#endregion
1320
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
1550
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
1321
1551
  /**
1322
- * @license lucide-react v1.61.0 - ISC
1552
+ * @license lucide-react v1.70.0 - ISC
1323
1553
  *
1324
1554
  * This source code is licensed under the ISC license.
1325
1555
  * See the LICENSE file in the root directory of this source tree.
1326
1556
  */
1327
1557
  const toKebabCase = (string) => string?.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
1328
- //#endregion
1329
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/toLucideIconData.mjs
1558
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toLucideIconData.mjs
1330
1559
  /**
1331
- * @license lucide-react v1.61.0 - ISC
1560
+ * @license lucide-react v1.70.0 - ISC
1332
1561
  *
1333
1562
  * This source code is licensed under the ISC license.
1334
1563
  * See the LICENSE file in the root directory of this source tree.
@@ -1342,10 +1571,9 @@ function toLucideIconData(iconName, iconNode, aliases = []) {
1342
1571
  ...aliases.length > 0 ? { aliases } : {}
1343
1572
  };
1344
1573
  }
1345
- //#endregion
1346
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
1574
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
1347
1575
  /**
1348
- * @license lucide-react v1.61.0 - ISC
1576
+ * @license lucide-react v1.70.0 - ISC
1349
1577
  *
1350
1578
  * This source code is licensed under the ISC license.
1351
1579
  * See the LICENSE file in the root directory of this source tree.
@@ -1364,10 +1592,9 @@ const toCamelCase = (string) => {
1364
1592
  }
1365
1593
  return out;
1366
1594
  };
1367
- //#endregion
1368
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
1595
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
1369
1596
  /**
1370
- * @license lucide-react v1.61.0 - ISC
1597
+ * @license lucide-react v1.70.0 - ISC
1371
1598
  *
1372
1599
  * This source code is licensed under the ISC license.
1373
1600
  * See the LICENSE file in the root directory of this source tree.
@@ -1376,10 +1603,9 @@ const toPascalCase = (string) => {
1376
1603
  const camelCase = toCamelCase(string);
1377
1604
  return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
1378
1605
  };
1379
- //#endregion
1380
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
1606
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
1381
1607
  /**
1382
- * @license lucide-react v1.61.0 - ISC
1608
+ * @license lucide-react v1.70.0 - ISC
1383
1609
  *
1384
1610
  * This source code is licensed under the ISC license.
1385
1611
  * See the LICENSE file in the root directory of this source tree.
@@ -1387,10 +1613,9 @@ const toPascalCase = (string) => {
1387
1613
  const mergeClasses = (...classes) => classes.filter((className, index, array) => {
1388
1614
  return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
1389
1615
  }).join(" ").trim();
1390
- //#endregion
1391
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/build/defaultAttributes.mjs
1616
+ // ../../node_modules/lucide-react/dist/esm/shared/src/build/defaultAttributes.mjs
1392
1617
  /**
1393
- * @license lucide-react v1.61.0 - ISC
1618
+ * @license lucide-react v1.70.0 - ISC
1394
1619
  *
1395
1620
  * This source code is licensed under the ISC license.
1396
1621
  * See the LICENSE file in the root directory of this source tree.
@@ -1406,10 +1631,9 @@ const defaultAttributes = {
1406
1631
  "stroke-linecap": "round",
1407
1632
  "stroke-linejoin": "round"
1408
1633
  };
1409
- //#endregion
1410
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconNode.mjs
1634
+ // ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconNode.mjs
1411
1635
  /**
1412
- * @license lucide-react v1.61.0 - ISC
1636
+ * @license lucide-react v1.70.0 - ISC
1413
1637
  *
1414
1638
  * This source code is licensed under the ISC license.
1415
1639
  * See the LICENSE file in the root directory of this source tree.
@@ -1461,10 +1685,9 @@ function buildLucideIconNode(icon, params = {}) {
1461
1685
  })
1462
1686
  ];
1463
1687
  }
1464
- //#endregion
1465
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconForReact.mjs
1688
+ // ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconForReact.mjs
1466
1689
  /**
1467
- * @license lucide-react v1.61.0 - ISC
1690
+ * @license lucide-react v1.70.0 - ISC
1468
1691
  *
1469
1692
  * This source code is licensed under the ISC license.
1470
1693
  * See the LICENSE file in the root directory of this source tree.
@@ -1482,10 +1705,9 @@ function buildLucideIconForReact(icon, params = {}) {
1482
1705
  }
1483
1706
  });
1484
1707
  }
1485
- //#endregion
1486
- //#region ../../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
1708
+ // ../../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
1487
1709
  /**
1488
- * @license lucide-react v1.61.0 - ISC
1710
+ * @license lucide-react v1.70.0 - ISC
1489
1711
  *
1490
1712
  * This source code is licensed under the ISC license.
1491
1713
  * See the LICENSE file in the root directory of this source tree.
@@ -1494,20 +1716,18 @@ const hasA11yProp = (props) => {
1494
1716
  for (const prop in props) if (prop.startsWith("aria-") || prop === "role" || prop === "title") return true;
1495
1717
  return false;
1496
1718
  };
1497
- //#endregion
1498
- //#region ../../node_modules/lucide-react/dist/esm/context.mjs
1719
+ // ../../node_modules/lucide-react/dist/esm/context.mjs
1499
1720
  /**
1500
- * @license lucide-react v1.61.0 - ISC
1721
+ * @license lucide-react v1.70.0 - ISC
1501
1722
  *
1502
1723
  * This source code is licensed under the ISC license.
1503
1724
  * See the LICENSE file in the root directory of this source tree.
1504
1725
  */
1505
1726
  const LucideContext = createContext({});
1506
1727
  const useLucideContext = () => useContext(LucideContext);
1507
- //#endregion
1508
- //#region ../../node_modules/lucide-react/dist/esm/Icon.mjs
1728
+ // ../../node_modules/lucide-react/dist/esm/Icon.mjs
1509
1729
  /**
1510
- * @license lucide-react v1.61.0 - ISC
1730
+ * @license lucide-react v1.70.0 - ISC
1511
1731
  *
1512
1732
  * This source code is licensed under the ISC license.
1513
1733
  * See the LICENSE file in the root directory of this source tree.
@@ -1535,10 +1755,9 @@ const Icon = forwardRef(({ color, size, width, height, strokeWidth, absoluteStro
1535
1755
  ...svgAttributes
1536
1756
  }, [...builtIconNode.map(([tag, attrs]) => createElement(tag, attrs)), ...Array.isArray(children) ? children : [children]]);
1537
1757
  });
1538
- //#endregion
1539
- //#region ../../node_modules/lucide-react/dist/esm/createLucideIcon.mjs
1758
+ // ../../node_modules/lucide-react/dist/esm/createLucideIcon.mjs
1540
1759
  /**
1541
- * @license lucide-react v1.61.0 - ISC
1760
+ * @license lucide-react v1.70.0 - ISC
1542
1761
  *
1543
1762
  * This source code is licensed under the ISC license.
1544
1763
  * See the LICENSE file in the root directory of this source tree.
@@ -1554,10 +1773,9 @@ function createLucideIcon(iconDataOrName, iconNode = [], aliases = []) {
1554
1773
  if (iconData.name) Component.displayName = toPascalCase(iconData.name);
1555
1774
  return Component;
1556
1775
  }
1557
- //#endregion
1558
- //#region ../../node_modules/lucide-react/dist/esm/icons/loader-circle.mjs
1776
+ // ../../node_modules/lucide-react/dist/esm/icons/loader-circle.mjs
1559
1777
  /**
1560
- * @license lucide-react v1.61.0 - ISC
1778
+ * @license lucide-react v1.70.0 - ISC
1561
1779
  *
1562
1780
  * This source code is licensed under the ISC license.
1563
1781
  * See the LICENSE file in the root directory of this source tree.
@@ -1573,8 +1791,7 @@ const __iconData = {
1573
1791
  };
1574
1792
  __iconData.node;
1575
1793
  const LoaderCircle = createLucideIcon(__iconData);
1576
- //#endregion
1577
- //#region ../ui/src/components/spinner.tsx
1794
+ // ../ui/src/components/spinner.tsx
1578
1795
  function Spinner({ className, ...props }) {
1579
1796
  return /* @__PURE__ */ jsx(LoaderCircle, {
1580
1797
  "data-slot": "spinner",
@@ -1584,8 +1801,7 @@ function Spinner({ className, ...props }) {
1584
1801
  ...props
1585
1802
  });
1586
1803
  }
1587
- //#endregion
1588
- //#region src/player-status.tsx
1804
+ // src/player-status.tsx
1589
1805
  function PlayerStatus({ state, error }) {
1590
1806
  if (state === "loading") return /* @__PURE__ */ jsx(Spinner, { "aria-label": "Composition loading" });
1591
1807
  if (state === "error") return /* @__PURE__ */ jsxs(Alert, {
@@ -1594,8 +1810,7 @@ function PlayerStatus({ state, error }) {
1594
1810
  });
1595
1811
  return null;
1596
1812
  }
1597
- //#endregion
1598
- //#region src/composition-player.tsx
1813
+ // src/composition-player.tsx
1599
1814
  function CompositionPlayer({ composition, components, ref }) {
1600
1815
  const { validated, registry, clips } = useMemo(() => {
1601
1816
  const validated = validateComposition(composition);
@@ -1638,7 +1853,8 @@ function CompositionPlayer({ composition, components, ref }) {
1638
1853
  useImperativeHandle(ref, () => ({
1639
1854
  whenReady: session.whenReady,
1640
1855
  seek: session.seek,
1641
- getComposition: session.getComposition
1856
+ getComposition: session.getComposition,
1857
+ ...session.audio ? { audio: session.audio } : {}
1642
1858
  }), [session]);
1643
1859
  useLayoutEffect(() => {
1644
1860
  let active = true;
@@ -1656,7 +1872,12 @@ function CompositionPlayer({ composition, components, ref }) {
1656
1872
  });
1657
1873
  return () => {
1658
1874
  active = false;
1659
- session.stop();
1875
+ session.stop().catch((error) => {
1876
+ window.dispatchEvent(new ErrorEvent("error", {
1877
+ error,
1878
+ message: "E_ASSET: audio shutdown failed"
1879
+ }));
1880
+ });
1660
1881
  };
1661
1882
  }, [session]);
1662
1883
  const currentStatus = status.session === session ? status : {
@@ -1671,22 +1892,26 @@ function CompositionPlayer({ composition, components, ref }) {
1671
1892
  height: validated.height,
1672
1893
  overflow: "hidden"
1673
1894
  },
1674
- children: clips
1895
+ children: /* @__PURE__ */ jsx(CompositionFps, {
1896
+ value: validated.fps,
1897
+ children: clips
1898
+ })
1675
1899
  }), /* @__PURE__ */ jsx(PlayerStatus, {
1676
1900
  state: currentStatus.state,
1677
1901
  error: currentStatus.error
1678
1902
  })] });
1679
1903
  }
1680
- //#endregion
1681
- //#region src/renderer-bridge.tsx
1904
+ // src/renderer-bridge.tsx
1682
1905
  function CompositionPlayerBridge(props) {
1683
1906
  const playerRef = useRef(null);
1684
1907
  useLayoutEffect(() => {
1685
1908
  const browserWindow = window;
1686
1909
  if (browserWindow.__serimoRenderer) throw new Error("Renderer bridge already installed");
1910
+ const installedPlayer = playerRef.current;
1911
+ let active = true;
1687
1912
  const currentPlayer = () => {
1688
1913
  const player = playerRef.current;
1689
- if (!player) throw new Error("Player is not mounted");
1914
+ if (!active || !player || player !== installedPlayer) throw new Error("Player is not mounted");
1690
1915
  return player;
1691
1916
  };
1692
1917
  const bridge = {
@@ -1698,17 +1923,634 @@ function CompositionPlayerBridge(props) {
1698
1923
  },
1699
1924
  getComposition() {
1700
1925
  return currentPlayer().getComposition();
1701
- }
1926
+ },
1927
+ ...installedPlayer?.audio ? { audio: {
1928
+ play(frame) {
1929
+ try {
1930
+ return currentPlayer().audio.play(frame);
1931
+ } catch (error) {
1932
+ return Promise.reject(error);
1933
+ }
1934
+ },
1935
+ pause() {
1936
+ if (active) installedPlayer.audio?.pause();
1937
+ }
1938
+ } } : {}
1702
1939
  };
1703
1940
  browserWindow.__serimoRenderer = bridge;
1704
1941
  return () => {
1942
+ active = false;
1943
+ installedPlayer?.audio?.pause();
1705
1944
  if (browserWindow.__serimoRenderer === bridge) delete browserWindow.__serimoRenderer;
1706
1945
  };
1707
- }, []);
1946
+ }, [props.composition, props.components]);
1708
1947
  return /* @__PURE__ */ jsx(CompositionPlayer, {
1709
1948
  ...props,
1710
1949
  ref: playerRef
1711
1950
  });
1712
1951
  }
1713
- //#endregion
1714
- export { CompositionPlayer, CompositionPlayerBridge };
1952
+ // src/image-resources.ts
1953
+ const stores = /* @__PURE__ */ new WeakMap();
1954
+ const MAX_DATA = 536870912;
1955
+ function imageStore(document) {
1956
+ let store = stores.get(document);
1957
+ if (!store) {
1958
+ store = {
1959
+ used: 0,
1960
+ queue: Promise.resolve(),
1961
+ entries: /* @__PURE__ */ new Map()
1962
+ };
1963
+ stores.set(document, store);
1964
+ }
1965
+ return store;
1966
+ }
1967
+ function reserveImageData(bytes, document = globalThis.document) {
1968
+ const store = imageStore(document);
1969
+ if (!Number.isSafeInteger(bytes) || bytes < 1 || store.used + bytes > MAX_DATA) throw Error("E_ASSET: image data budget exceeded");
1970
+ store.used += bytes;
1971
+ let released = false;
1972
+ return () => {
1973
+ if (!released) {
1974
+ released = true;
1975
+ store.used -= bytes;
1976
+ }
1977
+ };
1978
+ }
1979
+ function acquireImageFrame(frame, width, height, document = globalThis.document) {
1980
+ const fail = () => {
1981
+ throw Error("E_ASSET: invalid prepared image resource or data budget");
1982
+ };
1983
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192 || width * height > 16777216 || !Number.isSafeInteger(frame.bytes) || frame.bytes < 33 || frame.bytes > 134217728) fail();
1984
+ let url;
1985
+ try {
1986
+ url = new URL(frame.src, document.URL);
1987
+ } catch {
1988
+ return fail();
1989
+ }
1990
+ if (url.origin !== new URL(document.URL).origin || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) fail();
1991
+ const store = imageStore(document);
1992
+ const key = url.href;
1993
+ let resource = store.entries.get(key);
1994
+ if (resource) {
1995
+ if (resource.width !== width || resource.height !== height || resource.bytes !== frame.bytes) fail();
1996
+ resource.state.references++;
1997
+ } else {
1998
+ const surface = width * height * 4;
1999
+ if (store.used + surface > MAX_DATA) fail();
2000
+ store.used += surface;
2001
+ const state = {
2002
+ references: 1,
2003
+ controller: new AbortController(),
2004
+ complete: false,
2005
+ finished: false
2006
+ };
2007
+ const deadline = setTimeout(() => state.controller.abort(), 1e4);
2008
+ const finish = () => {
2009
+ if (state.finished) return;
2010
+ state.finished = true;
2011
+ state.bitmap?.close();
2012
+ store.used -= surface;
2013
+ if (store.entries.get(key)?.state === state) store.entries.delete(key);
2014
+ };
2015
+ const ready = store.queue.then(async () => {
2016
+ state.controller.signal.throwIfAborted();
2017
+ const temporary = frame.bytes * 2;
2018
+ if (store.used + temporary > MAX_DATA) fail();
2019
+ store.used += temporary;
2020
+ try {
2021
+ const response = await fetch(key, {
2022
+ signal: state.controller.signal,
2023
+ credentials: "omit",
2024
+ redirect: "error"
2025
+ });
2026
+ const claimed = response.headers.get("content-length");
2027
+ const body = response.body;
2028
+ if (!response.ok || !body || claimed !== null && Number(claimed) !== frame.bytes) return fail();
2029
+ const reader = body.getReader();
2030
+ const chunks = [];
2031
+ let received = 0;
2032
+ try {
2033
+ while (true) {
2034
+ const result = await reader.read();
2035
+ if (result.done) break;
2036
+ received += result.value.byteLength;
2037
+ if (received > frame.bytes) fail();
2038
+ chunks.push(result.value);
2039
+ }
2040
+ } finally {
2041
+ reader.releaseLock();
2042
+ }
2043
+ if (received !== frame.bytes) fail();
2044
+ const bytes = new Uint8Array(received);
2045
+ let offset = 0;
2046
+ for (const chunk of chunks) {
2047
+ bytes.set(chunk, offset);
2048
+ offset += chunk.length;
2049
+ }
2050
+ chunks.length = 0;
2051
+ const view = new DataView(bytes.buffer);
2052
+ if (bytes[0] !== 137 || bytes[1] !== 80 || bytes[2] !== 78 || bytes[3] !== 71 || view.getUint32(16) !== width || view.getUint32(20) !== height) fail();
2053
+ const bitmap = await createImageBitmap(new Blob([bytes.buffer], { type: "image/png" }));
2054
+ if (bitmap.width !== width || bitmap.height !== height || state.controller.signal.aborted) {
2055
+ bitmap.close();
2056
+ fail();
2057
+ }
2058
+ return bitmap;
2059
+ } finally {
2060
+ store.used -= temporary;
2061
+ }
2062
+ }).then((bitmap) => {
2063
+ state.complete = true;
2064
+ state.bitmap = bitmap;
2065
+ if (!state.references) finish();
2066
+ return bitmap;
2067
+ }, (error) => {
2068
+ state.complete = true;
2069
+ state.controller.abort();
2070
+ finish();
2071
+ throw Error("E_ASSET: prepared image resource failed", { cause: error });
2072
+ }).finally(() => clearTimeout(deadline));
2073
+ store.queue = ready.then(() => void 0, () => void 0);
2074
+ resource = {
2075
+ state,
2076
+ ready,
2077
+ width,
2078
+ height,
2079
+ bytes: frame.bytes
2080
+ };
2081
+ store.entries.set(key, resource);
2082
+ }
2083
+ const held = resource;
2084
+ let released = false;
2085
+ return {
2086
+ ready: held.ready,
2087
+ release() {
2088
+ if (released) return;
2089
+ released = true;
2090
+ const state = held.state;
2091
+ if (--state.references) return;
2092
+ state.controller.abort();
2093
+ if (store.entries.get(key) === held) store.entries.delete(key);
2094
+ if (state.complete && !state.finished) {
2095
+ state.finished = true;
2096
+ state.bitmap?.close();
2097
+ store.used -= width * height * 4;
2098
+ }
2099
+ }
2100
+ };
2101
+ }
2102
+ // src/image-sequence.ts
2103
+ function gcd(left, right) {
2104
+ while (right) [left, right] = [right, left % right];
2105
+ return left;
2106
+ }
2107
+ function createImageSequence(frames, plays, fps) {
2108
+ if (!frames.length || frames.length > 1e3 || !Number.isSafeInteger(fps) || fps < 1 || plays !== "infinite" && (!Number.isSafeInteger(plays) || plays < 1)) throw Error("E_ASSET: invalid image sequence");
2109
+ const timings = frames.map((frame) => {
2110
+ const time = frame.timing;
2111
+ if (!time || !Number.isSafeInteger(time.numerator) || time.numerator < 1 || !Number.isSafeInteger(time.denominator) || time.denominator < 1) throw Error("E_ASSET: invalid image frame duration");
2112
+ return {
2113
+ numerator: BigInt(time.numerator),
2114
+ denominator: BigInt(time.denominator)
2115
+ };
2116
+ });
2117
+ const denominator = timings.reduce((value, time) => value / gcd(value, time.denominator) * time.denominator, 1n);
2118
+ let total = 0n;
2119
+ const ends = timings.map((time) => {
2120
+ total += time.numerator * (denominator / time.denominator);
2121
+ return total * BigInt(fps);
2122
+ });
2123
+ const period = total * BigInt(fps);
2124
+ return (localFrame) => {
2125
+ if (!Number.isSafeInteger(localFrame) || localFrame < 0) throw Error("E_ASSET: invalid image seek frame");
2126
+ const elapsed = BigInt(localFrame) * denominator;
2127
+ if (plays !== "infinite" && elapsed >= period * BigInt(plays)) return frames.length - 1;
2128
+ const position = elapsed % period;
2129
+ let lower = 0;
2130
+ let upper = ends.length - 1;
2131
+ while (lower < upper) {
2132
+ const middle = Math.floor((lower + upper) / 2);
2133
+ const end = ends[middle];
2134
+ if (end === void 0) throw Error("E_ASSET: missing image interval");
2135
+ if (position < end) upper = middle;
2136
+ else lower = middle + 1;
2137
+ }
2138
+ return lower;
2139
+ };
2140
+ }
2141
+ // src/image-svg-animation.ts
2142
+ function prepareSvgAnimations(root) {
2143
+ const originals = root.getAnimations({ subtree: true });
2144
+ const effects = originals.map((animation) => {
2145
+ const effect = animation.effect;
2146
+ if (!(effect instanceof KeyframeEffect) || !(effect.target instanceof SVGElement) || effect.pseudoElement !== null) throw Error("E_ASSET: unsupported SVG animation effect");
2147
+ const target = effect.target;
2148
+ const frames = effect.getKeyframes();
2149
+ const properties = new Set(frames.flatMap((frame) => Object.keys(frame)).filter((name) => ![
2150
+ "offset",
2151
+ "computedOffset",
2152
+ "easing",
2153
+ "composite"
2154
+ ].includes(name)));
2155
+ const sampler = new KeyframeEffect(null, frames, effect.getTiming());
2156
+ sampler.composite = effect.composite;
2157
+ const sampled = new Animation(sampler, root.ownerDocument.timeline);
2158
+ sampled.pause();
2159
+ sampled.currentTime = 0;
2160
+ return {
2161
+ target,
2162
+ properties,
2163
+ effect: sampler,
2164
+ animation: sampled
2165
+ };
2166
+ });
2167
+ const underlying = /* @__PURE__ */ new Map();
2168
+ for (const { target, properties } of effects) {
2169
+ const styles = underlying.get(target) ?? /* @__PURE__ */ new Map();
2170
+ underlying.set(target, styles);
2171
+ for (const property of properties) {
2172
+ const name = property.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
2173
+ if (!styles.has(name)) styles.set(name, {
2174
+ value: target.style.getPropertyValue(name),
2175
+ priority: target.style.getPropertyPriority(name)
2176
+ });
2177
+ }
2178
+ }
2179
+ for (const animation of originals) animation.cancel();
2180
+ for (const target of underlying.keys()) target.style.setProperty("animation", "none", "important");
2181
+ return {
2182
+ seek(seconds) {
2183
+ for (const [target, styles] of underlying) for (const [name, original] of styles) if (original.value) target.style.setProperty(name, original.value, original.priority);
2184
+ else target.style.removeProperty(name);
2185
+ try {
2186
+ for (const value of effects) {
2187
+ value.effect.target = value.target;
2188
+ value.animation.currentTime = seconds * 1e3;
2189
+ }
2190
+ const values = [...underlying].map(([target, styles]) => {
2191
+ const computed = getComputedStyle(target);
2192
+ return {
2193
+ target,
2194
+ styles: [...styles.keys()].map((name) => [name, computed.getPropertyValue(name)])
2195
+ };
2196
+ });
2197
+ for (const value of effects) value.effect.target = null;
2198
+ for (const { target, styles } of values) for (const [name, value] of styles) target.style.setProperty(name, value, "important");
2199
+ } finally {
2200
+ for (const value of effects) value.effect.target = null;
2201
+ }
2202
+ },
2203
+ dispose() {
2204
+ for (const value of effects) value.animation.cancel();
2205
+ }
2206
+ };
2207
+ }
2208
+ // src/image-svg.tsx
2209
+ const tags = new Set("svg g defs rect circle ellipse path polygon polyline line text tspan title desc use linearGradient radialGradient stop clipPath mask style animate animateTransform animateMotion mpath set".split(" "));
2210
+ const attributes = new Set("xmlns xmlns:xlink id class style viewBox width height x y x1 x2 y1 y2 cx cy r rx ry d points dx dy fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-dasharray stroke-dashoffset opacity transform preserveAspectRatio href xlink:href offset stop-color stop-opacity gradientUnits gradientTransform spreadMethod clip-path clipPathUnits mask maskUnits maskContentUnits font-family font-size font-weight font-style text-anchor dominant-baseline attributeName from to by values keyTimes keySplines keyPoints calcMode type path rotate begin dur end repeatCount repeatDur additive accumulate restart".split(" "));
2211
+ const animated = new Set("x y x1 x2 y1 y2 cx cy r rx ry d points opacity fill fill-opacity stroke stroke-width stroke-opacity transform".split(" "));
2212
+ const paints = /* @__PURE__ */ new Set([
2213
+ "fill",
2214
+ "stroke",
2215
+ "clip-path",
2216
+ "mask",
2217
+ "stop-color"
2218
+ ]);
2219
+ const defaults = /* @__PURE__ */ new Map([
2220
+ ["-webkit-mask-position-x", "0%"],
2221
+ ["-webkit-mask-position-y", "0%"],
2222
+ ["mask-size", "auto"],
2223
+ ["mask-repeat", "repeat"],
2224
+ ["mask-origin", "border-box"],
2225
+ ["mask-clip", "border-box"],
2226
+ ["mask-composite", "add"],
2227
+ ["mask-mode", "match-source"]
2228
+ ]);
2229
+ const properties = new Set("animation animation-name animation-duration animation-delay animation-direction animation-fill-mode animation-iteration-count animation-play-state animation-timing-function animation-composition transform transform-origin transform-box translate rotate scale opacity fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-dasharray stroke-dashoffset clip-path mask stop-color stop-opacity color visibility display x y cx cy r rx ry d".split(" "));
2230
+ function fail() {
2231
+ throw Error("E_ASSET: invalid or unsupported prepared SVG");
2232
+ }
2233
+ function inspectSvgTree(tree, bytes, width, height) {
2234
+ let count = 0, characters = 0;
2235
+ const ids = /* @__PURE__ */ new Map();
2236
+ const seen = /* @__PURE__ */ new Set();
2237
+ const styles = [];
2238
+ const walk = (node, depth) => {
2239
+ if (!node || typeof node !== "object" || seen.has(node) || ++count > 1e4 || depth > 128 || !tags.has(node.tag) || !node.attributes || typeof node.attributes !== "object" || !Array.isArray(node.children) || Object.keys(node.attributes).length > 128) fail();
2240
+ seen.add(node);
2241
+ if (node.tag === "mask") {
2242
+ const units = node.attributes.maskUnits ?? "objectBoundingBox";
2243
+ if (!["objectBoundingBox", "userSpaceOnUse"].includes(units)) fail();
2244
+ for (const name of [
2245
+ "x",
2246
+ "y",
2247
+ "width",
2248
+ "height"
2249
+ ]) {
2250
+ const value = node.attributes[name];
2251
+ if (value === void 0) continue;
2252
+ if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)%?$/.test(value)) fail();
2253
+ const positive = name === "width" || name === "height";
2254
+ const limit = value.endsWith("%") ? positive ? 200 : 100 : units === "objectBoundingBox" ? positive ? 2 : 1 : (name === "x" || name === "width" ? width : height) * (positive ? 2 : 1);
2255
+ const number = parseFloat(value);
2256
+ if (!Number.isFinite(number) || Math.abs(number) > limit || positive && number <= 0) fail();
2257
+ }
2258
+ }
2259
+ for (const [name, value] of Object.entries(node.attributes)) {
2260
+ if (!attributes.has(name) && !/^data-[a-z-]+$/.test(name) || typeof value !== "string") fail();
2261
+ characters += name.length + value.length;
2262
+ if (characters > bytes) fail();
2263
+ if (name === "id") {
2264
+ if (!/^[a-zA-Z_][\w.-]*$/.test(value) || ids.has(value)) fail();
2265
+ ids.set(value, node);
2266
+ }
2267
+ if ((name === "href" || name === "xlink:href") && !/^#[a-zA-Z_][\w.-]*$/.test(value)) fail();
2268
+ if (name === "style") styles.push(`.inline{${value}}`);
2269
+ if (paints.has(name) && !(name === "fill" && [
2270
+ "animate",
2271
+ "animateTransform",
2272
+ "animateMotion",
2273
+ "set"
2274
+ ].includes(node.tag))) styles.push(`.paint{${name}:${value}}`);
2275
+ if ([
2276
+ "begin",
2277
+ "end",
2278
+ "dur",
2279
+ "repeatDur"
2280
+ ].includes(name)) {
2281
+ for (const time of value.split(";")) if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:ms|s)?$/.test(time.trim()) || !Number.isFinite(parseFloat(time))) fail();
2282
+ }
2283
+ }
2284
+ if (["animate", "set"].includes(node.tag)) {
2285
+ const name = node.attributes.attributeName ?? "";
2286
+ if (!animated.has(name)) fail();
2287
+ if (paints.has(name)) for (const attr of [
2288
+ "from",
2289
+ "to",
2290
+ "by",
2291
+ "values"
2292
+ ]) for (const value of (node.attributes[attr] ?? "").split(";").filter(Boolean)) styles.push(`.paint{${name}:${value}}`);
2293
+ }
2294
+ if (node.tag === "style") {
2295
+ if (node.children.some((child) => typeof child !== "string")) fail();
2296
+ styles.push(node.children.join(""));
2297
+ }
2298
+ for (const child of node.children) if (typeof child === "string") {
2299
+ if (++count > 1e4) fail();
2300
+ characters += child.length;
2301
+ if (characters > bytes) fail();
2302
+ } else walk(child, depth + 1);
2303
+ };
2304
+ walk(tree, 0);
2305
+ const visiting = /* @__PURE__ */ new Set(), costs = /* @__PURE__ */ new Map();
2306
+ const maskCosts = /* @__PURE__ */ new Map();
2307
+ const expansion = (node, depth) => {
2308
+ if (visiting.has(node) || depth > 128) return fail();
2309
+ const cached = costs.get(node);
2310
+ if (cached !== void 0) return cached;
2311
+ visiting.add(node);
2312
+ let cost = 1;
2313
+ let masks = node.tag === "mask" ? 1 : 0;
2314
+ for (const child of node.children) if (typeof child === "string") cost++;
2315
+ else {
2316
+ cost += expansion(child, depth + 1);
2317
+ masks += maskCosts.get(child) ?? 0;
2318
+ }
2319
+ for (const name of ["href", "xlink:href"]) {
2320
+ const href = node.attributes[name];
2321
+ if (href) {
2322
+ const target = ids.get(href.slice(1));
2323
+ if (!target) return fail();
2324
+ cost += expansion(target, depth + 1);
2325
+ masks += maskCosts.get(target) ?? 0;
2326
+ }
2327
+ }
2328
+ if (cost > 1e4) return fail();
2329
+ visiting.delete(node);
2330
+ costs.set(node, cost);
2331
+ maskCosts.set(node, masks);
2332
+ return cost;
2333
+ };
2334
+ return {
2335
+ styles,
2336
+ ids,
2337
+ nodes: expansion(tree, 0),
2338
+ masks: maskCosts.get(tree) ?? 0
2339
+ };
2340
+ }
2341
+ function validateStyles(styles, ids, nodes) {
2342
+ let cssCharacters = 0, cssFrames = 0, cssRules = 0, cssBraces = 0, animationNames = 0;
2343
+ for (const style of styles) {
2344
+ cssCharacters += style.length;
2345
+ cssBraces += style.match(/{/g)?.length ?? 0;
2346
+ if (cssBraces > 1e4) fail();
2347
+ if (/\\|@(?!keyframes\b)|:host|::|:(?:hover|active|focus|focus-within|focus-visible|target|visited|link|checked|disabled|enabled|state)\b|var\(|env\(|attr\(|image-set\(|cross-fade\(|paint\(|image\(|(?:animation|scroll|view)-timeline\s*:|transition(?:-[\w-]+)?\s*:/i.test(style)) fail();
2348
+ const sheet = new CSSStyleSheet();
2349
+ sheet.replaceSync(style);
2350
+ const visit = (rules) => {
2351
+ for (const rule of rules) {
2352
+ if (++cssRules > 1e4) fail();
2353
+ if (rule instanceof CSSKeyframesRule) {
2354
+ cssFrames += rule.cssRules.length;
2355
+ if (cssFrames > 1e3) fail();
2356
+ visit(rule.cssRules);
2357
+ } else if (rule instanceof CSSStyleRule || rule instanceof CSSKeyframeRule) {
2358
+ const names = rule.style.getPropertyValue("animation-name");
2359
+ if (names && names !== "none") animationNames = Math.max(animationNames, names.split(",").length);
2360
+ if (animationNames > 1e3) fail();
2361
+ for (const name of rule.style) {
2362
+ if (rule instanceof CSSKeyframeRule && (name === "display" || name === "visibility")) fail();
2363
+ const value = rule.style.getPropertyValue(name);
2364
+ if (defaults.get(name) === value) continue;
2365
+ if (name === "animation-timeline" && value === "auto" || (name === "animation-range-start" || name === "animation-range-end") && value === "normal") continue;
2366
+ if (!properties.has(name) && name !== "mask-image") fail();
2367
+ const remainder = value.replace(/url\(\s*["']?(#[a-zA-Z_][\w.-]*)["']?\s*\)/gi, (_match, target) => {
2368
+ if (!ids.has(target.slice(1))) fail();
2369
+ return "";
2370
+ });
2371
+ if (/url\s*\(|\\|image-set\(|cross-fade\(|image\(|attr\(|var\(|env\(/i.test(remainder)) fail();
2372
+ }
2373
+ } else fail();
2374
+ }
2375
+ };
2376
+ visit(sheet.cssRules);
2377
+ }
2378
+ return nodes * animationNames * (cssCharacters * 4 + (cssFrames + 1) * 2048);
2379
+ }
2380
+ function SvgImageAsset({ asset, clipId, registry, alt, className, style }) {
2381
+ const ref = useRef(null);
2382
+ const [failure, setFailure] = useState();
2383
+ useLayoutEffect(() => {
2384
+ const host = ref.current;
2385
+ if (!host) return;
2386
+ let active = true;
2387
+ let release, unregister;
2388
+ let releaseCss;
2389
+ let animations;
2390
+ const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
2391
+ host.style.visibility = "hidden";
2392
+ const dispose = () => {
2393
+ active = false;
2394
+ unregister?.();
2395
+ animations?.dispose();
2396
+ shadow.replaceChildren();
2397
+ releaseCss?.();
2398
+ release?.();
2399
+ release = void 0;
2400
+ };
2401
+ const prepare = async () => {
2402
+ try {
2403
+ const { tree, bytes } = asset;
2404
+ if (!tree || tree.tag !== "svg" || !Number.isSafeInteger(bytes) || !bytes || bytes < 1 || bytes > 67108864 || asset.frames.length || asset.plays !== 1) fail();
2405
+ const inspected = inspectSvgTree(tree, bytes, asset.width, asset.height);
2406
+ release = reserveImageData(bytes * 24 + asset.width * asset.height * (16 + 64 * inspected.masks * inspected.nodes) + inspected.nodes * 1024, host.ownerDocument);
2407
+ const cssBytes = validateStyles(inspected.styles, inspected.ids, inspected.nodes);
2408
+ if (cssBytes) releaseCss = reserveImageData(cssBytes, host.ownerDocument);
2409
+ const build = (node) => {
2410
+ if (typeof node === "string") return host.ownerDocument.createTextNode(node);
2411
+ const element = host.ownerDocument.createElementNS("http://www.w3.org/2000/svg", node.tag);
2412
+ for (const [name, value] of Object.entries(node.attributes)) if (name === "xlink:href") element.setAttributeNS("http://www.w3.org/1999/xlink", name, value);
2413
+ else element.setAttribute(name, value);
2414
+ for (const child of node.children) element.append(build(child));
2415
+ return element;
2416
+ };
2417
+ const root = build(tree);
2418
+ if (!(root instanceof SVGSVGElement)) return fail();
2419
+ root.style.width = "100%";
2420
+ root.style.height = "100%";
2421
+ root.style.display = "block";
2422
+ if (!root.hasAttribute("viewBox")) root.setAttribute("viewBox", `0 0 ${asset.width} ${asset.height}`);
2423
+ shadow.append(root);
2424
+ root.getBoundingClientRect();
2425
+ root.pauseAnimations();
2426
+ root.setCurrentTime(0);
2427
+ animations = prepareSvgAnimations(root);
2428
+ animations.seek(0);
2429
+ if (!active) return;
2430
+ unregister = registry.register(clipId, {
2431
+ seek(localSeconds) {
2432
+ if (!active) return;
2433
+ root.setCurrentTime(localSeconds);
2434
+ animations?.seek(localSeconds);
2435
+ },
2436
+ setActive(visible) {
2437
+ if (active) host.style.visibility = visible ? "visible" : "hidden";
2438
+ }
2439
+ });
2440
+ } catch (error) {
2441
+ if (active) {
2442
+ dispose();
2443
+ setFailure(Error("E_ASSET: SVG preparation failed", { cause: error }));
2444
+ }
2445
+ }
2446
+ };
2447
+ prepare();
2448
+ return dispose;
2449
+ }, [
2450
+ asset,
2451
+ clipId,
2452
+ registry
2453
+ ]);
2454
+ if (failure) throw failure;
2455
+ return /* @__PURE__ */ jsx("div", {
2456
+ ref,
2457
+ className,
2458
+ role: alt ? "img" : "presentation",
2459
+ "aria-label": alt || void 0,
2460
+ "aria-hidden": alt ? void 0 : true,
2461
+ style: {
2462
+ width: asset.width,
2463
+ height: asset.height,
2464
+ ...style,
2465
+ contain: "strict",
2466
+ overflow: "hidden"
2467
+ }
2468
+ });
2469
+ }
2470
+ // src/image-asset.tsx
2471
+ function ImageAsset(props) {
2472
+ const { asset, alt } = props;
2473
+ if (!asset || asset.schemaVersion !== 1 || !Number.isSafeInteger(asset.width) || !Number.isSafeInteger(asset.height) || asset.width < 1 || asset.height < 1 || asset.width > 8192 || asset.height > 8192 || asset.width * asset.height > 16777216 || typeof alt !== "string") throw Error("E_ASSET: invalid image declaration");
2474
+ return asset.kind === "svg" ? /* @__PURE__ */ jsx(SvgImageAsset, { ...props }) : /* @__PURE__ */ jsx(RasterImageAsset, { ...props });
2475
+ }
2476
+ function RasterImageAsset({ asset, clipId, registry, alt, className, style }) {
2477
+ const canvasRef = useRef(null);
2478
+ const [failure, setFailure] = useState();
2479
+ const fps = useContext(CompositionFps);
2480
+ if (!asset || asset.schemaVersion !== 1 || !["static", "sequence"].includes(asset.kind) || !asset.frames?.length || asset.frames.length > 1e3 || asset.kind === "static" && (asset.frames.length !== 1 || asset.plays !== 1 || asset.frames[0]?.timing !== void 0) || asset.kind === "sequence" && fps === null || !Number.isSafeInteger(asset.width) || !Number.isSafeInteger(asset.height) || asset.width < 1 || asset.height < 1 || asset.width > 8192 || asset.height > 8192 || asset.width * asset.height > 16777216 || typeof alt !== "string") throw Error("E_ASSET: invalid image declaration");
2481
+ useLayoutEffect(() => {
2482
+ const canvas = canvasRef.current;
2483
+ if (!canvas) throw Error("E_ASSET: missing image surface");
2484
+ let active = true;
2485
+ let unregister;
2486
+ let releaseSurface;
2487
+ const leases = [];
2488
+ const dispose = () => {
2489
+ active = false;
2490
+ unregister?.();
2491
+ unregister = void 0;
2492
+ canvas.width = 0;
2493
+ canvas.height = 0;
2494
+ for (const lease of leases) lease.release();
2495
+ releaseSurface?.();
2496
+ releaseSurface = void 0;
2497
+ };
2498
+ canvas.style.visibility = "hidden";
2499
+ const prepare = async () => {
2500
+ try {
2501
+ releaseSurface = reserveImageData(asset.width * asset.height * 4 + (asset.kind === "sequence" ? (asset.frames.length + 1) * (8 + asset.frames.length * 7) : 0), canvas.ownerDocument);
2502
+ canvas.width = asset.width;
2503
+ canvas.height = asset.height;
2504
+ const context = canvas.getContext("2d");
2505
+ if (!context) throw Error("E_ASSET: image surface unavailable");
2506
+ const select = asset.kind === "sequence" ? createImageSequence(asset.frames, asset.plays, fps ?? 0) : () => 0;
2507
+ const bitmaps = await Promise.all(asset.frames.map((frame) => {
2508
+ const lease = acquireImageFrame(frame, asset.width, asset.height, canvas.ownerDocument);
2509
+ leases.push(lease);
2510
+ return lease.ready;
2511
+ }));
2512
+ if (!active) return;
2513
+ unregister = registry.register(clipId, {
2514
+ seek(localSeconds) {
2515
+ if (active) {
2516
+ const bitmap = bitmaps[select(Math.round(localSeconds * (fps ?? 1)))];
2517
+ if (!bitmap) throw Error("E_ASSET: missing prepared image frame");
2518
+ context.clearRect(0, 0, canvas.width, canvas.height);
2519
+ context.drawImage(bitmap, 0, 0);
2520
+ }
2521
+ },
2522
+ setActive(visible) {
2523
+ if (active) canvas.style.visibility = visible ? "visible" : "hidden";
2524
+ }
2525
+ });
2526
+ } catch (error) {
2527
+ if (active) {
2528
+ dispose();
2529
+ setFailure(error instanceof Error ? error : Error("E_ASSET: image preparation failed", { cause: error }));
2530
+ }
2531
+ }
2532
+ };
2533
+ prepare();
2534
+ return dispose;
2535
+ }, [
2536
+ asset,
2537
+ clipId,
2538
+ registry,
2539
+ fps
2540
+ ]);
2541
+ if (failure) throw failure;
2542
+ return /* @__PURE__ */ jsx("canvas", {
2543
+ ref: canvasRef,
2544
+ className,
2545
+ role: alt ? "img" : "presentation",
2546
+ "aria-label": alt || void 0,
2547
+ "aria-hidden": alt ? void 0 : true,
2548
+ style: {
2549
+ display: "block",
2550
+ width: asset.width,
2551
+ height: asset.height,
2552
+ ...style
2553
+ }
2554
+ });
2555
+ }
2556
+ export { CompositionPlayer, CompositionPlayerBridge, ImageAsset };