@serimo/player 0.2.0 → 0.3.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 (42) hide show
  1. package/README.md +53 -2
  2. package/dist/audio/player-audio.d.ts +10 -0
  3. package/dist/audio/player-audio.d.ts.map +1 -0
  4. package/dist/audio/prepared-pcm.d.ts +8 -0
  5. package/dist/audio/prepared-pcm.d.ts.map +1 -0
  6. package/dist/composition/composition-player.d.ts.map +1 -0
  7. package/dist/composition/composition-timing.d.ts +2 -0
  8. package/dist/composition/composition-timing.d.ts.map +1 -0
  9. package/dist/{player-session.d.ts → composition/player-session.d.ts} +1 -9
  10. package/dist/composition/player-session.d.ts.map +1 -0
  11. package/dist/composition/player-status.d.ts.map +1 -0
  12. package/dist/composition/renderer-bridge.d.ts.map +1 -0
  13. package/dist/image/image-accessibility.d.ts +6 -0
  14. package/dist/image/image-accessibility.d.ts.map +1 -0
  15. package/dist/image/image-asset-types.d.ts +34 -0
  16. package/dist/image/image-asset-types.d.ts.map +1 -0
  17. package/dist/image/image-asset.d.ts +3 -0
  18. package/dist/image/image-asset.d.ts.map +1 -0
  19. package/dist/image/image-resources.d.ts +7 -0
  20. package/dist/image/image-resources.d.ts.map +1 -0
  21. package/dist/image/image-sequence.d.ts +3 -0
  22. package/dist/image/image-sequence.d.ts.map +1 -0
  23. package/dist/image/image-svg-animation.d.ts +5 -0
  24. package/dist/image/image-svg-animation.d.ts.map +1 -0
  25. package/dist/image/image-svg-validation.d.ts +10 -0
  26. package/dist/image/image-svg-validation.d.ts.map +1 -0
  27. package/dist/image/image-svg.d.ts +3 -0
  28. package/dist/image/image-svg.d.ts.map +1 -0
  29. package/dist/index.d.ts +6 -4
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +732 -124
  32. package/dist/styles.css +273 -261
  33. package/package.json +6 -6
  34. package/dist/composition-player.d.ts.map +0 -1
  35. package/dist/player-audio.d.ts +0 -12
  36. package/dist/player-audio.d.ts.map +0 -1
  37. package/dist/player-session.d.ts.map +0 -1
  38. package/dist/player-status.d.ts.map +0 -1
  39. package/dist/renderer-bridge.d.ts.map +0 -1
  40. /package/dist/{composition-player.d.ts → composition/composition-player.d.ts} +0 -0
  41. /package/dist/{player-status.d.ts → composition/player-status.d.ts} +0 -0
  42. /package/dist/{renderer-bridge.d.ts → composition/renderer-bridge.d.ts} +0 -0
