pixi-effects 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +11 -8
  3. package/ai/SKILL.md +2 -1
  4. package/ai/reference/cheatsheet.md +12 -1
  5. package/ai/reference/pitfalls.md +4 -0
  6. package/ai/reference/recipes.md +57 -0
  7. package/ai/template.html +8 -4
  8. package/ai/tools/check.mjs +17 -1
  9. package/ai/tools/render.mjs +13 -9
  10. package/dist/{Base-CyvSLoCP.d.ts → Base-CYH9vPCH.d.ts} +1 -1
  11. package/dist/{Base-CwUxTfja.d.cts → Base-W3sQzGPO.d.cts} +1 -1
  12. package/dist/Controller.cjs +58 -0
  13. package/dist/Controller.cjs.map +1 -1
  14. package/dist/Controller.d.cts +13 -3
  15. package/dist/Controller.d.ts +13 -3
  16. package/dist/Controller.js +58 -0
  17. package/dist/Controller.js.map +1 -1
  18. package/dist/{Movie-nzmWsxWX.d.ts → Movie-CY2QPVVM.d.cts} +90 -2
  19. package/dist/{Movie-DSSNOF3T.d.cts → Movie-EBF6_RfX.d.ts} +90 -2
  20. package/dist/Presenter.cjs +671 -0
  21. package/dist/Presenter.cjs.map +1 -0
  22. package/dist/Presenter.d.cts +123 -0
  23. package/dist/Presenter.d.ts +123 -0
  24. package/dist/Presenter.js +669 -0
  25. package/dist/Presenter.js.map +1 -0
  26. package/dist/index.cjs +645 -36
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +162 -5
  29. package/dist/index.d.ts +162 -5
  30. package/dist/index.js +640 -37
  31. package/dist/index.js.map +1 -1
  32. package/dist/loader.css +1 -1
  33. package/dist/three.d.cts +2 -2
  34. package/dist/three.d.ts +2 -2
  35. package/dist/{types-BXu28nJj.d.cts → types-mpqQO8MJ.d.cts} +39 -1
  36. package/dist/{types-BXu28nJj.d.ts → types-mpqQO8MJ.d.ts} +39 -1
  37. package/docs/api.md +79 -0
  38. package/docs/dsl.md +48 -0
  39. package/llms-full.txt +202 -2
  40. package/llms.txt +3 -3
  41. package/package.json +5 -1
package/dist/index.cjs CHANGED
@@ -181,7 +181,7 @@ function fft(re, im) {
181
181
  }
182
182
  var FRAME = 2048;
183
183
  function spectralCentroid(samples, sampleRate, from = 0, to = samples.length) {
184
- let num2 = 0;
184
+ let num3 = 0;
185
185
  let den = 0;
186
186
  const re = new Float64Array(FRAME);
187
187
  const im = new Float64Array(FRAME);
@@ -196,11 +196,11 @@ function spectralCentroid(samples, sampleRate, from = 0, to = samples.length) {
196
196
  fft(re, im);
197
197
  for (let b = 1; b < FRAME / 2; b++) {
198
198
  const power = re[b] * re[b] + im[b] * im[b];
199
- num2 += power * (b * sampleRate / FRAME);
199
+ num3 += power * (b * sampleRate / FRAME);
200
200
  den += power;
201
201
  }
202
202
  }
203
- return den > 1e-9 ? Math.round(num2 / den / 10) * 10 : 0;
203
+ return den > 1e-9 ? Math.round(num3 / den / 10) * 10 : 0;
204
204
  }
205
205
 
206
206
  // src/core/inspectAudio.ts
@@ -761,6 +761,7 @@ var TransitionMaskFilter = class extends PIXI.Filter {
761
761
  };
762
762
 
763
763
  // src/core/Transitions.ts
764
+ var EPS = 1e-6;
764
765
  var windows = /* @__PURE__ */ new WeakMap();