package/dist/index.js CHANGED
@@ -4,11 +4,13 @@ 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
- // src/player-audio.ts
8
- const MAX_PCM_BYTES = 268435456;
9
- function inspectPCM(bytes, required) {
7
+ // src/composition/composition-timing.ts
8
+ const CompositionFps = createContext(null);
9
+ // src/audio/prepared-pcm.ts
10
+ const PCM_SAMPLE_RATE = 48e3;
11
+ function inspectPreparedPcm(bytes, required) {
10
12
  const invalid = () => /* @__PURE__ */ new Error("E_ASSET: prepared audio must be sufficient PCM16 48 kHz mono or stereo WAV");
11
- if (bytes.byteLength < 44 || bytes.byteLength > MAX_PCM_BYTES) throw invalid();
13
+ if (bytes.byteLength < 44 || bytes.byteLength > 268435456) throw invalid();
12
14
  const view = new DataView(bytes);
13
15
  const text = (offset) => String.fromCharCode(...new Uint8Array(bytes, offset, 4));
14
16
  if (text(0) !== "RIFF" || text(8) !== "WAVE" || view.getUint32(4, true) + 8 !== bytes.byteLength) throw invalid();
@@ -35,12 +37,12 @@ function inspectPCM(bytes, required) {
35
37
  samples
36
38
  };
37
39
  }
38
- async function readPCM(src, signal) {
40
+ async function readPreparedPcm(src, signal) {
39
41
  const response = await fetch(src, {
40
42
  signal,
41
43
  credentials: "omit"
42
44
  });
43
- 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");
45
+ if (!response.ok || !response.body || Number(response.headers.get("content-length") ?? 0) > 268435456) throw new Error("E_ASSET: prepared PCM audio unavailable or too large");
44
46
  const native = response.clone();
45
47
  const reader = response.body.getReader();
46
48
  let size = 0;
@@ -50,7 +52,7 @@ async function readPCM(src, signal) {
50
52
  const { done, value } = await reader.read();
51
53
  if (done) break;
52
54
  size += value.byteLength;
53
- if (size > MAX_PCM_BYTES) throw new Error("E_ASSET: prepared PCM audio exceeds its size limit");
55
+ if (size > 268435456) throw new Error("E_ASSET: prepared PCM audio exceeds its size limit");
54
56
  }
55
57
  } catch (error) {
56
58
  await Promise.allSettled([reader.cancel(), native.body?.cancel()]);
@@ -62,10 +64,22 @@ async function readPCM(src, signal) {
62
64
  if (bytes.byteLength !== size) throw new Error("E_ASSET: prepared PCM byte count changed");
63
65
  return bytes;
64
66
  }
67
+ // src/audio/player-audio.ts
68
+ async function waitForOutputClock(context, assertCurrent) {
69
+ while (true) {
70
+ assertCurrent();
71
+ const { contextTime, performanceTime } = context.getOutputTimestamp();
72
+ if (typeof contextTime === "number" && contextTime > 0 && Number.isFinite(contextTime) && typeof performanceTime === "number" && performanceTime > 0 && Number.isFinite(performanceTime)) return {
73
+ contextTime,
74
+ performanceTime
75
+ };
76
+ await new Promise((resolve) => setTimeout(resolve, 10));
77
+ }
78
+ }
65
79
  function createPlayerAudio(composition, signal) {
66
80
  const tracks = getAudioTracks(composition.audio);
67
81
  if (!tracks.length) throw new Error("E_ASSET: audio declaration missing");
68
- const context = new AudioContext({ sampleRate: 48e3 });
82
+ const context = new AudioContext({ sampleRate: PCM_SAMPLE_RATE });
69
83
  const controller = new AbortController();
70
84
  const activeSignal = AbortSignal.any([signal, controller.signal]);
71
85
  const gains = tracks.map((track) => {
@@ -110,13 +124,13 @@ function createPlayerAudio(composition, signal) {
110
124
  let bytesTotal = 0;
111
125
  let channels = 1;
112
126
  for (const track of tracks) {
113
- const required = Math.ceil(track.durationInFrames * 48e3 / composition.fps);
127
+ const required = Math.ceil(track.durationInFrames * PCM_SAMPLE_RATE / composition.fps);
114
128
  let decoded = buffers.get(track.src);
115
129
  if (!decoded) {
116
- const bytes = await readPCM(track.src, activeSignal);
130
+ const bytes = await readPreparedPcm(track.src, activeSignal);
117
131
  bytesTotal += bytes.byteLength;
118
- if (bytesTotal > MAX_PCM_BYTES * 2) throw new Error("E_ASSET: prepared PCM audio exceeds its session size limit");
119
- const pcm = inspectPCM(bytes, required);
132
+ if (bytesTotal > 536870912) throw new Error("E_ASSET: prepared PCM audio exceeds its session size limit");
133
+ const pcm = inspectPreparedPcm(bytes, required);
120
134
  decoded = await context.decodeAudioData(bytes);
121
135
  activeSignal.throwIfAborted();
122
136
  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");
@@ -149,48 +163,42 @@ function createPlayerAudio(composition, signal) {
149
163
  const resume = context.resume();
150
164
  return (async () => {
151
165
  let timer;
152
- const check = () => {
166
+ const assertCurrent = () => {
153
167
  if (generation !== version || disposed || activeSignal.aborted) throw new DOMException("Stale audio playback", "AbortError");
154
168
  };
155
169
  try {
156
- const stamp = await Promise.race([resume.then(async () => {
157
- while (true) {
158
- check();
159
- const stamp = context.getOutputTimestamp();
160
- if (Number.isFinite(stamp.contextTime) && Number.isFinite(stamp.performanceTime) && stamp.contextTime > 0 && stamp.performanceTime > 0) return stamp;
161
- await new Promise((resolve) => setTimeout(resolve, 10));
162
- }
163
- }), new Promise((_resolve, reject) => {
170
+ const { contextTime, performanceTime } = await Promise.race([resume.then(() => waitForOutputClock(context, assertCurrent)), new Promise((_resolve, reject) => {
164
171
  timer = setTimeout(() => {
165
172
  if (generation === version) pause();
166
173
  reject(/* @__PURE__ */ new Error("E_ASSET: audio activation blocked or output clock unavailable"));
167
174
  }, 1e3);
168
175
  })]);
169
- check();
176
+ assertCurrent();
170
177
  const start = context.currentTime + .05;
171
- const seconds = frame / composition.fps;
178
+ const { fps } = composition;
179
+ const seconds = frame / fps;
172
180
  for (const [index, track] of tracks.entries()) {
173
- const offset = Math.max(0, seconds - track.startFrame / composition.fps);
174
- const remaining = track.durationInFrames / composition.fps - offset;
175
- if (remaining > 0) {
176
- const source = context.createBufferSource();
177
- source.buffer = buffers.get(track.src) ?? null;
178
- const gain = gains[index];
179
- if (!gain) throw new Error("E_ASSET: audio gain unavailable");
180
- source.connect(gain);
181
- source.onended = () => {
182
- if (sources.delete(source)) source.disconnect();
183
- };
184
- try {
185
- source.start(start + Math.max(0, track.startFrame / composition.fps - seconds), offset, remaining);
186
- sources.add(source);
187
- } catch (error) {
188
- source.disconnect();
189
- throw error;
190
- }
181
+ const trackStart = track.startFrame / fps;
182
+ const offset = Math.max(0, seconds - trackStart);
183
+ const remaining = track.durationInFrames / fps - offset;
184
+ if (!(remaining > 0)) continue;
185
+ const source = context.createBufferSource();
186
+ source.buffer = buffers.get(track.src) ?? null;
187
+ const gain = gains[index];
188
+ if (!gain) throw new Error("E_ASSET: audio gain unavailable");
189
+ source.connect(gain);
190
+ source.onended = () => {
191
+ if (sources.delete(source)) source.disconnect();
192
+ };
193
+ try {
194
+ source.start(start + Math.max(0, trackStart - seconds), offset, remaining);
195
+ sources.add(source);
196
+ } catch (error) {
197
+ source.disconnect();
198
+ throw error;
191
199
  }
192
200
  }
193
- return { originTimeMs: performance.timeOrigin + stamp.performanceTime + (start - stamp.contextTime) * 1e3 };
201
+ return { originTimeMs: performance.timeOrigin + performanceTime + (start - contextTime) * 1e3 };
194
202
  } catch (error) {
195
203
  if (generation === version) pause();
196
204
  throw error;
@@ -201,7 +209,7 @@ function createPlayerAudio(composition, signal) {
201
209
  }
202
210
  };
203
211
  }
204
- // src/player-session.ts
212
+ // src/composition/player-session.ts
205
213
  function createPlayerSession(composition, registry) {
206
214
  let current;
207
215
  const stop = () => {
@@ -245,9 +253,10 @@ function createPlayerSession(composition, registry) {
245
253
  } } : {}
246
254
  };
247
255
  return {
248
- ...handle,
256
+ handle,
249
257
  start() {
250
258
  const controller = new AbortController();
259
+ const { signal } = controller;
251
260
  stop().catch((error) => controller.abort(error));
252
261
  const active = {
253
262
  controller,
@@ -257,20 +266,20 @@ function createPlayerSession(composition, registry) {
257
266
  const timeout = setTimeout(() => {
258
267
  controller.abort(/* @__PURE__ */ new Error("Player timelines were not ready within 10000ms"));
259
268
  }, 1e4);
260
- const abortReady = () => rejectReady(controller.signal.reason);
269
+ const abortReady = () => rejectReady(signal.reason);
261
270
  let rejectReady = () => {};
262
271
  const cancelled = new Promise((_resolve, reject) => {
263
272
  rejectReady = reject;
264
273
  });
265
- controller.signal.addEventListener("abort", abortReady, { once: true });
266
- const ready = Promise.race([cancelled, Promise.all([registry.whenReady({ signal: controller.signal }), Promise.resolve().then(() => {
267
- controller.signal.throwIfAborted();
274
+ signal.addEventListener("abort", abortReady, { once: true });
275
+ const ready = Promise.race([cancelled, Promise.all([registry.whenReady({ signal }), Promise.resolve().then(() => {
276
+ signal.throwIfAborted();
268
277
  if (composition.audio) {
269
- active.audio = createPlayerAudio(composition, controller.signal);
278
+ active.audio = createPlayerAudio(composition, signal);
270
279
  return active.audio.ready;
271
280
  }
272
281
  })])]).then(() => {
273
- controller.signal.throwIfAborted();
282
+ signal.throwIfAborted();
274
283
  registry.seek(0);
275
284
  }).catch(async (error) => {
276
285
  controller.abort(error);
@@ -278,7 +287,7 @@ function createPlayerSession(composition, registry) {
278
287
  throw error;
279
288
  }).finally(() => {
280
289
  clearTimeout(timeout);
281
- controller.signal.removeEventListener("abort", abortReady);
290
+ signal.removeEventListener("abort", abortReady);
282
291
  });
283
292
  active.ready = ready;
284
293
  return ready;
@@ -415,20 +424,20 @@ const nodeVlist = (() => {
415
424
  for (let i = 0; i < A.length; i++) out[A[i]] = V[i];
416
425
  return out;
417
426
  })();
418
- 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) => {
427
+ 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) => {
419
428
  const tails = s.split(" ");
420
429
  const prefix = tails.shift();
421
430
  for (let i = 0; i < tails.length; i++) tails[i] = prefix + tails[i];
422
431
  return tails;
423
432
  });
424
433
  const AA = DZ("0000000000000000000000000000000000000000000000000000000000000262242:6@200000006:240B428:4422400002046044222426220026642642462026224222824220022400000000\\00N222422242222222224062242222222422226264222422222222222222442804222422222222222222222222220<4<0204260002444020204224422");
425
- 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");
426
- 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±");
427
- const litAnchor = /* @__PURE__ */ new Int32Array(995);
428
- const litGroup = /* @__PURE__ */ new Int32Array(995);
429
- const litPool = /* @__PURE__ */ new Int32Array(995);
434
+ 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");
435
+ const AS = DZ("02222222222222222222222222222222222222222222222222222222222222222202021422222222CF2200GJ021042222WZ222IL0ad2c10h2222U00X202[^2w0000120zy|}€22ƒ†…:22z22222222222G000q†OVI00000{˜2™<40000Œ›@00000G¦§000ª00000000000000021K¬«00®“000000000000000000000–222›HGH_1¸222½2¾2222ÇÊ000­°2±");
436
+ const litAnchor = /* @__PURE__ */ new Int32Array(987);
437
+ const litGroup = /* @__PURE__ */ new Int32Array(987);
438
+ const litPool = /* @__PURE__ */ new Int32Array(987);
430
439
  let poolText = "";
431
- const poolOffsets = /* @__PURE__ */ new Int32Array(1038);
440
+ const poolOffsets = /* @__PURE__ */ new Int32Array(1022);
432
441
  {
433
442
  const tailRef = /* @__PURE__ */ new Map();
434
443
  let nextRef = 0;
@@ -1547,7 +1556,7 @@ function AlertDescription({ className, ...props }) {
1547
1556
  }
1548
1557
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
1549
1558
  /**
1550
- * @license lucide-react v1.62.0 - ISC
1559
+ * @license lucide-react v1.70.0 - ISC
1551
1560
  *
1552
1561
  * This source code is licensed under the ISC license.
1553
1562
  * See the LICENSE file in the root directory of this source tree.
@@ -1555,7 +1564,7 @@ function AlertDescription({ className, ...props }) {
1555
1564
  const toKebabCase = (string) => string?.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
1556
1565
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toLucideIconData.mjs
1557
1566
  /**
1558
- * @license lucide-react v1.62.0 - ISC
1567
+ * @license lucide-react v1.70.0 - ISC
1559
1568
  *
1560
1569
  * This source code is licensed under the ISC license.
1561
1570
  * See the LICENSE file in the root directory of this source tree.
@@ -1571,7 +1580,7 @@ function toLucideIconData(iconName, iconNode, aliases = []) {
1571
1580
  }
1572
1581
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
1573
1582
  /**
1574
- * @license lucide-react v1.62.0 - ISC
1583
+ * @license lucide-react v1.70.0 - ISC
1575
1584
  *
1576
1585
  * This source code is licensed under the ISC license.
1577
1586
  * See the LICENSE file in the root directory of this source tree.
@@ -1592,7 +1601,7 @@ const toCamelCase = (string) => {
1592
1601
  };
1593
1602
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
1594
1603
  /**
1595
- * @license lucide-react v1.62.0 - ISC
1604
+ * @license lucide-react v1.70.0 - ISC
1596
1605
  *
1597
1606
  * This source code is licensed under the ISC license.
1598
1607
  * See the LICENSE file in the root directory of this source tree.
@@ -1603,7 +1612,7 @@ const toPascalCase = (string) => {
1603
1612
  };
1604
1613
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
1605
1614
  /**
1606
- * @license lucide-react v1.62.0 - ISC
1615
+ * @license lucide-react v1.70.0 - ISC
1607
1616
  *
1608
1617
  * This source code is licensed under the ISC license.
1609
1618
  * See the LICENSE file in the root directory of this source tree.
@@ -1613,7 +1622,7 @@ const mergeClasses = (...classes) => classes.filter((className, index, array) =>
1613
1622
  }).join(" ").trim();
1614
1623
  // ../../node_modules/lucide-react/dist/esm/shared/src/build/defaultAttributes.mjs
1615
1624
  /**
1616
- * @license lucide-react v1.62.0 - ISC
1625
+ * @license lucide-react v1.70.0 - ISC
1617
1626
  *
1618
1627
  * This source code is licensed under the ISC license.
1619
1628
  * See the LICENSE file in the root directory of this source tree.
@@ -1631,7 +1640,7 @@ const defaultAttributes = {
1631
1640
  };
1632
1641
  // ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconNode.mjs
1633
1642
  /**
1634
- * @license lucide-react v1.62.0 - ISC
1643
+ * @license lucide-react v1.70.0 - ISC
1635
1644
  *
1636
1645
  * This source code is licensed under the ISC license.
1637
1646
  * See the LICENSE file in the root directory of this source tree.
@@ -1685,7 +1694,7 @@ function buildLucideIconNode(icon, params = {}) {
1685
1694
  }
1686
1695
  // ../../node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconForReact.mjs
1687
1696
  /**
1688
- * @license lucide-react v1.62.0 - ISC
1697
+ * @license lucide-react v1.70.0 - ISC
1689
1698
  *
1690
1699
  * This source code is licensed under the ISC license.
1691
1700
  * See the LICENSE file in the root directory of this source tree.
@@ -1705,7 +1714,7 @@ function buildLucideIconForReact(icon, params = {}) {
1705
1714
  }
1706
1715
  // ../../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
1707
1716
  /**
1708
- * @license lucide-react v1.62.0 - ISC
1717
+ * @license lucide-react v1.70.0 - ISC
1709
1718
  *
1710
1719
  * This source code is licensed under the ISC license.
1711
1720
  * See the LICENSE file in the root directory of this source tree.
@@ -1716,7 +1725,7 @@ const hasA11yProp = (props) => {
1716
1725
  };
1717
1726
  // ../../node_modules/lucide-react/dist/esm/context.mjs
1718
1727
  /**
1719
- * @license lucide-react v1.62.0 - ISC
1728
+ * @license lucide-react v1.70.0 - ISC
1720
1729
  *
1721
1730
  * This source code is licensed under the ISC license.
1722
1731
  * See the LICENSE file in the root directory of this source tree.
@@ -1725,7 +1734,7 @@ const LucideContext = createContext({});
1725
1734
  const useLucideContext = () => useContext(LucideContext);
1726
1735
  // ../../node_modules/lucide-react/dist/esm/Icon.mjs
1727
1736
  /**
1728
- * @license lucide-react v1.62.0 - ISC
1737
+ * @license lucide-react v1.70.0 - ISC
1729
1738
  *
1730
1739
  * This source code is licensed under the ISC license.
1731
1740
  * See the LICENSE file in the root directory of this source tree.
@@ -1755,7 +1764,7 @@ const Icon = forwardRef(({ color, size, width, height, strokeWidth, absoluteStro
1755
1764
  });
1756
1765
  // ../../node_modules/lucide-react/dist/esm/createLucideIcon.mjs
1757
1766
  /**
1758
- * @license lucide-react v1.62.0 - ISC
1767
+ * @license lucide-react v1.70.0 - ISC
1759
1768
  *
1760
1769
  * This source code is licensed under the ISC license.
1761
1770
  * See the LICENSE file in the root directory of this source tree.
@@ -1773,7 +1782,7 @@ function createLucideIcon(iconDataOrName, iconNode = [], aliases = []) {
1773
1782
  }
1774
1783
  // ../../node_modules/lucide-react/dist/esm/icons/loader-circle.mjs
1775
1784
  /**
1776
- * @license lucide-react v1.62.0 - ISC
1785
+ * @license lucide-react v1.70.0 - ISC
1777
1786
  *
1778
1787
  * This source code is licensed under the ISC license.
1779
1788
  * See the LICENSE file in the root directory of this source tree.
@@ -1799,7 +1808,7 @@ function Spinner({ className, ...props }) {
1799
1808
  ...props
1800
1809
  });
1801
1810
  }
1802
- // src/player-status.tsx
1811
+ // src/composition/player-status.tsx
1803
1812
  function PlayerStatus({ state, error }) {
1804
1813
  if (state === "loading") return /* @__PURE__ */ jsx(Spinner, { "aria-label": "Composition loading" });
1805
1814
  if (state === "error") return /* @__PURE__ */ jsxs(Alert, {
@@ -1808,52 +1817,41 @@ function PlayerStatus({ state, error }) {
1808
1817
  });
1809
1818
  return null;
1810
1819
  }
1811
- // src/composition-player.tsx
1812
- function CompositionPlayer({ composition, components, ref }) {
1813
- const { validated, registry, clips } = useMemo(() => {
1814
- const validated = validateComposition(composition);
1815
- const registry = createTimelineRegistry(validated);
1816
- return {
1817
- validated,
1820
+ // src/composition/composition-player.tsx
1821
+ function prepareComposition(composition, components) {
1822
+ const validated = validateComposition(composition);
1823
+ const registry = createTimelineRegistry(validated);
1824
+ const clips = validated.clips.slice().sort((left, right) => left.layer - right.layer).map((clip) => {
1825
+ const renderComponent = Object.hasOwn(components, clip.component) ? components[clip.component] : void 0;
1826
+ if (typeof renderComponent !== "function") throw new RangeError(`Unknown player component: ${clip.component}`);
1827
+ const element = renderComponent({
1828
+ clip,
1818
1829
  registry,
1819
- clips: validated.clips.map((clip, declarationIndex) => ({
1820
- clip,
1821
- declarationIndex
1822
- })).sort((left, right) => {
1823
- if (left.clip.layer < right.clip.layer) return -1;
1824
- if (left.clip.layer > right.clip.layer) return 1;
1825
- return left.declarationIndex - right.declarationIndex;
1826
- }).map(({ clip }) => {
1827
- const renderComponent = Object.hasOwn(components, clip.component) ? components[clip.component] : void 0;
1828
- if (typeof renderComponent !== "function") throw new RangeError(`Unknown player component: ${clip.component}`);
1829
- const element = renderComponent({
1830
- clip,
1831
- registry,
1832
- durationSeconds: clip.durationInFrames / validated.fps
1833
- });
1834
- if (!isValidElement(element)) throw new TypeError(`Component ${clip.component} must return a React element`);
1835
- return /* @__PURE__ */ jsx("div", {
1836
- "data-clip-id": clip.id,
1837
- style: {
1838
- position: "absolute",
1839
- inset: 0
1840
- },
1841
- children: element
1842
- }, clip.id);
1843
- })
1844
- };
1845
- }, [composition, components]);
1846
- const session = useMemo(() => createPlayerSession(validated, registry), [validated, registry]);
1830
+ durationSeconds: clip.durationInFrames / validated.fps
1831
+ });
1832
+ if (!isValidElement(element)) throw new TypeError(`Component ${clip.component} must return a React element`);
1833
+ return /* @__PURE__ */ jsx("div", {
1834
+ "data-clip-id": clip.id,
1835
+ style: {
1836
+ position: "absolute",
1837
+ inset: 0
1838
+ },
1839
+ children: element
1840
+ }, clip.id);
1841
+ });
1842
+ return {
1843
+ validated,
1844
+ session: createPlayerSession(validated, registry),
1845
+ clips
1846
+ };
1847
+ }
1848
+ function CompositionPlayer({ composition, components, ref }) {
1849
+ const { validated, session, clips } = useMemo(() => prepareComposition(composition, components), [composition, components]);
1847
1850
  const [status, setStatus] = useState({
1848
1851
  session,
1849
1852
  state: "loading"
1850
1853
  });
1851
- useImperativeHandle(ref, () => ({
1852
- whenReady: session.whenReady,
1853
- seek: session.seek,
1854
- getComposition: session.getComposition,
1855
- ...session.audio ? { audio: session.audio } : {}
1856
- }), [session]);
1854
+ useImperativeHandle(ref, () => ({ ...session.handle }), [session]);
1857
1855
  useLayoutEffect(() => {
1858
1856
  let active = true;
1859
1857
  session.start().then(() => {
@@ -1890,24 +1888,25 @@ function CompositionPlayer({ composition, components, ref }) {
1890
1888
  height: validated.height,
1891
1889
  overflow: "hidden"
1892
1890
  },
1893
- children: clips
1891
+ children: /* @__PURE__ */ jsx(CompositionFps, {
1892
+ value: validated.fps,
1893
+ children: clips
1894
+ })
1894
1895
  }), /* @__PURE__ */ jsx(PlayerStatus, {
1895
1896
  state: currentStatus.state,
1896
1897
  error: currentStatus.error
1897
1898
  })] });
1898
1899
  }
1899
- // src/renderer-bridge.tsx
1900
+ // src/composition/renderer-bridge.tsx
1900
1901
  function CompositionPlayerBridge(props) {
1901
1902
  const playerRef = useRef(null);
1902
1903
  useLayoutEffect(() => {
1903
1904
  const browserWindow = window;
1904
1905
  if (browserWindow.__serimoRenderer) throw new Error("Renderer bridge already installed");
1905
- const installedPlayer = playerRef.current;
1906
- let active = true;
1906
+ let installedPlayer = playerRef.current;
1907
1907
  const currentPlayer = () => {
1908
- const player = playerRef.current;
1909
- if (!active || !player || player !== installedPlayer) throw new Error("Player is not mounted");
1910
- return player;
1908
+ if (!installedPlayer || playerRef.current !== installedPlayer) throw new Error("Player is not mounted");
1909
+ return installedPlayer;
1911
1910
  };
1912
1911
  const bridge = {
1913
1912
  async whenReady() {
@@ -1928,14 +1927,15 @@ function CompositionPlayerBridge(props) {
1928
1927
  }
1929
1928
  },
1930
1929
  pause() {
1931
- if (active) installedPlayer.audio?.pause();
1930
+ installedPlayer?.audio?.pause();
1932
1931
  }
1933
1932
  } } : {}
1934
1933
  };
1935
1934
  browserWindow.__serimoRenderer = bridge;
1936
1935
  return () => {
1937
- active = false;
1938
- installedPlayer?.audio?.pause();
1936
+ const player = installedPlayer;
1937
+ installedPlayer = null;
1938
+ player?.audio?.pause();
1939
1939
  if (browserWindow.__serimoRenderer === bridge) delete browserWindow.__serimoRenderer;
1940
1940
  };
1941
1941
  }, [props.composition, props.components]);
@@ -1944,4 +1944,612 @@ function CompositionPlayerBridge(props) {
1944
1944
  ref: playerRef
1945
1945
  });
1946
1946
  }
1947
- export { CompositionPlayer, CompositionPlayerBridge };
1947
+ // src/image/image-accessibility.ts
1948
+ function getImageAccessibilityProps(alt) {
1949
+ return {
1950
+ role: alt ? "img" : "presentation",
1951
+ "aria-label": alt || void 0,
1952
+ "aria-hidden": alt ? void 0 : true
1953
+ };
1954
+ }
1955
+ // src/image/image-resources.ts
1956
+ const stores = /* @__PURE__ */ new WeakMap();
1957
+ const MAX_DATA = 536870912;
1958
+ function imageStore(document) {
1959
+ let store = stores.get(document);
1960
+ if (!store) {
1961
+ store = {
1962
+ used: 0,
1963
+ queue: Promise.resolve(),
1964
+ entries: /* @__PURE__ */ new Map()
1965
+ };
1966
+ stores.set(document, store);
1967
+ }
1968
+ return store;
1969
+ }
1970
+ function reserveImageData(bytes, document = globalThis.document) {
1971
+ const store = imageStore(document);
1972
+ if (!Number.isSafeInteger(bytes) || bytes < 1 || store.used + bytes > MAX_DATA) throw Error("E_ASSET: image data budget exceeded");
1973
+ store.used += bytes;
1974
+ let released = false;
1975
+ return () => {
1976
+ if (!released) {
1977
+ released = true;
1978
+ store.used -= bytes;
1979
+ }
1980
+ };
1981
+ }
1982
+ function acquireImageFrame(frame, width, height, document = globalThis.document) {
1983
+ const fail = () => {
1984
+ throw Error("E_ASSET: invalid prepared image resource or data budget");
1985
+ };
1986
+ 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();
1987
+ let url;
1988
+ try {
1989
+ url = new URL(frame.src, document.URL);
1990
+ } catch {
1991
+ return fail();
1992
+ }
1993
+ if (url.origin !== new URL(document.URL).origin || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) fail();
1994
+ const store = imageStore(document);
1995
+ const key = url.href;
1996
+ let resource = store.entries.get(key);
1997
+ if (resource) {
1998
+ if (resource.width !== width || resource.height !== height || resource.bytes !== frame.bytes) fail();
1999
+ resource.state.references++;
2000
+ } else {
2001
+ const surface = width * height * 4;
2002
+ if (store.used + surface > MAX_DATA) fail();
2003
+ store.used += surface;
2004
+ const state = {
2005
+ references: 1,
2006
+ controller: new AbortController(),
2007
+ complete: false,
2008
+ finished: false
2009
+ };
2010
+ const deadline = setTimeout(() => state.controller.abort(), 1e4);
2011
+ const finish = () => {
2012
+ if (state.finished) return;
2013
+ state.finished = true;
2014
+ state.bitmap?.close();
2015
+ store.used -= surface;
2016
+ if (store.entries.get(key)?.state === state) store.entries.delete(key);
2017
+ };
2018
+ const ready = store.queue.then(async () => {
2019
+ state.controller.signal.throwIfAborted();
2020
+ const temporary = frame.bytes * 2;
2021
+ if (store.used + temporary > MAX_DATA) fail();
2022
+ store.used += temporary;
2023
+ try {
2024
+ const response = await fetch(key, {
2025
+ signal: state.controller.signal,
2026
+ credentials: "omit",
2027
+ redirect: "error"
2028
+ });
2029
+ const claimed = response.headers.get("content-length");
2030
+ const body = response.body;
2031
+ if (!response.ok || !body || claimed !== null && Number(claimed) !== frame.bytes) return fail();
2032
+ const reader = body.getReader();
2033
+ const chunks = [];
2034
+ let received = 0;
2035
+ try {
2036
+ while (true) {
2037
+ const result = await reader.read();
2038
+ if (result.done) break;
2039
+ received += result.value.byteLength;
2040
+ if (received > frame.bytes) fail();
2041
+ chunks.push(result.value);
2042
+ }
2043
+ } finally {
2044
+ reader.releaseLock();
2045
+ }
2046
+ if (received !== frame.bytes) fail();
2047
+ const bytes = new Uint8Array(received);
2048
+ let offset = 0;
2049
+ for (const chunk of chunks) {
2050
+ bytes.set(chunk, offset);
2051
+ offset += chunk.length;
2052
+ }
2053
+ chunks.length = 0;
2054
+ const view = new DataView(bytes.buffer);
2055
+ if (bytes[0] !== 137 || bytes[1] !== 80 || bytes[2] !== 78 || bytes[3] !== 71 || view.getUint32(16) !== width || view.getUint32(20) !== height) fail();
2056
+ const bitmap = await createImageBitmap(new Blob([bytes.buffer], { type: "image/png" }));
2057
+ if (bitmap.width !== width || bitmap.height !== height || state.controller.signal.aborted) {
2058
+ bitmap.close();
2059
+ fail();
2060
+ }
2061
+ return bitmap;
2062
+ } finally {
2063
+ store.used -= temporary;
2064
+ }
2065
+ }).then((bitmap) => {
2066
+ state.complete = true;
2067
+ state.bitmap = bitmap;
2068
+ if (!state.references) finish();
2069
+ return bitmap;
2070
+ }, (error) => {
2071
+ state.complete = true;
2072
+ state.controller.abort();
2073
+ finish();
2074
+ throw Error("E_ASSET: prepared image resource failed", { cause: error });
2075
+ }).finally(() => clearTimeout(deadline));
2076
+ store.queue = ready.then(() => void 0, () => void 0);
2077
+ resource = {
2078
+ state,
2079
+ ready,
2080
+ width,
2081
+ height,
2082
+ bytes: frame.bytes,
2083
+ finish
2084
+ };
2085
+ store.entries.set(key, resource);
2086
+ }
2087
+ const held = resource;
2088
+ let released = false;
2089
+ return {
2090
+ ready: held.ready,
2091
+ release() {
2092
+ if (released) return;
2093
+ released = true;
2094
+ const state = held.state;
2095
+ if (--state.references) return;
2096
+ state.controller.abort();
2097
+ if (store.entries.get(key) === held) store.entries.delete(key);
2098
+ if (state.complete) held.finish();
2099
+ }
2100
+ };
2101
+ }
2102
+ // src/image/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
+ const frameRate = BigInt(fps);
2119
+ let total = 0n;
2120
+ const ends = timings.map((time) => {
2121
+ total += time.numerator * (denominator / time.denominator);
2122
+ return total * frameRate;
2123
+ });
2124
+ const period = total * frameRate;
2125
+ const endOfPlayback = plays === "infinite" ? void 0 : period * BigInt(plays);
2126
+ return (localFrame) => {
2127
+ if (!Number.isSafeInteger(localFrame) || localFrame < 0) throw Error("E_ASSET: invalid image seek frame");
2128
+ const elapsed = BigInt(localFrame) * denominator;
2129
+ if (endOfPlayback !== void 0 && elapsed >= endOfPlayback) return frames.length - 1;
2130
+ const position = elapsed % period;
2131
+ let lower = 0;
2132
+ let upper = ends.length - 1;
2133
+ while (lower < upper) {
2134
+ const middle = Math.floor((lower + upper) / 2);
2135
+ const end = ends[middle];
2136
+ if (end === void 0) throw Error("E_ASSET: missing image interval");
2137
+ if (position < end) upper = middle;
2138
+ else lower = middle + 1;
2139
+ }
2140
+ return lower;
2141
+ };
2142
+ }
2143
+ // src/image/image-svg-animation.ts
2144
+ function prepareSvgAnimations(root) {
2145
+ const originals = root.getAnimations({ subtree: true });
2146
+ const effects = originals.map((animation) => {
2147
+ const effect = animation.effect;
2148
+ if (!(effect instanceof KeyframeEffect) || !(effect.target instanceof SVGElement) || effect.pseudoElement !== null) throw Error("E_ASSET: unsupported SVG animation effect");
2149
+ const target = effect.target;
2150
+ const frames = effect.getKeyframes();
2151
+ const properties = new Set(frames.flatMap((frame) => Object.keys(frame)).filter((name) => ![
2152
+ "offset",
2153
+ "computedOffset",
2154
+ "easing",
2155
+ "composite"
2156
+ ].includes(name)));
2157
+ const sampler = new KeyframeEffect(null, frames, effect.getTiming());
2158
+ sampler.composite = effect.composite;
2159
+ const sampled = new Animation(sampler, root.ownerDocument.timeline);
2160
+ sampled.pause();
2161
+ sampled.currentTime = 0;
2162
+ return {
2163
+ target,
2164
+ properties,
2165
+ effect: sampler,
2166
+ animation: sampled
2167
+ };
2168
+ });
2169
+ const underlying = /* @__PURE__ */ new Map();
2170
+ for (const { target, properties } of effects) {
2171
+ const styles = underlying.get(target) ?? /* @__PURE__ */ new Map();
2172
+ underlying.set(target, styles);
2173
+ for (const property of properties) {
2174
+ const name = property.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
2175
+ if (!styles.has(name)) styles.set(name, {
2176
+ value: target.style.getPropertyValue(name),
2177
+ priority: target.style.getPropertyPriority(name)
2178
+ });
2179
+ }
2180
+ }
2181
+ for (const animation of originals) animation.cancel();
2182
+ for (const target of underlying.keys()) target.style.setProperty("animation", "none", "important");
2183
+ return {
2184
+ seek(seconds) {
2185
+ for (const [target, styles] of underlying) for (const [name, original] of styles) if (original.value) target.style.setProperty(name, original.value, original.priority);
2186
+ else target.style.removeProperty(name);
2187
+ try {
2188
+ for (const value of effects) {
2189
+ value.effect.target = value.target;
2190
+ value.animation.currentTime = seconds * 1e3;
2191
+ }
2192
+ const values = [...underlying].map(([target, styles]) => {
2193
+ const computed = getComputedStyle(target);
2194
+ return {
2195
+ target,
2196
+ styles: [...styles.keys()].map((name) => [name, computed.getPropertyValue(name)])
2197
+ };
2198
+ });
2199
+ for (const value of effects) value.effect.target = null;
2200
+ for (const { target, styles } of values) for (const [name, value] of styles) target.style.setProperty(name, value, "important");
2201
+ } finally {
2202
+ for (const value of effects) value.effect.target = null;
2203
+ }
2204
+ },
2205
+ dispose() {
2206
+ for (const value of effects) value.animation.cancel();
2207
+ }
2208
+ };
2209
+ }
2210
+ // src/image/image-svg-validation.ts
2211
+ 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(" "));
2212
+ 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(" "));
2213
+ 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(" "));
2214
+ const paints = /* @__PURE__ */ new Set([
2215
+ "fill",
2216
+ "stroke",
2217
+ "clip-path",
2218
+ "mask",
2219
+ "stop-color"
2220
+ ]);
2221
+ const defaults = /* @__PURE__ */ new Map([
2222
+ ["-webkit-mask-position-x", "0%"],
2223
+ ["-webkit-mask-position-y", "0%"],
2224
+ ["mask-size", "auto"],
2225
+ ["mask-repeat", "repeat"],
2226
+ ["mask-origin", "border-box"],
2227
+ ["mask-clip", "border-box"],
2228
+ ["mask-composite", "add"],
2229
+ ["mask-mode", "match-source"]
2230
+ ]);
2231
+ 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(" "));
2232
+ function rejectPreparedSvg() {
2233
+ throw Error("E_ASSET: invalid or unsupported prepared SVG");
2234
+ }
2235
+ function inspectSvgTree(tree, bytes, width, height) {
2236
+ let count = 0, characters = 0;
2237
+ const ids = /* @__PURE__ */ new Map();
2238
+ const seen = /* @__PURE__ */ new Set();
2239
+ const styles = [];
2240
+ const walk = (node, depth) => {
2241
+ 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) rejectPreparedSvg();
2242
+ seen.add(node);
2243
+ if (node.tag === "mask") {
2244
+ const units = node.attributes.maskUnits ?? "objectBoundingBox";
2245
+ if (!["objectBoundingBox", "userSpaceOnUse"].includes(units)) rejectPreparedSvg();
2246
+ for (const name of [
2247
+ "x",
2248
+ "y",
2249
+ "width",
2250
+ "height"
2251
+ ]) {
2252
+ const value = node.attributes[name];
2253
+ if (value === void 0) continue;
2254
+ if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)%?$/.test(value)) rejectPreparedSvg();
2255
+ const positive = name === "width" || name === "height";
2256
+ const limit = value.endsWith("%") ? positive ? 200 : 100 : units === "objectBoundingBox" ? positive ? 2 : 1 : (name === "x" || name === "width" ? width : height) * (positive ? 2 : 1);
2257
+ const number = parseFloat(value);
2258
+ if (!Number.isFinite(number) || Math.abs(number) > limit || positive && number <= 0) rejectPreparedSvg();
2259
+ }
2260
+ }
2261
+ for (const [name, value] of Object.entries(node.attributes)) {
2262
+ if (!attributes.has(name) && !/^data-[a-z-]+$/.test(name) || typeof value !== "string") rejectPreparedSvg();
2263
+ characters += name.length + value.length;
2264
+ if (characters > bytes) rejectPreparedSvg();
2265
+ if (name === "id") {
2266
+ if (!/^[a-zA-Z_][\w.-]*$/.test(value) || ids.has(value)) rejectPreparedSvg();
2267
+ ids.set(value, node);
2268
+ }
2269
+ if ((name === "href" || name === "xlink:href") && !/^#[a-zA-Z_][\w.-]*$/.test(value)) rejectPreparedSvg();
2270
+ if (name === "style") styles.push(`.inline{${value}}`);
2271
+ if (paints.has(name) && !(name === "fill" && [
2272
+ "animate",
2273
+ "animateTransform",
2274
+ "animateMotion",
2275
+ "set"
2276
+ ].includes(node.tag))) styles.push(`.paint{${name}:${value}}`);
2277
+ if ([
2278
+ "begin",
2279
+ "end",
2280
+ "dur",
2281
+ "repeatDur"
2282
+ ].includes(name)) {
2283
+ for (const time of value.split(";")) if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:ms|s)?$/.test(time.trim()) || !Number.isFinite(parseFloat(time))) rejectPreparedSvg();
2284
+ }
2285
+ }
2286
+ if (["animate", "set"].includes(node.tag)) {
2287
+ const name = node.attributes.attributeName ?? "";
2288
+ if (!animated.has(name)) rejectPreparedSvg();
2289
+ if (paints.has(name)) for (const attr of [
2290
+ "from",
2291
+ "to",
2292
+ "by",
2293
+ "values"
2294
+ ]) for (const value of (node.attributes[attr] ?? "").split(";").filter(Boolean)) styles.push(`.paint{${name}:${value}}`);
2295
+ }
2296
+ if (node.tag === "style") {
2297
+ if (node.children.some((child) => typeof child !== "string")) rejectPreparedSvg();
2298
+ styles.push(node.children.join(""));
2299
+ }
2300
+ for (const child of node.children) if (typeof child === "string") {
2301
+ if (++count > 1e4) rejectPreparedSvg();
2302
+ characters += child.length;
2303
+ if (characters > bytes) rejectPreparedSvg();
2304
+ } else walk(child, depth + 1);
2305
+ };
2306
+ walk(tree, 0);
2307
+ const visiting = /* @__PURE__ */ new Set(), costs = /* @__PURE__ */ new Map();
2308
+ const maskCosts = /* @__PURE__ */ new Map();
2309
+ const expansion = (node, depth) => {
2310
+ if (visiting.has(node) || depth > 128) return rejectPreparedSvg();
2311
+ const cached = costs.get(node);
2312
+ if (cached !== void 0) return cached;
2313
+ visiting.add(node);
2314
+ let cost = 1;
2315
+ let masks = node.tag === "mask" ? 1 : 0;
2316
+ for (const child of node.children) if (typeof child === "string") cost++;
2317
+ else {
2318
+ cost += expansion(child, depth + 1);
2319
+ masks += maskCosts.get(child) ?? 0;
2320
+ }
2321
+ for (const name of ["href", "xlink:href"]) {
2322
+ const href = node.attributes[name];
2323
+ if (href) {
2324
+ const target = ids.get(href.slice(1));
2325
+ if (!target) return rejectPreparedSvg();
2326
+ cost += expansion(target, depth + 1);
2327
+ masks += maskCosts.get(target) ?? 0;
2328
+ }
2329
+ }
2330
+ if (cost > 1e4) return rejectPreparedSvg();
2331
+ visiting.delete(node);
2332
+ costs.set(node, cost);
2333
+ maskCosts.set(node, masks);
2334
+ return cost;
2335
+ };
2336
+ return {
2337
+ styles,
2338
+ ids,
2339
+ nodes: expansion(tree, 0),
2340
+ masks: maskCosts.get(tree) ?? 0
2341
+ };
2342
+ }
2343
+ function validateSvgStyles(styles, ids, nodes) {
2344
+ let cssCharacters = 0, cssFrames = 0, cssRules = 0, cssBraces = 0, animationNames = 0;
2345
+ for (const style of styles) {
2346
+ cssCharacters += style.length;
2347
+ cssBraces += style.match(/{/g)?.length ?? 0;
2348
+ if (cssBraces > 1e4) rejectPreparedSvg();
2349
+ 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)) rejectPreparedSvg();
2350
+ const sheet = new CSSStyleSheet();
2351
+ sheet.replaceSync(style);
2352
+ const visit = (rules) => {
2353
+ for (const rule of rules) {
2354
+ if (++cssRules > 1e4) rejectPreparedSvg();
2355
+ if (rule instanceof CSSKeyframesRule) {
2356
+ cssFrames += rule.cssRules.length;
2357
+ if (cssFrames > 1e3) rejectPreparedSvg();
2358
+ visit(rule.cssRules);
2359
+ } else if (rule instanceof CSSStyleRule || rule instanceof CSSKeyframeRule) {
2360
+ const names = rule.style.getPropertyValue("animation-name");
2361
+ if (names && names !== "none") animationNames = Math.max(animationNames, names.split(",").length);
2362
+ if (animationNames > 1e3) rejectPreparedSvg();
2363
+ for (const name of rule.style) {
2364
+ if (rule instanceof CSSKeyframeRule && (name === "display" || name === "visibility")) rejectPreparedSvg();
2365
+ const value = rule.style.getPropertyValue(name);
2366
+ if (defaults.get(name) === value) continue;
2367
+ if (name === "animation-timeline" && value === "auto" || (name === "animation-range-start" || name === "animation-range-end") && value === "normal") continue;
2368
+ if (!properties.has(name) && name !== "mask-image") rejectPreparedSvg();
2369
+ const remainder = value.replace(/url\(\s*["']?(#[a-zA-Z_][\w.-]*)["']?\s*\)/gi, (_match, target) => {
2370
+ if (!ids.has(target.slice(1))) rejectPreparedSvg();
2371
+ return "";
2372
+ });
2373
+ if (/url\s*\(|\\|image-set\(|cross-fade\(|image\(|attr\(|var\(|env\(/i.test(remainder)) rejectPreparedSvg();
2374
+ }
2375
+ } else rejectPreparedSvg();
2376
+ }
2377
+ };
2378
+ visit(sheet.cssRules);
2379
+ }
2380
+ return nodes * animationNames * (cssCharacters * 4 + (cssFrames + 1) * 2048);
2381
+ }
2382
+ // src/image/image-svg.tsx
2383
+ function SvgImageAsset({ asset, clipId, registry, alt, className, style }) {
2384
+ const ref = useRef(null);
2385
+ const [failure, setFailure] = useState();
2386
+ useLayoutEffect(() => {
2387
+ const host = ref.current;
2388
+ if (!host) return;
2389
+ let active = true;
2390
+ let release, unregister;
2391
+ let releaseCss;
2392
+ let animations;
2393
+ const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
2394
+ host.style.visibility = "hidden";
2395
+ const dispose = () => {
2396
+ active = false;
2397
+ unregister?.();
2398
+ animations?.dispose();
2399
+ shadow.replaceChildren();
2400
+ releaseCss?.();
2401
+ release?.();
2402
+ release = void 0;
2403
+ };
2404
+ const prepare = async () => {
2405
+ try {
2406
+ const { tree, bytes } = asset;
2407
+ if (!tree || tree.tag !== "svg" || !Number.isSafeInteger(bytes) || !bytes || bytes < 1 || bytes > 67108864 || asset.frames.length || asset.plays !== 1) rejectPreparedSvg();
2408
+ const inspected = inspectSvgTree(tree, bytes, asset.width, asset.height);
2409
+ release = reserveImageData(bytes * 24 + asset.width * asset.height * (16 + 64 * inspected.masks * inspected.nodes) + inspected.nodes * 1024, host.ownerDocument);
2410
+ const cssBytes = validateSvgStyles(inspected.styles, inspected.ids, inspected.nodes);
2411
+ if (cssBytes) releaseCss = reserveImageData(cssBytes, host.ownerDocument);
2412
+ const build = (node) => {
2413
+ if (typeof node === "string") return host.ownerDocument.createTextNode(node);
2414
+ const element = host.ownerDocument.createElementNS("http://www.w3.org/2000/svg", node.tag);
2415
+ for (const [name, value] of Object.entries(node.attributes)) if (name === "xlink:href") element.setAttributeNS("http://www.w3.org/1999/xlink", name, value);
2416
+ else element.setAttribute(name, value);
2417
+ for (const child of node.children) element.append(build(child));
2418
+ return element;
2419
+ };
2420
+ const root = build(tree);
2421
+ if (!(root instanceof SVGSVGElement)) return rejectPreparedSvg();
2422
+ root.style.width = "100%";
2423
+ root.style.height = "100%";
2424
+ root.style.display = "block";
2425
+ if (!root.hasAttribute("viewBox")) root.setAttribute("viewBox", `0 0 ${asset.width} ${asset.height}`);
2426
+ shadow.append(root);
2427
+ root.getBoundingClientRect();
2428
+ root.pauseAnimations();
2429
+ root.setCurrentTime(0);
2430
+ animations = prepareSvgAnimations(root);
2431
+ animations.seek(0);
2432
+ if (!active) return;
2433
+ unregister = registry.register(clipId, {
2434
+ seek(localSeconds) {
2435
+ if (!active) return;
2436
+ root.setCurrentTime(localSeconds);
2437
+ animations?.seek(localSeconds);
2438
+ },
2439
+ setActive(visible) {
2440
+ if (active) host.style.visibility = visible ? "visible" : "hidden";
2441
+ }
2442
+ });
2443
+ } catch (error) {
2444
+ if (active) {
2445
+ dispose();
2446
+ setFailure(Error("E_ASSET: SVG preparation failed", { cause: error }));
2447
+ }
2448
+ }
2449
+ };
2450
+ prepare();
2451
+ return dispose;
2452
+ }, [
2453
+ asset,
2454
+ clipId,
2455
+ registry
2456
+ ]);
2457
+ if (failure) throw failure;
2458
+ return /* @__PURE__ */ jsx("div", {
2459
+ ref,
2460
+ className,
2461
+ ...getImageAccessibilityProps(alt),
2462
+ style: {
2463
+ width: asset.width,
2464
+ height: asset.height,
2465
+ ...style,
2466
+ contain: "strict",
2467
+ overflow: "hidden"
2468
+ }
2469
+ });
2470
+ }
2471
+ // src/image/image-asset.tsx
2472
+ function ImageAsset(props) {
2473
+ const { asset, alt } = props;
2474
+ 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");
2475
+ return asset.kind === "svg" ? /* @__PURE__ */ jsx(SvgImageAsset, { ...props }) : /* @__PURE__ */ jsx(RasterImageAsset, { ...props });
2476
+ }
2477
+ function RasterImageAsset({ asset, clipId, registry, alt, className, style }) {
2478
+ const canvasRef = useRef(null);
2479
+ const [failure, setFailure] = useState();
2480
+ const fps = useContext(CompositionFps);
2481
+ if (asset.kind !== "static" && asset.kind !== "sequence" || !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) throw Error("E_ASSET: invalid image declaration");
2482
+ useLayoutEffect(() => {
2483
+ const canvas = canvasRef.current;
2484
+ if (!canvas) throw Error("E_ASSET: missing image surface");
2485
+ let active = true;
2486
+ let unregister;
2487
+ let releaseSurface;
2488
+ const leases = [];
2489
+ const dispose = () => {
2490
+ active = false;
2491
+ unregister?.();
2492
+ unregister = void 0;
2493
+ canvas.width = 0;
2494
+ canvas.height = 0;
2495
+ for (const lease of leases) lease.release();
2496
+ releaseSurface?.();
2497
+ releaseSurface = void 0;
2498
+ };
2499
+ canvas.style.visibility = "hidden";
2500
+ const prepare = async () => {
2501
+ try {
2502
+ releaseSurface = reserveImageData(asset.width * asset.height * 4 + (asset.kind === "sequence" ? (asset.frames.length + 1) * (8 + asset.frames.length * 7) : 0), canvas.ownerDocument);
2503
+ canvas.width = asset.width;
2504
+ canvas.height = asset.height;
2505
+ const context = canvas.getContext("2d");
2506
+ if (!context) throw Error("E_ASSET: image surface unavailable");
2507
+ const select = asset.kind === "sequence" ? createImageSequence(asset.frames, asset.plays, fps ?? 0) : () => 0;
2508
+ const bitmaps = await Promise.all(asset.frames.map((frame) => {
2509
+ const lease = acquireImageFrame(frame, asset.width, asset.height, canvas.ownerDocument);
2510
+ leases.push(lease);
2511
+ return lease.ready;
2512
+ }));
2513
+ if (!active) return;
2514
+ unregister = registry.register(clipId, {
2515
+ seek(localSeconds) {
2516
+ if (active) {
2517
+ const bitmap = bitmaps[select(Math.round(localSeconds * (fps ?? 1)))];
2518
+ if (!bitmap) throw Error("E_ASSET: missing prepared image frame");
2519
+ context.clearRect(0, 0, canvas.width, canvas.height);
2520
+ context.drawImage(bitmap, 0, 0);
2521
+ }
2522
+ },
2523
+ setActive(visible) {
2524
+ if (active) canvas.style.visibility = visible ? "visible" : "hidden";
2525
+ }
2526
+ });
2527
+ } catch (error) {
2528
+ if (active) {
2529
+ dispose();
2530
+ setFailure(error instanceof Error ? error : Error("E_ASSET: image preparation failed", { cause: error }));
2531
+ }
2532
+ }
2533
+ };
2534
+ prepare();
2535
+ return dispose;
2536
+ }, [
2537
+ asset,
2538
+ clipId,
2539
+ registry,
2540
+ fps
2541
+ ]);
2542
+ if (failure) throw failure;
2543
+ return /* @__PURE__ */ jsx("canvas", {
2544
+ ref: canvasRef,
2545
+ className,
2546
+ ...getImageAccessibilityProps(alt),
2547
+ style: {
2548
+ display: "block",
2549
+ width: asset.width,
2550
+ height: asset.height,
2551
+ ...style
2552
+ }
2553
+ });
2554
+ }
2555
+ export { CompositionPlayer, CompositionPlayerBridge, ImageAsset };