765
766
  function transitionWindowsOf(spec) {
766
767
  return windows.get(spec) ?? [];
@@ -871,13 +872,13 @@ function expandTransitions(spec) {
871
872
  const fromSeq = fromEntry.seq;
872
873
  const fromStart = chunk6NWJLVCA_cjs.resolveAt(fromSeq.at, parentDuration);
873
874
  const fromEnd = fromStart + (fromSeq.duration ?? parentDuration);
874
- if (tStart < fromStart || tEnd > fromEnd) {
875
+ if (tStart < fromStart - EPS || tEnd > fromEnd + EPS) {
875
876
  throw new Error(`pixi-effects: ${tag} window [${tStart}, ${tEnd}] is not covered by \`from\` "${t.from}" (lives [${fromStart}, ${fromEnd}], so it ends at ${fromEnd})`);
876
877
  }
877
878
  const toSeq = toEntry.seq;
878
879
  const toStart = chunk6NWJLVCA_cjs.resolveAt(toSeq.at, parentDuration);
879
880
  const toEnd = toStart + (toSeq.duration ?? parentDuration);
880
- if (tStart < toStart || tEnd > toEnd) {
881
+ if (tStart < toStart - EPS || tEnd > toEnd + EPS) {
881
882
  throw new Error(`pixi-effects: ${tag} window [${tStart}, ${tEnd}] is not covered by \`to\` "${t.to}" (lives [${toStart}, ${toEnd}], so it starts at ${toStart})`);
882
883
  }
883
884
  const record = windows.get(out) ?? [];
@@ -1495,6 +1496,141 @@ function normalizePoster(poster, duration, frameRate) {
1495
1496
  return { seconds, frame: Math.round(seconds * frameRate) };
1496
1497
  }
1497
1498
 
1499
+ // src/core/pdf.ts
1500
+ var enc = (s) => {
1501
+ const out = new Uint8Array(s.length);
1502
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 255;
1503
+ return out;
1504
+ };
1505
+ var num2 = (n) => String(Math.round(n * 1e3) / 1e3);
1506
+ var textString = (s) => {
1507
+ if (/^[\x20-\x7e]*$/.test(s)) return `(${s.replace(/[\\()]/g, (m) => `\\${m}`)})`;
1508
+ let hex = "FEFF";
1509
+ for (let i = 0; i < s.length; i++) hex += s.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0");
1510
+ return `<${hex}>`;
1511
+ };
1512
+ function buildPdf(pages, opts = {}) {
1513
+ if (pages.length === 0) throw new Error("pixi-effects: a PDF needs at least one page");
1514
+ const first = (i) => 3 + i * 3;
1515
+ const objects = [];
1516
+ objects[1] = [enc("<< /Type /Catalog /Pages 2 0 R >>")];
1517
+ objects[2] = [enc(`<< /Type /Pages /Kids [${pages.map((_, i) => `${first(i)} 0 R`).join(" ")}] /Count ${pages.length} >>`)];
1518
+ pages.forEach((p, i) => {
1519
+ const w = p.width * 0.75, h = p.height * 0.75, n = first(i);
1520
+ objects[n] = [enc(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${num2(w)} ${num2(h)}] /Resources << /XObject << /Im0 ${n + 2} 0 R >> >> /Contents ${n + 1} 0 R >>`)];
1521
+ const content = `q ${num2(w)} 0 0 ${num2(h)} 0 0 cm /Im0 Do Q`;
1522
+ objects[n + 1] = [enc(`<< /Length ${content.length} >>
1523
+ stream
1524
+ ${content}
1525
+ endstream`)];
1526
+ objects[n + 2] = [enc(`<< /Type /XObject /Subtype /Image /Width ${p.width} /Height ${p.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${p.jpeg.length} >>
1527
+ stream
1528
+ `), p.jpeg, enc("\nendstream")];
1529
+ });
1530
+ const infoNo = opts.title !== void 0 ? first(pages.length) : 0;
1531
+ if (infoNo) objects[infoNo] = [enc(`<< /Title ${textString(opts.title)} /Producer (pixi-effects) >>`)];
1532
+ const count = infoNo || first(pages.length);
1533
+ const chunks = [enc("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n")];
1534
+ let offset = chunks[0].length;
1535
+ const offsets = [];
1536
+ for (let n = 1; n < count + (infoNo ? 1 : 0); n++) {
1537
+ const body = objects[n];
1538
+ if (!body) continue;
1539
+ offsets[n] = offset;
1540
+ const parts = [enc(`${n} 0 obj
1541
+ `), ...body, enc("\nendobj\n")];
1542
+ for (const part of parts) {
1543
+ chunks.push(part);
1544
+ offset += part.length;
1545
+ }
1546
+ }
1547
+ const size = (infoNo || first(pages.length)) + (infoNo ? 1 : 0);
1548
+ let xref = `xref
1549
+ 0 ${size}
1550
+ 0000000000 65535 f
1551
+ `;
1552
+ for (let n = 1; n < size; n++) xref += `${String(offsets[n] ?? 0).padStart(10, "0")} 00000 n
1553
+ `;
1554
+ xref += `trailer
1555
+ << /Size ${size} /Root 1 0 R${infoNo ? ` /Info ${infoNo} 0 R` : ""} >>
1556
+ startxref
1557
+ ${offset}
1558
+ %%EOF
1559
+ `;
1560
+ chunks.push(enc(xref));
1561
+ const total = chunks.reduce((sum, c) => sum + c.length, 0);
1562
+ const out = new Uint8Array(total);
1563
+ let at = 0;
1564
+ for (const c of chunks) {
1565
+ out.set(c, at);
1566
+ at += c.length;
1567
+ }
1568
+ return out;
1569
+ }
1570
+
1571
+ // src/core/stops.ts
1572
+ var KEYS = ["at", "page", "notes", "advance"];
1573
+ function normalizeStops(raw, duration, frameRate) {
1574
+ if (!raw || raw.length === 0) return [];
1575
+ const total = Math.round(duration * frameRate);
1576
+ const specs = [];
1577
+ raw.forEach((r, i) => {
1578
+ const spec = typeof r === "number" ? { at: r } : r && typeof r === "object" ? r : null;
1579
+ if (!spec || typeof spec.at !== "number" || !Number.isFinite(spec.at)) {
1580
+ console.warn(`pixi-effects: stops[${i}] ${JSON.stringify(r)} is not a time in seconds (or { at, page?, notes?, advance? }); ignored`);
1581
+ return;
1582
+ }
1583
+ if (typeof r === "object") chunkUQBGW5DO_cjs.warnUnknownOptions(`stops[${i}]`, r, KEYS);
1584
+ const at = spec.at < 0 ? duration + spec.at : spec.at;
1585
+ if (at < -1e-9 || at > duration + 1e-9) {
1586
+ console.warn(`pixi-effects: stops[${i}] at ${spec.at} s is outside the movie (0 to ${duration} s); ignored`);
1587
+ return;
1588
+ }
1589
+ specs.push({ ...spec, at });
1590
+ });
1591
+ specs.sort((a, b) => a.at - b.at);
1592
+ const kept = [];
1593
+ for (const s of specs) {
1594
+ const frame = Math.min(total, Math.max(0, Math.round(s.at * frameRate)));
1595
+ const last = kept[kept.length - 1];
1596
+ if (last && Math.min(total, Math.max(0, Math.round(last.at * frameRate))) === frame) {
1597
+ console.warn(`pixi-effects: two stops are on the same frame (${frame}, about ${s.at.toFixed(2)} s); one is kept`);
1598
+ continue;
1599
+ }
1600
+ kept.push(s);
1601
+ }
1602
+ const anyPage = kept.some((s) => s.page !== void 0);
1603
+ let pageIndex = -1, pageName = null;
1604
+ return kept.map((s, index) => {
1605
+ const pageStart = index === 0 || (anyPage ? s.page !== void 0 : true);
1606
+ if (pageStart) {
1607
+ pageIndex++;
1608
+ pageName = typeof s.page === "string" ? s.page : null;
1609
+ }
1610
+ const stop = { index, at: s.at, frame: Math.min(total, Math.max(0, Math.round(s.at * frameRate))), page: pageName, pageIndex, pageStart };
1611
+ if (typeof s.notes === "string") stop.notes = s.notes;
1612
+ if (s.advance !== void 0) {
1613
+ if (typeof s.advance === "number" && Number.isFinite(s.advance) && s.advance >= 0) stop.advance = s.advance;
1614
+ else console.warn(`pixi-effects: stops[${index}] advance must be a number of seconds >= 0, got ${JSON.stringify(s.advance)}; ignored`);
1615
+ }
1616
+ return stop;
1617
+ });
1618
+ }
1619
+ function nextStopAfter(stops, frame) {
1620
+ return stops.find((s) => s.frame > frame) ?? null;
1621
+ }
1622
+ function previousStopBefore(stops, frame) {
1623
+ for (let i = stops.length - 1; i >= 0; i--) if (stops[i].frame < frame) return stops[i];
1624
+ return null;
1625
+ }
1626
+ function stopAtOrBefore(stops, frame) {
1627
+ for (let i = stops.length - 1; i >= 0; i--) if (stops[i].frame <= frame) return stops[i];
1628
+ return null;
1629
+ }
1630
+ function pageStarts(stops) {
1631
+ return stops.filter((s) => s.pageStart);
1632
+ }
1633
+
1498
1634
  // src/core/loader.ts
1499
1635
  var FADE_FALLBACK_MS = 900;
1500
1636
  function resolveLoader(option, canvas) {
@@ -1545,6 +1681,12 @@ var Movie = class {
1545
1681
  _cancelAudioStart = null;
1546
1682
  /** The poster time in seconds (`movie.init({ poster })`), or null. */
1547
1683
  poster = null;
1684
+ /** The stops of the composition (`composition.stops`), checked and in order: where `next()` pauses. Empty for an ordinary movie. */
1685
+ stops = [];
1686
+ /** The frame `next()` is playing toward, or null. */
1687
+ _stopAt = null;
1688
+ _stopWaiters = [];
1689
+ _arriving = false;
1548
1690
  /** The motion blur `render()`, `snapshot()` and `contactSheet()` apply unless told otherwise (`movie.init({ motionBlur })`), or null. */
1549
1691
  motionBlur = null;
1550
1692
  _posterFrame = null;
@@ -1642,6 +1784,7 @@ var Movie = class {
1642
1784
  const poster = normalizePoster(options.poster, this.duration, this.frameRate);
1643
1785
  this.poster = poster.seconds;
1644
1786
  this.motionBlur = resolveMotionBlur(options.motionBlur, "movie.init()");
1787
+ this.stops = normalizeStops(options.composition?.stops, this.duration, this.frameRate);
1645
1788
  this._posterFrame = poster.frame;
1646
1789
  this.background = options.background ?? "#000000";
1647
1790
  this.timeline = gsap.gsap.timeline({ paused: true, defaults: { ease: "none" } });
@@ -1722,6 +1865,7 @@ var Movie = class {
1722
1865
  }
1723
1866
  async gotoFrame(frame, force = false) {
1724
1867
  if (this._initState !== "ready") return;
1868
+ if (!this._arriving) this._cancelStop();
1725
1869
  if (!force && !this._atPoster && this.currentFrame === frame) return;
1726
1870
  if (this._quiet > 0) return this._goto(frame);
1727
1871
  const target = Math.max(0, Math.min(frame, this.totalFrames));
@@ -1771,19 +1915,80 @@ var Movie = class {
1771
1915
  async snapshot(frame = this.currentFrame, opts = {}) {
1772
1916
  chunkUQBGW5DO_cjs.warnUnknownOptions("movie.snapshot()", opts, ["scale", "type", "as", "motionBlur"]);
1773
1917
  this._requireReady("snapshot");
1774
- const mb = this._blurFor(opts.motionBlur, "movie.snapshot()");
1775
- const f = clampFrame(frame, this.totalFrames);
1918
+ return this._captureFrame(clampFrame(frame, this.totalFrames), { scale: opts.scale ?? 1, type: opts.type ?? "image/png", as: opts.as ?? "blob", motionBlur: opts.motionBlur });
1919
+ }
1920
+ /** Seek to `frame` (quietly, and stay there) and encode the canvas as a picture. */
1921
+ async _captureFrame(frame, o) {
1922
+ const mb = this._blurFor(o.motionBlur, "a picture");
1776
1923
  let source = this.app.canvas;
1777
1924
  if (mb) {
1778
1925
  source = this._blurCanvas();
1779
- await this._quietly(() => this._exposeFrame(f, mb, source, true));
1780
- } else await this._quietly(() => this.gotoFrame(f, true));
1781
- const scale = opts.scale ?? 1;
1926
+ await this._quietly(() => this._exposeFrame(frame, mb, source, true));
1927
+ } else await this._quietly(() => this.gotoFrame(frame, true));
1782
1928
  const out = document.createElement("canvas");
1783
- out.width = Math.max(1, Math.round(this.width * scale));
1784
- out.height = Math.max(1, Math.round(this.height * scale));
1929
+ out.width = Math.max(1, Math.round(this.width * o.scale));
1930
+ out.height = Math.max(1, Math.round(this.height * o.scale));
1785
1931
  out.getContext("2d").drawImage(source, 0, 0, out.width, out.height);
1786
- return encodeCanvas(out, opts.type ?? "image/png", opts.as ?? "blob");
1932
+ return encodeCanvas(out, o.type, o.as, o.quality);
1933
+ }
1934
+ async stopImages(opts = {}) {
1935
+ chunkUQBGW5DO_cjs.warnUnknownOptions("movie.stopImages()", opts, ["which", "pick", "scale", "type", "quality", "as", "motionBlur", "onImage"]);
1936
+ this._requireReady("stopImages");
1937
+ if (this.stops.length === 0) return [];
1938
+ let picks;
1939
+ if (opts.which === "stops") picks = this.stops;
1940
+ else {
1941
+ const byPage = /* @__PURE__ */ new Map();
1942
+ for (const s of this.stops) byPage.set(s.pageIndex, [...byPage.get(s.pageIndex) ?? [], s]);
1943
+ picks = [...byPage.values()].map((list) => opts.pick === "first" ? list[0] : list[list.length - 1]);
1944
+ }
1945
+ this.pause();
1946
+ const back = this.currentFrame, wasAtPoster = this._atPoster;
1947
+ const out = [];
1948
+ try {
1949
+ for (const stop of picks) {
1950
+ const image = await this._captureFrame(stop.frame, {
1951
+ scale: opts.scale ?? 1,
1952
+ type: opts.type ?? "image/png",
1953
+ quality: opts.quality,
1954
+ as: opts.as ?? "blob",
1955
+ motionBlur: opts.motionBlur === void 0 ? false : opts.motionBlur
1956
+ });
1957
+ const item = { stop, page: stop.pageIndex, image };
1958
+ out.push(item);
1959
+ opts.onImage?.(item);
1960
+ }
1961
+ } finally {
1962
+ if (wasAtPoster) await this._showPoster();
1963
+ else await this._quietly(() => this.gotoFrame(back, true));
1964
+ }
1965
+ return out;
1966
+ }
1967
+ /**
1968
+ * The deck as a PDF: one page per page of the talk (the page's last stop, fully built; `which: 'stops'` makes a page of every stop), each a
1969
+ * JPEG at the canvas size. Needs `composition.stops`. A transparent background comes out black: give the movie a `background`.
1970
+ */
1971
+ async exportPDF(opts = {}) {
1972
+ chunkUQBGW5DO_cjs.warnUnknownOptions("movie.exportPDF()", opts, ["which", "pick", "scale", "quality", "title", "motionBlur", "onImage"]);
1973
+ this._requireReady("exportPDF");
1974
+ if (this.stops.length === 0) throw new Error("pixi-effects: movie.exportPDF(): this movie has no stops, so there are no pages; add `stops` to the composition (or build it with deck())");
1975
+ const scale = opts.scale ?? 1;
1976
+ const images = await this.stopImages({
1977
+ which: opts.which,
1978
+ pick: opts.pick,
1979
+ scale,
1980
+ type: "image/jpeg",
1981
+ quality: opts.quality ?? 0.92,
1982
+ as: "blob",
1983
+ motionBlur: opts.motionBlur,
1984
+ onImage: opts.onImage
1985
+ });
1986
+ const pages = await Promise.all(images.map(async (i) => ({
1987
+ jpeg: new Uint8Array(await i.image.arrayBuffer()),
1988
+ width: Math.max(1, Math.round(this.width * scale)),
1989
+ height: Math.max(1, Math.round(this.height * scale))
1990
+ })));
1991
+ return new Blob([buildPdf(pages, { title: opts.title })], { type: "application/pdf" });
1787
1992
  }
1788
1993
  async contactSheet(opts = {}) {
1789
1994
  chunkUQBGW5DO_cjs.warnUnknownOptions("movie.contactSheet()", opts, ["frames", "times", "count", "columns", "cellWidth", "as", "motionBlur"]);
@@ -1917,6 +2122,99 @@ var Movie = class {
1917
2122
  c.height = stage.height;
1918
2123
  return c;
1919
2124
  }
2125
+ /** Which stop the playhead is on or has passed (-1 before the first). */
2126
+ get stopIndex() {
2127
+ return stopAtOrBefore(this.stops, this.currentFrame)?.index ?? -1;
2128
+ }
2129
+ /** The stop the playhead is on or has passed, or null. */
2130
+ get currentStop() {
2131
+ return stopAtOrBefore(this.stops, this.currentFrame);
2132
+ }
2133
+ /** Which page the playhead is in (0-based), -1 before the first stop. */
2134
+ get pageIndex() {
2135
+ return this.currentStop?.pageIndex ?? -1;
2136
+ }
2137
+ /** How many pages the stops make. */
2138
+ get pageCount() {
2139
+ return pageStarts(this.stops).length;
2140
+ }
2141
+ _cancelStop() {
2142
+ this._stopAt = null;
2143
+ this._settleStopWaiters();
2144
+ }
2145
+ _settleStopWaiters() {
2146
+ const waiters = this._stopWaiters;
2147
+ this._stopWaiters = [];
2148
+ waiters.forEach((w) => w());
2149
+ }
2150
+ _emitStop(stop) {
2151
+ this.emit("stop", { index: stop.index, stop, pageIndex: stop.pageIndex });
2152
+ }
2153
+ /** Land exactly on a stop's frame, pause, and say so. */
2154
+ async _arriveAtStop(frame) {
2155
+ this._arriving = true;
2156
+ this._stopAt = null;
2157
+ try {
2158
+ this.pause();
2159
+ await this._goto(frame);
2160
+ } catch (err) {
2161
+ console.warn("pixi-effects: could not land on a stop:", err);
2162
+ this._emitError("playback", err);
2163
+ } finally {
2164
+ this._arriving = false;
2165
+ }
2166
+ const stop = this.stops.find((s) => s.frame === frame);
2167
+ if (stop) this._emitStop(stop);
2168
+ this._settleStopWaiters();
2169
+ }
2170
+ /**
2171
+ * Play to the next stop and pause exactly there (a presentation's "next"). Pressed again while it is playing toward a stop, it skips the
2172
+ * rest of the animation and lands on that stop at once. After the last stop it plays to the end. Resolves when it has landed (or
2173
+ * stopped for another reason). An ordinary `play()` ignores the stops.
2174
+ */
2175
+ async next() {
2176
+ if (this._initState !== "ready") return;
2177
+ if (this._stopAt !== null) {
2178
+ await this._arriveAtStop(this._stopAt);
2179
+ return;
2180
+ }
2181
+ if (this.currentFrame >= this.totalFrames) return;
2182
+ const target = nextStopAfter(this.stops, this.currentFrame);
2183
+ this._stopAt = target ? target.frame : null;
2184
+ const landed = new Promise((resolve) => this._stopWaiters.push(resolve));
2185
+ this.play();
2186
+ await landed;
2187
+ }
2188
+ /** Jump back to the previous stop at once (no reverse playback); from the first stop, to the start. */
2189
+ async prev() {
2190
+ if (this._initState !== "ready") return;
2191
+ this.pause();
2192
+ const target = previousStopBefore(this.stops, this.currentFrame);
2193
+ await this.gotoFrame(target ? target.frame : 0, true);
2194
+ if (target) this._emitStop(target);
2195
+ }
2196
+ /** Jump to stop `index` (0-based). */
2197
+ async goToStop(index) {
2198
+ if (this._initState !== "ready") return;
2199
+ const stop = this.stops[index];
2200
+ if (!stop) {
2201
+ console.warn(`pixi-effects: movie.goToStop(${index}): there are ${this.stops.length} stops (0 to ${this.stops.length - 1})`);
2202
+ return;
2203
+ }
2204
+ this.pause();
2205
+ await this.gotoFrame(stop.frame, true);
2206
+ this._emitStop(stop);
2207
+ }
2208
+ /** Jump to the first stop of page `page` (0-based). */
2209
+ async goToPage(page) {
2210
+ const starts = pageStarts(this.stops);
2211
+ const stop = starts[page];
2212
+ if (!stop) {
2213
+ console.warn(`pixi-effects: movie.goToPage(${page}): there are ${starts.length} pages (0 to ${starts.length - 1})`);
2214
+ return;
2215
+ }
2216
+ await this.goToStop(stop.index);
2217
+ }
1920
2218
  play() {
1921
2219
  if (this._initState !== "ready") return;
1922
2220
  if (this.currentFrame >= this.totalFrames) this.currentFrame = 0;
@@ -1932,6 +2230,10 @@ var Movie = class {
1932
2230
  }
1933
2231
  const elapsed = (time - startTime) / 1e3;
1934
2232
  const frame = Math.floor(elapsed * this.frameRate);
2233
+ if (this._stopAt !== null && frame >= this._stopAt) {
2234
+ void this._arriveAtStop(this._stopAt);
2235
+ return;
2236
+ }
1935
2237
  if (frame <= this.totalFrames) {
1936
2238
  inFlight = true;
1937
2239
  this._goto(frame).catch((err) => {
@@ -1948,6 +2250,7 @@ var Movie = class {
1948
2250
  this._emitError("playback", err);
1949
2251
  });
1950
2252
  this.emit("ended");
2253
+ this._settleStopWaiters();
1951
2254
  }
1952
2255
  };
1953
2256
  this._raf = requestAnimationFrame(tick);
@@ -1989,6 +2292,7 @@ var Movie = class {
1989
2292
  this.gainNode = null;
1990
2293
  }
1991
2294
  if (wasPlaying) this.emit("pause");
2295
+ if (!this._arriving) this._cancelStop();
1992
2296
  }
1993
2297
  set volume(v) {
1994
2298
  const next = Math.max(0, Math.min(1, v));
@@ -2041,9 +2345,9 @@ var Movie = class {
2041
2345
  };
2042
2346
  var END_MARGIN = 1e-4;
2043
2347
  var clampFrame = (f, last) => Math.max(0, Math.min(Math.round(f), last));
2044
- function encodeCanvas(canvas, type, as) {
2045
- if (as === "dataURL") return Promise.resolve(canvas.toDataURL(type));
2046
- return new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(new Error("pixi-effects: could not encode the image")), type));
2348
+ function encodeCanvas(canvas, type, as, quality) {
2349
+ if (as === "dataURL") return Promise.resolve(canvas.toDataURL(type, quality));
2350
+ return new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(new Error("pixi-effects: could not encode the image")), type, quality));
2047
2351
  }
2048
2352
  function safeRun(fn) {
2049
2353
  try {
@@ -2282,11 +2586,11 @@ function orbit(opts) {
2282
2586
  }
2283
2587
 
2284
2588
  // src/presets/particles.ts
2285
- var KEYS = ["count", "at", "emit", "life", "area", "angle", "speed", "gravity", "wind", "drag", "sway", "size", "scale", "fade", "colors", "shape", "spin", "seed", "name", "blendMode", "template", "sampleRate"];
2589
+ var KEYS2 = ["count", "at", "emit", "life", "area", "angle", "speed", "gravity", "wind", "drag", "sway", "size", "scale", "fade", "colors", "shape", "spin", "seed", "name", "blendMode", "template", "sampleRate"];
2286
2590
  var SHAPES = ["circle", "rect", "star"];
2287
2591
  var MAX_KEYFRAMES = 3e4;
2288
2592
  function particles(opts) {
2289
- chunkUQBGW5DO_cjs.warnUnknownOptions("particles()", opts, KEYS);
2593
+ chunkUQBGW5DO_cjs.warnUnknownOptions("particles()", opts, KEYS2);
2290
2594
  const { count, at = 0, emit = 0, gravity = 0, wind = 0, drag = 0, sway, fade, colors = ["#ffffff"], shape = "circle", seed = 0, name = "particle", template, sampleRate = 20 } = opts;
2291
2595
  if (!(Number.isInteger(count) && count > 0)) throw new Error(`particles(): count must be a whole number of particles (at least 1), got ${count}`);
2292
2596
  const life = range("life", opts.life, 1e-6);
@@ -2306,7 +2610,7 @@ function particles(opts) {
2306
2610
  if (count * worst > MAX_KEYFRAMES) {
2307
2611
  throw new Error(`particles(): too many keyframes (${count} particles \xD7 up to ${worst} samples each): lower count or life, or lower sampleRate (now ${sampleRate})`);
2308
2612
  }
2309
- const round2 = (v) => Math.round(v * 1e6) / 1e6;
2613
+ const round3 = (v) => Math.round(v * 1e6) / 1e6;
2310
2614
  const out = [];
2311
2615
  for (let i = 0; i < count; i++) {
2312
2616
  const r = chunk6NWJLVCA_cjs.random(seed * 1000003 + i * 7919 + 17);
@@ -2339,30 +2643,30 @@ function particles(opts) {
2339
2643
  const step = lifetime / steps;
2340
2644
  for (let k = 1; k <= steps; k++) {
2341
2645
  const p = at_(k * step);
2342
- kfs.push({ at: round2((k - 1) * step), to: { x: round2(p.x), y: round2(p.y) }, duration: round2(step), ease: "none" });
2646
+ kfs.push({ at: round3((k - 1) * step), to: { x: round3(p.x), y: round3(p.y) }, duration: round3(step), ease: "none" });
2343
2647
  }
2344
- if (opts.scale) kfs.push({ at: 0, to: { scale: opts.scale[1] }, duration: round2(lifetime), ease: "none" });
2345
- if (turn !== 0) kfs.push({ at: 0, to: { rotation: round2(startAngle + turn * lifetime) }, duration: round2(lifetime), ease: "none" });
2648
+ if (opts.scale) kfs.push({ at: 0, to: { scale: opts.scale[1] }, duration: round3(lifetime), ease: "none" });
2649
+ if (turn !== 0) kfs.push({ at: 0, to: { rotation: round3(startAngle + turn * lifetime) }, duration: round3(lifetime), ease: "none" });
2346
2650
  if (fade?.in) kfs.push({ at: 0, to: { alpha: 1 }, duration: fade.in, ease: "none" });
2347
2651
  if (fade?.out) kfs.push({ at: -fade.out, from: { alpha: 1 }, to: { alpha: 0 }, duration: fade.out, ease: "none" });
2348
- const initial = { x: round2(x0), y: round2(y0) };
2652
+ const initial = { x: round3(x0), y: round3(y0) };
2349
2653
  if (opts.scale) initial.scale = opts.scale[0];
2350
2654
  if (fade?.in) initial.alpha = 0;
2351
- if (spin) initial.rotation = round2(startAngle);
2352
- const common = { name: `${name}-${i}`, at: round2(born), duration: round2(lifetime), ...opts.blendMode ? { blendMode: opts.blendMode } : {} };
2655
+ if (spin) initial.rotation = round3(startAngle);
2656
+ const common = { name: `${name}-${i}`, at: round3(born), duration: round3(lifetime), ...opts.blendMode ? { blendMode: opts.blendMode } : {} };
2353
2657
  if (template) {
2354
2658
  const t = template;
2355
2659
  out.push({ ...t, ...common, initial: { ...t.initial, ...initial }, keyframes: [...t.keyframes ?? [], ...kfs] });
2356
2660
  continue;
2357
2661
  }
2358
2662
  const style = { ...initial, fillColor: color };
2359
- if (shape === "circle") out.push({ type: "shape", shape: "circle", radius: round2(s), ...common, initial: style, keyframes: kfs });
2360
- else if (shape === "rect") out.push({ type: "shape", shape: "rect", width: round2(s * 2), height: round2(s * 2), ...common, initial: style, keyframes: kfs });
2663
+ if (shape === "circle") out.push({ type: "shape", shape: "circle", radius: round3(s), ...common, initial: style, keyframes: kfs });
2664
+ else if (shape === "rect") out.push({ type: "shape", shape: "rect", width: round3(s * 2), height: round3(s * 2), ...common, initial: style, keyframes: kfs });
2361
2665
  else {
2362
2666
  const points = [];
2363
2667
  for (let p = 0; p < 10; p++) {
2364
2668
  const rad = p % 2 === 0 ? s : s * 0.45, ang = -Math.PI / 2 + p * Math.PI / 5;
2365
- points.push([round2(rad * Math.cos(ang)), round2(rad * Math.sin(ang))]);
2669
+ points.push([round3(rad * Math.cos(ang)), round3(rad * Math.sin(ang))]);
2366
2670
  }
2367
2671
  out.push({ type: "shape", shape: "polygon", points, ...common, initial: style, keyframes: kfs });
2368
2672
  }
@@ -2378,10 +2682,10 @@ function range(name, v, min) {
2378
2682
  }
2379
2683
 
2380
2684
  // src/presets/followPath.ts
2381
- var KEYS2 = ["d", "at", "duration", "ease", "from", "to", "orient", "rotate", "frameRate"];
2685
+ var KEYS3 = ["d", "at", "duration", "ease", "from", "to", "orient", "rotate", "frameRate"];
2382
2686
  var MAX_STEPS = 2e3;
2383
2687
  function followPath(opts) {
2384
- chunkUQBGW5DO_cjs.warnUnknownOptions("followPath()", opts, KEYS2);
2688
+ chunkUQBGW5DO_cjs.warnUnknownOptions("followPath()", opts, KEYS3);
2385
2689
  const { d, at = 0, duration, ease = "none", from = 0, to = 1, orient = false, rotate = 0, frameRate = 30 } = opts;
2386
2690
  if (typeof d !== "string" || d.trim() === "") throw new Error('followPath(): d must be SVG path data, e.g. "M 100 600 C 300 100 900 100 1180 600"');
2387
2691
  if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`followPath(): duration must be a positive number of seconds, got ${duration}`);
@@ -2419,12 +2723,12 @@ function followPath(opts) {
2419
2723
  return { x: g.x0 + (g.x1 - g.x0) * t, y: g.y0 + (g.y1 - g.y0) * t, heading: Math.atan2(g.y1 - g.y0, g.x1 - g.x0) * 180 / Math.PI };
2420
2724
  };
2421
2725
  const shape = parseEase(ease);
2422
- const round2 = (v) => Math.round(v * 1e6) / 1e6;
2726
+ const round3 = (v) => Math.round(v * 1e6) / 1e6;
2423
2727
  let turn = 0;
2424
2728
  const sample = (k) => {
2425
2729
  const p = from + (to - from) * shape(k / steps);
2426
2730
  const pt = at_(p);
2427
- const out2 = { x: round2(pt.x), y: round2(pt.y) };
2731
+ const out2 = { x: round3(pt.x), y: round3(pt.y) };
2428
2732
  if (orient) {
2429
2733
  let h = pt.heading + rotate;
2430
2734
  if (k === 0) turn = h;
@@ -2433,13 +2737,13 @@ function followPath(opts) {
2433
2737
  delta -= 360 * Math.round(delta / 360);
2434
2738
  turn += delta;
2435
2739
  }
2436
- out2.rotation = round2(turn);
2740
+ out2.rotation = round3(turn);
2437
2741
  }
2438
2742
  return out2;
2439
2743
  };
2440
2744
  const out = [{ at, set: sample(0) }];
2441
2745
  const step = duration / steps;
2442
- for (let k = 1; k <= steps; k++) out.push({ at: round2(at + (k - 1) * step), to: sample(k), duration: round2(step), ease: "none" });
2746
+ for (let k = 1; k <= steps; k++) out.push({ at: round3(at + (k - 1) * step), to: sample(k), duration: round3(step), ease: "none" });
2443
2747
  return out;
2444
2748
  }
2445
2749
 
@@ -2545,7 +2849,7 @@ function wiggle(opts) {
2545
2849
  }
2546
2850
 
2547
2851
  // src/presets/animateText.ts
2548
- var KEYS3 = ["by", "x", "y", "align", "name", "at", "duration", "in", "out", "stagger", "idle", "styleFor"];
2852
+ var KEYS4 = ["by", "x", "y", "align", "name", "at", "duration", "in", "out", "stagger", "idle", "styleFor"];
2549
2853
  var PRESETS = {
2550
2854
  rise: { from: { y: 40, alpha: 0 }, duration: 0.5, ease: "back.out(2)" },
2551
2855
  drop: { from: { y: -50, alpha: 0 }, duration: 0.7, ease: "bounce.out" },
@@ -2557,7 +2861,7 @@ var PRESETS = {
2557
2861
  };
2558
2862
  var PRESET_NAMES = Object.keys(PRESETS);
2559
2863
  function animateText(text, style, options) {
2560
- chunkUQBGW5DO_cjs.warnUnknownOptions("animateText()", options, KEYS3);
2864
+ chunkUQBGW5DO_cjs.warnUnknownOptions("animateText()", options, KEYS4);
2561
2865
  const { by = "chars", x = 0, y = 0, align = "left", name = "text", at = 0, duration, idle, styleFor } = options;
2562
2866
  if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`animateText(): duration must be a positive number of seconds (how long until the last piece is gone), got ${duration}`);
2563
2867
  const pieces = splitText(text, style, { by, x, y, align });
@@ -2640,6 +2944,305 @@ function resolveTween(spec, which) {
2640
2944
  return { from, to: { ...to }, duration: t.duration ?? base?.duration ?? 0.5, ease };
2641
2945
  }
2642
2946
 
2947
+ // src/presets/react.ts
2948
+ var KEYS5 = ["at", "duration", "props", "audioOffset", "loop", "frameRate"];
2949
+ var PROP_KEYS = ["base", "amount", "band", "beats", "decay", "attack", "release", "invert", "curve"];
2950
+ var MAX_STEPS3 = 4e3;
2951
+ function react(env, options) {
2952
+ chunkUQBGW5DO_cjs.warnUnknownOptions("react()", options, KEYS5);
2953
+ const { at = 0, duration, props, audioOffset = 0, loop = false } = options;
2954
+ const frameRate = options.frameRate ?? env.frameRate;
2955
+ if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`react(): duration must be a positive number of seconds, got ${duration}`);
2956
+ if (!(Number.isFinite(frameRate) && frameRate > 0)) throw new Error(`react(): frameRate must be a positive number, got ${frameRate}`);
2957
+ const names = Object.keys(props ?? {});
2958
+ if (names.length === 0) throw new Error("react(): props is empty; name at least one property, e.g. props: { scale: { base: 1, amount: 0.3 } }");
2959
+ for (const n of names) {
2960
+ const p = props[n];
2961
+ chunkUQBGW5DO_cjs.warnUnknownOptions(`react() props.${n}`, p, PROP_KEYS);
2962
+ if (!Number.isFinite(p.amount)) throw new Error(`react(): props.${n}.amount must be a number, got ${p.amount}`);
2963
+ if (!p.beats && p.band !== void 0 && !env.series[p.band]) throw new Error(`react(): props.${n}: band "${p.band}" is not in this envelope (it has: ${Object.keys(env.series).join(", ")})`);
2964
+ if (p.beats && !(p.decay === void 0 || Number.isFinite(p.decay) && p.decay > 0)) throw new Error(`react(): props.${n}.decay must be a positive number of seconds, got ${p.decay}`);
2965
+ }
2966
+ const steps = Math.max(1, Math.round(duration * frameRate));
2967
+ if (steps > MAX_STEPS3) throw new Error(`react(): too many keyframes (${steps} steps, max ${MAX_STEPS3}); lower frameRate (now ${frameRate}) or duration`);
2968
+ const wrap = (a) => loop && env.duration > 0 ? (a % env.duration + env.duration) % env.duration : a;
2969
+ const beatPulse = (a, decay) => {
2970
+ const beats = env.beats;
2971
+ let lo = 0, hi = beats.length - 1, found = -1;
2972
+ while (lo <= hi) {
2973
+ const mid = lo + hi >> 1;
2974
+ if (beats[mid] <= a + 1e-9) {
2975
+ found = mid;
2976
+ lo = mid + 1;
2977
+ } else hi = mid - 1;
2978
+ }
2979
+ if (found < 0) return 0;
2980
+ return Math.exp(-(a - beats[found]) / decay);
2981
+ };
2982
+ const round3 = (v) => Math.round(v * 1e4) / 1e4;
2983
+ const state = {};
2984
+ const values = (k) => {
2985
+ const t = k / frameRate, a = wrap(audioOffset + t);
2986
+ const out2 = {};
2987
+ for (const n of names) {
2988
+ const p = props[n];
2989
+ let x = p.beats ? beatPulse(a, p.decay ?? 0.2) : env.at(a, p.band ?? "level");
2990
+ if (p.invert) x = 1 - x;
2991
+ const prev = state[n];
2992
+ if (prev !== void 0 && (p.attack || p.release)) {
2993
+ const tau = x > prev ? p.attack ?? 0 : p.release ?? 0;
2994
+ if (tau > 0) x = prev + (x - prev) * (1 - Math.exp(-(1 / frameRate) / tau));
2995
+ }
2996
+ state[n] = x;
2997
+ const shaped = p.curve && p.curve !== 1 ? Math.pow(Math.max(0, x), p.curve) : x;
2998
+ out2[n] = round3((p.base ?? 0) + p.amount * shaped);
2999
+ }
3000
+ return out2;
3001
+ };
3002
+ const out = [{ at, set: values(0) }];
3003
+ const step = duration / steps;
3004
+ for (let k = 1; k <= steps; k++) out.push({ at: round6(at + (k - 1) * step), to: values(k), duration: round6(step), ease: "none" });
3005
+ return out;
3006
+ }
3007
+ var round6 = (v) => Math.round(v * 1e6) / 1e6;
3008
+
3009
+ // src/audio/envelope.ts
3010
+ var DEFAULT_BANDS = { bass: [20, 150], mid: [150, 2e3], treble: [2e3, 1e4] };
3011
+ var WINDOW = 2048;
3012
+ var RANGE_DB = 36;
3013
+ var MIN_BEAT_GAP = 0.2;
3014
+ var OPTION_KEYS = ["frameRate", "bands", "beatBand", "beatSensitivity"];
3015
+ function makeAt(frameRate, series) {
3016
+ return (time, name = "level") => {
3017
+ const s = series[name];
3018
+ if (!s) throw new Error(`pixi-effects: this envelope has no series "${name}" (it has: ${Object.keys(series).join(", ")})`);
3019
+ const x = Math.min(Math.max(time * frameRate, 0), s.length - 1);
3020
+ const i = Math.floor(x), f = x - i;
3021
+ return i + 1 < s.length ? s[i] + (s[i + 1] - s[i]) * f : s[i];
3022
+ };
3023
+ }
3024
+ function percentile(values, p) {
3025
+ if (values.length === 0) return 0;
3026
+ const sorted = Float64Array.from(values).sort();
3027
+ return sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))];
3028
+ }
3029
+ function pickBeats(strength, frameRate, sensitivity) {
3030
+ const n = strength.length;
3031
+ const flux = new Float64Array(n);
3032
+ for (let i = 1; i < n; i++) flux[i] = Math.max(0, strength[i] - strength[i - 1]);
3033
+ const half = Math.max(2, Math.round(frameRate * 0.5));
3034
+ const gap = Math.max(1, Math.round(MIN_BEAT_GAP * frameRate));
3035
+ const beats = [];
3036
+ let last = -gap;
3037
+ for (let i = 1; i < n; i++) {
3038
+ const v = flux[i];
3039
+ if (v < 0.12 / sensitivity || v < flux[i - 1] || v <= (flux[i + 1] ?? 0)) continue;
3040
+ let mean = 0, sq = 0, count = 0;
3041
+ for (let j = Math.max(0, i - half); j <= Math.min(n - 1, i + half); j++) {
3042
+ mean += flux[j];
3043
+ sq += flux[j] * flux[j];
3044
+ count++;
3045
+ }
3046
+ mean /= count;
3047
+ const std = Math.sqrt(Math.max(0, sq / count - mean * mean));
3048
+ if (v < mean + 1 * std / sensitivity) continue;
3049
+ if (i - last < gap) {
3050
+ if (beats.length && v > flux[last]) {
3051
+ beats[beats.length - 1] = i / frameRate;
3052
+ last = i;
3053
+ }
3054
+ continue;
3055
+ }
3056
+ beats.push(i / frameRate);
3057
+ last = i;
3058
+ }
3059
+ return beats;
3060
+ }
3061
+ function tempo(beats) {
3062
+ if (beats.length < 4) return null;
3063
+ const gaps = beats.slice(1).map((b, i) => b - beats[i]).sort((a, b) => a - b);
3064
+ const median = gaps[Math.floor(gaps.length / 2)];
3065
+ return Math.round(60 / median * 10) / 10;
3066
+ }
3067
+ function computeEnvelope(audio, options = {}) {
3068
+ chunkUQBGW5DO_cjs.warnUnknownOptions("audioEnvelope()", options, OPTION_KEYS);
3069
+ const frameRate = options.frameRate ?? 30;
3070
+ if (!(Number.isFinite(frameRate) && frameRate > 0)) throw new Error(`pixi-effects: audioEnvelope(): frameRate must be a positive number, got ${frameRate}`);
3071
+ const bands = options.bands ?? DEFAULT_BANDS;
3072
+ for (const [name, range2] of Object.entries(bands)) {
3073
+ if (!(Array.isArray(range2) && range2.length === 2 && range2[0] >= 0 && range2[0] < range2[1])) throw new Error(`pixi-effects: audioEnvelope(): band "${name}" must be [from, to] in Hz with from < to, got ${JSON.stringify(range2)}`);
3074
+ }
3075
+ const sr = audio.sampleRate, length = audio.length;
3076
+ const mono2 = new Float32Array(length);
3077
+ for (let c = 0; c < audio.numberOfChannels; c++) {
3078
+ const d = audio.getChannelData(c);
3079
+ for (let i = 0; i < length; i++) mono2[i] += d[i] / audio.numberOfChannels;
3080
+ }
3081
+ const duration = length / sr;
3082
+ const frames = Math.floor(duration * frameRate + 1e-9) + 1;
3083
+ const hop = sr / frameRate;
3084
+ const names = Object.keys(bands);
3085
+ const raw = { level: new Float64Array(frames) };
3086
+ for (const n of names) raw[n] = new Float64Array(frames);
3087
+ const re = new Float64Array(WINDOW), im = new Float64Array(WINDOW);
3088
+ const win = new Float64Array(WINDOW);
3089
+ let winPower = 0;
3090
+ for (let i = 0; i < WINDOW; i++) {
3091
+ win[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (WINDOW - 1));
3092
+ winPower += win[i] * win[i];
3093
+ }
3094
+ winPower /= WINDOW;
3095
+ const binHz = sr / WINDOW;
3096
+ for (let f = 0; f < frames; f++) {
3097
+ const center = Math.round(f / frameRate * sr);
3098
+ let sum = 0, cnt = 0;
3099
+ for (let i = Math.max(0, Math.round(center - hop / 2)); i < Math.min(length, Math.round(center + hop / 2)); i++) {
3100
+ sum += mono2[i] * mono2[i];
3101
+ cnt++;
3102
+ }
3103
+ raw.level[f] = cnt ? Math.sqrt(sum / cnt) : 0;
3104
+ for (let i = 0; i < WINDOW; i++) {
3105
+ const k = center - WINDOW / 2 + i;
3106
+ re[i] = k >= 0 && k < length ? mono2[k] * win[i] : 0;
3107
+ im[i] = 0;
3108
+ }
3109
+ fft(re, im);
3110
+ for (const n of names) {
3111
+ const [lo, hi] = bands[n];
3112
+ let p = 0;
3113
+ for (let b = Math.max(1, Math.ceil(lo / binHz)); b <= Math.min(WINDOW / 2 - 1, Math.floor(hi / binHz)); b++) p += re[b] * re[b] + im[b] * im[b];
3114
+ raw[n][f] = Math.sqrt(2 * p / (WINDOW * WINDOW * winPower));
3115
+ }
3116
+ }
3117
+ let ref = 0;
3118
+ for (const s of Object.values(raw)) ref = Math.max(ref, percentile(s, 0.98));
3119
+ const series = {};
3120
+ for (const [name, s] of Object.entries(raw)) {
3121
+ const out = new Float32Array(frames);
3122
+ if (ref > 1e-7) for (let f = 0; f < frames; f++) {
3123
+ const v = s[f];
3124
+ out[f] = v > 0 ? Math.min(1, Math.max(0, 1 + 20 * Math.log10(v / ref) / RANGE_DB)) : 0;
3125
+ }
3126
+ series[name] = out;
3127
+ }
3128
+ const beatName = options.beatBand ?? (series.bass ? "bass" : "level");
3129
+ if (!series[beatName]) throw new Error(`pixi-effects: audioEnvelope(): beatBand "${beatName}" is not one of ${Object.keys(series).join(", ")}`);
3130
+ const beats = ref > 1e-7 ? pickBeats(series[beatName], frameRate, options.beatSensitivity ?? 1) : [];
3131
+ return { frameRate, duration, frames, series, beats, bpm: tempo(beats), at: makeAt(frameRate, series) };
3132
+ }
3133
+ function bpmEnvelope(bpm, options) {
3134
+ const { duration, frameRate = 30, swing = 0 } = options;
3135
+ if (!(Number.isFinite(bpm) && bpm > 0)) throw new Error(`pixi-effects: bpmEnvelope(): bpm must be a positive number, got ${bpm}`);
3136
+ if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`pixi-effects: bpmEnvelope(): duration must be a positive number of seconds, got ${duration}`);
3137
+ const beat = 60 / bpm;
3138
+ const frames = Math.round(duration * frameRate) + 1;
3139
+ const pulse = (hits, decay, t) => {
3140
+ let v = 0;
3141
+ for (let i = hits.length - 1; i >= 0; i--) {
3142
+ if (hits[i] <= t + 1e-9) {
3143
+ v = Math.exp(-(t - hits[i]) / decay);
3144
+ break;
3145
+ }
3146
+ }
3147
+ return v;
3148
+ };
3149
+ const beats = [], snares = [], hats = [];
3150
+ for (let k = 0; k * beat < duration - 1e-9; k++) {
3151
+ beats.push(round62(k * beat));
3152
+ if (k % 2 === 1) snares.push(round62(k * beat));
3153
+ hats.push(round62(k * beat), round62(k * beat + beat / 2 + swing * beat));
3154
+ }
3155
+ hats.sort((a, b) => a - b);
3156
+ const series = { level: new Float32Array(frames), bass: new Float32Array(frames), mid: new Float32Array(frames), treble: new Float32Array(frames) };
3157
+ for (let f = 0; f < frames; f++) {
3158
+ const t = f / frameRate;
3159
+ const b = pulse(beats, 0.14, t), m = pulse(snares, 0.1, t), h = pulse(hats, 0.045, t);
3160
+ series.bass[f] = b;
3161
+ series.mid[f] = m;
3162
+ series.treble[f] = h;
3163
+ series.level[f] = Math.max(b, m * 0.9, h * 0.55);
3164
+ }
3165
+ return { frameRate, duration, frames, series, beats, bpm, at: makeAt(frameRate, series) };
3166
+ }
3167
+ var round62 = (v) => Math.round(v * 1e6) / 1e6;
3168
+ async function audioEnvelope(source, options = {}) {
3169
+ let audio;
3170
+ if (typeof source.getChannelData === "function") audio = source;
3171
+ else {
3172
+ let data;
3173
+ if (typeof source === "string" || source instanceof URL) {
3174
+ const res = await fetch(String(source));
3175
+ if (!res.ok) throw new Error(`pixi-effects: audioEnvelope(): could not fetch ${String(source)} (${res.status})`);
3176
+ data = await res.arrayBuffer();
3177
+ } else if (source instanceof Blob) data = await source.arrayBuffer();
3178
+ else data = source;
3179
+ const Ctx = globalThis.OfflineAudioContext ?? globalThis.webkitOfflineAudioContext;
3180
+ if (!Ctx) throw new Error("pixi-effects: audioEnvelope() needs a browser with Web Audio (OfflineAudioContext)");
3181
+ try {
3182
+ audio = await new Ctx(1, 1, 44100).decodeAudioData(data.slice(0));
3183
+ } catch (err) {
3184
+ throw new Error(`pixi-effects: audioEnvelope(): could not decode the audio (${err instanceof Error ? err.message : String(err)}); is it an mp3, wav, ogg, m4a or webm file?`);
3185
+ }
3186
+ }
3187
+ return computeEnvelope(audio, options);
3188
+ }
3189
+
3190
+ // src/presets/deck.ts
3191
+ var PAGE_KEYS = ["name", "duration", "sequences", "stops", "notes", "advance", "initial", "keyframes", "filters", "filterArea", "blendMode", "mask", "maskInverted"];
3192
+ var DECK_KEYS = ["pages", "transition", "width", "height", "frameRate", "background", "canvas", "assets", "poster", "motionBlur", "loader"];
3193
+ function deck(options) {
3194
+ if (!options || !Array.isArray(options.pages) || options.pages.length === 0) throw new Error("deck(): pages must be a list with at least one page: { pages: [{ name, duration, stops, sequences }] }");
3195
+ chunkUQBGW5DO_cjs.warnUnknownOptions("deck()", options, DECK_KEYS);
3196
+ const { pages, transition, ...movieOptions } = options;
3197
+ pages.forEach((p, i) => {
3198
+ if (!p || typeof p !== "object") throw new Error(`deck(): pages[${i}] must be an object`);
3199
+ chunkUQBGW5DO_cjs.warnUnknownOptions(`deck() pages[${i}]`, p, PAGE_KEYS);
3200
+ if (!(typeof p.duration === "number" && Number.isFinite(p.duration) && p.duration > 0)) throw new Error(`deck(): pages[${i}].duration must be a positive number of seconds, got ${String(p.duration)}`);
3201
+ if (!Array.isArray(p.sequences)) throw new Error(`deck(): pages[${i}].sequences must be a list of layers (it may be empty), got ${typeof p.sequences}`);
3202
+ });
3203
+ let overlap = 0;
3204
+ if (transition) {
3205
+ if (!(typeof transition.duration === "number" && transition.duration > 0)) throw new Error("deck(): transition needs a duration in seconds: { kind: 'crossfade', duration: 0.6 }");
3206
+ const shortest = Math.min(...pages.map((p) => p.duration));
3207
+ if (pages.length > 1 && transition.duration >= shortest) throw new Error(`deck(): the transition (${transition.duration} s) must be shorter than every page (the shortest is ${shortest} s)`);
3208
+ overlap = pages.length > 1 ? transition.duration : 0;
3209
+ }
3210
+ const sequences = [];
3211
+ const transitions = [];
3212
+ const stops = [];
3213
+ let start = 0;
3214
+ pages.forEach((page, i) => {
3215
+ const id = `page-${i + 1}`;
3216
+ const label = page.name ? `"${page.name}"` : `pages[${i}]`;
3217
+ const isLast = i === pages.length - 1;
3218
+ const local = page.stops ?? [isLast ? page.duration : page.duration - overlap];
3219
+ local.forEach((s, k) => {
3220
+ if (!(typeof s === "number" && Number.isFinite(s) && s > 0 && s <= page.duration + 1e-9)) throw new Error(`deck(): page ${label} has stop ${String(s)}, outside the page (0 to ${page.duration} s)`);
3221
+ if (k > 0 && s <= local[k - 1]) throw new Error(`deck(): page ${label} stops must be in order, earliest first (got ${local.join(", ")})`);
3222
+ });
3223
+ const { name: _n, duration: _d, sequences: inner, stops: _s, notes: _no, advance: _a, ...layerProps } = page;
3224
+ sequences.push({ type: "composition", name: id, at: round2(start), duration: page.duration, ...layerProps, sequences: inner });
3225
+ local.forEach((s, k) => {
3226
+ const stop = { at: round2(start + s) };
3227
+ if (k === 0) {
3228
+ stop.page = page.name ?? true;
3229
+ if (page.notes !== void 0) stop.notes = page.notes;
3230
+ }
3231
+ if (k === local.length - 1 && page.advance !== void 0) stop.advance = page.advance;
3232
+ stops.push(stop);
3233
+ });
3234
+ if (transition && !isLast) {
3235
+ const next = start + page.duration - overlap;
3236
+ transitions.push({ ...transition, from: id, to: `page-${i + 2}`, at: round2(next), duration: transition.duration });
3237
+ }
3238
+ start = start + page.duration - (isLast ? 0 : overlap);
3239
+ });
3240
+ const composition = { sequences, stops };
3241
+ if (transitions.length > 0) composition.transitions = transitions;
3242
+ return { ...movieOptions, duration: round2(start), composition };
3243
+ }
3244
+ var round2 = (v) => Math.round(v * 1e6) / 1e6;
3245
+
2643
3246
  // src/transforms/withFade.ts
2644
3247
  function withFade(spec, opts) {
2645
3248
  chunkUQBGW5DO_cjs.warnUnknownOptions("withFade()", opts, ["in", "out"]);
@@ -2678,13 +3281,19 @@ Object.defineProperty(exports, "registerSequenceType", {
2678
3281
  });
2679
3282
  exports.Movie = Movie;
2680
3283
  exports.animateText = animateText;
3284
+ exports.audioEnvelope = audioEnvelope;
3285
+ exports.bpmEnvelope = bpmEnvelope;
3286
+ exports.computeEnvelope = computeEnvelope;
3287
+ exports.deck = deck;
2681
3288
  exports.dismissLoader = dismissLoader;
2682
3289
  exports.failLoader = failLoader;
2683
3290
  exports.followPath = followPath;
2684
3291
  exports.kenBurns = kenBurns;
2685
3292
  exports.measureText = measureText;
3293
+ exports.normalizeStops = normalizeStops;
2686
3294
  exports.orbit = orbit;
2687
3295
  exports.particles = particles;
3296
+ exports.react = react;
2688
3297
  exports.resolveLoader = resolveLoader;
2689
3298
  exports.splitText = splitText;
2690
3299
  exports.stagger = stagger;