@munusshih/p5.export 0.1.0-beta.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.
@@ -0,0 +1,4406 @@
1
+ function _t(t, e) {
2
+ const i = URL.createObjectURL(t), r = document.createElement("a");
3
+ r.href = i, r.download = e, r.style.display = "none", document.body.appendChild(r), r.click(), r.remove(), setTimeout(() => URL.revokeObjectURL(i), 0);
4
+ }
5
+ function xt(t, e = "sketch") {
6
+ const i = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
7
+ return `${e}-${i}.${t}`;
8
+ }
9
+ function St(t, e) {
10
+ return t.toLowerCase().endsWith("." + e.toLowerCase()) ? t : `${t}.${e}`;
11
+ }
12
+ function Tt(t) {
13
+ return t ? t instanceof HTMLCanvasElement ? t : t.canvas instanceof HTMLCanvasElement ? t.canvas : t.elt instanceof HTMLCanvasElement ? t.elt : Fr() : Fr();
14
+ }
15
+ function Fr() {
16
+ const t = document.querySelector("canvas.p5Canvas");
17
+ return t || document.querySelector("canvas");
18
+ }
19
+ function Di(t) {
20
+ if (!t) return !1;
21
+ const e = t._renderer;
22
+ if (!e) return !1;
23
+ const i = e.drawingContext;
24
+ return !!(i && typeof i.fillRect != "function" || e.GL);
25
+ }
26
+ const en = {
27
+ png: "image/png",
28
+ jpg: "image/jpeg",
29
+ jpeg: "image/jpeg",
30
+ webp: "image/webp"
31
+ };
32
+ async function Jr(t, e, i, r) {
33
+ const s = t && t._p5ExportSVGRecorder;
34
+ if (!s || !s.ops || s.ops.length === 0) return null;
35
+ const n = Tt(t);
36
+ if (!n) return null;
37
+ const a = typeof t.pixelDensity == "function" ? t.pixelDensity() : 1, l = Math.max(1, Math.round(n.width / a)), u = Math.max(1, Math.round(n.height / a)), g = l * e, v = u * e, p = document.createElement("canvas");
38
+ p.width = g, p.height = v;
39
+ const h = p.getContext("2d");
40
+ if (!h) return null;
41
+ const d = e / a, f = s.ops;
42
+ for (let w = 0; w < f.length; w++) {
43
+ const y = f[w];
44
+ try {
45
+ if (y[0] === 0) {
46
+ const C = y[1];
47
+ if (C === "setTransform") {
48
+ const x = y[2];
49
+ h.setTransform(x[0] * d, x[1] * d, x[2] * d, x[3] * d, x[4] * d, x[5] * d);
50
+ } else
51
+ h[C](...y[2]);
52
+ } else
53
+ h[y[1]] = y[2];
54
+ } catch {
55
+ }
56
+ }
57
+ const m = en[i] || "image/png";
58
+ return new Promise((w, y) => {
59
+ p.toBlob(
60
+ (C) => C ? w(C) : y(new Error("[p5.export] toBlob returned null")),
61
+ m,
62
+ r
63
+ );
64
+ });
65
+ }
66
+ async function Kr(t, e, i) {
67
+ if (!e || e <= 1) return i();
68
+ const r = typeof t.pixelDensity == "function" ? t.pixelDensity() : 1;
69
+ if (e <= r) return i();
70
+ const s = typeof t.isLooping == "function" ? t.isLooping() : !0;
71
+ s && typeof t.noLoop == "function" && t.noLoop();
72
+ try {
73
+ return t.pixelDensity(e), typeof t.redraw == "function" && await t.redraw(), await new Promise((n) => requestAnimationFrame(n)), await i();
74
+ } finally {
75
+ t.pixelDensity(r), typeof t.redraw == "function" && await t.redraw(), s && typeof t.loop == "function" && t.loop();
76
+ }
77
+ }
78
+ const rn = {
79
+ png: "image/png",
80
+ jpg: "image/jpeg",
81
+ jpeg: "image/jpeg",
82
+ webp: "image/webp"
83
+ };
84
+ function Ai(t, e, i) {
85
+ const r = Tt(t);
86
+ if (!r) return Promise.reject(new Error("[p5.export] no canvas found"));
87
+ const s = rn[e];
88
+ return s ? new Promise((n, a) => {
89
+ r.toBlob(
90
+ (l) => l ? n(l) : a(new Error("[p5.export] toBlob returned null")),
91
+ s,
92
+ i
93
+ );
94
+ }) : Promise.reject(new Error(`[p5.export] unknown image format: ${e}`));
95
+ }
96
+ async function Xe(t, e, i, r) {
97
+ if (!e || e <= 1) return Ai(t, i, r);
98
+ const s = typeof t.pixelDensity == "function" ? t.pixelDensity() : 1;
99
+ if (e <= s) return Ai(t, i, r);
100
+ const n = await Jr(t, e, i, r);
101
+ return n || Kr(t, e, () => Ai(t, i, r));
102
+ }
103
+ function sn(t, e) {
104
+ e.savePNG = async function(i, r = {}) {
105
+ const s = await Xe(this, r.scale, "png");
106
+ return _t(s, i ? St(i, "png") : xt("png")), s;
107
+ }, e.saveJPG = async function(i, r = {}) {
108
+ const s = r.quality ?? 0.92, n = await Xe(this, r.scale, "jpg", s);
109
+ return _t(n, i ? St(i, "jpg") : xt("jpg")), n;
110
+ }, e.saveJPEG = e.saveJPG, e.saveWebP = async function(i, r = {}) {
111
+ const s = r.quality ?? 0.92, n = await Xe(this, r.scale, "webp", s);
112
+ return _t(n, i ? St(i, "webp") : xt("webp")), n;
113
+ }, e.saveImage = async function(i, r, s = {}) {
114
+ i = (i || "png").toLowerCase(), i === "jpeg" && (i = "jpg");
115
+ const n = await Xe(this, s.scale, i, s.quality);
116
+ return _t(n, r ? St(r, i) : xt(i)), n;
117
+ };
118
+ }
119
+ function nn(t) {
120
+ return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
121
+ }
122
+ var Zr = { exports: {} };
123
+ /*!!
124
+ * Canvas 2 Svg v1.0.15
125
+ * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document.
126
+ *
127
+ * Licensed under the MIT license:
128
+ * http://www.opensource.org/licenses/mit-license.php
129
+ *
130
+ * Author:
131
+ * Kerry Liu
132
+ *
133
+ * Copyright (c) 2014 Gliffy Inc.
134
+ */
135
+ (function(t) {
136
+ (function() {
137
+ var e, i, r, s, n;
138
+ function a(h, d) {
139
+ var f = Object.keys(d), m;
140
+ for (m = 0; m < f.length; m++)
141
+ h = h.replace(new RegExp("\\{" + f[m] + "\\}", "gi"), d[f[m]]);
142
+ return h;
143
+ }
144
+ function l(h) {
145
+ var d, f, m;
146
+ if (!h)
147
+ throw new Error("cannot create a random attribute name for an undefined object");
148
+ d = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz", f = "";
149
+ do
150
+ for (f = "", m = 0; m < 12; m++)
151
+ f += d[Math.floor(Math.random() * d.length)];
152
+ while (h[f]);
153
+ return f;
154
+ }
155
+ function u(h, d) {
156
+ var f, m, w = {}, y;
157
+ for (h = h.split(","), d = d || 10, f = 0; f < h.length; f += 2)
158
+ m = "&" + h[f + 1] + ";", y = parseInt(h[f], d), w[m] = "&#" + y + ";";
159
+ return w["\\xa0"] = "&#160;", w;
160
+ }
161
+ function g(h) {
162
+ var d = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
163
+ return d[h] || d.start;
164
+ }
165
+ function v(h) {
166
+ var d = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
167
+ return d[h] || d.alphabetic;
168
+ }
169
+ n = u(
170
+ "50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro",
171
+ 32
172
+ ), e = {
173
+ strokeStyle: {
174
+ svgAttr: "stroke",
175
+ //corresponding svg attribute
176
+ canvas: "#000000",
177
+ //canvas default
178
+ svg: "none",
179
+ //svg default
180
+ apply: "stroke"
181
+ //apply on stroke() or fill()
182
+ },
183
+ fillStyle: {
184
+ svgAttr: "fill",
185
+ canvas: "#000000",
186
+ svg: null,
187
+ //svg default is black, but we need to special case this to handle canvas stroke without fill
188
+ apply: "fill"
189
+ },
190
+ lineCap: {
191
+ svgAttr: "stroke-linecap",
192
+ canvas: "butt",
193
+ svg: "butt",
194
+ apply: "stroke"
195
+ },
196
+ lineJoin: {
197
+ svgAttr: "stroke-linejoin",
198
+ canvas: "miter",
199
+ svg: "miter",
200
+ apply: "stroke"
201
+ },
202
+ miterLimit: {
203
+ svgAttr: "stroke-miterlimit",
204
+ canvas: 10,
205
+ svg: 4,
206
+ apply: "stroke"
207
+ },
208
+ lineWidth: {
209
+ svgAttr: "stroke-width",
210
+ canvas: 1,
211
+ svg: 1,
212
+ apply: "stroke"
213
+ },
214
+ globalAlpha: {
215
+ svgAttr: "opacity",
216
+ canvas: 1,
217
+ svg: 1,
218
+ apply: "fill stroke"
219
+ },
220
+ font: {
221
+ //font converts to multiple svg attributes, there is custom logic for this
222
+ canvas: "10px sans-serif"
223
+ },
224
+ shadowColor: {
225
+ canvas: "#000000"
226
+ },
227
+ shadowOffsetX: {
228
+ canvas: 0
229
+ },
230
+ shadowOffsetY: {
231
+ canvas: 0
232
+ },
233
+ shadowBlur: {
234
+ canvas: 0
235
+ },
236
+ textAlign: {
237
+ canvas: "start"
238
+ },
239
+ textBaseline: {
240
+ canvas: "alphabetic"
241
+ }
242
+ }, r = function(h, d) {
243
+ this.__root = h, this.__ctx = d;
244
+ }, r.prototype.addColorStop = function(h, d) {
245
+ var f = this.__ctx.__createElement("stop"), m, w;
246
+ f.setAttribute("offset", h), d.indexOf("rgba") !== -1 ? (m = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi, w = m.exec(d), f.setAttribute("stop-color", a("rgb({r},{g},{b})", { r: w[1], g: w[2], b: w[3] })), f.setAttribute("stop-opacity", w[4])) : f.setAttribute("stop-color", d), this.__root.appendChild(f);
247
+ }, s = function(h, d) {
248
+ this.__root = h, this.__ctx = d;
249
+ }, i = function(h) {
250
+ var d = { width: 500, height: 500, enableMirroring: !1 }, f;
251
+ if (arguments.length > 1 ? (f = d, f.width = arguments[0], f.height = arguments[1]) : h ? f = h : f = d, !(this instanceof i))
252
+ return new i(f);
253
+ this.width = f.width || d.width, this.height = f.height || d.height, this.enableMirroring = f.enableMirroring !== void 0 ? f.enableMirroring : d.enableMirroring, this.canvas = this, this.__document = f.document || document, this.__canvas = this.__document.createElement("canvas"), this.__ctx = this.__canvas.getContext("2d"), this.__setDefaultStyles(), this.__stack = [this.__getStyleState()], this.__groupStack = [], this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"), this.__root.setAttribute("version", 1.1), this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"), this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"), this.__root.setAttribute("width", this.width), this.__root.setAttribute("height", this.height), this.__ids = {}, this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs"), this.__root.appendChild(this.__defs), this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"), this.__root.appendChild(this.__currentElement);
254
+ }, i.prototype.__createElement = function(h, d, f) {
255
+ typeof d > "u" && (d = {});
256
+ var m = this.__document.createElementNS("http://www.w3.org/2000/svg", h), w = Object.keys(d), y, C;
257
+ for (f && (m.setAttribute("fill", "none"), m.setAttribute("stroke", "none")), y = 0; y < w.length; y++)
258
+ C = w[y], m.setAttribute(C, d[C]);
259
+ return m;
260
+ }, i.prototype.__setDefaultStyles = function() {
261
+ var h = Object.keys(e), d, f;
262
+ for (d = 0; d < h.length; d++)
263
+ f = h[d], this[f] = e[f].canvas;
264
+ }, i.prototype.__applyStyleState = function(h) {
265
+ var d = Object.keys(h), f, m;
266
+ for (f = 0; f < d.length; f++)
267
+ m = d[f], this[m] = h[m];
268
+ }, i.prototype.__getStyleState = function() {
269
+ var h, d = {}, f = Object.keys(e), m;
270
+ for (h = 0; h < f.length; h++)
271
+ m = f[h], d[m] = this[m];
272
+ return d;
273
+ }, i.prototype.__applyStyleToCurrentElement = function(h) {
274
+ var d = Object.keys(e), f, m, w, y, C, x;
275
+ for (f = 0; f < d.length; f++)
276
+ if (m = e[d[f]], w = this[d[f]], m.apply)
277
+ if (m.apply.indexOf("fill") !== -1 && w instanceof s) {
278
+ if (w.__ctx)
279
+ for (; w.__ctx.__defs.childNodes.length; )
280
+ y = w.__ctx.__defs.childNodes[0].getAttribute("id"), this.__ids[y] = y, this.__defs.appendChild(w.__ctx.__defs.childNodes[0]);
281
+ this.__currentElement.setAttribute("fill", a("url(#{id})", { id: w.__root.getAttribute("id") }));
282
+ } else m.apply.indexOf("fill") !== -1 && w instanceof r ? this.__currentElement.setAttribute("fill", a("url(#{id})", { id: w.__root.getAttribute("id") })) : m.apply.indexOf(h) !== -1 && m.svg !== w && ((m.svgAttr === "stroke" || m.svgAttr === "fill") && w.indexOf("rgba") !== -1 ? (C = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi, x = C.exec(w), this.__currentElement.setAttribute(m.svgAttr, a("rgb({r},{g},{b})", { r: x[1], g: x[2], b: x[3] })), this.__currentElement.setAttribute(m.svgAttr + "-opacity", x[4])) : this.__currentElement.setAttribute(m.svgAttr, w));
283
+ }, i.prototype.__closestGroupOrSvg = function(h) {
284
+ return h = h || this.__currentElement, h.nodeName === "g" || h.nodeName === "svg" ? h : this.__closestGroupOrSvg(h.parentNode);
285
+ }, i.prototype.getSerializedSvg = function(h) {
286
+ var d = new XMLSerializer().serializeToString(this.__root), f, m, w, y, C, x;
287
+ if (x = /xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi, x.test(d) && (d = d.replace('xmlns="http://www.w3.org/2000/svg', 'xmlns:xlink="http://www.w3.org/1999/xlink')), h)
288
+ for (f = Object.keys(n), m = 0; m < f.length; m++)
289
+ w = f[m], y = n[w], C = new RegExp(w, "gi"), C.test(d) && (d = d.replace(C, y));
290
+ return d;
291
+ }, i.prototype.getSvg = function() {
292
+ return this.__root;
293
+ }, i.prototype.save = function() {
294
+ var h = this.__createElement("g"), d = this.__closestGroupOrSvg();
295
+ this.__groupStack.push(d), d.appendChild(h), this.__currentElement = h, this.__stack.push(this.__getStyleState());
296
+ }, i.prototype.restore = function() {
297
+ this.__currentElement = this.__groupStack.pop();
298
+ var h = this.__stack.pop();
299
+ this.__applyStyleState(h);
300
+ }, i.prototype.__addTransform = function(h) {
301
+ var d = this.__closestGroupOrSvg();
302
+ if (d.childNodes.length > 0) {
303
+ var f = this.__createElement("g");
304
+ d.appendChild(f), this.__currentElement = f;
305
+ }
306
+ var m = this.__currentElement.getAttribute("transform");
307
+ m ? m += " " : m = "", m += h, this.__currentElement.setAttribute("transform", m);
308
+ }, i.prototype.scale = function(h, d) {
309
+ d === void 0 && (d = h), this.__addTransform(a("scale({x},{y})", { x: h, y: d }));
310
+ }, i.prototype.rotate = function(h) {
311
+ var d = h * 180 / Math.PI;
312
+ this.__addTransform(a("rotate({angle},{cx},{cy})", { angle: d, cx: 0, cy: 0 }));
313
+ }, i.prototype.translate = function(h, d) {
314
+ this.__addTransform(a("translate({x},{y})", { x: h, y: d }));
315
+ }, i.prototype.transform = function(h, d, f, m, w, y) {
316
+ this.__addTransform(a("matrix({a},{b},{c},{d},{e},{f})", { a: h, b: d, c: f, d: m, e: w, f: y }));
317
+ }, i.prototype.beginPath = function() {
318
+ var h, d;
319
+ this.__currentDefaultPath = "", this.__currentPosition = {}, h = this.__createElement("path", {}, !0), d = this.__closestGroupOrSvg(), d.appendChild(h), this.__currentElement = h;
320
+ }, i.prototype.__applyCurrentDefaultPath = function() {
321
+ if (this.__currentElement.nodeName === "path") {
322
+ var h = this.__currentDefaultPath;
323
+ this.__currentElement.setAttribute("d", h);
324
+ } else
325
+ throw new Error("Attempted to apply path command to node " + this.__currentElement.nodeName);
326
+ }, i.prototype.__addPathCommand = function(h) {
327
+ this.__currentDefaultPath += " ", this.__currentDefaultPath += h;
328
+ }, i.prototype.moveTo = function(h, d) {
329
+ this.__currentElement.nodeName !== "path" && this.beginPath(), this.__currentPosition = { x: h, y: d }, this.__addPathCommand(a("M {x} {y}", { x: h, y: d }));
330
+ }, i.prototype.closePath = function() {
331
+ this.__addPathCommand("Z");
332
+ }, i.prototype.lineTo = function(h, d) {
333
+ this.__currentPosition = { x: h, y: d }, this.__currentDefaultPath.indexOf("M") > -1 ? this.__addPathCommand(a("L {x} {y}", { x: h, y: d })) : this.__addPathCommand(a("M {x} {y}", { x: h, y: d }));
334
+ }, i.prototype.bezierCurveTo = function(h, d, f, m, w, y) {
335
+ this.__currentPosition = { x: w, y }, this.__addPathCommand(a(
336
+ "C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",
337
+ { cp1x: h, cp1y: d, cp2x: f, cp2y: m, x: w, y }
338
+ ));
339
+ }, i.prototype.quadraticCurveTo = function(h, d, f, m) {
340
+ this.__currentPosition = { x: f, y: m }, this.__addPathCommand(a("Q {cpx} {cpy} {x} {y}", { cpx: h, cpy: d, x: f, y: m }));
341
+ };
342
+ var p = function(h) {
343
+ var d = Math.sqrt(h[0] * h[0] + h[1] * h[1]);
344
+ return [h[0] / d, h[1] / d];
345
+ };
346
+ i.prototype.arcTo = function(h, d, f, m, w) {
347
+ var y = this.__currentPosition && this.__currentPosition.x, C = this.__currentPosition && this.__currentPosition.y;
348
+ if (!(typeof y > "u" || typeof C > "u")) {
349
+ if (w < 0)
350
+ throw new Error("IndexSizeError: The radius provided (" + w + ") is negative.");
351
+ if (y === h && C === d || h === f && d === m || w === 0) {
352
+ this.lineTo(h, d);
353
+ return;
354
+ }
355
+ var x = p([y - h, C - d]), _ = p([f - h, m - d]);
356
+ if (x[0] * _[1] === x[1] * _[0]) {
357
+ this.lineTo(h, d);
358
+ return;
359
+ }
360
+ var M = x[0] * _[0] + x[1] * _[1], $ = Math.acos(Math.abs(M)), B = p([
361
+ x[0] + _[0],
362
+ x[1] + _[1]
363
+ ]), O = w / Math.sin($ / 2), G = h + O * B[0], Z = d + O * B[1], X = [
364
+ -x[1],
365
+ x[0]
366
+ ], q = [
367
+ _[1],
368
+ -_[0]
369
+ ], ot = function(A) {
370
+ var F = A[0], b = A[1];
371
+ return b >= 0 ? Math.acos(F) : -Math.acos(F);
372
+ }, Y = ot(X), V = ot(q);
373
+ this.lineTo(
374
+ G + X[0] * w,
375
+ Z + X[1] * w
376
+ ), this.arc(G, Z, w, Y, V);
377
+ }
378
+ }, i.prototype.stroke = function() {
379
+ this.__currentElement.nodeName === "path" && this.__currentElement.setAttribute("paint-order", "fill stroke markers"), this.__applyCurrentDefaultPath(), this.__applyStyleToCurrentElement("stroke");
380
+ }, i.prototype.fill = function() {
381
+ this.__currentElement.nodeName === "path" && this.__currentElement.setAttribute("paint-order", "stroke fill markers"), this.__applyCurrentDefaultPath(), this.__applyStyleToCurrentElement("fill");
382
+ }, i.prototype.rect = function(h, d, f, m) {
383
+ this.__currentElement.nodeName !== "path" && this.beginPath(), this.moveTo(h, d), this.lineTo(h + f, d), this.lineTo(h + f, d + m), this.lineTo(h, d + m), this.lineTo(h, d), this.closePath();
384
+ }, i.prototype.fillRect = function(h, d, f, m) {
385
+ var w, y;
386
+ w = this.__createElement("rect", {
387
+ x: h,
388
+ y: d,
389
+ width: f,
390
+ height: m
391
+ }, !0), y = this.__closestGroupOrSvg(), y.appendChild(w), this.__currentElement = w, this.__applyStyleToCurrentElement("fill");
392
+ }, i.prototype.strokeRect = function(h, d, f, m) {
393
+ var w, y;
394
+ w = this.__createElement("rect", {
395
+ x: h,
396
+ y: d,
397
+ width: f,
398
+ height: m
399
+ }, !0), y = this.__closestGroupOrSvg(), y.appendChild(w), this.__currentElement = w, this.__applyStyleToCurrentElement("stroke");
400
+ }, i.prototype.clearRect = function(h, d, f, m) {
401
+ var w, y = this.__closestGroupOrSvg();
402
+ w = this.__createElement("rect", {
403
+ x: h,
404
+ y: d,
405
+ width: f,
406
+ height: m,
407
+ fill: "#FFFFFF"
408
+ }, !0), y.appendChild(w);
409
+ }, i.prototype.createLinearGradient = function(h, d, f, m) {
410
+ var w = this.__createElement("linearGradient", {
411
+ id: l(this.__ids),
412
+ x1: h + "px",
413
+ x2: f + "px",
414
+ y1: d + "px",
415
+ y2: m + "px",
416
+ gradientUnits: "userSpaceOnUse"
417
+ }, !1);
418
+ return this.__defs.appendChild(w), new r(w, this);
419
+ }, i.prototype.createRadialGradient = function(h, d, f, m, w, y) {
420
+ var C = this.__createElement("radialGradient", {
421
+ id: l(this.__ids),
422
+ cx: m + "px",
423
+ cy: w + "px",
424
+ r: y + "px",
425
+ fx: h + "px",
426
+ fy: d + "px",
427
+ gradientUnits: "userSpaceOnUse"
428
+ }, !1);
429
+ return this.__defs.appendChild(C), new r(C, this);
430
+ }, i.prototype.__parseFont = function() {
431
+ var h = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/i, d = h.exec(this.font), f = {
432
+ style: d[1] || "normal",
433
+ size: d[4] || "10px",
434
+ family: d[6] || "sans-serif",
435
+ weight: d[3] || "normal",
436
+ decoration: d[2] || "normal",
437
+ href: null
438
+ };
439
+ return this.__fontUnderline === "underline" && (f.decoration = "underline"), this.__fontHref && (f.href = this.__fontHref), f;
440
+ }, i.prototype.__wrapTextLink = function(h, d) {
441
+ if (h.href) {
442
+ var f = this.__createElement("a");
443
+ return f.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", h.href), f.appendChild(d), f;
444
+ }
445
+ return d;
446
+ }, i.prototype.__applyText = function(h, d, f, m) {
447
+ var w = this.__parseFont(), y = this.__closestGroupOrSvg(), C = this.__createElement("text", {
448
+ "font-family": w.family,
449
+ "font-size": w.size,
450
+ "font-style": w.style,
451
+ "font-weight": w.weight,
452
+ "text-decoration": w.decoration,
453
+ x: d,
454
+ y: f,
455
+ "text-anchor": g(this.textAlign),
456
+ "dominant-baseline": v(this.textBaseline)
457
+ }, !0);
458
+ C.appendChild(this.__document.createTextNode(h)), this.__currentElement = C, this.__applyStyleToCurrentElement(m), y.appendChild(this.__wrapTextLink(w, C));
459
+ }, i.prototype.fillText = function(h, d, f) {
460
+ this.__applyText(h, d, f, "fill");
461
+ }, i.prototype.strokeText = function(h, d, f) {
462
+ this.__applyText(h, d, f, "stroke");
463
+ }, i.prototype.measureText = function(h) {
464
+ return this.__ctx.font = this.font, this.__ctx.measureText(h);
465
+ }, i.prototype.arc = function(h, d, f, m, w, y) {
466
+ if (m !== w) {
467
+ m = m % (2 * Math.PI), w = w % (2 * Math.PI), m === w && (w = (w + 2 * Math.PI - 1e-3 * (y ? -1 : 1)) % (2 * Math.PI));
468
+ var C = h + f * Math.cos(w), x = d + f * Math.sin(w), _ = h + f * Math.cos(m), M = d + f * Math.sin(m), $ = y ? 0 : 1, B = 0, O = w - m;
469
+ O < 0 && (O += 2 * Math.PI), y ? B = O > Math.PI ? 0 : 1 : B = O > Math.PI ? 1 : 0, this.lineTo(_, M), this.__addPathCommand(a(
470
+ "A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",
471
+ { rx: f, ry: f, xAxisRotation: 0, largeArcFlag: B, sweepFlag: $, endX: C, endY: x }
472
+ )), this.__currentPosition = { x: C, y: x };
473
+ }
474
+ }, i.prototype.clip = function() {
475
+ var h = this.__closestGroupOrSvg(), d = this.__createElement("clipPath"), f = l(this.__ids), m = this.__createElement("g");
476
+ h.removeChild(this.__currentElement), d.setAttribute("id", f), d.appendChild(this.__currentElement), this.__defs.appendChild(d), h.setAttribute("clip-path", a("url(#{id})", { id: f })), h.appendChild(m), this.__currentElement = m;
477
+ }, i.prototype.drawImage = function() {
478
+ var h = Array.prototype.slice.call(arguments), d = h[0], f, m, w, y, C = 0, x = 0, _, M, $, B, O, G, Z, X, q, ot, Y;
479
+ if (h.length === 3)
480
+ f = h[1], m = h[2], _ = d.width, M = d.height, w = _, y = M;
481
+ else if (h.length === 5)
482
+ f = h[1], m = h[2], w = h[3], y = h[4], _ = d.width, M = d.height;
483
+ else if (h.length === 9)
484
+ C = h[1], x = h[2], _ = h[3], M = h[4], f = h[5], m = h[6], w = h[7], y = h[8];
485
+ else
486
+ throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length);
487
+ if ($ = this.__closestGroupOrSvg(), Z = this.__currentElement, d instanceof i) {
488
+ for (B = d.getSvg(), O = B.childNodes[0]; O.childNodes.length; )
489
+ Y = O.childNodes[0].getAttribute("id"), this.__ids[Y] = Y, this.__defs.appendChild(O.childNodes[0]);
490
+ G = B.childNodes[1], $.appendChild(G), this.__currentElement = G, this.translate(f, m), this.__currentElement = Z;
491
+ } else (d.nodeName === "CANVAS" || d.nodeName === "IMG") && (X = this.__createElement("image"), X.setAttribute("width", w), X.setAttribute("height", y), X.setAttribute("preserveAspectRatio", "none"), (C || x || _ !== d.width || M !== d.height) && (q = this.__document.createElement("canvas"), q.width = w, q.height = y, ot = q.getContext("2d"), ot.drawImage(d, C, x, _, M, 0, 0, w, y), d = q), X.setAttributeNS(
492
+ "http://www.w3.org/1999/xlink",
493
+ "xlink:href",
494
+ d.nodeName === "CANVAS" ? d.toDataURL() : d.getAttribute("src")
495
+ ), $.appendChild(X), this.__currentElement = X, this.translate(f, m), this.__currentElement = Z);
496
+ }, i.prototype.createPattern = function(h, d) {
497
+ var f = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), m = l(this.__ids), w;
498
+ return f.setAttribute("id", m), f.setAttribute("width", h.width), f.setAttribute("height", h.height), h.nodeName === "CANVAS" || h.nodeName === "IMG" ? (w = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"), w.setAttribute("width", h.width), w.setAttribute("height", h.height), w.setAttributeNS(
499
+ "http://www.w3.org/1999/xlink",
500
+ "xlink:href",
501
+ h.nodeName === "CANVAS" ? h.toDataURL() : h.getAttribute("src")
502
+ ), f.appendChild(w), this.__defs.appendChild(f)) : h instanceof i && (f.appendChild(h.__root.childNodes[1]), this.__defs.appendChild(f)), new s(f, this);
503
+ }, i.prototype.drawFocusRing = function() {
504
+ }, i.prototype.createImageData = function() {
505
+ }, i.prototype.getImageData = function() {
506
+ }, i.prototype.putImageData = function() {
507
+ }, i.prototype.globalCompositeOperation = function() {
508
+ }, i.prototype.setTransform = function() {
509
+ }, typeof window == "object" && (window.C2S = i), t.exports = i;
510
+ })();
511
+ })(Zr);
512
+ var an = Zr.exports;
513
+ const gt = /* @__PURE__ */ nn(an), on = Math.PI * 2;
514
+ let hn = 0;
515
+ function ln() {
516
+ return `p5ExportPattern_${++hn}`;
517
+ }
518
+ function dn(t) {
519
+ const e = t._patternControler, i = e && Array.isArray(e.colors) ? e.colors : null;
520
+ if (!i || i.length === 0) return "#888888";
521
+ const r = i[i.length - 1];
522
+ return typeof r == "string" ? r : r && typeof r.toString == "function" ? r.toString() : "#888888";
523
+ }
524
+ function ve(t, e, i, r, s) {
525
+ return s === "corners" ? { x: t, y: e, w: i - t, h: r - e } : s === "radius" ? { x: t - i, y: e - r, w: 2 * i, h: 2 * r } : s === "center" ? { x: t - i * 0.5, y: e - r * 0.5, w: i, h: r } : { x: t, y: e, w: i, h: r };
526
+ }
527
+ function Ur(t) {
528
+ return t._renderer && t._renderer.states && t._renderer.states.rectMode || "corner";
529
+ }
530
+ function Mi(t) {
531
+ return t._renderer && t._renderer.states && t._renderer.states.ellipseMode || "center";
532
+ }
533
+ function cn(t, e, i) {
534
+ const r = t._p5ExportSVGRecorder;
535
+ r && r.ops.push([3, e, i]);
536
+ }
537
+ function fn(t, e) {
538
+ const i = t._p5ExportSVGRecorder;
539
+ i && i.ops.push([2, "beginRaster", e]);
540
+ }
541
+ function un(t) {
542
+ const e = t._p5ExportSVGRecorder;
543
+ e && e.ops.push([2, "endRaster"]);
544
+ }
545
+ function Ut(t, e, i) {
546
+ const r = t[e];
547
+ typeof r != "function" || r.__p5ExportWrapped || (t[e] = function(...s) {
548
+ let n, a;
549
+ try {
550
+ if (a = i(this, s), a) {
551
+ n = ln();
552
+ const u = dn(this);
553
+ cn(this, a.kind, { ...a, color: u, patternId: n });
554
+ }
555
+ } catch {
556
+ }
557
+ const l = !!this._p5ExportSVGRecorder && !!n && !!a;
558
+ l && fn(this, { bbox: a, patternId: n });
559
+ try {
560
+ return r.apply(this, s);
561
+ } finally {
562
+ l && un(this);
563
+ }
564
+ }, t[e].__p5ExportWrapped = !0);
565
+ }
566
+ const pn = [
567
+ "rectPattern",
568
+ "squarePattern",
569
+ "ellipsePattern",
570
+ "circlePattern",
571
+ "arcPattern",
572
+ "trianglePattern",
573
+ "quadPattern"
574
+ ];
575
+ function Dr(t, e) {
576
+ if (!t || !t.prototype) return !1;
577
+ const i = t.prototype;
578
+ if (typeof i.rectPattern != "function") return !1;
579
+ const r = !!i.__p5ExportPatternHooksInstalled;
580
+ if (r || (i.__p5ExportPatternHooksInstalled = !0), e && e._renderer && e._renderer.states) {
581
+ const n = t.Renderer || e._renderer.constructor;
582
+ if (n && n.prototype && !n.prototype.__p5ExportModeBridged) {
583
+ n.prototype.__p5ExportModeBridged = !0;
584
+ for (const a of ["rectMode", "ellipseMode", "imageMode", "colorMode"])
585
+ Object.defineProperty(n.prototype, "_" + a, {
586
+ configurable: !0,
587
+ get() {
588
+ return this.states && this.states[a];
589
+ },
590
+ set(l) {
591
+ this.states && (this.states[a] = l);
592
+ }
593
+ });
594
+ }
595
+ }
596
+ r || (Ut(i, "rectPattern", (n, a) => ({
597
+ kind: "rect",
598
+ ...ve(a[0], a[1], a[2], a[3], Ur(n))
599
+ })), Ut(i, "squarePattern", (n, a) => ({
600
+ kind: "rect",
601
+ ...ve(a[0], a[1], a[2], a[2], Ur(n))
602
+ })), Ut(i, "ellipsePattern", (n, a) => ({
603
+ kind: "ellipse",
604
+ ...ve(a[0], a[1], a[2], a[3], Mi(n))
605
+ })), Ut(i, "circlePattern", (n, a) => ({
606
+ kind: "ellipse",
607
+ ...ve(a[0], a[1], a[2], a[2], Mi(n))
608
+ })), Ut(i, "arcPattern", (n, a) => ({
609
+ kind: "ellipse",
610
+ ...ve(a[0], a[1], a[2], a[3], Mi(n))
611
+ })), Ut(i, "trianglePattern", (n, a) => {
612
+ const l = [a[0], a[2], a[4]], u = [a[1], a[3], a[5]], g = Math.min(...l), v = Math.max(...l), p = Math.min(...u), h = Math.max(...u);
613
+ return {
614
+ kind: "polygon",
615
+ points: [[a[0], a[1]], [a[2], a[3]], [a[4], a[5]]],
616
+ x: g,
617
+ y: p,
618
+ w: v - g,
619
+ h: h - p
620
+ };
621
+ }), Ut(i, "quadPattern", (n, a) => {
622
+ const l = [a[0], a[2], a[4], a[6]], u = [a[1], a[3], a[5], a[7]], g = Math.min(...l), v = Math.max(...l), p = Math.min(...u), h = Math.max(...u);
623
+ return {
624
+ kind: "polygon",
625
+ points: [[a[0], a[1]], [a[2], a[3]], [a[4], a[5]], [a[6], a[7]]],
626
+ x: g,
627
+ y: p,
628
+ w: v - g,
629
+ h: h - p
630
+ };
631
+ }));
632
+ const s = e && e._isGlobal && e || typeof window < "u" && window.p5 && window.p5.instance || null;
633
+ if (s && s._isGlobal && typeof window < "u")
634
+ for (const n of pn) {
635
+ const a = i[n];
636
+ if (typeof a == "function")
637
+ try {
638
+ let l = a.bind(s);
639
+ Object.defineProperty(window, n, {
640
+ configurable: !0,
641
+ enumerable: !0,
642
+ get() {
643
+ return l;
644
+ },
645
+ set(u) {
646
+ }
647
+ });
648
+ } catch {
649
+ }
650
+ }
651
+ return !0;
652
+ }
653
+ const Qr = "p5ExportSharedRaster";
654
+ function mn(t, e, i, r) {
655
+ if (!i || !t) return;
656
+ const s = t.fillStyle;
657
+ i.patternId ? t.fillStyle = `url(#${i.patternId})` : t.fillStyle = `url(#${Qr})`;
658
+ try {
659
+ if (e === "rect")
660
+ t.beginPath(), t.rect(i.x, i.y, i.w, i.h), t.fill();
661
+ else if (e === "ellipse") {
662
+ const n = i.w / 2, a = i.h / 2, l = i.x + n, u = i.y + a;
663
+ t.beginPath(), t.ellipse(l, u, n, a, 0, 0, on), t.fill();
664
+ } else if (e === "polygon") {
665
+ const n = i.points || [];
666
+ if (n.length >= 2) {
667
+ t.beginPath(), t.moveTo(n[0][0], n[0][1]);
668
+ for (let a = 1; a < n.length; a++) t.lineTo(n[a][0], n[a][1]);
669
+ t.closePath(), t.fill();
670
+ }
671
+ }
672
+ } finally {
673
+ t.fillStyle = s;
674
+ }
675
+ }
676
+ let Wr = !1;
677
+ function wn() {
678
+ if (Wr) return;
679
+ Wr = !0, gt.prototype.setTransform = function(r, s, n, a, l, u) {
680
+ const v = this.__groupStack && this.__groupStack.length > 0 ? this.__closestGroupOrSvg() : this.__root, p = this.__createElement("g");
681
+ v.appendChild(p), this.__currentElement = p, r === 1 && s === 0 && n === 0 && a === 1 && l === 0 && u === 0 || this.__currentElement.setAttribute("transform", `matrix(${r},${s},${n},${a},${l},${u})`);
682
+ }, gt.prototype.resetTransform = function() {
683
+ this.setTransform(1, 0, 0, 1, 0, 0);
684
+ }, gt.prototype.ellipse = function(r, s, n, a, l, u, g, v) {
685
+ if (u === g) return;
686
+ l = l || 0;
687
+ const p = Math.PI * 2;
688
+ u = u % p, g = g % p, u === g && (g = (g + p - 1e-3 * (v ? -1 : 1)) % p);
689
+ const h = Math.cos(l), d = Math.sin(l), f = (M) => {
690
+ const $ = n * Math.cos(M), B = a * Math.sin(M);
691
+ return { x: r + $ * h - B * d, y: s + $ * d + B * h };
692
+ }, m = f(u), w = f(g);
693
+ let y = g - u;
694
+ y < 0 && (y += p);
695
+ const C = v ? 0 : 1, x = v ? y > Math.PI ? 0 : 1 : y > Math.PI ? 1 : 0, _ = l * 180 / Math.PI;
696
+ this.lineTo(m.x, m.y), this.__addPathCommand(
697
+ "A " + n + " " + a + " " + _ + " " + x + " " + C + " " + w.x + " " + w.y
698
+ ), this.__currentPosition = { x: w.x, y: w.y };
699
+ }, typeof gt.prototype.roundRect != "function" && (gt.prototype.roundRect = function(r, s, n, a, l) {
700
+ let u, g, v, p;
701
+ typeof l == "number" ? u = g = v = p = l : Array.isArray(l) ? l.length === 1 ? u = g = v = p = l[0] : l.length === 2 ? (u = v = l[0], g = p = l[1]) : [u, g, v, p] = [l[0], l[1], l[2], l[3] ?? l[1]] : u = g = v = p = 0;
702
+ const h = Math.min(Math.abs(n), Math.abs(a)) / 2;
703
+ u = Math.min(u, h), g = Math.min(g, h), v = Math.min(v, h), p = Math.min(p, h), this.moveTo(r + u, s), this.lineTo(r + n - g, s), this.ellipse(r + n - g, s + g, g, g, 0, -Math.PI / 2, 0), this.lineTo(r + n, s + a - v), this.ellipse(r + n - v, s + a - v, v, v, 0, 0, Math.PI / 2), this.lineTo(r + p, s + a), this.ellipse(r + p, s + a - p, p, p, 0, Math.PI / 2, Math.PI), this.lineTo(r, s + u), this.ellipse(r + u, s + u, u, u, 0, Math.PI, Math.PI * 1.5);
704
+ }), delete gt.prototype.globalCompositeOperation;
705
+ const t = gt.prototype.__applyStyleToCurrentElement, e = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i, i = (r) => {
706
+ if (typeof r != "string") return r;
707
+ const s = e.exec(r);
708
+ if (!s) return r;
709
+ const n = Math.round(parseInt(s[4], 16) / 255 * 1e3) / 1e3;
710
+ return `rgba(${parseInt(s[1], 16)},${parseInt(s[2], 16)},${parseInt(s[3], 16)},${n})`;
711
+ };
712
+ gt.prototype.__applyStyleToCurrentElement = function(r) {
713
+ const s = this.fillStyle, n = this.strokeStyle;
714
+ typeof s == "string" && (this.fillStyle = i(s)), typeof n == "string" && (this.strokeStyle = i(n));
715
+ try {
716
+ return t.call(this, r);
717
+ } finally {
718
+ this.fillStyle = s, this.strokeStyle = n;
719
+ }
720
+ };
721
+ }
722
+ const gn = 60, ts = /* @__PURE__ */ new Set([
723
+ "fillStyle",
724
+ "strokeStyle",
725
+ "lineWidth",
726
+ "lineCap",
727
+ "lineJoin",
728
+ "miterLimit",
729
+ "globalAlpha",
730
+ "font",
731
+ "textAlign",
732
+ "textBaseline",
733
+ "shadowColor",
734
+ "shadowBlur",
735
+ "shadowOffsetX",
736
+ "shadowOffsetY"
737
+ ]);
738
+ let vn = 0;
739
+ const es = /* @__PURE__ */ new Map();
740
+ function yn() {
741
+ return `p5ExportGrad_${++vn}`;
742
+ }
743
+ function bn(t) {
744
+ const e = [], i = [0], r = {
745
+ proxy: null,
746
+ ops: e,
747
+ maxFrames: gn,
748
+ clear() {
749
+ e.length = 0, i.length = 1, i[0] = 0;
750
+ },
751
+ /**
752
+ * Mark the boundary between two frames. Called from `predraw`. Trims
753
+ * the oldest frame's ops if we've exceeded `maxFrames` — but before
754
+ * each splice, captures the latest value of every preserved style
755
+ * property in the dropped region and re-emits those at the start of
756
+ * the kept region. That guarantees subsequent ops don't lose the
757
+ * fillStyle/strokeStyle/etc. they implicitly depend on.
758
+ */
759
+ markFrameBoundary() {
760
+ if (this.maxFrames === 1 / 0) {
761
+ i.push(e.length);
762
+ return;
763
+ }
764
+ for (i.push(e.length); i.length > this.maxFrames + 1; ) {
765
+ const a = i[1];
766
+ if (a > 0) {
767
+ const l = {};
768
+ for (let v = 0; v < a; v++) {
769
+ const p = e[v];
770
+ p[0] === 1 && ts.has(p[1]) && (l[p[1]] = p[2]);
771
+ }
772
+ e.splice(0, a);
773
+ const u = [];
774
+ for (const v in l) u.push([1, v, l[v]]);
775
+ u.length && e.unshift(...u);
776
+ const g = u.length - a;
777
+ for (let v = 1; v < i.length; v++) i[v] += g;
778
+ }
779
+ i.shift();
780
+ }
781
+ }
782
+ }, s = /* @__PURE__ */ new Set(["createLinearGradient", "createRadialGradient", "createConicGradient"]), n = (a, l, u) => {
783
+ if (!a) return a;
784
+ const g = yn(), v = { id: g, kind: l, args: Array.from(u), stops: [] };
785
+ es.set(g, v);
786
+ try {
787
+ a.__p5ExportGradId = g;
788
+ } catch {
789
+ }
790
+ return new Proxy(a, {
791
+ get(p, h) {
792
+ if (h === "addColorStop" && typeof p[h] == "function")
793
+ return function(f, m) {
794
+ return v.stops.push({ offset: f, color: m }), p[h].call(p, f, m);
795
+ };
796
+ const d = p[h];
797
+ return typeof d == "function" ? d.bind(p) : d;
798
+ }
799
+ });
800
+ };
801
+ return r.proxy = new Proxy(t, {
802
+ get(a, l) {
803
+ const u = a[l];
804
+ return typeof u == "function" ? function(...g) {
805
+ e.push([0, l, g]);
806
+ const v = u.apply(a, g);
807
+ return s.has(l) ? n(v, l, g) : v;
808
+ } : u;
809
+ },
810
+ set(a, l, u) {
811
+ if ((l === "fillStyle" || l === "strokeStyle") && u && typeof u == "object") {
812
+ const g = u.__p5ExportGradId;
813
+ e.push([1, l, g ? { __p5ExportGradId: g } : u]);
814
+ } else
815
+ e.push([1, l, u]);
816
+ return a[l] = u, !0;
817
+ }
818
+ }), r;
819
+ }
820
+ function _n(t) {
821
+ return !!(t && typeof t.fillRect == "function");
822
+ }
823
+ function zr(t) {
824
+ if (!t || t._p5ExportSVGRecorder) return;
825
+ const e = t._renderer;
826
+ if (!e) return;
827
+ const i = e.drawingContext;
828
+ if (!_n(i)) return;
829
+ const r = bn(i), s = typeof window < "u" && window.p5ExportConfig || {};
830
+ typeof s.svgMaxFrames == "number" && (r.maxFrames = s.svgMaxFrames > 0 ? s.svgMaxFrames : 1 / 0), t._p5ExportSVGRecorder = r;
831
+ const n = { value: r.proxy, configurable: !0, writable: !0, enumerable: !0 };
832
+ Object.defineProperty(e, "drawingContext", n), Object.defineProperty(t, "drawingContext", n);
833
+ }
834
+ function Vr(t) {
835
+ if (typeof t != "string") return t;
836
+ const e = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);
837
+ if (!e) return t;
838
+ const i = parseInt(e[4], 16) / 255;
839
+ return `rgba(${parseInt(e[1], 16)},${parseInt(e[2], 16)},${parseInt(e[3], 16)},${i})`;
840
+ }
841
+ function xn(t) {
842
+ if (typeof t != "string") return !0;
843
+ let e = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);
844
+ return e ? parseInt(e[4], 16) === 255 : (e = /^rgba\(\s*[^,]+,\s*[^,]+,\s*[^,]+,\s*([\d.]+)\s*\)$/i.exec(t), e ? parseFloat(e[1]) >= 1 : (e = /^#[0-9a-f]{3}([0-9a-f])$/i.exec(t), e ? parseInt(e[1], 16) === 15 : !0));
845
+ }
846
+ function is(t, e, i) {
847
+ let r = -1, s = "#000000";
848
+ const n = 0.5;
849
+ let a = !1;
850
+ for (let l = 0; l < t.length; l++) {
851
+ const u = t[l];
852
+ if (u[0] === 2) {
853
+ u[1] === "beginRaster" ? a = !0 : u[1] === "endRaster" && (a = !1);
854
+ continue;
855
+ }
856
+ if (!a) {
857
+ if (u[0] === 1 && u[1] === "fillStyle")
858
+ s = u[2];
859
+ else if (u[0] === 0 && (u[1] === "fillRect" || u[1] === "clearRect")) {
860
+ const g = u[2], v = g[0], p = g[1], h = g[2], d = g[3];
861
+ Math.abs(v) <= n && Math.abs(p) <= n && Math.abs(h - e) <= n && Math.abs(d - i) <= n && (u[1] === "clearRect" || xn(s)) && (r = l);
862
+ }
863
+ }
864
+ }
865
+ return r;
866
+ }
867
+ function Lr(t) {
868
+ wn();
869
+ const e = t._p5ExportSVGRecorder, i = t.width || 100, r = t.height || 100, s = new gt(i, r);
870
+ if (s.setTransform(1, 0, 0, 1, 0, 0), !e) return s.getSerializedSvg();
871
+ let n = "#000000", a = "#000000";
872
+ const l = /* @__PURE__ */ new Set(), u = "http://www.w3.org/2000/svg", g = (V) => {
873
+ if (!V || l.has(V.id)) return !0;
874
+ const A = s.__defs, F = s.__document;
875
+ let b;
876
+ if (V.kind === "createLinearGradient") {
877
+ const [W, Q, ht, kt] = V.args;
878
+ b = F.createElementNS(u, "linearGradient"), b.setAttribute("gradientUnits", "userSpaceOnUse"), b.setAttribute("x1", String(W)), b.setAttribute("y1", String(Q)), b.setAttribute("x2", String(ht)), b.setAttribute("y2", String(kt));
879
+ } else if (V.kind === "createRadialGradient") {
880
+ const [W, Q, ht, kt, we, ki] = V.args;
881
+ b = F.createElementNS(u, "radialGradient"), b.setAttribute("gradientUnits", "userSpaceOnUse"), b.setAttribute("fx", String(W)), b.setAttribute("fy", String(Q)), b.setAttribute("fr", String(ht)), b.setAttribute("cx", String(kt)), b.setAttribute("cy", String(we)), b.setAttribute("r", String(ki));
882
+ } else
883
+ return !1;
884
+ b.setAttribute("id", V.id);
885
+ for (const W of V.stops) {
886
+ const Q = F.createElementNS(u, "stop");
887
+ Q.setAttribute("offset", String(W.offset)), Q.setAttribute("stop-color", String(W.color)), b.appendChild(Q);
888
+ }
889
+ return A.appendChild(b), l.add(V.id), !0;
890
+ }, v = typeof t.pixelDensity == "function" ? t.pixelDensity() : 1, p = 1 / v, h = e.ops.slice(), d = is(h, i, r);
891
+ let f = 0;
892
+ if (d > 0) {
893
+ let V = 0, A = -1;
894
+ for (let b = d - 1; b >= 0; b--)
895
+ if (h[b][0] === 0) {
896
+ if (h[b][1] === "restore") V++;
897
+ else if (h[b][1] === "save") {
898
+ if (V === 0) {
899
+ A = b;
900
+ break;
901
+ }
902
+ V--;
903
+ }
904
+ }
905
+ f = A >= 0 ? A : d;
906
+ const F = {};
907
+ for (let b = 0; b < f; b++) {
908
+ const W = h[b];
909
+ W[0] === 1 && ts.has(W[1]) && (F[W[1]] = W[2]);
910
+ }
911
+ for (const b in F) {
912
+ const W = F[b];
913
+ b === "fillStyle" || b === "strokeStyle" ? typeof W == "string" ? (b === "fillStyle" ? n = W : a = W, s[b] = Vr(W)) : s[b] = b === "fillStyle" ? n : a : s[b] = W;
914
+ }
915
+ }
916
+ const m = Tt(t), w = m ? m.width : i * v, y = m ? m.height : r * v;
917
+ let C = null, x = null, _ = null, M = null, $ = null, B = !1;
918
+ const O = "http://www.w3.org/2000/svg", G = "http://www.w3.org/1999/xlink", Z = () => {
919
+ C || (C = document.createElement("canvas"), C.width = w, C.height = y, x = C.getContext("2d")), x.setTransform(1, 0, 0, 1, 0, 0), x.clearRect(0, 0, C.width, C.height), x.setTransform(v, 0, 0, v, 0, 0);
920
+ }, X = () => {
921
+ M || (M = document.createElement("canvas"), M.width = w, M.height = y, $ = M.getContext("2d"), $.setTransform(v, 0, 0, v, 0, 0));
922
+ }, q = (V) => {
923
+ if (!V || !V.hasContent || !C) return;
924
+ const A = V.bbox;
925
+ if (!A) return;
926
+ const F = Math.max(0, Math.floor(A.x * v)), b = Math.max(0, Math.floor(A.y * v)), W = Math.min(C.width, Math.ceil((A.x + A.w) * v)), Q = Math.min(C.height, Math.ceil((A.y + A.h) * v)), ht = W - F, kt = Q - b;
927
+ if (ht <= 0 || kt <= 0) return;
928
+ let we;
929
+ try {
930
+ const ge = document.createElement("canvas");
931
+ ge.width = ht, ge.height = kt, ge.getContext("2d").drawImage(C, F, b, ht, kt, 0, 0, ht, kt), we = ge.toDataURL();
932
+ } catch {
933
+ return;
934
+ }
935
+ const ki = s.__defs, At = s.__document.createElementNS(O, "pattern");
936
+ At.setAttribute("id", V.patternId), At.setAttribute("patternUnits", "userSpaceOnUse"), At.setAttribute("x", String(A.x)), At.setAttribute("y", String(A.y)), At.setAttribute("width", String(A.w)), At.setAttribute("height", String(A.h));
937
+ const Mt = s.__document.createElementNS(O, "image");
938
+ Mt.setAttribute("x", "0"), Mt.setAttribute("y", "0"), Mt.setAttribute("width", String(A.w)), Mt.setAttribute("height", String(A.h)), Mt.setAttributeNS(G, "xlink:href", we), Mt.setAttribute("href", we), Mt.setAttribute("preserveAspectRatio", "none"), At.appendChild(Mt), ki.appendChild(At);
939
+ }, ot = () => {
940
+ if (!(!M || !B))
941
+ try {
942
+ const V = M.toDataURL(), A = s.__defs, F = s.__document.createElementNS(O, "pattern");
943
+ F.setAttribute("id", Qr), F.setAttribute("patternUnits", "userSpaceOnUse"), F.setAttribute("x", "0"), F.setAttribute("y", "0"), F.setAttribute("width", String(i)), F.setAttribute("height", String(r));
944
+ const b = s.__document.createElementNS(O, "image");
945
+ b.setAttribute("x", "0"), b.setAttribute("y", "0"), b.setAttribute("width", String(i)), b.setAttribute("height", String(r)), b.setAttributeNS(G, "xlink:href", V), b.setAttribute("href", V), F.appendChild(b), A.appendChild(F);
946
+ const W = s.__document.createElementNS(O, "image");
947
+ W.setAttribute("x", "0"), W.setAttribute("y", "0"), W.setAttribute("width", String(i)), W.setAttribute("height", String(r)), W.setAttributeNS(G, "xlink:href", V), W.setAttribute("href", V), s.__root.appendChild(W);
948
+ } catch {
949
+ }
950
+ };
951
+ let Y = !1;
952
+ for (let V = f; V < h.length; V++) {
953
+ const A = h[V];
954
+ if (A[0] === 2) {
955
+ if (A[1] === "beginRaster") {
956
+ const b = A[2];
957
+ b && b.bbox && b.patternId ? (Z(), _ = { bbox: b.bbox, patternId: b.patternId, hasContent: !1 }) : (X(), _ = null), Y = !0;
958
+ } else A[1] === "endRaster" && (_ && (q(_), _ = null), Y = !1);
959
+ continue;
960
+ }
961
+ if (A[0] === 3) {
962
+ try {
963
+ mn(s, A[1], A[2], !0);
964
+ } catch {
965
+ }
966
+ continue;
967
+ }
968
+ const F = Y ? _ ? x : $ : s;
969
+ Y && A[0] === 0 && (_ ? _.hasContent = !0 : B = !0);
970
+ try {
971
+ if (A[0] === 0)
972
+ if (A[1] === "setTransform") {
973
+ const b = A[2];
974
+ F === s ? F.setTransform(b[0] * p, b[1] * p, b[2] * p, b[3] * p, b[4] * p, b[5] * p) : F.setTransform(b[0], b[1], b[2], b[3], b[4], b[5]);
975
+ } else {
976
+ const b = F[A[1]];
977
+ typeof b == "function" && b.apply(F, A[2]);
978
+ }
979
+ else if (A[1] === "fillStyle" || A[1] === "strokeStyle") {
980
+ const b = A[2], W = A[1] === "fillStyle";
981
+ if (typeof b == "string")
982
+ W ? n = b : a = b, F[A[1]] = F === s ? Vr(b) : b;
983
+ else if (b && typeof b == "object" && b.__p5ExportGradId) {
984
+ const Q = es.get(b.__p5ExportGradId);
985
+ F === s && g(Q) ? F[A[1]] = `url(#${Q.id})` : F === s && (F[A[1]] = W ? n : a);
986
+ } else if (F === s)
987
+ F[A[1]] = W ? n : a;
988
+ else
989
+ try {
990
+ F[A[1]] = b;
991
+ } catch {
992
+ }
993
+ } else if (A[1] === "globalCompositeOperation") {
994
+ if (F[A[1]] = A[2], F === s) {
995
+ const b = A[2], W = s.__currentElement;
996
+ if (W && W.setAttribute && b && b !== "source-over") {
997
+ const Q = W.getAttribute("style") || "";
998
+ if (Q.indexOf("mix-blend-mode") === -1) {
999
+ const ht = Q && !Q.trim().endsWith(";") ? ";" : "";
1000
+ W.setAttribute("style", Q + ht + "mix-blend-mode:" + b);
1001
+ }
1002
+ }
1003
+ }
1004
+ } else
1005
+ F[A[1]] = A[2];
1006
+ } catch {
1007
+ }
1008
+ }
1009
+ return _ && q(_), ot(), s.getSerializedSvg();
1010
+ }
1011
+ function Sn(t) {
1012
+ const e = t.toDataURL("image/png"), i = t.width, r = t.height;
1013
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${r}" viewBox="0 0 ${i} ${r}"><image href="${e}" width="${i}" height="${r}"/></svg>`;
1014
+ }
1015
+ function Cn(t, e, i) {
1016
+ e.saveSVG = function(s, n = {}) {
1017
+ let a;
1018
+ const l = !!this._p5ExportSVGRecorder, u = 2e6;
1019
+ let g = 0;
1020
+ if (l) {
1021
+ const d = this._p5ExportSVGRecorder.ops.slice(), f = this.width || 100, m = this.height || 100, w = is(d, f, m);
1022
+ let y = 0;
1023
+ if (w > 0) {
1024
+ let x = 0;
1025
+ for (let _ = w - 1; _ >= 0; _--)
1026
+ if (d[_][0] === 0) {
1027
+ if (d[_][1] === "restore") x++;
1028
+ else if (d[_][1] === "save") {
1029
+ if (x === 0) {
1030
+ y = _;
1031
+ break;
1032
+ }
1033
+ x--;
1034
+ }
1035
+ }
1036
+ }
1037
+ let C = !1;
1038
+ for (let x = y; x < d.length; x++) {
1039
+ const _ = d[x];
1040
+ if (_[0] === 2) {
1041
+ _[1] === "beginRaster" ? C = !0 : _[1] === "endRaster" && (C = !1);
1042
+ continue;
1043
+ }
1044
+ C || g++;
1045
+ }
1046
+ }
1047
+ const v = l && !n.forceVector && g > u;
1048
+ if (!n.raster && (!l || v) && !n.silent && typeof window < "u" && typeof window.confirm == "function") {
1049
+ const d = v ? `This sketch produced ${g.toLocaleString()} vector ops — too many to render as vector SVG cleanly (viewers crash above ~250k paths).` : "This sketch's renderer (likely WEBGL) can't be captured as vector. SVG would only contain a single embedded PNG.";
1050
+ if (!window.confirm(
1051
+ `[p5.export] SVG export problem
1052
+
1053
+ ${d}
1054
+
1055
+ Click OK to export a raster-only SVG anyway (a single <image> tag) — useful for archival.
1056
+ Click Cancel to abort the download.
1057
+
1058
+ Tips:
1059
+ • Wrap expensive draws in beginRasterRegion()/endRasterRegion() for hybrid output.
1060
+ • saveSVG('out', { forceVector: true }) — force vector despite the size.
1061
+ • saveSVG('out', { silent: true }) — never prompt; matches old behavior.`
1062
+ ))
1063
+ return console.info("[p5.export] saveSVG cancelled by user"), null;
1064
+ }
1065
+ if (n.raster || !l || v) {
1066
+ const d = Tt(this);
1067
+ if (!d) throw new Error("[p5.export] saveSVG: no canvas found");
1068
+ v ? console.warn(`[p5.export] saveSVG: ${g.toLocaleString()} vector ops — falling back to raster.`) : !l && !n.raster && console.info("[p5.export] saveSVG: WebGL renderer detected — embedding canvas as raster <image> in SVG."), a = Sn(d);
1069
+ } else
1070
+ a = Lr(this);
1071
+ const h = new Blob([a], { type: "image/svg+xml" });
1072
+ return _t(h, s ? St(s, "svg") : xt("svg")), h;
1073
+ }, e.getSVG = function() {
1074
+ return this._p5ExportSVGRecorder ? Lr(this) : "";
1075
+ }, e.clearSVGRecording = function() {
1076
+ this._p5ExportSVGRecorder && this._p5ExportSVGRecorder.clear();
1077
+ }, e.beginRasterRegion = function() {
1078
+ this._p5ExportSVGRecorder && this._p5ExportSVGRecorder.ops.push([2, "beginRaster"]);
1079
+ }, e.endRasterRegion = function() {
1080
+ this._p5ExportSVGRecorder && this._p5ExportSVGRecorder.ops.push([2, "endRaster"]);
1081
+ }, e.rasterize = function(s) {
1082
+ this.beginRasterRegion();
1083
+ try {
1084
+ return s.call(this);
1085
+ } finally {
1086
+ this.endRasterRegion();
1087
+ }
1088
+ }, e.setSVGRecordingFrames = function(s) {
1089
+ this._p5ExportSVGRecorder && (s === 1 / 0 || s < 0 ? this._p5ExportSVGRecorder.maxFrames = 1 / 0 : this._p5ExportSVGRecorder.maxFrames = Math.max(1, Math.floor(s)));
1090
+ };
1091
+ const r = e.createCanvas;
1092
+ if (typeof r == "function" && (e.createCanvas = function(...s) {
1093
+ const n = r.apply(this, s);
1094
+ this._p5ExportSVGRecorder = null, zr(this);
1095
+ try {
1096
+ Dr(t, this);
1097
+ } catch {
1098
+ }
1099
+ return n;
1100
+ }), i && typeof i == "object") {
1101
+ const s = i.presetup;
1102
+ i.presetup = function() {
1103
+ typeof s == "function" && s.call(this);
1104
+ try {
1105
+ Dr(t, this);
1106
+ } catch {
1107
+ }
1108
+ };
1109
+ const n = i.postsetup;
1110
+ i.postsetup = function() {
1111
+ typeof n == "function" && n.call(this), zr(this);
1112
+ };
1113
+ const a = i.predraw;
1114
+ i.predraw = function() {
1115
+ typeof a == "function" && a.call(this), this._p5ExportSVGRecorder && this._p5ExportSVGRecorder.markFrameBoundary();
1116
+ };
1117
+ }
1118
+ }
1119
+ function En(t) {
1120
+ return new Promise((e, i) => {
1121
+ const r = new FileReader();
1122
+ r.onload = () => e(r.result), r.onerror = i, r.readAsDataURL(t);
1123
+ });
1124
+ }
1125
+ let Ye = null;
1126
+ function Tn() {
1127
+ return Ye || (Ye = (async () => {
1128
+ if (typeof window < "u") {
1129
+ if (window.jspdf && window.jspdf.jsPDF) return window.jspdf.jsPDF;
1130
+ if (window.jsPDF) return window.jsPDF;
1131
+ }
1132
+ try {
1133
+ const t = await import("jspdf");
1134
+ if (t && t.jsPDF) return t.jsPDF;
1135
+ } catch {
1136
+ }
1137
+ throw new Error(
1138
+ '[p5.export] savePDF requires jspdf. Install it (npm i jspdf) or include <script src="https://cdn.jsdelivr.net/npm/jspdf@2/dist/jspdf.umd.min.js"><\/script> before your sketch.'
1139
+ );
1140
+ })(), Ye);
1141
+ }
1142
+ function kn(t, e) {
1143
+ e.savePDF = async function(i, r = {}) {
1144
+ const s = Tt(this);
1145
+ if (!s) throw new Error("[p5.export] savePDF: no canvas found");
1146
+ const n = await Tn(), a = (r.imageFormat || "png").toUpperCase(), l = a === "JPEG" ? "image/jpeg" : a === "WEBP" ? "image/webp" : "image/png", u = s.width, g = s.height, v = a === "JPEG" ? "jpg" : a === "WEBP" ? "webp" : "png", p = r.scale;
1147
+ let h;
1148
+ if (!p || p <= 1 || p <= (this.pixelDensity ? this.pixelDensity() : 1))
1149
+ h = s.toDataURL(l, r.quality);
1150
+ else {
1151
+ const O = await Jr(this, p, v, r.quality);
1152
+ O ? h = await En(O) : h = await Kr(this, p, () => Tt(this).toDataURL(l, r.quality));
1153
+ }
1154
+ const d = r.unit || "pt", f = r.orientation || (u >= g ? "l" : "p"), m = r.format || [u, g], w = new n({ orientation: f, unit: d, format: m }), y = w.internal.pageSize.getWidth(), C = w.internal.pageSize.getHeight(), x = Math.min(y / u, C / g), _ = u * x, M = g * x, $ = (y - _) / 2, B = (C - M) / 2;
1155
+ return w.addImage(h, a, $, B, _, M), w.save(i ? St(i, "pdf") : xt("pdf")), w;
1156
+ };
1157
+ }
1158
+ var An = { trailer: 59 };
1159
+ function rs(t = 256) {
1160
+ let e = 0, i = new Uint8Array(t);
1161
+ return { get buffer() {
1162
+ return i.buffer;
1163
+ }, reset() {
1164
+ e = 0;
1165
+ }, bytesView() {
1166
+ return i.subarray(0, e);
1167
+ }, bytes() {
1168
+ return i.slice(0, e);
1169
+ }, writeByte(s) {
1170
+ r(e + 1), i[e] = s, e++;
1171
+ }, writeBytes(s, n = 0, a = s.length) {
1172
+ r(e + a);
1173
+ for (let l = 0; l < a; l++) i[e++] = s[l + n];
1174
+ }, writeBytesView(s, n = 0, a = s.byteLength) {
1175
+ r(e + a), i.set(s.subarray(n, n + a), e), e += a;
1176
+ } };
1177
+ function r(s) {
1178
+ var n = i.length;
1179
+ if (n >= s) return;
1180
+ var a = 1024 * 1024;
1181
+ s = Math.max(s, n * (n < a ? 2 : 1.125) >>> 0), n != 0 && (s = Math.max(s, 256));
1182
+ let l = i;
1183
+ i = new Uint8Array(s), e > 0 && i.set(l.subarray(0, e), 0);
1184
+ }
1185
+ }
1186
+ var Pi = 12, Or = 5003, Mn = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535];
1187
+ function Pn(t, e, i, r, s = rs(512), n = new Uint8Array(256), a = new Int32Array(Or), l = new Int32Array(Or)) {
1188
+ let u = a.length, g = Math.max(2, r);
1189
+ n.fill(0), l.fill(0), a.fill(-1);
1190
+ let v = 0, p = 0, h = g + 1, d = h, f = !1, m = d, w = (1 << m) - 1, y = 1 << h - 1, C = y + 1, x = y + 2, _ = 0, M = i[0], $ = 0;
1191
+ for (let G = u; G < 65536; G *= 2) ++$;
1192
+ $ = 8 - $, s.writeByte(g), O(y);
1193
+ let B = i.length;
1194
+ for (let G = 1; G < B; G++)
1195
+ t: {
1196
+ let Z = i[G], X = (Z << Pi) + M, q = Z << $ ^ M;
1197
+ if (a[q] === X) {
1198
+ M = l[q];
1199
+ break t;
1200
+ }
1201
+ let ot = q === 0 ? 1 : u - q;
1202
+ for (; a[q] >= 0; ) if (q -= ot, q < 0 && (q += u), a[q] === X) {
1203
+ M = l[q];
1204
+ break t;
1205
+ }
1206
+ O(M), M = Z, x < 1 << Pi ? (l[q] = x++, a[q] = X) : (a.fill(-1), x = y + 2, f = !0, O(y));
1207
+ }
1208
+ return O(M), O(C), s.writeByte(0), s.bytesView();
1209
+ function O(G) {
1210
+ for (v &= Mn[p], p > 0 ? v |= G << p : v = G, p += m; p >= 8; ) n[_++] = v & 255, _ >= 254 && (s.writeByte(_), s.writeBytesView(n, 0, _), _ = 0), v >>= 8, p -= 8;
1211
+ if ((x > w || f) && (f ? (m = d, w = (1 << m) - 1, f = !1) : (++m, w = m === Pi ? 1 << m : (1 << m) - 1)), G == C) {
1212
+ for (; p > 0; ) n[_++] = v & 255, _ >= 254 && (s.writeByte(_), s.writeBytesView(n, 0, _), _ = 0), v >>= 8, p -= 8;
1213
+ _ > 0 && (s.writeByte(_), s.writeBytesView(n, 0, _), _ = 0);
1214
+ }
1215
+ }
1216
+ }
1217
+ var In = Pn;
1218
+ function ss(t, e, i) {
1219
+ return t << 8 & 63488 | e << 2 & 992 | i >> 3;
1220
+ }
1221
+ function ns(t, e, i, r) {
1222
+ return t >> 4 | e & 240 | (i & 240) << 4 | (r & 240) << 8;
1223
+ }
1224
+ function as(t, e, i) {
1225
+ return t >> 4 << 8 | e & 240 | i >> 4;
1226
+ }
1227
+ function Je(t, e, i) {
1228
+ return t < e ? e : t > i ? i : t;
1229
+ }
1230
+ function Qe(t) {
1231
+ return t * t;
1232
+ }
1233
+ function Gr(t, e, i) {
1234
+ var r = 0, s = 1e100;
1235
+ let n = t[e], a = n.cnt;
1236
+ n.ac;
1237
+ let l = n.rc, u = n.gc, g = n.bc;
1238
+ for (var v = n.fw; v != 0; v = t[v].fw) {
1239
+ let h = t[v], d = h.cnt, f = a * d / (a + d);
1240
+ if (!(f >= s)) {
1241
+ var p = 0;
1242
+ p += f * Qe(h.rc - l), !(p >= s) && (p += f * Qe(h.gc - u), !(p >= s) && (p += f * Qe(h.bc - g), !(p >= s) && (s = p, r = v)));
1243
+ }
1244
+ }
1245
+ n.err = s, n.nn = r;
1246
+ }
1247
+ function Ii() {
1248
+ return { ac: 0, rc: 0, gc: 0, bc: 0, cnt: 0, nn: 0, fw: 0, bk: 0, tm: 0, mtm: 0, err: 0 };
1249
+ }
1250
+ function Rn(t, e) {
1251
+ let i = e === "rgb444" ? 4096 : 65536, r = new Array(i), s = t.length;
1252
+ if (e === "rgba4444") for (let n = 0; n < s; ++n) {
1253
+ let a = t[n], l = a >> 24 & 255, u = a >> 16 & 255, g = a >> 8 & 255, v = a & 255, p = ns(v, g, u, l), h = p in r ? r[p] : r[p] = Ii();
1254
+ h.rc += v, h.gc += g, h.bc += u, h.ac += l, h.cnt++;
1255
+ }
1256
+ else if (e === "rgb444") for (let n = 0; n < s; ++n) {
1257
+ let a = t[n], l = a >> 16 & 255, u = a >> 8 & 255, g = a & 255, v = as(g, u, l), p = v in r ? r[v] : r[v] = Ii();
1258
+ p.rc += g, p.gc += u, p.bc += l, p.cnt++;
1259
+ }
1260
+ else for (let n = 0; n < s; ++n) {
1261
+ let a = t[n], l = a >> 16 & 255, u = a >> 8 & 255, g = a & 255, v = ss(g, u, l), p = v in r ? r[v] : r[v] = Ii();
1262
+ p.rc += g, p.gc += u, p.bc += l, p.cnt++;
1263
+ }
1264
+ return r;
1265
+ }
1266
+ function os(t, e, i = {}) {
1267
+ let { format: r = "rgb565", clearAlpha: s = !0, clearAlphaColor: n = 0, clearAlphaThreshold: a = 0, oneBitAlpha: l = !1 } = i;
1268
+ if (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");
1269
+ if (!(t instanceof Uint8Array) && !(t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");
1270
+ let u = new Uint32Array(t.buffer), g = i.useSqrt !== !1, v = r === "rgba4444", p = Rn(u, r), h = p.length, d = h - 1, f = new Uint32Array(h + 1);
1271
+ for (var m = 0, w = 0; w < h; ++w) {
1272
+ let Y = p[w];
1273
+ if (Y != null) {
1274
+ var y = 1 / Y.cnt;
1275
+ v && (Y.ac *= y), Y.rc *= y, Y.gc *= y, Y.bc *= y, p[m++] = Y;
1276
+ }
1277
+ }
1278
+ Qe(e) / m < 0.022 && (g = !1);
1279
+ for (var w = 0; w < m - 1; ++w) p[w].fw = w + 1, p[w + 1].bk = w, g && (p[w].cnt = Math.sqrt(p[w].cnt));
1280
+ g && (p[w].cnt = Math.sqrt(p[w].cnt));
1281
+ var C, x, _;
1282
+ for (w = 0; w < m; ++w) {
1283
+ Gr(p, w);
1284
+ var M = p[w].err;
1285
+ for (x = ++f[0]; x > 1 && (_ = x >> 1, !(p[C = f[_]].err <= M)); x = _) f[x] = C;
1286
+ f[x] = w;
1287
+ }
1288
+ var $ = m - e;
1289
+ for (w = 0; w < $; ) {
1290
+ for (var B; ; ) {
1291
+ var O = f[1];
1292
+ if (B = p[O], B.tm >= B.mtm && p[B.nn].mtm <= B.tm) break;
1293
+ B.mtm == d ? O = f[1] = f[f[0]--] : (Gr(p, O), B.tm = w);
1294
+ var M = p[O].err;
1295
+ for (x = 1; (_ = x + x) <= f[0] && (_ < f[0] && p[f[_]].err > p[f[_ + 1]].err && _++, !(M <= p[C = f[_]].err)); x = _) f[x] = C;
1296
+ f[x] = O;
1297
+ }
1298
+ var G = p[B.nn], Z = B.cnt, X = G.cnt, y = 1 / (Z + X);
1299
+ v && (B.ac = y * (Z * B.ac + X * G.ac)), B.rc = y * (Z * B.rc + X * G.rc), B.gc = y * (Z * B.gc + X * G.gc), B.bc = y * (Z * B.bc + X * G.bc), B.cnt += G.cnt, B.mtm = ++w, p[G.bk].fw = G.fw, p[G.fw].bk = G.bk, G.mtm = d;
1300
+ }
1301
+ let q = [];
1302
+ var ot = 0;
1303
+ for (w = 0; ; ++ot) {
1304
+ let Y = Je(Math.round(p[w].rc), 0, 255), V = Je(Math.round(p[w].gc), 0, 255), A = Je(Math.round(p[w].bc), 0, 255), F = 255;
1305
+ v && (F = Je(Math.round(p[w].ac), 0, 255), l && (F = F <= (typeof l == "number" ? l : 127) ? 0 : 255), s && F <= a && (Y = V = A = n, F = 0));
1306
+ let b = v ? [Y, V, A, F] : [Y, V, A];
1307
+ if (Bn(q, b) || q.push(b), (w = p[w].fw) == 0) break;
1308
+ }
1309
+ return q;
1310
+ }
1311
+ function Bn(t, e) {
1312
+ for (let i = 0; i < t.length; i++) {
1313
+ let r = t[i], s = r[0] === e[0] && r[1] === e[1] && r[2] === e[2], n = r.length >= 4 && e.length >= 4 ? r[3] === e[3] : !0;
1314
+ if (s && n) return !0;
1315
+ }
1316
+ return !1;
1317
+ }
1318
+ function hs(t, e, i = "rgb565") {
1319
+ if (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");
1320
+ if (!(t instanceof Uint8Array) && !(t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");
1321
+ if (e.length > 256) throw new Error("applyPalette() only works with 256 colors or less");
1322
+ let r = new Uint32Array(t.buffer), s = r.length, n = i === "rgb444" ? 4096 : 65536, a = new Uint8Array(s), l = new Array(n);
1323
+ if (i === "rgba4444") for (let u = 0; u < s; u++) {
1324
+ let g = r[u], v = g >> 24 & 255, p = g >> 16 & 255, h = g >> 8 & 255, d = g & 255, f = ns(d, h, p, v), m = f in l ? l[f] : l[f] = Fn(d, h, p, v, e);
1325
+ a[u] = m;
1326
+ }
1327
+ else {
1328
+ let u = i === "rgb444" ? as : ss;
1329
+ for (let g = 0; g < s; g++) {
1330
+ let v = r[g], p = v >> 16 & 255, h = v >> 8 & 255, d = v & 255, f = u(d, h, p), m = f in l ? l[f] : l[f] = Un(d, h, p, e);
1331
+ a[g] = m;
1332
+ }
1333
+ }
1334
+ return a;
1335
+ }
1336
+ function Fn(t, e, i, r, s) {
1337
+ let n = 0, a = 1e100;
1338
+ for (let l = 0; l < s.length; l++) {
1339
+ let u = s[l], g = u[3], v = jt(g - r);
1340
+ if (v > a) continue;
1341
+ let p = u[0];
1342
+ if (v += jt(p - t), v > a) continue;
1343
+ let h = u[1];
1344
+ if (v += jt(h - e), v > a) continue;
1345
+ let d = u[2];
1346
+ v += jt(d - i), !(v > a) && (a = v, n = l);
1347
+ }
1348
+ return n;
1349
+ }
1350
+ function Un(t, e, i, r) {
1351
+ let s = 0, n = 1e100;
1352
+ for (let a = 0; a < r.length; a++) {
1353
+ let l = r[a], u = l[0], g = jt(u - t);
1354
+ if (g > n) continue;
1355
+ let v = l[1];
1356
+ if (g += jt(v - e), g > n) continue;
1357
+ let p = l[2];
1358
+ g += jt(p - i), !(g > n) && (n = g, s = a);
1359
+ }
1360
+ return s;
1361
+ }
1362
+ function jt(t) {
1363
+ return t * t;
1364
+ }
1365
+ function ls(t = {}) {
1366
+ let { initialCapacity: e = 4096, auto: i = !0 } = t, r = rs(e), s = 5003, n = new Uint8Array(256), a = new Int32Array(s), l = new Int32Array(s), u = !1;
1367
+ return { reset() {
1368
+ r.reset(), u = !1;
1369
+ }, finish() {
1370
+ r.writeByte(An.trailer);
1371
+ }, bytes() {
1372
+ return r.bytes();
1373
+ }, bytesView() {
1374
+ return r.bytesView();
1375
+ }, get buffer() {
1376
+ return r.buffer;
1377
+ }, get stream() {
1378
+ return r;
1379
+ }, writeHeader: g, writeFrame(v, p, h, d = {}) {
1380
+ let { transparent: f = !1, transparentIndex: m = 0, delay: w = 0, palette: y = null, repeat: C = 0, colorDepth: x = 8, dispose: _ = -1 } = d, M = !1;
1381
+ if (i ? u || (M = !0, g(), u = !0) : M = !!d.first, p = Math.max(0, Math.floor(p)), h = Math.max(0, Math.floor(h)), M) {
1382
+ if (!y) throw new Error("First frame must include a { palette } option");
1383
+ Wn(r, p, h, y, x), Nr(r, y), C >= 0 && zn(r, C);
1384
+ }
1385
+ let $ = Math.round(w / 10);
1386
+ Dn(r, _, $, f, m);
1387
+ let B = !!y && !M;
1388
+ Vn(r, p, h, B ? y : null), B && Nr(r, y), Ln(r, v, p, h, x, n, a, l);
1389
+ } };
1390
+ function g() {
1391
+ ds(r, "GIF89a");
1392
+ }
1393
+ }
1394
+ function Dn(t, e, i, r, s) {
1395
+ t.writeByte(33), t.writeByte(249), t.writeByte(4), s < 0 && (s = 0, r = !1);
1396
+ var n, a;
1397
+ r ? (n = 1, a = 2) : (n = 0, a = 0), e >= 0 && (a = e & 7), a <<= 2, t.writeByte(0 | a | 0 | n), Rt(t, i), t.writeByte(s || 0), t.writeByte(0);
1398
+ }
1399
+ function Wn(t, e, i, r, s = 8) {
1400
+ let n = 1, a = 0, l = nr(r.length) - 1, u = n << 7 | s - 1 << 4 | a << 3 | l;
1401
+ Rt(t, e), Rt(t, i), t.writeBytes([u, 0, 0]);
1402
+ }
1403
+ function zn(t, e) {
1404
+ t.writeByte(33), t.writeByte(255), t.writeByte(11), ds(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), Rt(t, e), t.writeByte(0);
1405
+ }
1406
+ function Nr(t, e) {
1407
+ let i = 1 << nr(e.length);
1408
+ for (let r = 0; r < i; r++) {
1409
+ let s = [0, 0, 0];
1410
+ r < e.length && (s = e[r]), t.writeByte(s[0]), t.writeByte(s[1]), t.writeByte(s[2]);
1411
+ }
1412
+ }
1413
+ function Vn(t, e, i, r) {
1414
+ if (t.writeByte(44), Rt(t, 0), Rt(t, 0), Rt(t, e), Rt(t, i), r) {
1415
+ let s = 0, n = 0, a = nr(r.length) - 1;
1416
+ t.writeByte(128 | s | n | 0 | a);
1417
+ } else t.writeByte(0);
1418
+ }
1419
+ function Ln(t, e, i, r, s = 8, n, a, l) {
1420
+ In(i, r, e, s, t, n, a, l);
1421
+ }
1422
+ function Rt(t, e) {
1423
+ t.writeByte(e & 255), t.writeByte(e >> 8 & 255);
1424
+ }
1425
+ function ds(t, e) {
1426
+ for (var i = 0; i < e.length; i++) t.writeByte(e.charCodeAt(i));
1427
+ }
1428
+ function nr(t) {
1429
+ return Math.max(Math.ceil(Math.log2(t)), 1);
1430
+ }
1431
+ class On {
1432
+ /**
1433
+ * @param {object} opts
1434
+ * @param {HTMLCanvasElement} opts.canvas
1435
+ * @param {number} [opts.fps=30]
1436
+ * @param {number} [opts.duration] seconds; if set, recorder auto-stops
1437
+ * @param {number} [opts.maxColors=256]
1438
+ * @param {string} [opts.filename]
1439
+ * @param {(p:number)=>void} [opts.onProgress] 0..1 during finalize
1440
+ */
1441
+ constructor(e) {
1442
+ this.canvas = e.canvas, this.fps = e.fps ?? 30, this.duration = e.duration, this.maxColors = e.maxColors ?? 256, this.filename = e.filename, this.onProgress = e.onProgress || (() => {
1443
+ }), this.frames = [], this.startTime = 0, this.active = !1, this.framesRecorded = 0;
1444
+ }
1445
+ start() {
1446
+ this.active || (this.frames = [], this.framesRecorded = 0, this.startTime = performance.now(), this.active = !0, this._nextFrameAt = this.startTime);
1447
+ }
1448
+ /** Called every draw frame; decides whether to grab a frame based on target fps. */
1449
+ tick() {
1450
+ if (!this.active) return;
1451
+ const e = performance.now();
1452
+ if (e < this._nextFrameAt) return;
1453
+ const i = this.canvas.getContext("2d", { willReadFrequently: !0 }) || this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
1454
+ let r;
1455
+ if (i && i.getImageData)
1456
+ r = i.getImageData(0, 0, this.canvas.width, this.canvas.height).data;
1457
+ else {
1458
+ const s = document.createElement("canvas");
1459
+ s.width = this.canvas.width, s.height = this.canvas.height, s.getContext("2d").drawImage(this.canvas, 0, 0), r = s.getContext("2d").getImageData(0, 0, s.width, s.height).data;
1460
+ }
1461
+ this.frames.push({
1462
+ data: new Uint8ClampedArray(r),
1463
+ width: this.canvas.width,
1464
+ height: this.canvas.height
1465
+ }), this.framesRecorded++, this._nextFrameAt += 1e3 / this.fps, this.duration && e - this.startTime >= this.duration * 1e3 && this.stop();
1466
+ }
1467
+ /** Stop capture and encode. Returns a Promise<Blob>. */
1468
+ async stop() {
1469
+ if (!this.active) return null;
1470
+ this.active = !1;
1471
+ const e = await this._encode(), i = this.filename ? St(this.filename, "gif") : xt("gif");
1472
+ return _t(e, i), e;
1473
+ }
1474
+ /** Encode without downloading — useful when the caller wants the Blob directly. */
1475
+ async encode() {
1476
+ return this.active = !1, this._encode();
1477
+ }
1478
+ async _encode() {
1479
+ const e = ls(), i = Math.round(1e3 / this.fps), r = this.frames.length;
1480
+ for (let s = 0; s < r; s++) {
1481
+ const n = this.frames[s], a = os(n.data, this.maxColors), l = hs(n.data, a);
1482
+ e.writeFrame(l, n.width, n.height, { palette: a, delay: i }), this.onProgress((s + 1) / r), s % 4 === 3 && await new Promise((u) => setTimeout(u, 0));
1483
+ }
1484
+ return e.finish(), new Blob([e.bytes()], { type: "image/gif" });
1485
+ }
1486
+ }
1487
+ function Gn(t, e, i) {
1488
+ if (e.recordGIF = function(r = {}) {
1489
+ const s = Tt(this);
1490
+ if (!s) throw new Error("[p5.export] recordGIF: no canvas found");
1491
+ if (this._p5ExportGIF && this._p5ExportGIF.active)
1492
+ throw new Error("[p5.export] a GIF recording is already in progress");
1493
+ const n = new On({ canvas: s, ...r });
1494
+ return n.start(), this._p5ExportGIF = n, n;
1495
+ }, e.stopGIF = function() {
1496
+ const r = this._p5ExportGIF;
1497
+ return r ? (this._p5ExportGIF = null, r.stop()) : null;
1498
+ }, i && typeof i == "object") {
1499
+ const r = i.postdraw;
1500
+ i.postdraw = function() {
1501
+ typeof r == "function" && r.call(this), this._p5ExportGIF && this._p5ExportGIF.active && this._p5ExportGIF.tick();
1502
+ };
1503
+ }
1504
+ }
1505
+ class Nn {
1506
+ /**
1507
+ * @param {object} opts
1508
+ * @param {HTMLCanvasElement} opts.canvas
1509
+ * @param {number} [opts.fps=30]
1510
+ * @param {number} [opts.duration] seconds; auto-stops when reached
1511
+ * @param {number} [opts.maxFrames=900] safety cap (default ≈ 30 s @ 30 fps)
1512
+ */
1513
+ constructor({ canvas: e, fps: i = 30, duration: r, maxFrames: s = 900 }) {
1514
+ this.canvas = e, this.fps = i, this.duration = r, this.maxFrames = s, this.width = e.width, this.height = e.height, this.frames = [], this.recording = !1, this.startTime = 0, this._nextFrameAt = 0;
1515
+ }
1516
+ start() {
1517
+ this.frames = [], this.recording = !0, this.startTime = performance.now(), this._nextFrameAt = this.startTime;
1518
+ }
1519
+ /**
1520
+ * Pull one frame off the canvas if enough time has elapsed. Called every
1521
+ * `postdraw` via a lifecycle hook in video.js.
1522
+ */
1523
+ tick() {
1524
+ if (!this.recording) return;
1525
+ const e = performance.now();
1526
+ if (e < this._nextFrameAt) return;
1527
+ if (this.frames.length >= this.maxFrames) {
1528
+ this.stop();
1529
+ return;
1530
+ }
1531
+ let i;
1532
+ const r = this.canvas.getContext("2d", { willReadFrequently: !0 });
1533
+ if (r && typeof r.getImageData == "function")
1534
+ i = r.getImageData(0, 0, this.width, this.height).data;
1535
+ else {
1536
+ const s = document.createElement("canvas");
1537
+ s.width = this.width, s.height = this.height;
1538
+ const n = s.getContext("2d");
1539
+ n.drawImage(this.canvas, 0, 0), i = n.getImageData(0, 0, this.width, this.height).data;
1540
+ }
1541
+ this.frames.push(new Uint8ClampedArray(i)), this._nextFrameAt += 1e3 / this.fps, this.duration && e - this.startTime >= this.duration * 1e3 && this.stop();
1542
+ }
1543
+ stop() {
1544
+ this.recording = !1;
1545
+ }
1546
+ clear() {
1547
+ this.frames = [];
1548
+ }
1549
+ get framesRecorded() {
1550
+ return this.frames.length;
1551
+ }
1552
+ /** Duration in seconds of what's been captured so far. */
1553
+ get capturedSeconds() {
1554
+ return this.frames.length / this.fps;
1555
+ }
1556
+ }
1557
+ var ar = (t, e, i) => {
1558
+ if (!e.has(t))
1559
+ throw TypeError("Cannot " + i);
1560
+ }, c = (t, e, i) => (ar(t, e, "read from private field"), i ? i.call(t) : e.get(t)), D = (t, e, i) => {
1561
+ if (e.has(t))
1562
+ throw TypeError("Cannot add the same private member more than once");
1563
+ e instanceof WeakSet ? e.add(t) : e.set(t, i);
1564
+ }, et = (t, e, i, r) => (ar(t, e, "write to private field"), e.set(t, i), i), $n = (t, e, i, r) => ({
1565
+ set _(s) {
1566
+ et(t, e, s);
1567
+ },
1568
+ get _() {
1569
+ return c(t, e, r);
1570
+ }
1571
+ }), z = (t, e, i) => (ar(t, e, "access private method"), i), L = new Uint8Array(8), wt = new DataView(L.buffer), K = (t) => [(t % 256 + 256) % 256], j = (t) => (wt.setUint16(0, t, !1), [L[0], L[1]]), jn = (t) => (wt.setInt16(0, t, !1), [L[0], L[1]]), cs = (t) => (wt.setUint32(0, t, !1), [L[1], L[2], L[3]]), E = (t) => (wt.setUint32(0, t, !1), [L[0], L[1], L[2], L[3]]), qn = (t) => (wt.setInt32(0, t, !1), [L[0], L[1], L[2], L[3]]), Yt = (t) => (wt.setUint32(0, Math.floor(t / 2 ** 32), !1), wt.setUint32(4, t, !1), [L[0], L[1], L[2], L[3], L[4], L[5], L[6], L[7]]), or = (t) => (wt.setInt16(0, 2 ** 8 * t, !1), [L[0], L[1]]), ut = (t) => (wt.setInt32(0, 2 ** 16 * t, !1), [L[0], L[1], L[2], L[3]]), Ri = (t) => (wt.setInt32(0, 2 ** 30 * t, !1), [L[0], L[1], L[2], L[3]]), at = (t, e = !1) => {
1572
+ let i = Array(t.length).fill(null).map((r, s) => t.charCodeAt(s));
1573
+ return e && i.push(0), i;
1574
+ }, ci = (t) => t && t[t.length - 1], hr = (t) => {
1575
+ let e;
1576
+ for (let i of t)
1577
+ (!e || i.presentationTimestamp > e.presentationTimestamp) && (e = i);
1578
+ return e;
1579
+ }, mt = (t, e, i = !0) => {
1580
+ let r = t * e;
1581
+ return i ? Math.round(r) : r;
1582
+ }, fs = (t) => {
1583
+ let e = t * (Math.PI / 180), i = Math.cos(e), r = Math.sin(e);
1584
+ return [
1585
+ i,
1586
+ r,
1587
+ 0,
1588
+ -r,
1589
+ i,
1590
+ 0,
1591
+ 0,
1592
+ 0,
1593
+ 1
1594
+ ];
1595
+ }, us = fs(0), ps = (t) => [
1596
+ ut(t[0]),
1597
+ ut(t[1]),
1598
+ Ri(t[2]),
1599
+ ut(t[3]),
1600
+ ut(t[4]),
1601
+ Ri(t[5]),
1602
+ ut(t[6]),
1603
+ ut(t[7]),
1604
+ Ri(t[8])
1605
+ ], Ee = (t) => !t || typeof t != "object" ? t : Array.isArray(t) ? t.map(Ee) : Object.fromEntries(Object.entries(t).map(([e, i]) => [e, Ee(i)])), ce = (t) => t >= 0 && t < 2 ** 32, J = (t, e, i) => ({
1606
+ type: t,
1607
+ contents: e && new Uint8Array(e.flat(10)),
1608
+ children: i
1609
+ }), H = (t, e, i, r, s) => J(
1610
+ t,
1611
+ [K(e), cs(i), r ?? []],
1612
+ s
1613
+ ), Hn = (t) => {
1614
+ let e = 512;
1615
+ return t.fragmented ? J("ftyp", [
1616
+ at("iso5"),
1617
+ // Major brand
1618
+ E(e),
1619
+ // Minor version
1620
+ // Compatible brands
1621
+ at("iso5"),
1622
+ at("iso6"),
1623
+ at("mp41")
1624
+ ]) : J("ftyp", [
1625
+ at("isom"),
1626
+ // Major brand
1627
+ E(e),
1628
+ // Minor version
1629
+ // Compatible brands
1630
+ at("isom"),
1631
+ t.holdsAvc ? at("avc1") : [],
1632
+ at("mp41")
1633
+ ]);
1634
+ }, Wi = (t) => ({ type: "mdat", largeSize: t }), Xn = (t) => ({ type: "free", size: t }), ti = (t, e, i = !1) => J("moov", null, [
1635
+ Yn(e, t),
1636
+ ...t.map((r) => Jn(r, e)),
1637
+ i ? ka(t) : null
1638
+ ]), Yn = (t, e) => {
1639
+ let i = mt(Math.max(
1640
+ 0,
1641
+ ...e.filter((a) => a.samples.length > 0).map((a) => {
1642
+ const l = hr(a.samples);
1643
+ return l.presentationTimestamp + l.duration;
1644
+ })
1645
+ ), Li), r = Math.max(...e.map((a) => a.id)) + 1, s = !ce(t) || !ce(i), n = s ? Yt : E;
1646
+ return H("mvhd", +s, 0, [
1647
+ n(t),
1648
+ // Creation time
1649
+ n(t),
1650
+ // Modification time
1651
+ E(Li),
1652
+ // Timescale
1653
+ n(i),
1654
+ // Duration
1655
+ ut(1),
1656
+ // Preferred rate
1657
+ or(1),
1658
+ // Preferred volume
1659
+ Array(10).fill(0),
1660
+ // Reserved
1661
+ ps(us),
1662
+ // Matrix
1663
+ Array(24).fill(0),
1664
+ // Pre-defined
1665
+ E(r)
1666
+ // Next track ID
1667
+ ]);
1668
+ }, Jn = (t, e) => J("trak", null, [
1669
+ Kn(t, e),
1670
+ Zn(t, e)
1671
+ ]), Kn = (t, e) => {
1672
+ let i = hr(t.samples), r = mt(
1673
+ i ? i.presentationTimestamp + i.duration : 0,
1674
+ Li
1675
+ ), s = !ce(e) || !ce(r), n = s ? Yt : E, a;
1676
+ return t.info.type === "video" ? a = typeof t.info.rotation == "number" ? fs(t.info.rotation) : t.info.rotation : a = us, H("tkhd", +s, 3, [
1677
+ n(e),
1678
+ // Creation time
1679
+ n(e),
1680
+ // Modification time
1681
+ E(t.id),
1682
+ // Track ID
1683
+ E(0),
1684
+ // Reserved
1685
+ n(r),
1686
+ // Duration
1687
+ Array(8).fill(0),
1688
+ // Reserved
1689
+ j(0),
1690
+ // Layer
1691
+ j(0),
1692
+ // Alternate group
1693
+ or(t.info.type === "audio" ? 1 : 0),
1694
+ // Volume
1695
+ j(0),
1696
+ // Reserved
1697
+ ps(a),
1698
+ // Matrix
1699
+ ut(t.info.type === "video" ? t.info.width : 0),
1700
+ // Track width
1701
+ ut(t.info.type === "video" ? t.info.height : 0)
1702
+ // Track height
1703
+ ]);
1704
+ }, Zn = (t, e) => J("mdia", null, [
1705
+ Qn(t, e),
1706
+ ta(t.info.type === "video" ? "vide" : "soun"),
1707
+ ea(t)
1708
+ ]), Qn = (t, e) => {
1709
+ let i = hr(t.samples), r = mt(
1710
+ i ? i.presentationTimestamp + i.duration : 0,
1711
+ t.timescale
1712
+ ), s = !ce(e) || !ce(r), n = s ? Yt : E;
1713
+ return H("mdhd", +s, 0, [
1714
+ n(e),
1715
+ // Creation time
1716
+ n(e),
1717
+ // Modification time
1718
+ E(t.timescale),
1719
+ // Timescale
1720
+ n(r),
1721
+ // Duration
1722
+ j(21956),
1723
+ // Language ("und", undetermined)
1724
+ j(0)
1725
+ // Quality
1726
+ ]);
1727
+ }, ta = (t) => H("hdlr", 0, 0, [
1728
+ at("mhlr"),
1729
+ // Component type
1730
+ at(t),
1731
+ // Component subtype
1732
+ E(0),
1733
+ // Component manufacturer
1734
+ E(0),
1735
+ // Component flags
1736
+ E(0),
1737
+ // Component flags mask
1738
+ at("mp4-muxer-hdlr", !0)
1739
+ // Component name
1740
+ ]), ea = (t) => J("minf", null, [
1741
+ t.info.type === "video" ? ia() : ra(),
1742
+ sa(),
1743
+ oa(t)
1744
+ ]), ia = () => H("vmhd", 0, 1, [
1745
+ j(0),
1746
+ // Graphics mode
1747
+ j(0),
1748
+ // Opcolor R
1749
+ j(0),
1750
+ // Opcolor G
1751
+ j(0)
1752
+ // Opcolor B
1753
+ ]), ra = () => H("smhd", 0, 0, [
1754
+ j(0),
1755
+ // Balance
1756
+ j(0)
1757
+ // Reserved
1758
+ ]), sa = () => J("dinf", null, [
1759
+ na()
1760
+ ]), na = () => H("dref", 0, 0, [
1761
+ E(1)
1762
+ // Entry count
1763
+ ], [
1764
+ aa()
1765
+ ]), aa = () => H("url ", 0, 1), oa = (t) => {
1766
+ const e = t.compositionTimeOffsetTable.length > 1 || t.compositionTimeOffsetTable.some((i) => i.sampleCompositionTimeOffset !== 0);
1767
+ return J("stbl", null, [
1768
+ ha(t),
1769
+ _a(t),
1770
+ xa(t),
1771
+ Sa(t),
1772
+ Ca(t),
1773
+ Ea(t),
1774
+ e ? Ta(t) : null
1775
+ ]);
1776
+ }, ha = (t) => H("stsd", 0, 0, [
1777
+ E(1)
1778
+ // Entry count
1779
+ ], [
1780
+ t.info.type === "video" ? la(
1781
+ Wa[t.info.codec],
1782
+ t
1783
+ ) : va(
1784
+ Va[t.info.codec],
1785
+ t
1786
+ )
1787
+ ]), la = (t, e) => J(t, [
1788
+ Array(6).fill(0),
1789
+ // Reserved
1790
+ j(1),
1791
+ // Data reference index
1792
+ j(0),
1793
+ // Pre-defined
1794
+ j(0),
1795
+ // Reserved
1796
+ Array(12).fill(0),
1797
+ // Pre-defined
1798
+ j(e.info.width),
1799
+ // Width
1800
+ j(e.info.height),
1801
+ // Height
1802
+ E(4718592),
1803
+ // Horizontal resolution
1804
+ E(4718592),
1805
+ // Vertical resolution
1806
+ E(0),
1807
+ // Reserved
1808
+ j(1),
1809
+ // Frame count
1810
+ Array(32).fill(0),
1811
+ // Compressor name
1812
+ j(24),
1813
+ // Depth
1814
+ jn(65535)
1815
+ // Pre-defined
1816
+ ], [
1817
+ za[e.info.codec](e),
1818
+ e.info.decoderConfig.colorSpace ? ua(e) : null
1819
+ ]), da = {
1820
+ bt709: 1,
1821
+ // ITU-R BT.709
1822
+ bt470bg: 5,
1823
+ // ITU-R BT.470BG
1824
+ smpte170m: 6
1825
+ // ITU-R BT.601 525 - SMPTE 170M
1826
+ }, ca = {
1827
+ bt709: 1,
1828
+ // ITU-R BT.709
1829
+ smpte170m: 6,
1830
+ // SMPTE 170M
1831
+ "iec61966-2-1": 13
1832
+ // IEC 61966-2-1
1833
+ }, fa = {
1834
+ rgb: 0,
1835
+ // Identity
1836
+ bt709: 1,
1837
+ // ITU-R BT.709
1838
+ bt470bg: 5,
1839
+ // ITU-R BT.470BG
1840
+ smpte170m: 6
1841
+ // SMPTE 170M
1842
+ }, ua = (t) => J("colr", [
1843
+ at("nclx"),
1844
+ // Colour type
1845
+ j(da[t.info.decoderConfig.colorSpace.primaries]),
1846
+ // Colour primaries
1847
+ j(ca[t.info.decoderConfig.colorSpace.transfer]),
1848
+ // Transfer characteristics
1849
+ j(fa[t.info.decoderConfig.colorSpace.matrix]),
1850
+ // Matrix coefficients
1851
+ K((t.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
1852
+ // Full range flag
1853
+ ]), pa = (t) => t.info.decoderConfig && J("avcC", [
1854
+ // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
1855
+ ...new Uint8Array(t.info.decoderConfig.description)
1856
+ ]), ma = (t) => t.info.decoderConfig && J("hvcC", [
1857
+ // For HEVC, description is a HEVCDecoderConfigurationRecord, so nothing else to do here
1858
+ ...new Uint8Array(t.info.decoderConfig.description)
1859
+ ]), wa = (t) => {
1860
+ if (!t.info.decoderConfig)
1861
+ return null;
1862
+ let e = t.info.decoderConfig;
1863
+ if (!e.colorSpace)
1864
+ throw new Error("'colorSpace' is required in the decoder config for VP9.");
1865
+ let i = e.codec.split("."), r = Number(i[1]), s = Number(i[2]), l = (Number(i[3]) << 4) + (0 << 1) + Number(e.colorSpace.fullRange);
1866
+ return H("vpcC", 1, 0, [
1867
+ K(r),
1868
+ // Profile
1869
+ K(s),
1870
+ // Level
1871
+ K(l),
1872
+ // Bit depth, chroma subsampling, full range
1873
+ K(2),
1874
+ // Colour primaries
1875
+ K(2),
1876
+ // Transfer characteristics
1877
+ K(2),
1878
+ // Matrix coefficients
1879
+ j(0)
1880
+ // Codec initialization data size
1881
+ ]);
1882
+ }, ga = () => {
1883
+ let i = (1 << 7) + 1;
1884
+ return J("av1C", [
1885
+ i,
1886
+ 0,
1887
+ 0,
1888
+ 0
1889
+ ]);
1890
+ }, va = (t, e) => J(t, [
1891
+ Array(6).fill(0),
1892
+ // Reserved
1893
+ j(1),
1894
+ // Data reference index
1895
+ j(0),
1896
+ // Version
1897
+ j(0),
1898
+ // Revision level
1899
+ E(0),
1900
+ // Vendor
1901
+ j(e.info.numberOfChannels),
1902
+ // Number of channels
1903
+ j(16),
1904
+ // Sample size (bits)
1905
+ j(0),
1906
+ // Compression ID
1907
+ j(0),
1908
+ // Packet size
1909
+ ut(e.info.sampleRate)
1910
+ // Sample rate
1911
+ ], [
1912
+ La[e.info.codec](e)
1913
+ ]), ya = (t) => {
1914
+ let e = new Uint8Array(t.info.decoderConfig.description);
1915
+ return H("esds", 0, 0, [
1916
+ // https://stackoverflow.com/a/54803118
1917
+ E(58753152),
1918
+ // TAG(3) = Object Descriptor ([2])
1919
+ K(32 + e.byteLength),
1920
+ // length of this OD (which includes the next 2 tags)
1921
+ j(1),
1922
+ // ES_ID = 1
1923
+ K(0),
1924
+ // flags etc = 0
1925
+ E(75530368),
1926
+ // TAG(4) = ES Descriptor ([2]) embedded in above OD
1927
+ K(18 + e.byteLength),
1928
+ // length of this ESD
1929
+ K(64),
1930
+ // MPEG-4 Audio
1931
+ K(21),
1932
+ // stream type(6bits)=5 audio, flags(2bits)=1
1933
+ cs(0),
1934
+ // 24bit buffer size
1935
+ E(130071),
1936
+ // max bitrate
1937
+ E(130071),
1938
+ // avg bitrate
1939
+ E(92307584),
1940
+ // TAG(5) = ASC ([2],[3]) embedded in above OD
1941
+ K(e.byteLength),
1942
+ // length
1943
+ ...e,
1944
+ E(109084800),
1945
+ // TAG(6)
1946
+ K(1),
1947
+ // length
1948
+ K(2)
1949
+ // data
1950
+ ]);
1951
+ }, ba = (t) => {
1952
+ var s;
1953
+ let e = 3840, i = 0;
1954
+ const r = (s = t.info.decoderConfig) == null ? void 0 : s.description;
1955
+ if (r) {
1956
+ if (r.byteLength < 18)
1957
+ throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");
1958
+ const n = ArrayBuffer.isView(r) ? new DataView(r.buffer, r.byteOffset, r.byteLength) : new DataView(r);
1959
+ e = n.getUint16(10, !0), i = n.getInt16(14, !0);
1960
+ }
1961
+ return J("dOps", [
1962
+ K(0),
1963
+ // Version
1964
+ K(t.info.numberOfChannels),
1965
+ // OutputChannelCount
1966
+ j(e),
1967
+ E(t.info.sampleRate),
1968
+ // InputSampleRate
1969
+ or(i),
1970
+ // OutputGain
1971
+ K(0)
1972
+ // ChannelMappingFamily
1973
+ ]);
1974
+ }, _a = (t) => H("stts", 0, 0, [
1975
+ E(t.timeToSampleTable.length),
1976
+ // Number of entries
1977
+ t.timeToSampleTable.map((e) => [
1978
+ // Time-to-sample table
1979
+ E(e.sampleCount),
1980
+ // Sample count
1981
+ E(e.sampleDelta)
1982
+ // Sample duration
1983
+ ])
1984
+ ]), xa = (t) => {
1985
+ if (t.samples.every((i) => i.type === "key"))
1986
+ return null;
1987
+ let e = [...t.samples.entries()].filter(([, i]) => i.type === "key");
1988
+ return H("stss", 0, 0, [
1989
+ E(e.length),
1990
+ // Number of entries
1991
+ e.map(([i]) => E(i + 1))
1992
+ // Sync sample table
1993
+ ]);
1994
+ }, Sa = (t) => H("stsc", 0, 0, [
1995
+ E(t.compactlyCodedChunkTable.length),
1996
+ // Number of entries
1997
+ t.compactlyCodedChunkTable.map((e) => [
1998
+ // Sample-to-chunk table
1999
+ E(e.firstChunk),
2000
+ // First chunk
2001
+ E(e.samplesPerChunk),
2002
+ // Samples per chunk
2003
+ E(1)
2004
+ // Sample description index
2005
+ ])
2006
+ ]), Ca = (t) => H("stsz", 0, 0, [
2007
+ E(0),
2008
+ // Sample size (0 means non-constant size)
2009
+ E(t.samples.length),
2010
+ // Number of entries
2011
+ t.samples.map((e) => E(e.size))
2012
+ // Sample size table
2013
+ ]), Ea = (t) => t.finalizedChunks.length > 0 && ci(t.finalizedChunks).offset >= 2 ** 32 ? H("co64", 0, 0, [
2014
+ E(t.finalizedChunks.length),
2015
+ // Number of entries
2016
+ t.finalizedChunks.map((e) => Yt(e.offset))
2017
+ // Chunk offset table
2018
+ ]) : H("stco", 0, 0, [
2019
+ E(t.finalizedChunks.length),
2020
+ // Number of entries
2021
+ t.finalizedChunks.map((e) => E(e.offset))
2022
+ // Chunk offset table
2023
+ ]), Ta = (t) => H("ctts", 0, 0, [
2024
+ E(t.compositionTimeOffsetTable.length),
2025
+ // Number of entries
2026
+ t.compositionTimeOffsetTable.map((e) => [
2027
+ // Time-to-sample table
2028
+ E(e.sampleCount),
2029
+ // Sample count
2030
+ E(e.sampleCompositionTimeOffset)
2031
+ // Sample offset
2032
+ ])
2033
+ ]), ka = (t) => J("mvex", null, t.map(Aa)), Aa = (t) => H("trex", 0, 0, [
2034
+ E(t.id),
2035
+ // Track ID
2036
+ E(1),
2037
+ // Default sample description index
2038
+ E(0),
2039
+ // Default sample duration
2040
+ E(0),
2041
+ // Default sample size
2042
+ E(0)
2043
+ // Default sample flags
2044
+ ]), $r = (t, e) => J("moof", null, [
2045
+ Ma(t),
2046
+ ...e.map(Pa)
2047
+ ]), Ma = (t) => H("mfhd", 0, 0, [
2048
+ E(t)
2049
+ // Sequence number
2050
+ ]), ms = (t) => {
2051
+ let e = 0, i = 0, r = 0, s = 0, n = t.type === "delta";
2052
+ return i |= +n, n ? e |= 1 : e |= 2, e << 24 | i << 16 | r << 8 | s;
2053
+ }, Pa = (t) => J("traf", null, [
2054
+ Ia(t),
2055
+ Ra(t),
2056
+ Ba(t)
2057
+ ]), Ia = (t) => {
2058
+ let e = 0;
2059
+ e |= 8, e |= 16, e |= 32, e |= 131072;
2060
+ let i = t.currentChunk.samples[1] ?? t.currentChunk.samples[0], r = {
2061
+ duration: i.timescaleUnitsToNextSample,
2062
+ size: i.size,
2063
+ flags: ms(i)
2064
+ };
2065
+ return H("tfhd", 0, e, [
2066
+ E(t.id),
2067
+ // Track ID
2068
+ E(r.duration),
2069
+ // Default sample duration
2070
+ E(r.size),
2071
+ // Default sample size
2072
+ E(r.flags)
2073
+ // Default sample flags
2074
+ ]);
2075
+ }, Ra = (t) => H("tfdt", 1, 0, [
2076
+ Yt(mt(t.currentChunk.startTimestamp, t.timescale))
2077
+ // Base Media Decode Time
2078
+ ]), Ba = (t) => {
2079
+ let e = t.currentChunk.samples.map((m) => m.timescaleUnitsToNextSample), i = t.currentChunk.samples.map((m) => m.size), r = t.currentChunk.samples.map(ms), s = t.currentChunk.samples.map((m) => mt(m.presentationTimestamp - m.decodeTimestamp, t.timescale)), n = new Set(e), a = new Set(i), l = new Set(r), u = new Set(s), g = l.size === 2 && r[0] !== r[1], v = n.size > 1, p = a.size > 1, h = !g && l.size > 1, d = u.size > 1 || [...u].some((m) => m !== 0), f = 0;
2080
+ return f |= 1, f |= 4 * +g, f |= 256 * +v, f |= 512 * +p, f |= 1024 * +h, f |= 2048 * +d, H("trun", 1, f, [
2081
+ E(t.currentChunk.samples.length),
2082
+ // Sample count
2083
+ E(t.currentChunk.offset - t.currentChunk.moofOffset || 0),
2084
+ // Data offset
2085
+ g ? E(r[0]) : [],
2086
+ t.currentChunk.samples.map((m, w) => [
2087
+ v ? E(e[w]) : [],
2088
+ // Sample duration
2089
+ p ? E(i[w]) : [],
2090
+ // Sample size
2091
+ h ? E(r[w]) : [],
2092
+ // Sample flags
2093
+ // Sample composition time offsets
2094
+ d ? qn(s[w]) : []
2095
+ ])
2096
+ ]);
2097
+ }, Fa = (t) => J("mfra", null, [
2098
+ ...t.map(Ua),
2099
+ Da()
2100
+ ]), Ua = (t, e) => H("tfra", 1, 0, [
2101
+ E(t.id),
2102
+ // Track ID
2103
+ E(63),
2104
+ // This specifies that traf number, trun number and sample number are 32-bit ints
2105
+ E(t.finalizedChunks.length),
2106
+ // Number of entries
2107
+ t.finalizedChunks.map((r) => [
2108
+ Yt(mt(r.startTimestamp, t.timescale)),
2109
+ // Time
2110
+ Yt(r.moofOffset),
2111
+ // moof offset
2112
+ E(e + 1),
2113
+ // traf number
2114
+ E(1),
2115
+ // trun number
2116
+ E(1)
2117
+ // Sample number
2118
+ ])
2119
+ ]), Da = () => H("mfro", 0, 0, [
2120
+ // This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box
2121
+ // is known
2122
+ E(0)
2123
+ // Size
2124
+ ]), Wa = {
2125
+ avc: "avc1",
2126
+ hevc: "hvc1",
2127
+ vp9: "vp09",
2128
+ av1: "av01"
2129
+ }, za = {
2130
+ avc: pa,
2131
+ hevc: ma,
2132
+ vp9: wa,
2133
+ av1: ga
2134
+ }, Va = {
2135
+ aac: "mp4a",
2136
+ opus: "Opus"
2137
+ }, La = {
2138
+ aac: ya,
2139
+ opus: ba
2140
+ }, Si = class {
2141
+ }, ws = class extends Si {
2142
+ constructor() {
2143
+ super(...arguments), this.buffer = null;
2144
+ }
2145
+ }, gs = class extends Si {
2146
+ constructor(e) {
2147
+ if (super(), this.options = e, typeof e != "object")
2148
+ throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
2149
+ if (e.onData) {
2150
+ if (typeof e.onData != "function")
2151
+ throw new TypeError("options.onData, when provided, must be a function.");
2152
+ if (e.onData.length < 2)
2153
+ throw new TypeError(
2154
+ "options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
2155
+ );
2156
+ }
2157
+ if (e.chunked !== void 0 && typeof e.chunked != "boolean")
2158
+ throw new TypeError("options.chunked, when provided, must be a boolean.");
2159
+ if (e.chunkSize !== void 0 && (!Number.isInteger(e.chunkSize) || e.chunkSize < 1024))
2160
+ throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
2161
+ }
2162
+ }, Oa = class extends Si {
2163
+ constructor(e, i) {
2164
+ if (super(), this.stream = e, this.options = i, !(e instanceof FileSystemWritableFileStream))
2165
+ throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
2166
+ if (i !== void 0 && typeof i != "object")
2167
+ throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
2168
+ if (i && i.chunkSize !== void 0 && (!Number.isInteger(i.chunkSize) || i.chunkSize <= 0))
2169
+ throw new TypeError("options.chunkSize, when provided, must be a positive integer");
2170
+ }
2171
+ }, Dt, Kt, vs = class {
2172
+ constructor() {
2173
+ this.pos = 0, D(this, Dt, new Uint8Array(8)), D(this, Kt, new DataView(c(this, Dt).buffer)), this.offsets = /* @__PURE__ */ new WeakMap();
2174
+ }
2175
+ /** Sets the current position for future writes to a new one. */
2176
+ seek(e) {
2177
+ this.pos = e;
2178
+ }
2179
+ writeU32(e) {
2180
+ c(this, Kt).setUint32(0, e, !1), this.write(c(this, Dt).subarray(0, 4));
2181
+ }
2182
+ writeU64(e) {
2183
+ c(this, Kt).setUint32(0, Math.floor(e / 2 ** 32), !1), c(this, Kt).setUint32(4, e, !1), this.write(c(this, Dt).subarray(0, 8));
2184
+ }
2185
+ writeAscii(e) {
2186
+ for (let i = 0; i < e.length; i++)
2187
+ c(this, Kt).setUint8(i % 8, e.charCodeAt(i)), i % 8 === 7 && this.write(c(this, Dt));
2188
+ e.length % 8 !== 0 && this.write(c(this, Dt).subarray(0, e.length % 8));
2189
+ }
2190
+ writeBox(e) {
2191
+ if (this.offsets.set(e, this.pos), e.contents && !e.children)
2192
+ this.writeBoxHeader(e, e.size ?? e.contents.byteLength + 8), this.write(e.contents);
2193
+ else {
2194
+ let i = this.pos;
2195
+ if (this.writeBoxHeader(e, 0), e.contents && this.write(e.contents), e.children)
2196
+ for (let n of e.children)
2197
+ n && this.writeBox(n);
2198
+ let r = this.pos, s = e.size ?? r - i;
2199
+ this.seek(i), this.writeBoxHeader(e, s), this.seek(r);
2200
+ }
2201
+ }
2202
+ writeBoxHeader(e, i) {
2203
+ this.writeU32(e.largeSize ? 1 : i), this.writeAscii(e.type), e.largeSize && this.writeU64(i);
2204
+ }
2205
+ measureBoxHeader(e) {
2206
+ return 8 + (e.largeSize ? 8 : 0);
2207
+ }
2208
+ patchBox(e) {
2209
+ let i = this.pos;
2210
+ this.seek(this.offsets.get(e)), this.writeBox(e), this.seek(i);
2211
+ }
2212
+ measureBox(e) {
2213
+ if (e.contents && !e.children)
2214
+ return this.measureBoxHeader(e) + e.contents.byteLength;
2215
+ {
2216
+ let i = this.measureBoxHeader(e);
2217
+ if (e.contents && (i += e.contents.byteLength), e.children)
2218
+ for (let r of e.children)
2219
+ r && (i += this.measureBox(r));
2220
+ return i;
2221
+ }
2222
+ }
2223
+ };
2224
+ Dt = /* @__PURE__ */ new WeakMap();
2225
+ Kt = /* @__PURE__ */ new WeakMap();
2226
+ var ei, qt, ze, ye, ii, zi, Ga = class extends vs {
2227
+ constructor(e) {
2228
+ super(), D(this, ii), D(this, ei, void 0), D(this, qt, new ArrayBuffer(2 ** 16)), D(this, ze, new Uint8Array(c(this, qt))), D(this, ye, 0), et(this, ei, e);
2229
+ }
2230
+ write(e) {
2231
+ z(this, ii, zi).call(this, this.pos + e.byteLength), c(this, ze).set(e, this.pos), this.pos += e.byteLength, et(this, ye, Math.max(c(this, ye), this.pos));
2232
+ }
2233
+ finalize() {
2234
+ z(this, ii, zi).call(this, this.pos), c(this, ei).buffer = c(this, qt).slice(0, Math.max(c(this, ye), this.pos));
2235
+ }
2236
+ };
2237
+ ei = /* @__PURE__ */ new WeakMap();
2238
+ qt = /* @__PURE__ */ new WeakMap();
2239
+ ze = /* @__PURE__ */ new WeakMap();
2240
+ ye = /* @__PURE__ */ new WeakMap();
2241
+ ii = /* @__PURE__ */ new WeakSet();
2242
+ zi = function(t) {
2243
+ let e = c(this, qt).byteLength;
2244
+ for (; e < t; )
2245
+ e *= 2;
2246
+ if (e === c(this, qt).byteLength)
2247
+ return;
2248
+ let i = new ArrayBuffer(e), r = new Uint8Array(i);
2249
+ r.set(c(this, ze), 0), et(this, qt, i), et(this, ze, r);
2250
+ };
2251
+ var Na = 2 ** 24, $a = 2, Te, Wt, be, Ct, st, fi, Vi, lr, ys, dr, bs, ke, ui, cr = class extends vs {
2252
+ constructor(e) {
2253
+ var i, r;
2254
+ super(), D(this, fi), D(this, lr), D(this, dr), D(this, ke), D(this, Te, void 0), D(this, Wt, []), D(this, be, void 0), D(this, Ct, void 0), D(this, st, []), et(this, Te, e), et(this, be, ((i = e.options) == null ? void 0 : i.chunked) ?? !1), et(this, Ct, ((r = e.options) == null ? void 0 : r.chunkSize) ?? Na);
2255
+ }
2256
+ write(e) {
2257
+ c(this, Wt).push({
2258
+ data: e.slice(),
2259
+ start: this.pos
2260
+ }), this.pos += e.byteLength;
2261
+ }
2262
+ flush() {
2263
+ var r, s;
2264
+ if (c(this, Wt).length === 0)
2265
+ return;
2266
+ let e = [], i = [...c(this, Wt)].sort((n, a) => n.start - a.start);
2267
+ e.push({
2268
+ start: i[0].start,
2269
+ size: i[0].data.byteLength
2270
+ });
2271
+ for (let n = 1; n < i.length; n++) {
2272
+ let a = e[e.length - 1], l = i[n];
2273
+ l.start <= a.start + a.size ? a.size = Math.max(a.size, l.start + l.data.byteLength - a.start) : e.push({
2274
+ start: l.start,
2275
+ size: l.data.byteLength
2276
+ });
2277
+ }
2278
+ for (let n of e) {
2279
+ n.data = new Uint8Array(n.size);
2280
+ for (let a of c(this, Wt))
2281
+ n.start <= a.start && a.start < n.start + n.size && n.data.set(a.data, a.start - n.start);
2282
+ c(this, be) ? (z(this, fi, Vi).call(this, n.data, n.start), z(this, ke, ui).call(this)) : (s = (r = c(this, Te).options).onData) == null || s.call(r, n.data, n.start);
2283
+ }
2284
+ c(this, Wt).length = 0;
2285
+ }
2286
+ finalize() {
2287
+ c(this, be) && z(this, ke, ui).call(this, !0);
2288
+ }
2289
+ };
2290
+ Te = /* @__PURE__ */ new WeakMap();
2291
+ Wt = /* @__PURE__ */ new WeakMap();
2292
+ be = /* @__PURE__ */ new WeakMap();
2293
+ Ct = /* @__PURE__ */ new WeakMap();
2294
+ st = /* @__PURE__ */ new WeakMap();
2295
+ fi = /* @__PURE__ */ new WeakSet();
2296
+ Vi = function(t, e) {
2297
+ let i = c(this, st).findIndex((l) => l.start <= e && e < l.start + c(this, Ct));
2298
+ i === -1 && (i = z(this, dr, bs).call(this, e));
2299
+ let r = c(this, st)[i], s = e - r.start, n = t.subarray(0, Math.min(c(this, Ct) - s, t.byteLength));
2300
+ r.data.set(n, s);
2301
+ let a = {
2302
+ start: s,
2303
+ end: s + n.byteLength
2304
+ };
2305
+ if (z(this, lr, ys).call(this, r, a), r.written[0].start === 0 && r.written[0].end === c(this, Ct) && (r.shouldFlush = !0), c(this, st).length > $a) {
2306
+ for (let l = 0; l < c(this, st).length - 1; l++)
2307
+ c(this, st)[l].shouldFlush = !0;
2308
+ z(this, ke, ui).call(this);
2309
+ }
2310
+ n.byteLength < t.byteLength && z(this, fi, Vi).call(this, t.subarray(n.byteLength), e + n.byteLength);
2311
+ };
2312
+ lr = /* @__PURE__ */ new WeakSet();
2313
+ ys = function(t, e) {
2314
+ let i = 0, r = t.written.length - 1, s = -1;
2315
+ for (; i <= r; ) {
2316
+ let n = Math.floor(i + (r - i + 1) / 2);
2317
+ t.written[n].start <= e.start ? (i = n + 1, s = n) : r = n - 1;
2318
+ }
2319
+ for (t.written.splice(s + 1, 0, e), (s === -1 || t.written[s].end < e.start) && s++; s < t.written.length - 1 && t.written[s].end >= t.written[s + 1].start; )
2320
+ t.written[s].end = Math.max(t.written[s].end, t.written[s + 1].end), t.written.splice(s + 1, 1);
2321
+ };
2322
+ dr = /* @__PURE__ */ new WeakSet();
2323
+ bs = function(t) {
2324
+ let i = {
2325
+ start: Math.floor(t / c(this, Ct)) * c(this, Ct),
2326
+ data: new Uint8Array(c(this, Ct)),
2327
+ written: [],
2328
+ shouldFlush: !1
2329
+ };
2330
+ return c(this, st).push(i), c(this, st).sort((r, s) => r.start - s.start), c(this, st).indexOf(i);
2331
+ };
2332
+ ke = /* @__PURE__ */ new WeakSet();
2333
+ ui = function(t = !1) {
2334
+ var e, i;
2335
+ for (let r = 0; r < c(this, st).length; r++) {
2336
+ let s = c(this, st)[r];
2337
+ if (!(!s.shouldFlush && !t)) {
2338
+ for (let n of s.written)
2339
+ (i = (e = c(this, Te).options).onData) == null || i.call(
2340
+ e,
2341
+ s.data.subarray(n.start, n.end),
2342
+ s.start + n.start
2343
+ );
2344
+ c(this, st).splice(r--, 1);
2345
+ }
2346
+ }
2347
+ };
2348
+ var ja = class extends cr {
2349
+ constructor(e) {
2350
+ var i;
2351
+ super(new gs({
2352
+ onData: (r, s) => e.stream.write({
2353
+ type: "write",
2354
+ data: r,
2355
+ position: s
2356
+ }),
2357
+ chunked: !0,
2358
+ chunkSize: (i = e.options) == null ? void 0 : i.chunkSize
2359
+ }));
2360
+ }
2361
+ }, Li = 1e3, qa = ["avc", "hevc", "vp9", "av1"], Ha = ["aac", "opus"], Xa = 2082844800, Ya = ["strict", "offset", "cross-track-offset"], P, R, pi, rt, it, tt, Qt, re, fr, zt, Vt, Ae, Oi, _s, Gi, xs, ur, Ss, Ni, Cs, pr, Es, ri, $i, lt, vt, mr, Ts, Me, mi, wi, wr, fe, je, si, ji, Ja = class {
2362
+ constructor(e) {
2363
+ if (D(this, Oi), D(this, Gi), D(this, ur), D(this, Ni), D(this, pr), D(this, ri), D(this, lt), D(this, mr), D(this, Me), D(this, wi), D(this, fe), D(this, si), D(this, P, void 0), D(this, R, void 0), D(this, pi, void 0), D(this, rt, void 0), D(this, it, null), D(this, tt, null), D(this, Qt, Math.floor(Date.now() / 1e3) + Xa), D(this, re, []), D(this, fr, 1), D(this, zt, []), D(this, Vt, []), D(this, Ae, !1), z(this, Oi, _s).call(this, e), e.video = Ee(e.video), e.audio = Ee(e.audio), e.fastStart = Ee(e.fastStart), this.target = e.target, et(this, P, {
2364
+ firstTimestampBehavior: "strict",
2365
+ ...e
2366
+ }), e.target instanceof ws)
2367
+ et(this, R, new Ga(e.target));
2368
+ else if (e.target instanceof gs)
2369
+ et(this, R, new cr(e.target));
2370
+ else if (e.target instanceof Oa)
2371
+ et(this, R, new ja(e.target));
2372
+ else
2373
+ throw new Error(`Invalid target: ${e.target}`);
2374
+ z(this, Ni, Cs).call(this), z(this, Gi, xs).call(this);
2375
+ }
2376
+ addVideoChunk(e, i, r, s) {
2377
+ if (!(e instanceof EncodedVideoChunk))
2378
+ throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");
2379
+ if (i && typeof i != "object")
2380
+ throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
2381
+ if (r !== void 0 && (!Number.isFinite(r) || r < 0))
2382
+ throw new TypeError(
2383
+ "addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
2384
+ );
2385
+ if (s !== void 0 && !Number.isFinite(s))
2386
+ throw new TypeError(
2387
+ "addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number."
2388
+ );
2389
+ let n = new Uint8Array(e.byteLength);
2390
+ e.copyTo(n), this.addVideoChunkRaw(
2391
+ n,
2392
+ e.type,
2393
+ r ?? e.timestamp,
2394
+ e.duration,
2395
+ i,
2396
+ s
2397
+ );
2398
+ }
2399
+ addVideoChunkRaw(e, i, r, s, n, a) {
2400
+ if (!(e instanceof Uint8Array))
2401
+ throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
2402
+ if (i !== "key" && i !== "delta")
2403
+ throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
2404
+ if (!Number.isFinite(r) || r < 0)
2405
+ throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
2406
+ if (!Number.isFinite(s) || s < 0)
2407
+ throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");
2408
+ if (n && typeof n != "object")
2409
+ throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");
2410
+ if (a !== void 0 && !Number.isFinite(a))
2411
+ throw new TypeError(
2412
+ "addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number."
2413
+ );
2414
+ if (z(this, si, ji).call(this), !c(this, P).video)
2415
+ throw new Error("No video track declared.");
2416
+ if (typeof c(this, P).fastStart == "object" && c(this, it).samples.length === c(this, P).fastStart.expectedVideoChunks)
2417
+ throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${c(this, P).fastStart.expectedVideoChunks}).`);
2418
+ let l = z(this, ri, $i).call(this, c(this, it), e, i, r, s, n, a);
2419
+ if (c(this, P).fastStart === "fragmented" && c(this, tt)) {
2420
+ for (; c(this, Vt).length > 0 && c(this, Vt)[0].decodeTimestamp <= l.decodeTimestamp; ) {
2421
+ let u = c(this, Vt).shift();
2422
+ z(this, lt, vt).call(this, c(this, tt), u);
2423
+ }
2424
+ l.decodeTimestamp <= c(this, tt).lastDecodeTimestamp ? z(this, lt, vt).call(this, c(this, it), l) : c(this, zt).push(l);
2425
+ } else
2426
+ z(this, lt, vt).call(this, c(this, it), l);
2427
+ }
2428
+ addAudioChunk(e, i, r) {
2429
+ if (!(e instanceof EncodedAudioChunk))
2430
+ throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");
2431
+ if (i && typeof i != "object")
2432
+ throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
2433
+ if (r !== void 0 && (!Number.isFinite(r) || r < 0))
2434
+ throw new TypeError(
2435
+ "addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
2436
+ );
2437
+ let s = new Uint8Array(e.byteLength);
2438
+ e.copyTo(s), this.addAudioChunkRaw(s, e.type, r ?? e.timestamp, e.duration, i);
2439
+ }
2440
+ addAudioChunkRaw(e, i, r, s, n) {
2441
+ if (!(e instanceof Uint8Array))
2442
+ throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
2443
+ if (i !== "key" && i !== "delta")
2444
+ throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
2445
+ if (!Number.isFinite(r) || r < 0)
2446
+ throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
2447
+ if (!Number.isFinite(s) || s < 0)
2448
+ throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");
2449
+ if (n && typeof n != "object")
2450
+ throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");
2451
+ if (z(this, si, ji).call(this), !c(this, P).audio)
2452
+ throw new Error("No audio track declared.");
2453
+ if (typeof c(this, P).fastStart == "object" && c(this, tt).samples.length === c(this, P).fastStart.expectedAudioChunks)
2454
+ throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${c(this, P).fastStart.expectedAudioChunks}).`);
2455
+ let a = z(this, ri, $i).call(this, c(this, tt), e, i, r, s, n);
2456
+ if (c(this, P).fastStart === "fragmented" && c(this, it)) {
2457
+ for (; c(this, zt).length > 0 && c(this, zt)[0].decodeTimestamp <= a.decodeTimestamp; ) {
2458
+ let l = c(this, zt).shift();
2459
+ z(this, lt, vt).call(this, c(this, it), l);
2460
+ }
2461
+ a.decodeTimestamp <= c(this, it).lastDecodeTimestamp ? z(this, lt, vt).call(this, c(this, tt), a) : c(this, Vt).push(a);
2462
+ } else
2463
+ z(this, lt, vt).call(this, c(this, tt), a);
2464
+ }
2465
+ /** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
2466
+ finalize() {
2467
+ if (c(this, Ae))
2468
+ throw new Error("Cannot finalize a muxer more than once.");
2469
+ if (c(this, P).fastStart === "fragmented") {
2470
+ for (let i of c(this, zt))
2471
+ z(this, lt, vt).call(this, c(this, it), i);
2472
+ for (let i of c(this, Vt))
2473
+ z(this, lt, vt).call(this, c(this, tt), i);
2474
+ z(this, wi, wr).call(this, !1);
2475
+ } else
2476
+ c(this, it) && z(this, Me, mi).call(this, c(this, it)), c(this, tt) && z(this, Me, mi).call(this, c(this, tt));
2477
+ let e = [c(this, it), c(this, tt)].filter(Boolean);
2478
+ if (c(this, P).fastStart === "in-memory") {
2479
+ let i;
2480
+ for (let s = 0; s < 2; s++) {
2481
+ let n = ti(e, c(this, Qt)), a = c(this, R).measureBox(n);
2482
+ i = c(this, R).measureBox(c(this, rt));
2483
+ let l = c(this, R).pos + a + i;
2484
+ for (let u of c(this, re)) {
2485
+ u.offset = l;
2486
+ for (let { data: g } of u.samples)
2487
+ l += g.byteLength, i += g.byteLength;
2488
+ }
2489
+ if (l < 2 ** 32)
2490
+ break;
2491
+ i >= 2 ** 32 && (c(this, rt).largeSize = !0);
2492
+ }
2493
+ let r = ti(e, c(this, Qt));
2494
+ c(this, R).writeBox(r), c(this, rt).size = i, c(this, R).writeBox(c(this, rt));
2495
+ for (let s of c(this, re))
2496
+ for (let n of s.samples)
2497
+ c(this, R).write(n.data), n.data = null;
2498
+ } else if (c(this, P).fastStart === "fragmented") {
2499
+ let i = c(this, R).pos, r = Fa(e);
2500
+ c(this, R).writeBox(r);
2501
+ let s = c(this, R).pos - i;
2502
+ c(this, R).seek(c(this, R).pos - 4), c(this, R).writeU32(s);
2503
+ } else {
2504
+ let i = c(this, R).offsets.get(c(this, rt)), r = c(this, R).pos - i;
2505
+ c(this, rt).size = r, c(this, rt).largeSize = r >= 2 ** 32, c(this, R).patchBox(c(this, rt));
2506
+ let s = ti(e, c(this, Qt));
2507
+ if (typeof c(this, P).fastStart == "object") {
2508
+ c(this, R).seek(c(this, pi)), c(this, R).writeBox(s);
2509
+ let n = i - c(this, R).pos;
2510
+ c(this, R).writeBox(Xn(n));
2511
+ } else
2512
+ c(this, R).writeBox(s);
2513
+ }
2514
+ z(this, fe, je).call(this), c(this, R).finalize(), et(this, Ae, !0);
2515
+ }
2516
+ };
2517
+ P = /* @__PURE__ */ new WeakMap();
2518
+ R = /* @__PURE__ */ new WeakMap();
2519
+ pi = /* @__PURE__ */ new WeakMap();
2520
+ rt = /* @__PURE__ */ new WeakMap();
2521
+ it = /* @__PURE__ */ new WeakMap();
2522
+ tt = /* @__PURE__ */ new WeakMap();
2523
+ Qt = /* @__PURE__ */ new WeakMap();
2524
+ re = /* @__PURE__ */ new WeakMap();
2525
+ fr = /* @__PURE__ */ new WeakMap();
2526
+ zt = /* @__PURE__ */ new WeakMap();
2527
+ Vt = /* @__PURE__ */ new WeakMap();
2528
+ Ae = /* @__PURE__ */ new WeakMap();
2529
+ Oi = /* @__PURE__ */ new WeakSet();
2530
+ _s = function(t) {
2531
+ if (typeof t != "object")
2532
+ throw new TypeError("The muxer requires an options object to be passed to its constructor.");
2533
+ if (!(t.target instanceof Si))
2534
+ throw new TypeError("The target must be provided and an instance of Target.");
2535
+ if (t.video) {
2536
+ if (!qa.includes(t.video.codec))
2537
+ throw new TypeError(`Unsupported video codec: ${t.video.codec}`);
2538
+ if (!Number.isInteger(t.video.width) || t.video.width <= 0)
2539
+ throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);
2540
+ if (!Number.isInteger(t.video.height) || t.video.height <= 0)
2541
+ throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);
2542
+ const e = t.video.rotation;
2543
+ if (typeof e == "number" && ![0, 90, 180, 270].includes(e))
2544
+ throw new TypeError(`Invalid video rotation: ${e}. Has to be 0, 90, 180 or 270.`);
2545
+ if (Array.isArray(e) && (e.length !== 9 || e.some((i) => typeof i != "number")))
2546
+ throw new TypeError(`Invalid video transformation matrix: ${e.join()}`);
2547
+ if (t.video.frameRate !== void 0 && (!Number.isInteger(t.video.frameRate) || t.video.frameRate <= 0))
2548
+ throw new TypeError(
2549
+ `Invalid video frame rate: ${t.video.frameRate}. Must be a positive integer.`
2550
+ );
2551
+ }
2552
+ if (t.audio) {
2553
+ if (!Ha.includes(t.audio.codec))
2554
+ throw new TypeError(`Unsupported audio codec: ${t.audio.codec}`);
2555
+ if (!Number.isInteger(t.audio.numberOfChannels) || t.audio.numberOfChannels <= 0)
2556
+ throw new TypeError(
2557
+ `Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`
2558
+ );
2559
+ if (!Number.isInteger(t.audio.sampleRate) || t.audio.sampleRate <= 0)
2560
+ throw new TypeError(
2561
+ `Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`
2562
+ );
2563
+ }
2564
+ if (t.firstTimestampBehavior && !Ya.includes(t.firstTimestampBehavior))
2565
+ throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);
2566
+ if (typeof t.fastStart == "object") {
2567
+ if (t.video) {
2568
+ if (t.fastStart.expectedVideoChunks === void 0)
2569
+ throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");
2570
+ if (!Number.isInteger(t.fastStart.expectedVideoChunks) || t.fastStart.expectedVideoChunks < 0)
2571
+ throw new TypeError("'expectedVideoChunks' must be a non-negative integer.");
2572
+ }
2573
+ if (t.audio) {
2574
+ if (t.fastStart.expectedAudioChunks === void 0)
2575
+ throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");
2576
+ if (!Number.isInteger(t.fastStart.expectedAudioChunks) || t.fastStart.expectedAudioChunks < 0)
2577
+ throw new TypeError("'expectedAudioChunks' must be a non-negative integer.");
2578
+ }
2579
+ } else if (![!1, "in-memory", "fragmented"].includes(t.fastStart))
2580
+ throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");
2581
+ if (t.minFragmentDuration !== void 0 && (!Number.isFinite(t.minFragmentDuration) || t.minFragmentDuration < 0))
2582
+ throw new TypeError("'minFragmentDuration' must be a non-negative number.");
2583
+ };
2584
+ Gi = /* @__PURE__ */ new WeakSet();
2585
+ xs = function() {
2586
+ var t;
2587
+ if (c(this, R).writeBox(Hn({
2588
+ holdsAvc: ((t = c(this, P).video) == null ? void 0 : t.codec) === "avc",
2589
+ fragmented: c(this, P).fastStart === "fragmented"
2590
+ })), et(this, pi, c(this, R).pos), c(this, P).fastStart === "in-memory")
2591
+ et(this, rt, Wi(!1));
2592
+ else if (c(this, P).fastStart !== "fragmented") {
2593
+ if (typeof c(this, P).fastStart == "object") {
2594
+ let e = z(this, ur, Ss).call(this);
2595
+ c(this, R).seek(c(this, R).pos + e);
2596
+ }
2597
+ et(this, rt, Wi(!0)), c(this, R).writeBox(c(this, rt));
2598
+ }
2599
+ z(this, fe, je).call(this);
2600
+ };
2601
+ ur = /* @__PURE__ */ new WeakSet();
2602
+ Ss = function() {
2603
+ if (typeof c(this, P).fastStart != "object")
2604
+ return;
2605
+ let t = 0, e = [
2606
+ c(this, P).fastStart.expectedVideoChunks,
2607
+ c(this, P).fastStart.expectedAudioChunks
2608
+ ];
2609
+ for (let i of e)
2610
+ i && (t += 8 * Math.ceil(2 / 3 * i), t += 4 * i, t += 12 * Math.ceil(2 / 3 * i), t += 4 * i, t += 8 * i);
2611
+ return t += 4096, t;
2612
+ };
2613
+ Ni = /* @__PURE__ */ new WeakSet();
2614
+ Cs = function() {
2615
+ if (c(this, P).video && et(this, it, {
2616
+ id: 1,
2617
+ info: {
2618
+ type: "video",
2619
+ codec: c(this, P).video.codec,
2620
+ width: c(this, P).video.width,
2621
+ height: c(this, P).video.height,
2622
+ rotation: c(this, P).video.rotation ?? 0,
2623
+ decoderConfig: null
2624
+ },
2625
+ // The fallback contains many common frame rates as factors
2626
+ timescale: c(this, P).video.frameRate ?? 57600,
2627
+ samples: [],
2628
+ finalizedChunks: [],
2629
+ currentChunk: null,
2630
+ firstDecodeTimestamp: void 0,
2631
+ lastDecodeTimestamp: -1,
2632
+ timeToSampleTable: [],
2633
+ compositionTimeOffsetTable: [],
2634
+ lastTimescaleUnits: null,
2635
+ lastSample: null,
2636
+ compactlyCodedChunkTable: []
2637
+ }), c(this, P).audio && (et(this, tt, {
2638
+ id: c(this, P).video ? 2 : 1,
2639
+ info: {
2640
+ type: "audio",
2641
+ codec: c(this, P).audio.codec,
2642
+ numberOfChannels: c(this, P).audio.numberOfChannels,
2643
+ sampleRate: c(this, P).audio.sampleRate,
2644
+ decoderConfig: null
2645
+ },
2646
+ timescale: c(this, P).audio.sampleRate,
2647
+ samples: [],
2648
+ finalizedChunks: [],
2649
+ currentChunk: null,
2650
+ firstDecodeTimestamp: void 0,
2651
+ lastDecodeTimestamp: -1,
2652
+ timeToSampleTable: [],
2653
+ compositionTimeOffsetTable: [],
2654
+ lastTimescaleUnits: null,
2655
+ lastSample: null,
2656
+ compactlyCodedChunkTable: []
2657
+ }), c(this, P).audio.codec === "aac")) {
2658
+ let t = z(this, pr, Es).call(
2659
+ this,
2660
+ 2,
2661
+ // Object type for AAC-LC, since it's the most common
2662
+ c(this, P).audio.sampleRate,
2663
+ c(this, P).audio.numberOfChannels
2664
+ );
2665
+ c(this, tt).info.decoderConfig = {
2666
+ codec: c(this, P).audio.codec,
2667
+ description: t,
2668
+ numberOfChannels: c(this, P).audio.numberOfChannels,
2669
+ sampleRate: c(this, P).audio.sampleRate
2670
+ };
2671
+ }
2672
+ };
2673
+ pr = /* @__PURE__ */ new WeakSet();
2674
+ Es = function(t, e, i) {
2675
+ let s = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350].indexOf(e), n = i, a = "";
2676
+ a += t.toString(2).padStart(5, "0"), a += s.toString(2).padStart(4, "0"), s === 15 && (a += e.toString(2).padStart(24, "0")), a += n.toString(2).padStart(4, "0");
2677
+ let l = Math.ceil(a.length / 8) * 8;
2678
+ a = a.padEnd(l, "0");
2679
+ let u = new Uint8Array(a.length / 8);
2680
+ for (let g = 0; g < a.length; g += 8)
2681
+ u[g / 8] = parseInt(a.slice(g, g + 8), 2);
2682
+ return u;
2683
+ };
2684
+ ri = /* @__PURE__ */ new WeakSet();
2685
+ $i = function(t, e, i, r, s, n, a) {
2686
+ let l = r / 1e6, u = (r - (a ?? 0)) / 1e6, g = s / 1e6, v = z(this, mr, Ts).call(this, l, u, t);
2687
+ return l = v.presentationTimestamp, u = v.decodeTimestamp, n != null && n.decoderConfig && (t.info.decoderConfig === null ? t.info.decoderConfig = n.decoderConfig : Object.assign(t.info.decoderConfig, n.decoderConfig)), {
2688
+ presentationTimestamp: l,
2689
+ decodeTimestamp: u,
2690
+ duration: g,
2691
+ data: e,
2692
+ size: e.byteLength,
2693
+ type: i,
2694
+ // Will be refined once the next sample comes in
2695
+ timescaleUnitsToNextSample: mt(g, t.timescale)
2696
+ };
2697
+ };
2698
+ lt = /* @__PURE__ */ new WeakSet();
2699
+ vt = function(t, e) {
2700
+ c(this, P).fastStart !== "fragmented" && t.samples.push(e);
2701
+ const i = mt(e.presentationTimestamp - e.decodeTimestamp, t.timescale);
2702
+ if (t.lastTimescaleUnits !== null) {
2703
+ let s = mt(e.decodeTimestamp, t.timescale, !1), n = Math.round(s - t.lastTimescaleUnits);
2704
+ if (t.lastTimescaleUnits += n, t.lastSample.timescaleUnitsToNextSample = n, c(this, P).fastStart !== "fragmented") {
2705
+ let a = ci(t.timeToSampleTable);
2706
+ a.sampleCount === 1 ? (a.sampleDelta = n, a.sampleCount++) : a.sampleDelta === n ? a.sampleCount++ : (a.sampleCount--, t.timeToSampleTable.push({
2707
+ sampleCount: 2,
2708
+ sampleDelta: n
2709
+ }));
2710
+ const l = ci(t.compositionTimeOffsetTable);
2711
+ l.sampleCompositionTimeOffset === i ? l.sampleCount++ : t.compositionTimeOffsetTable.push({
2712
+ sampleCount: 1,
2713
+ sampleCompositionTimeOffset: i
2714
+ });
2715
+ }
2716
+ } else
2717
+ t.lastTimescaleUnits = 0, c(this, P).fastStart !== "fragmented" && (t.timeToSampleTable.push({
2718
+ sampleCount: 1,
2719
+ sampleDelta: mt(e.duration, t.timescale)
2720
+ }), t.compositionTimeOffsetTable.push({
2721
+ sampleCount: 1,
2722
+ sampleCompositionTimeOffset: i
2723
+ }));
2724
+ t.lastSample = e;
2725
+ let r = !1;
2726
+ if (!t.currentChunk)
2727
+ r = !0;
2728
+ else {
2729
+ let s = e.presentationTimestamp - t.currentChunk.startTimestamp;
2730
+ if (c(this, P).fastStart === "fragmented") {
2731
+ let n = c(this, it) ?? c(this, tt);
2732
+ const a = c(this, P).minFragmentDuration ?? 1;
2733
+ t === n && e.type === "key" && s >= a && (r = !0, z(this, wi, wr).call(this));
2734
+ } else
2735
+ r = s >= 0.5;
2736
+ }
2737
+ r && (t.currentChunk && z(this, Me, mi).call(this, t), t.currentChunk = {
2738
+ startTimestamp: e.presentationTimestamp,
2739
+ samples: []
2740
+ }), t.currentChunk.samples.push(e);
2741
+ };
2742
+ mr = /* @__PURE__ */ new WeakSet();
2743
+ Ts = function(t, e, i) {
2744
+ var a, l;
2745
+ const r = c(this, P).firstTimestampBehavior === "strict", s = i.lastDecodeTimestamp === -1;
2746
+ if (r && s && e !== 0)
2747
+ throw new Error(
2748
+ `The first chunk for your media track must have a timestamp of 0 (received DTS=${e}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
2749
+
2750
+ If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
2751
+ `
2752
+ );
2753
+ if (c(this, P).firstTimestampBehavior === "offset" || c(this, P).firstTimestampBehavior === "cross-track-offset") {
2754
+ i.firstDecodeTimestamp === void 0 && (i.firstDecodeTimestamp = e);
2755
+ let u;
2756
+ c(this, P).firstTimestampBehavior === "offset" ? u = i.firstDecodeTimestamp : u = Math.min(
2757
+ ((a = c(this, it)) == null ? void 0 : a.firstDecodeTimestamp) ?? 1 / 0,
2758
+ ((l = c(this, tt)) == null ? void 0 : l.firstDecodeTimestamp) ?? 1 / 0
2759
+ ), e -= u, t -= u;
2760
+ }
2761
+ if (e < i.lastDecodeTimestamp)
2762
+ throw new Error(
2763
+ `Timestamps must be monotonically increasing (DTS went from ${i.lastDecodeTimestamp * 1e6} to ${e * 1e6}).`
2764
+ );
2765
+ return i.lastDecodeTimestamp = e, { presentationTimestamp: t, decodeTimestamp: e };
2766
+ };
2767
+ Me = /* @__PURE__ */ new WeakSet();
2768
+ mi = function(t) {
2769
+ if (c(this, P).fastStart === "fragmented")
2770
+ throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");
2771
+ if (t.currentChunk) {
2772
+ if (t.finalizedChunks.push(t.currentChunk), c(this, re).push(t.currentChunk), (t.compactlyCodedChunkTable.length === 0 || ci(t.compactlyCodedChunkTable).samplesPerChunk !== t.currentChunk.samples.length) && t.compactlyCodedChunkTable.push({
2773
+ firstChunk: t.finalizedChunks.length,
2774
+ // 1-indexed
2775
+ samplesPerChunk: t.currentChunk.samples.length
2776
+ }), c(this, P).fastStart === "in-memory") {
2777
+ t.currentChunk.offset = 0;
2778
+ return;
2779
+ }
2780
+ t.currentChunk.offset = c(this, R).pos;
2781
+ for (let e of t.currentChunk.samples)
2782
+ c(this, R).write(e.data), e.data = null;
2783
+ z(this, fe, je).call(this);
2784
+ }
2785
+ };
2786
+ wi = /* @__PURE__ */ new WeakSet();
2787
+ wr = function(t = !0) {
2788
+ if (c(this, P).fastStart !== "fragmented")
2789
+ throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");
2790
+ let e = [c(this, it), c(this, tt)].filter((l) => l && l.currentChunk);
2791
+ if (e.length === 0)
2792
+ return;
2793
+ let i = $n(this, fr)._++;
2794
+ if (i === 1) {
2795
+ let l = ti(e, c(this, Qt), !0);
2796
+ c(this, R).writeBox(l);
2797
+ }
2798
+ let r = c(this, R).pos, s = $r(i, e);
2799
+ c(this, R).writeBox(s);
2800
+ {
2801
+ let l = Wi(!1), u = 0;
2802
+ for (let v of e)
2803
+ for (let p of v.currentChunk.samples)
2804
+ u += p.size;
2805
+ let g = c(this, R).measureBox(l) + u;
2806
+ g >= 2 ** 32 && (l.largeSize = !0, g = c(this, R).measureBox(l) + u), l.size = g, c(this, R).writeBox(l);
2807
+ }
2808
+ for (let l of e) {
2809
+ l.currentChunk.offset = c(this, R).pos, l.currentChunk.moofOffset = r;
2810
+ for (let u of l.currentChunk.samples)
2811
+ c(this, R).write(u.data), u.data = null;
2812
+ }
2813
+ let n = c(this, R).pos;
2814
+ c(this, R).seek(c(this, R).offsets.get(s));
2815
+ let a = $r(i, e);
2816
+ c(this, R).writeBox(a), c(this, R).seek(n);
2817
+ for (let l of e)
2818
+ l.finalizedChunks.push(l.currentChunk), c(this, re).push(l.currentChunk), l.currentChunk = null;
2819
+ t && z(this, fe, je).call(this);
2820
+ };
2821
+ fe = /* @__PURE__ */ new WeakSet();
2822
+ je = function() {
2823
+ c(this, R) instanceof cr && c(this, R).flush();
2824
+ };
2825
+ si = /* @__PURE__ */ new WeakSet();
2826
+ ji = function() {
2827
+ if (c(this, Ae))
2828
+ throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
2829
+ };
2830
+ var gr = (t, e, i) => {
2831
+ if (!e.has(t))
2832
+ throw TypeError("Cannot " + i);
2833
+ }, o = (t, e, i) => (gr(t, e, "read from private field"), i ? i.call(t) : e.get(t)), S = (t, e, i) => {
2834
+ if (e.has(t))
2835
+ throw TypeError("Cannot add the same private member more than once");
2836
+ e instanceof WeakSet ? e.add(t) : e.set(t, i);
2837
+ }, U = (t, e, i, r) => (gr(t, e, "write to private field"), e.set(t, i), i), T = (t, e, i) => (gr(t, e, "access private method"), i), ks = class {
2838
+ constructor(t) {
2839
+ this.value = t;
2840
+ }
2841
+ }, vr = class {
2842
+ constructor(t) {
2843
+ this.value = t;
2844
+ }
2845
+ }, As = (t) => t < 256 ? 1 : t < 65536 ? 2 : t < 1 << 24 ? 3 : t < 2 ** 32 ? 4 : t < 2 ** 40 ? 5 : 6, Ka = (t) => {
2846
+ if (t < 127)
2847
+ return 1;
2848
+ if (t < 16383)
2849
+ return 2;
2850
+ if (t < (1 << 21) - 1)
2851
+ return 3;
2852
+ if (t < (1 << 28) - 1)
2853
+ return 4;
2854
+ if (t < 2 ** 35 - 1)
2855
+ return 5;
2856
+ if (t < 2 ** 42 - 1)
2857
+ return 6;
2858
+ throw new Error("EBML VINT size not supported " + t);
2859
+ }, Jt = (t, e, i) => {
2860
+ let r = 0;
2861
+ for (let s = e; s < i; s++) {
2862
+ let n = Math.floor(s / 8), a = t[n], l = 7 - (s & 7), u = (a & 1 << l) >> l;
2863
+ r <<= 1, r |= u;
2864
+ }
2865
+ return r;
2866
+ }, Za = (t, e, i, r) => {
2867
+ for (let s = e; s < i; s++) {
2868
+ let n = Math.floor(s / 8), a = t[n], l = 7 - (s & 7);
2869
+ a &= ~(1 << l), a |= (r & 1 << i - s - 1) >> i - s - 1 << l, t[n] = a;
2870
+ }
2871
+ }, Ci = class {
2872
+ }, Ms = class extends Ci {
2873
+ constructor() {
2874
+ super(...arguments), this.buffer = null;
2875
+ }
2876
+ }, Ps = class extends Ci {
2877
+ constructor(t) {
2878
+ if (super(), this.options = t, typeof t != "object")
2879
+ throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
2880
+ if (t.onData) {
2881
+ if (typeof t.onData != "function")
2882
+ throw new TypeError("options.onData, when provided, must be a function.");
2883
+ if (t.onData.length < 2)
2884
+ throw new TypeError(
2885
+ "options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
2886
+ );
2887
+ }
2888
+ if (t.onHeader && typeof t.onHeader != "function")
2889
+ throw new TypeError("options.onHeader, when provided, must be a function.");
2890
+ if (t.onCluster && typeof t.onCluster != "function")
2891
+ throw new TypeError("options.onCluster, when provided, must be a function.");
2892
+ if (t.chunked !== void 0 && typeof t.chunked != "boolean")
2893
+ throw new TypeError("options.chunked, when provided, must be a boolean.");
2894
+ if (t.chunkSize !== void 0 && (!Number.isInteger(t.chunkSize) || t.chunkSize < 1024))
2895
+ throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
2896
+ }
2897
+ }, Qa = class extends Ci {
2898
+ constructor(t, e) {
2899
+ if (super(), this.stream = t, this.options = e, !(t instanceof FileSystemWritableFileStream))
2900
+ throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
2901
+ if (e !== void 0 && typeof e != "object")
2902
+ throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
2903
+ if (e && e.chunkSize !== void 0 && (!Number.isInteger(e.chunkSize) || e.chunkSize <= 0))
2904
+ throw new TypeError("options.chunkSize, when provided, must be a positive integer");
2905
+ }
2906
+ }, Bt, N, qi, Is, Hi, Rs, Xi, Bs, ni, Yi, Ji, Fs, Us = class {
2907
+ constructor() {
2908
+ S(this, qi), S(this, Hi), S(this, Xi), S(this, ni), S(this, Ji), this.pos = 0, S(this, Bt, new Uint8Array(8)), S(this, N, new DataView(o(this, Bt).buffer)), this.offsets = /* @__PURE__ */ new WeakMap(), this.dataOffsets = /* @__PURE__ */ new WeakMap();
2909
+ }
2910
+ seek(t) {
2911
+ this.pos = t;
2912
+ }
2913
+ writeEBMLVarInt(t, e = Ka(t)) {
2914
+ let i = 0;
2915
+ switch (e) {
2916
+ case 1:
2917
+ o(this, N).setUint8(i++, 128 | t);
2918
+ break;
2919
+ case 2:
2920
+ o(this, N).setUint8(i++, 64 | t >> 8), o(this, N).setUint8(i++, t);
2921
+ break;
2922
+ case 3:
2923
+ o(this, N).setUint8(i++, 32 | t >> 16), o(this, N).setUint8(i++, t >> 8), o(this, N).setUint8(i++, t);
2924
+ break;
2925
+ case 4:
2926
+ o(this, N).setUint8(i++, 16 | t >> 24), o(this, N).setUint8(i++, t >> 16), o(this, N).setUint8(i++, t >> 8), o(this, N).setUint8(i++, t);
2927
+ break;
2928
+ case 5:
2929
+ o(this, N).setUint8(i++, 8 | t / 2 ** 32 & 7), o(this, N).setUint8(i++, t >> 24), o(this, N).setUint8(i++, t >> 16), o(this, N).setUint8(i++, t >> 8), o(this, N).setUint8(i++, t);
2930
+ break;
2931
+ case 6:
2932
+ o(this, N).setUint8(i++, 4 | t / 2 ** 40 & 3), o(this, N).setUint8(i++, t / 2 ** 32 | 0), o(this, N).setUint8(i++, t >> 24), o(this, N).setUint8(i++, t >> 16), o(this, N).setUint8(i++, t >> 8), o(this, N).setUint8(i++, t);
2933
+ break;
2934
+ default:
2935
+ throw new Error("Bad EBML VINT size " + e);
2936
+ }
2937
+ this.write(o(this, Bt).subarray(0, i));
2938
+ }
2939
+ writeEBML(t) {
2940
+ if (t !== null)
2941
+ if (t instanceof Uint8Array)
2942
+ this.write(t);
2943
+ else if (Array.isArray(t))
2944
+ for (let e of t)
2945
+ this.writeEBML(e);
2946
+ else if (this.offsets.set(t, this.pos), T(this, ni, Yi).call(this, t.id), Array.isArray(t.data)) {
2947
+ let e = this.pos, i = t.size === -1 ? 1 : t.size ?? 4;
2948
+ t.size === -1 ? T(this, qi, Is).call(this, 255) : this.seek(this.pos + i);
2949
+ let r = this.pos;
2950
+ if (this.dataOffsets.set(t, r), this.writeEBML(t.data), t.size !== -1) {
2951
+ let s = this.pos - r, n = this.pos;
2952
+ this.seek(e), this.writeEBMLVarInt(s, i), this.seek(n);
2953
+ }
2954
+ } else if (typeof t.data == "number") {
2955
+ let e = t.size ?? As(t.data);
2956
+ this.writeEBMLVarInt(e), T(this, ni, Yi).call(this, t.data, e);
2957
+ } else typeof t.data == "string" ? (this.writeEBMLVarInt(t.data.length), T(this, Ji, Fs).call(this, t.data)) : t.data instanceof Uint8Array ? (this.writeEBMLVarInt(t.data.byteLength, t.size), this.write(t.data)) : t.data instanceof ks ? (this.writeEBMLVarInt(4), T(this, Hi, Rs).call(this, t.data.value)) : t.data instanceof vr && (this.writeEBMLVarInt(8), T(this, Xi, Bs).call(this, t.data.value));
2958
+ }
2959
+ };
2960
+ Bt = /* @__PURE__ */ new WeakMap();
2961
+ N = /* @__PURE__ */ new WeakMap();
2962
+ qi = /* @__PURE__ */ new WeakSet();
2963
+ Is = function(t) {
2964
+ o(this, N).setUint8(0, t), this.write(o(this, Bt).subarray(0, 1));
2965
+ };
2966
+ Hi = /* @__PURE__ */ new WeakSet();
2967
+ Rs = function(t) {
2968
+ o(this, N).setFloat32(0, t, !1), this.write(o(this, Bt).subarray(0, 4));
2969
+ };
2970
+ Xi = /* @__PURE__ */ new WeakSet();
2971
+ Bs = function(t) {
2972
+ o(this, N).setFloat64(0, t, !1), this.write(o(this, Bt));
2973
+ };
2974
+ ni = /* @__PURE__ */ new WeakSet();
2975
+ Yi = function(t, e = As(t)) {
2976
+ let i = 0;
2977
+ switch (e) {
2978
+ case 6:
2979
+ o(this, N).setUint8(i++, t / 2 ** 40 | 0);
2980
+ case 5:
2981
+ o(this, N).setUint8(i++, t / 2 ** 32 | 0);
2982
+ case 4:
2983
+ o(this, N).setUint8(i++, t >> 24);
2984
+ case 3:
2985
+ o(this, N).setUint8(i++, t >> 16);
2986
+ case 2:
2987
+ o(this, N).setUint8(i++, t >> 8);
2988
+ case 1:
2989
+ o(this, N).setUint8(i++, t);
2990
+ break;
2991
+ default:
2992
+ throw new Error("Bad UINT size " + e);
2993
+ }
2994
+ this.write(o(this, Bt).subarray(0, i));
2995
+ };
2996
+ Ji = /* @__PURE__ */ new WeakSet();
2997
+ Fs = function(t) {
2998
+ this.write(new Uint8Array(t.split("").map((e) => e.charCodeAt(0))));
2999
+ };
3000
+ var ai, Ht, Ve, oi, Ki, to = class extends Us {
3001
+ constructor(t) {
3002
+ super(), S(this, oi), S(this, ai, void 0), S(this, Ht, new ArrayBuffer(2 ** 16)), S(this, Ve, new Uint8Array(o(this, Ht))), U(this, ai, t);
3003
+ }
3004
+ write(t) {
3005
+ T(this, oi, Ki).call(this, this.pos + t.byteLength), o(this, Ve).set(t, this.pos), this.pos += t.byteLength;
3006
+ }
3007
+ finalize() {
3008
+ T(this, oi, Ki).call(this, this.pos), o(this, ai).buffer = o(this, Ht).slice(0, this.pos);
3009
+ }
3010
+ };
3011
+ ai = /* @__PURE__ */ new WeakMap();
3012
+ Ht = /* @__PURE__ */ new WeakMap();
3013
+ Ve = /* @__PURE__ */ new WeakMap();
3014
+ oi = /* @__PURE__ */ new WeakSet();
3015
+ Ki = function(t) {
3016
+ let e = o(this, Ht).byteLength;
3017
+ for (; e < t; )
3018
+ e *= 2;
3019
+ if (e === o(this, Ht).byteLength)
3020
+ return;
3021
+ let i = new ArrayBuffer(e), r = new Uint8Array(i);
3022
+ r.set(o(this, Ve), 0), U(this, Ht, i), U(this, Ve, r);
3023
+ };
3024
+ var Zt, dt, ct, Lt, qe = class extends Us {
3025
+ constructor(t) {
3026
+ super(), this.target = t, S(this, Zt, !1), S(this, dt, void 0), S(this, ct, void 0), S(this, Lt, void 0);
3027
+ }
3028
+ write(t) {
3029
+ if (!o(this, Zt))
3030
+ return;
3031
+ let e = this.pos;
3032
+ if (e < o(this, ct)) {
3033
+ if (e + t.byteLength <= o(this, ct))
3034
+ return;
3035
+ t = t.subarray(o(this, ct) - e), e = 0;
3036
+ }
3037
+ let i = e + t.byteLength - o(this, ct), r = o(this, dt).byteLength;
3038
+ for (; r < i; )
3039
+ r *= 2;
3040
+ if (r !== o(this, dt).byteLength) {
3041
+ let s = new Uint8Array(r);
3042
+ s.set(o(this, dt), 0), U(this, dt, s);
3043
+ }
3044
+ o(this, dt).set(t, e - o(this, ct)), U(this, Lt, Math.max(o(this, Lt), e + t.byteLength));
3045
+ }
3046
+ startTrackingWrites() {
3047
+ U(this, Zt, !0), U(this, dt, new Uint8Array(2 ** 10)), U(this, ct, this.pos), U(this, Lt, this.pos);
3048
+ }
3049
+ getTrackedWrites() {
3050
+ if (!o(this, Zt))
3051
+ throw new Error("Can't get tracked writes since nothing was tracked.");
3052
+ let e = {
3053
+ data: o(this, dt).subarray(0, o(this, Lt) - o(this, ct)),
3054
+ start: o(this, ct),
3055
+ end: o(this, Lt)
3056
+ };
3057
+ return U(this, dt, void 0), U(this, Zt, !1), e;
3058
+ }
3059
+ };
3060
+ Zt = /* @__PURE__ */ new WeakMap();
3061
+ dt = /* @__PURE__ */ new WeakMap();
3062
+ ct = /* @__PURE__ */ new WeakMap();
3063
+ Lt = /* @__PURE__ */ new WeakMap();
3064
+ var eo = 2 ** 24, io = 2, Ot, se, Pe, _e, Et, nt, gi, Zi, yr, Ds, br, Ws, Ie, vi, _r = class extends qe {
3065
+ constructor(t, e) {
3066
+ var i, r;
3067
+ super(t), S(this, gi), S(this, yr), S(this, br), S(this, Ie), S(this, Ot, []), S(this, se, 0), S(this, Pe, void 0), S(this, _e, void 0), S(this, Et, void 0), S(this, nt, []), U(this, Pe, e), U(this, _e, ((i = t.options) == null ? void 0 : i.chunked) ?? !1), U(this, Et, ((r = t.options) == null ? void 0 : r.chunkSize) ?? eo);
3068
+ }
3069
+ write(t) {
3070
+ super.write(t), o(this, Ot).push({
3071
+ data: t.slice(),
3072
+ start: this.pos
3073
+ }), this.pos += t.byteLength;
3074
+ }
3075
+ flush() {
3076
+ var i, r;
3077
+ if (o(this, Ot).length === 0)
3078
+ return;
3079
+ let t = [], e = [...o(this, Ot)].sort((s, n) => s.start - n.start);
3080
+ t.push({
3081
+ start: e[0].start,
3082
+ size: e[0].data.byteLength
3083
+ });
3084
+ for (let s = 1; s < e.length; s++) {
3085
+ let n = t[t.length - 1], a = e[s];
3086
+ a.start <= n.start + n.size ? n.size = Math.max(n.size, a.start + a.data.byteLength - n.start) : t.push({
3087
+ start: a.start,
3088
+ size: a.data.byteLength
3089
+ });
3090
+ }
3091
+ for (let s of t) {
3092
+ s.data = new Uint8Array(s.size);
3093
+ for (let n of o(this, Ot))
3094
+ s.start <= n.start && n.start < s.start + s.size && s.data.set(n.data, n.start - s.start);
3095
+ if (o(this, _e))
3096
+ T(this, gi, Zi).call(this, s.data, s.start), T(this, Ie, vi).call(this);
3097
+ else {
3098
+ if (o(this, Pe) && s.start < o(this, se))
3099
+ throw new Error("Internal error: Monotonicity violation.");
3100
+ (r = (i = this.target.options).onData) == null || r.call(i, s.data, s.start), U(this, se, s.start + s.data.byteLength);
3101
+ }
3102
+ }
3103
+ o(this, Ot).length = 0;
3104
+ }
3105
+ finalize() {
3106
+ o(this, _e) && T(this, Ie, vi).call(this, !0);
3107
+ }
3108
+ };
3109
+ Ot = /* @__PURE__ */ new WeakMap();
3110
+ se = /* @__PURE__ */ new WeakMap();
3111
+ Pe = /* @__PURE__ */ new WeakMap();
3112
+ _e = /* @__PURE__ */ new WeakMap();
3113
+ Et = /* @__PURE__ */ new WeakMap();
3114
+ nt = /* @__PURE__ */ new WeakMap();
3115
+ gi = /* @__PURE__ */ new WeakSet();
3116
+ Zi = function(t, e) {
3117
+ let i = o(this, nt).findIndex((l) => l.start <= e && e < l.start + o(this, Et));
3118
+ i === -1 && (i = T(this, br, Ws).call(this, e));
3119
+ let r = o(this, nt)[i], s = e - r.start, n = t.subarray(0, Math.min(o(this, Et) - s, t.byteLength));
3120
+ r.data.set(n, s);
3121
+ let a = {
3122
+ start: s,
3123
+ end: s + n.byteLength
3124
+ };
3125
+ if (T(this, yr, Ds).call(this, r, a), r.written[0].start === 0 && r.written[0].end === o(this, Et) && (r.shouldFlush = !0), o(this, nt).length > io) {
3126
+ for (let l = 0; l < o(this, nt).length - 1; l++)
3127
+ o(this, nt)[l].shouldFlush = !0;
3128
+ T(this, Ie, vi).call(this);
3129
+ }
3130
+ n.byteLength < t.byteLength && T(this, gi, Zi).call(this, t.subarray(n.byteLength), e + n.byteLength);
3131
+ };
3132
+ yr = /* @__PURE__ */ new WeakSet();
3133
+ Ds = function(t, e) {
3134
+ let i = 0, r = t.written.length - 1, s = -1;
3135
+ for (; i <= r; ) {
3136
+ let n = Math.floor(i + (r - i + 1) / 2);
3137
+ t.written[n].start <= e.start ? (i = n + 1, s = n) : r = n - 1;
3138
+ }
3139
+ for (t.written.splice(s + 1, 0, e), (s === -1 || t.written[s].end < e.start) && s++; s < t.written.length - 1 && t.written[s].end >= t.written[s + 1].start; )
3140
+ t.written[s].end = Math.max(t.written[s].end, t.written[s + 1].end), t.written.splice(s + 1, 1);
3141
+ };
3142
+ br = /* @__PURE__ */ new WeakSet();
3143
+ Ws = function(t) {
3144
+ let i = {
3145
+ start: Math.floor(t / o(this, Et)) * o(this, Et),
3146
+ data: new Uint8Array(o(this, Et)),
3147
+ written: [],
3148
+ shouldFlush: !1
3149
+ };
3150
+ return o(this, nt).push(i), o(this, nt).sort((r, s) => r.start - s.start), o(this, nt).indexOf(i);
3151
+ };
3152
+ Ie = /* @__PURE__ */ new WeakSet();
3153
+ vi = function(t = !1) {
3154
+ var e, i;
3155
+ for (let r = 0; r < o(this, nt).length; r++) {
3156
+ let s = o(this, nt)[r];
3157
+ if (!(!s.shouldFlush && !t)) {
3158
+ for (let n of s.written) {
3159
+ if (o(this, Pe) && s.start + n.start < o(this, se))
3160
+ throw new Error("Internal error: Monotonicity violation.");
3161
+ (i = (e = this.target.options).onData) == null || i.call(
3162
+ e,
3163
+ s.data.subarray(n.start, n.end),
3164
+ s.start + n.start
3165
+ ), U(this, se, s.start + n.end);
3166
+ }
3167
+ o(this, nt).splice(r--, 1);
3168
+ }
3169
+ }
3170
+ };
3171
+ var ro = class extends _r {
3172
+ constructor(t, e) {
3173
+ var i;
3174
+ super(new Ps({
3175
+ onData: (r, s) => t.stream.write({
3176
+ type: "write",
3177
+ data: r,
3178
+ position: s
3179
+ }),
3180
+ chunked: !0,
3181
+ chunkSize: (i = t.options) == null ? void 0 : i.chunkSize
3182
+ }), e);
3183
+ }
3184
+ }, ue = 1, Le = 2, yi = 3, so = 1, no = 2, ao = 17, oo = 2 ** 15, Re = 2 ** 13, jr = "https://github.com/Vanilagy/webm-muxer", zs = 6, Vs = 5, ho = ["strict", "offset", "permissive"], I, k, Oe, Ge, bt, pe, te, Xt, me, Ft, ne, ae, pt, He, oe, Pt, It, Gt, Be, Fe, he, le, bi, Ne, Ue, Qi, Ls, tr, Os, xr, Gs, Sr, Ns, Cr, $s, Er, js, Tr, qs, Ei, kr, Ti, Ar, Mr, Hs, Nt, ee, $t, ie, er, Xs, ir, Ys, xe, hi, Se, li, Pr, Js, ft, yt, de, $e, De, _i, Ir, Ks, xi, Rr, Ce, di, lo = class {
3185
+ constructor(t) {
3186
+ S(this, Qi), S(this, tr), S(this, xr), S(this, Sr), S(this, Cr), S(this, Er), S(this, Tr), S(this, Ei), S(this, Ti), S(this, Mr), S(this, Nt), S(this, $t), S(this, er), S(this, ir), S(this, xe), S(this, Se), S(this, Pr), S(this, ft), S(this, de), S(this, De), S(this, Ir), S(this, xi), S(this, Ce), S(this, I, void 0), S(this, k, void 0), S(this, Oe, void 0), S(this, Ge, void 0), S(this, bt, void 0), S(this, pe, void 0), S(this, te, void 0), S(this, Xt, void 0), S(this, me, void 0), S(this, Ft, void 0), S(this, ne, void 0), S(this, ae, void 0), S(this, pt, void 0), S(this, He, void 0), S(this, oe, 0), S(this, Pt, []), S(this, It, []), S(this, Gt, []), S(this, Be, void 0), S(this, Fe, void 0), S(this, he, -1), S(this, le, -1), S(this, bi, -1), S(this, Ne, void 0), S(this, Ue, !1), T(this, Qi, Ls).call(this, t), U(this, I, {
3187
+ type: "webm",
3188
+ firstTimestampBehavior: "strict",
3189
+ ...t
3190
+ }), this.target = t.target;
3191
+ let e = !!o(this, I).streaming;
3192
+ if (t.target instanceof Ms)
3193
+ U(this, k, new to(t.target));
3194
+ else if (t.target instanceof Ps)
3195
+ U(this, k, new _r(t.target, e));
3196
+ else if (t.target instanceof Qa)
3197
+ U(this, k, new ro(t.target, e));
3198
+ else
3199
+ throw new Error(`Invalid target: ${t.target}`);
3200
+ T(this, tr, Os).call(this);
3201
+ }
3202
+ addVideoChunk(t, e, i) {
3203
+ if (!(t instanceof EncodedVideoChunk))
3204
+ throw new TypeError("addVideoChunk's first argument (chunk) must be of type EncodedVideoChunk.");
3205
+ if (e && typeof e != "object")
3206
+ throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
3207
+ if (i !== void 0 && (!Number.isFinite(i) || i < 0))
3208
+ throw new TypeError(
3209
+ "addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
3210
+ );
3211
+ let r = new Uint8Array(t.byteLength);
3212
+ t.copyTo(r), this.addVideoChunkRaw(r, t.type, i ?? t.timestamp, e);
3213
+ }
3214
+ addVideoChunkRaw(t, e, i, r) {
3215
+ if (!(t instanceof Uint8Array))
3216
+ throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
3217
+ if (e !== "key" && e !== "delta")
3218
+ throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
3219
+ if (!Number.isFinite(i) || i < 0)
3220
+ throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
3221
+ if (r && typeof r != "object")
3222
+ throw new TypeError("addVideoChunkRaw's fourth argument (meta), when provided, must be an object.");
3223
+ if (T(this, Ce, di).call(this), !o(this, I).video)
3224
+ throw new Error("No video track declared.");
3225
+ o(this, Be) === void 0 && U(this, Be, i), r && T(this, er, Xs).call(this, r);
3226
+ let s = T(this, Se, li).call(this, t, e, i, ue);
3227
+ for (o(this, I).video.codec === "V_VP9" && T(this, ir, Ys).call(this, s), U(this, he, s.timestamp); o(this, It).length > 0 && o(this, It)[0].timestamp <= s.timestamp; ) {
3228
+ let n = o(this, It).shift();
3229
+ T(this, ft, yt).call(this, n, !1);
3230
+ }
3231
+ !o(this, I).audio || s.timestamp <= o(this, le) ? T(this, ft, yt).call(this, s, !0) : o(this, Pt).push(s), T(this, xe, hi).call(this), T(this, Nt, ee).call(this);
3232
+ }
3233
+ addAudioChunk(t, e, i) {
3234
+ if (!(t instanceof EncodedAudioChunk))
3235
+ throw new TypeError("addAudioChunk's first argument (chunk) must be of type EncodedAudioChunk.");
3236
+ if (e && typeof e != "object")
3237
+ throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
3238
+ if (i !== void 0 && (!Number.isFinite(i) || i < 0))
3239
+ throw new TypeError(
3240
+ "addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
3241
+ );
3242
+ let r = new Uint8Array(t.byteLength);
3243
+ t.copyTo(r), this.addAudioChunkRaw(r, t.type, i ?? t.timestamp, e);
3244
+ }
3245
+ addAudioChunkRaw(t, e, i, r) {
3246
+ if (!(t instanceof Uint8Array))
3247
+ throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
3248
+ if (e !== "key" && e !== "delta")
3249
+ throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
3250
+ if (!Number.isFinite(i) || i < 0)
3251
+ throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
3252
+ if (r && typeof r != "object")
3253
+ throw new TypeError("addAudioChunkRaw's fourth argument (meta), when provided, must be an object.");
3254
+ if (T(this, Ce, di).call(this), !o(this, I).audio)
3255
+ throw new Error("No audio track declared.");
3256
+ o(this, Fe) === void 0 && U(this, Fe, i), r != null && r.decoderConfig && (o(this, I).streaming ? U(this, Ft, T(this, de, $e).call(this, r.decoderConfig.description)) : T(this, De, _i).call(this, o(this, Ft), r.decoderConfig.description));
3257
+ let s = T(this, Se, li).call(this, t, e, i, Le);
3258
+ for (U(this, le, s.timestamp); o(this, Pt).length > 0 && o(this, Pt)[0].timestamp <= s.timestamp; ) {
3259
+ let n = o(this, Pt).shift();
3260
+ T(this, ft, yt).call(this, n, !0);
3261
+ }
3262
+ !o(this, I).video || s.timestamp <= o(this, he) ? T(this, ft, yt).call(this, s, !o(this, I).video) : o(this, It).push(s), T(this, xe, hi).call(this), T(this, Nt, ee).call(this);
3263
+ }
3264
+ addSubtitleChunk(t, e, i) {
3265
+ if (typeof t != "object" || !t)
3266
+ throw new TypeError("addSubtitleChunk's first argument (chunk) must be an object.");
3267
+ if (!(t.body instanceof Uint8Array))
3268
+ throw new TypeError("body must be an instance of Uint8Array.");
3269
+ if (!Number.isFinite(t.timestamp) || t.timestamp < 0)
3270
+ throw new TypeError("timestamp must be a non-negative real number.");
3271
+ if (!Number.isFinite(t.duration) || t.duration < 0)
3272
+ throw new TypeError("duration must be a non-negative real number.");
3273
+ if (t.additions && !(t.additions instanceof Uint8Array))
3274
+ throw new TypeError("additions, when present, must be an instance of Uint8Array.");
3275
+ if (typeof e != "object")
3276
+ throw new TypeError("addSubtitleChunk's second argument (meta) must be an object.");
3277
+ if (T(this, Ce, di).call(this), !o(this, I).subtitles)
3278
+ throw new Error("No subtitle track declared.");
3279
+ e != null && e.decoderConfig && (o(this, I).streaming ? U(this, ne, T(this, de, $e).call(this, e.decoderConfig.description)) : T(this, De, _i).call(this, o(this, ne), e.decoderConfig.description));
3280
+ let r = T(this, Se, li).call(this, t.body, "key", i ?? t.timestamp, yi, t.duration, t.additions);
3281
+ U(this, bi, r.timestamp), o(this, Gt).push(r), T(this, xe, hi).call(this), T(this, Nt, ee).call(this);
3282
+ }
3283
+ finalize() {
3284
+ if (o(this, Ue))
3285
+ throw new Error("Cannot finalize a muxer more than once.");
3286
+ for (; o(this, Pt).length > 0; )
3287
+ T(this, ft, yt).call(this, o(this, Pt).shift(), !0);
3288
+ for (; o(this, It).length > 0; )
3289
+ T(this, ft, yt).call(this, o(this, It).shift(), !0);
3290
+ for (; o(this, Gt).length > 0 && o(this, Gt)[0].timestamp <= o(this, oe); )
3291
+ T(this, ft, yt).call(this, o(this, Gt).shift(), !1);
3292
+ if (o(this, pt) && T(this, xi, Rr).call(this), o(this, k).writeEBML(o(this, ae)), !o(this, I).streaming) {
3293
+ let t = o(this, k).pos, e = o(this, k).pos - o(this, $t, ie);
3294
+ o(this, k).seek(o(this, k).offsets.get(o(this, Oe)) + 4), o(this, k).writeEBMLVarInt(e, zs), o(this, te).data = new vr(o(this, oe)), o(this, k).seek(o(this, k).offsets.get(o(this, te))), o(this, k).writeEBML(o(this, te)), o(this, bt).data[0].data[1].data = o(this, k).offsets.get(o(this, ae)) - o(this, $t, ie), o(this, bt).data[1].data[1].data = o(this, k).offsets.get(o(this, Ge)) - o(this, $t, ie), o(this, bt).data[2].data[1].data = o(this, k).offsets.get(o(this, pe)) - o(this, $t, ie), o(this, k).seek(o(this, k).offsets.get(o(this, bt))), o(this, k).writeEBML(o(this, bt)), o(this, k).seek(t);
3295
+ }
3296
+ T(this, Nt, ee).call(this), o(this, k).finalize(), U(this, Ue, !0);
3297
+ }
3298
+ };
3299
+ I = /* @__PURE__ */ new WeakMap();
3300
+ k = /* @__PURE__ */ new WeakMap();
3301
+ Oe = /* @__PURE__ */ new WeakMap();
3302
+ Ge = /* @__PURE__ */ new WeakMap();
3303
+ bt = /* @__PURE__ */ new WeakMap();
3304
+ pe = /* @__PURE__ */ new WeakMap();
3305
+ te = /* @__PURE__ */ new WeakMap();
3306
+ Xt = /* @__PURE__ */ new WeakMap();
3307
+ me = /* @__PURE__ */ new WeakMap();
3308
+ Ft = /* @__PURE__ */ new WeakMap();
3309
+ ne = /* @__PURE__ */ new WeakMap();
3310
+ ae = /* @__PURE__ */ new WeakMap();
3311
+ pt = /* @__PURE__ */ new WeakMap();
3312
+ He = /* @__PURE__ */ new WeakMap();
3313
+ oe = /* @__PURE__ */ new WeakMap();
3314
+ Pt = /* @__PURE__ */ new WeakMap();
3315
+ It = /* @__PURE__ */ new WeakMap();
3316
+ Gt = /* @__PURE__ */ new WeakMap();
3317
+ Be = /* @__PURE__ */ new WeakMap();
3318
+ Fe = /* @__PURE__ */ new WeakMap();
3319
+ he = /* @__PURE__ */ new WeakMap();
3320
+ le = /* @__PURE__ */ new WeakMap();
3321
+ bi = /* @__PURE__ */ new WeakMap();
3322
+ Ne = /* @__PURE__ */ new WeakMap();
3323
+ Ue = /* @__PURE__ */ new WeakMap();
3324
+ Qi = /* @__PURE__ */ new WeakSet();
3325
+ Ls = function(t) {
3326
+ if (typeof t != "object")
3327
+ throw new TypeError("The muxer requires an options object to be passed to its constructor.");
3328
+ if (!(t.target instanceof Ci))
3329
+ throw new TypeError("The target must be provided and an instance of Target.");
3330
+ if (t.video) {
3331
+ if (typeof t.video.codec != "string")
3332
+ throw new TypeError(`Invalid video codec: ${t.video.codec}. Must be a string.`);
3333
+ if (!Number.isInteger(t.video.width) || t.video.width <= 0)
3334
+ throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);
3335
+ if (!Number.isInteger(t.video.height) || t.video.height <= 0)
3336
+ throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);
3337
+ if (t.video.frameRate !== void 0 && (!Number.isFinite(t.video.frameRate) || t.video.frameRate <= 0))
3338
+ throw new TypeError(
3339
+ `Invalid video frame rate: ${t.video.frameRate}. Must be a positive number.`
3340
+ );
3341
+ if (t.video.alpha !== void 0 && typeof t.video.alpha != "boolean")
3342
+ throw new TypeError(`Invalid video alpha: ${t.video.alpha}. Must be a boolean.`);
3343
+ }
3344
+ if (t.audio) {
3345
+ if (typeof t.audio.codec != "string")
3346
+ throw new TypeError(`Invalid audio codec: ${t.audio.codec}. Must be a string.`);
3347
+ if (!Number.isInteger(t.audio.numberOfChannels) || t.audio.numberOfChannels <= 0)
3348
+ throw new TypeError(
3349
+ `Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`
3350
+ );
3351
+ if (!Number.isInteger(t.audio.sampleRate) || t.audio.sampleRate <= 0)
3352
+ throw new TypeError(
3353
+ `Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`
3354
+ );
3355
+ if (t.audio.bitDepth !== void 0 && (!Number.isInteger(t.audio.bitDepth) || t.audio.bitDepth <= 0))
3356
+ throw new TypeError(
3357
+ `Invalid audio bit depth: ${t.audio.bitDepth}. Must be a positive integer.`
3358
+ );
3359
+ }
3360
+ if (t.subtitles && typeof t.subtitles.codec != "string")
3361
+ throw new TypeError(`Invalid subtitles codec: ${t.subtitles.codec}. Must be a string.`);
3362
+ if (t.type !== void 0 && !["webm", "matroska"].includes(t.type))
3363
+ throw new TypeError(`Invalid type: ${t.type}. Must be 'webm' or 'matroska'.`);
3364
+ if (t.firstTimestampBehavior && !ho.includes(t.firstTimestampBehavior))
3365
+ throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);
3366
+ if (t.streaming !== void 0 && typeof t.streaming != "boolean")
3367
+ throw new TypeError(`Invalid streaming option: ${t.streaming}. Must be a boolean.`);
3368
+ };
3369
+ tr = /* @__PURE__ */ new WeakSet();
3370
+ Os = function() {
3371
+ o(this, k) instanceof qe && o(this, k).target.options.onHeader && o(this, k).startTrackingWrites(), T(this, xr, Gs).call(this), o(this, I).streaming || T(this, Er, js).call(this), T(this, Tr, qs).call(this), T(this, Sr, Ns).call(this), T(this, Cr, $s).call(this), o(this, I).streaming || (T(this, Ei, kr).call(this), T(this, Ti, Ar).call(this)), T(this, Mr, Hs).call(this), T(this, Nt, ee).call(this);
3372
+ };
3373
+ xr = /* @__PURE__ */ new WeakSet();
3374
+ Gs = function() {
3375
+ let t = { id: 440786851, data: [
3376
+ { id: 17030, data: 1 },
3377
+ { id: 17143, data: 1 },
3378
+ { id: 17138, data: 4 },
3379
+ { id: 17139, data: 8 },
3380
+ { id: 17026, data: o(this, I).type ?? "webm" },
3381
+ { id: 17031, data: 2 },
3382
+ { id: 17029, data: 2 }
3383
+ ] };
3384
+ o(this, k).writeEBML(t);
3385
+ };
3386
+ Sr = /* @__PURE__ */ new WeakSet();
3387
+ Ns = function() {
3388
+ U(this, me, { id: 236, size: 4, data: new Uint8Array(Re) }), U(this, Ft, { id: 236, size: 4, data: new Uint8Array(Re) }), U(this, ne, { id: 236, size: 4, data: new Uint8Array(Re) });
3389
+ };
3390
+ Cr = /* @__PURE__ */ new WeakSet();
3391
+ $s = function() {
3392
+ U(this, Xt, { id: 21936, data: [
3393
+ { id: 21937, data: 2 },
3394
+ { id: 21946, data: 2 },
3395
+ { id: 21947, data: 2 },
3396
+ { id: 21945, data: 0 }
3397
+ ] });
3398
+ };
3399
+ Er = /* @__PURE__ */ new WeakSet();
3400
+ js = function() {
3401
+ const t = new Uint8Array([28, 83, 187, 107]), e = new Uint8Array([21, 73, 169, 102]), i = new Uint8Array([22, 84, 174, 107]);
3402
+ U(this, bt, { id: 290298740, data: [
3403
+ { id: 19899, data: [
3404
+ { id: 21419, data: t },
3405
+ { id: 21420, size: 5, data: 0 }
3406
+ ] },
3407
+ { id: 19899, data: [
3408
+ { id: 21419, data: e },
3409
+ { id: 21420, size: 5, data: 0 }
3410
+ ] },
3411
+ { id: 19899, data: [
3412
+ { id: 21419, data: i },
3413
+ { id: 21420, size: 5, data: 0 }
3414
+ ] }
3415
+ ] });
3416
+ };
3417
+ Tr = /* @__PURE__ */ new WeakSet();
3418
+ qs = function() {
3419
+ let t = { id: 17545, data: new vr(0) };
3420
+ U(this, te, t);
3421
+ let e = { id: 357149030, data: [
3422
+ { id: 2807729, data: 1e6 },
3423
+ { id: 19840, data: jr },
3424
+ { id: 22337, data: jr },
3425
+ o(this, I).streaming ? null : t
3426
+ ] };
3427
+ U(this, Ge, e);
3428
+ };
3429
+ Ei = /* @__PURE__ */ new WeakSet();
3430
+ kr = function() {
3431
+ let t = { id: 374648427, data: [] };
3432
+ U(this, pe, t), o(this, I).video && t.data.push({ id: 174, data: [
3433
+ { id: 215, data: ue },
3434
+ { id: 29637, data: ue },
3435
+ { id: 131, data: so },
3436
+ { id: 134, data: o(this, I).video.codec },
3437
+ o(this, me),
3438
+ o(this, I).video.frameRate ? { id: 2352003, data: 1e9 / o(this, I).video.frameRate } : null,
3439
+ { id: 224, data: [
3440
+ { id: 176, data: o(this, I).video.width },
3441
+ { id: 186, data: o(this, I).video.height },
3442
+ o(this, I).video.alpha ? { id: 21440, data: 1 } : null,
3443
+ o(this, Xt)
3444
+ ] }
3445
+ ] }), o(this, I).audio && (U(this, Ft, o(this, I).streaming ? o(this, Ft) || null : { id: 236, size: 4, data: new Uint8Array(Re) }), t.data.push({ id: 174, data: [
3446
+ { id: 215, data: Le },
3447
+ { id: 29637, data: Le },
3448
+ { id: 131, data: no },
3449
+ { id: 134, data: o(this, I).audio.codec },
3450
+ o(this, Ft),
3451
+ { id: 225, data: [
3452
+ { id: 181, data: new ks(o(this, I).audio.sampleRate) },
3453
+ { id: 159, data: o(this, I).audio.numberOfChannels },
3454
+ o(this, I).audio.bitDepth ? { id: 25188, data: o(this, I).audio.bitDepth } : null
3455
+ ] }
3456
+ ] })), o(this, I).subtitles && t.data.push({ id: 174, data: [
3457
+ { id: 215, data: yi },
3458
+ { id: 29637, data: yi },
3459
+ { id: 131, data: ao },
3460
+ { id: 134, data: o(this, I).subtitles.codec },
3461
+ o(this, ne)
3462
+ ] });
3463
+ };
3464
+ Ti = /* @__PURE__ */ new WeakSet();
3465
+ Ar = function() {
3466
+ let t = {
3467
+ id: 408125543,
3468
+ size: o(this, I).streaming ? -1 : zs,
3469
+ data: [
3470
+ o(this, I).streaming ? null : o(this, bt),
3471
+ o(this, Ge),
3472
+ o(this, pe)
3473
+ ]
3474
+ };
3475
+ if (U(this, Oe, t), o(this, k).writeEBML(t), o(this, k) instanceof qe && o(this, k).target.options.onHeader) {
3476
+ let { data: e, start: i } = o(this, k).getTrackedWrites();
3477
+ o(this, k).target.options.onHeader(e, i);
3478
+ }
3479
+ };
3480
+ Mr = /* @__PURE__ */ new WeakSet();
3481
+ Hs = function() {
3482
+ U(this, ae, { id: 475249515, data: [] });
3483
+ };
3484
+ Nt = /* @__PURE__ */ new WeakSet();
3485
+ ee = function() {
3486
+ o(this, k) instanceof _r && o(this, k).flush();
3487
+ };
3488
+ $t = /* @__PURE__ */ new WeakSet();
3489
+ ie = function() {
3490
+ return o(this, k).dataOffsets.get(o(this, Oe));
3491
+ };
3492
+ er = /* @__PURE__ */ new WeakSet();
3493
+ Xs = function(t) {
3494
+ if (t.decoderConfig) {
3495
+ if (t.decoderConfig.colorSpace) {
3496
+ let e = t.decoderConfig.colorSpace;
3497
+ if (U(this, Ne, e), o(this, Xt).data = [
3498
+ { id: 21937, data: {
3499
+ rgb: 1,
3500
+ bt709: 1,
3501
+ bt470bg: 5,
3502
+ smpte170m: 6
3503
+ }[e.matrix] },
3504
+ { id: 21946, data: {
3505
+ bt709: 1,
3506
+ smpte170m: 6,
3507
+ "iec61966-2-1": 13
3508
+ }[e.transfer] },
3509
+ { id: 21947, data: {
3510
+ bt709: 1,
3511
+ bt470bg: 5,
3512
+ smpte170m: 6
3513
+ }[e.primaries] },
3514
+ { id: 21945, data: [1, 2][Number(e.fullRange)] }
3515
+ ], !o(this, I).streaming) {
3516
+ let i = o(this, k).pos;
3517
+ o(this, k).seek(o(this, k).offsets.get(o(this, Xt))), o(this, k).writeEBML(o(this, Xt)), o(this, k).seek(i);
3518
+ }
3519
+ }
3520
+ t.decoderConfig.description && (o(this, I).streaming ? U(this, me, T(this, de, $e).call(this, t.decoderConfig.description)) : T(this, De, _i).call(this, o(this, me), t.decoderConfig.description));
3521
+ }
3522
+ };
3523
+ ir = /* @__PURE__ */ new WeakSet();
3524
+ Ys = function(t) {
3525
+ if (t.type !== "key" || !o(this, Ne))
3526
+ return;
3527
+ let e = 0;
3528
+ if (Jt(t.data, 0, 2) !== 2)
3529
+ return;
3530
+ e += 2;
3531
+ let i = (Jt(t.data, e + 1, e + 2) << 1) + Jt(t.data, e + 0, e + 1);
3532
+ e += 2, i === 3 && e++;
3533
+ let r = Jt(t.data, e + 0, e + 1);
3534
+ if (e++, r)
3535
+ return;
3536
+ let s = Jt(t.data, e + 0, e + 1);
3537
+ if (e++, s !== 0)
3538
+ return;
3539
+ e += 2;
3540
+ let n = Jt(t.data, e + 0, e + 24);
3541
+ if (e += 24, n !== 4817730)
3542
+ return;
3543
+ i >= 2 && e++;
3544
+ let a = {
3545
+ rgb: 7,
3546
+ bt709: 2,
3547
+ bt470bg: 1,
3548
+ smpte170m: 3
3549
+ }[o(this, Ne).matrix];
3550
+ Za(t.data, e + 0, e + 3, a);
3551
+ };
3552
+ xe = /* @__PURE__ */ new WeakSet();
3553
+ hi = function() {
3554
+ let t = Math.min(
3555
+ o(this, I).video ? o(this, he) : 1 / 0,
3556
+ o(this, I).audio ? o(this, le) : 1 / 0
3557
+ ), e = o(this, Gt);
3558
+ for (; e.length > 0 && e[0].timestamp <= t; )
3559
+ T(this, ft, yt).call(this, e.shift(), !o(this, I).video && !o(this, I).audio);
3560
+ };
3561
+ Se = /* @__PURE__ */ new WeakSet();
3562
+ li = function(t, e, i, r, s, n) {
3563
+ let a = T(this, Pr, Js).call(this, i, r);
3564
+ return {
3565
+ data: t,
3566
+ additions: n,
3567
+ type: e,
3568
+ timestamp: a,
3569
+ duration: s,
3570
+ trackNumber: r
3571
+ };
3572
+ };
3573
+ Pr = /* @__PURE__ */ new WeakSet();
3574
+ Js = function(t, e) {
3575
+ let i = e === ue ? o(this, he) : e === Le ? o(this, le) : o(this, bi);
3576
+ if (e !== yi) {
3577
+ let r = e === ue ? o(this, Be) : o(this, Fe);
3578
+ if (o(this, I).firstTimestampBehavior === "strict" && i === -1 && t !== 0)
3579
+ throw new Error(
3580
+ `The first chunk for your media track must have a timestamp of 0 (received ${t}). Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of the document, which is probably what you want.
3581
+
3582
+ If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
3583
+ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'permissive'.
3584
+ `
3585
+ );
3586
+ o(this, I).firstTimestampBehavior === "offset" && (t -= r);
3587
+ }
3588
+ if (t < i)
3589
+ throw new Error(
3590
+ `Timestamps must be monotonically increasing (went from ${i} to ${t}).`
3591
+ );
3592
+ if (t < 0)
3593
+ throw new Error(`Timestamps must be non-negative (received ${t}).`);
3594
+ return t;
3595
+ };
3596
+ ft = /* @__PURE__ */ new WeakSet();
3597
+ yt = function(t, e) {
3598
+ o(this, I).streaming && !o(this, pe) && (T(this, Ei, kr).call(this), T(this, Ti, Ar).call(this));
3599
+ let i = Math.floor(t.timestamp / 1e3), r = i - o(this, He), s = e && t.type === "key" && r >= 1e3, n = r >= oo;
3600
+ if ((!o(this, pt) || s || n) && (T(this, Ir, Ks).call(this, i), r = 0), r < 0)
3601
+ return;
3602
+ let a = new Uint8Array(4), l = new DataView(a.buffer);
3603
+ if (l.setUint8(0, 128 | t.trackNumber), l.setInt16(1, r, !1), t.duration === void 0 && !t.additions) {
3604
+ l.setUint8(3, +(t.type === "key") << 7);
3605
+ let u = { id: 163, data: [
3606
+ a,
3607
+ t.data
3608
+ ] };
3609
+ o(this, k).writeEBML(u);
3610
+ } else {
3611
+ let u = Math.floor(t.duration / 1e3), g = { id: 160, data: [
3612
+ { id: 161, data: [
3613
+ a,
3614
+ t.data
3615
+ ] },
3616
+ t.duration !== void 0 ? { id: 155, data: u } : null,
3617
+ t.additions ? { id: 30113, data: t.additions } : null
3618
+ ] };
3619
+ o(this, k).writeEBML(g);
3620
+ }
3621
+ U(this, oe, Math.max(o(this, oe), i));
3622
+ };
3623
+ de = /* @__PURE__ */ new WeakSet();
3624
+ $e = function(t) {
3625
+ return { id: 25506, size: 4, data: new Uint8Array(t) };
3626
+ };
3627
+ De = /* @__PURE__ */ new WeakSet();
3628
+ _i = function(t, e) {
3629
+ let i = o(this, k).pos;
3630
+ o(this, k).seek(o(this, k).offsets.get(t));
3631
+ let r = 6 + e.byteLength, s = Re - r;
3632
+ if (s < 0) {
3633
+ let n = e.byteLength + s;
3634
+ e instanceof ArrayBuffer ? e = e.slice(0, n) : e = e.buffer.slice(0, n), s = 0;
3635
+ }
3636
+ t = [
3637
+ T(this, de, $e).call(this, e),
3638
+ { id: 236, size: 4, data: new Uint8Array(s) }
3639
+ ], o(this, k).writeEBML(t), o(this, k).seek(i);
3640
+ };
3641
+ Ir = /* @__PURE__ */ new WeakSet();
3642
+ Ks = function(t) {
3643
+ o(this, pt) && T(this, xi, Rr).call(this), o(this, k) instanceof qe && o(this, k).target.options.onCluster && o(this, k).startTrackingWrites(), U(this, pt, {
3644
+ id: 524531317,
3645
+ size: o(this, I).streaming ? -1 : Vs,
3646
+ data: [
3647
+ { id: 231, data: t }
3648
+ ]
3649
+ }), o(this, k).writeEBML(o(this, pt)), U(this, He, t);
3650
+ let e = o(this, k).offsets.get(o(this, pt)) - o(this, $t, ie);
3651
+ o(this, ae).data.push({ id: 187, data: [
3652
+ { id: 179, data: t },
3653
+ o(this, I).video ? { id: 183, data: [
3654
+ { id: 247, data: ue },
3655
+ { id: 241, data: e }
3656
+ ] } : null,
3657
+ o(this, I).audio ? { id: 183, data: [
3658
+ { id: 247, data: Le },
3659
+ { id: 241, data: e }
3660
+ ] } : null
3661
+ ] });
3662
+ };
3663
+ xi = /* @__PURE__ */ new WeakSet();
3664
+ Rr = function() {
3665
+ if (!o(this, I).streaming) {
3666
+ let t = o(this, k).pos - o(this, k).dataOffsets.get(o(this, pt)), e = o(this, k).pos;
3667
+ o(this, k).seek(o(this, k).offsets.get(o(this, pt)) + 4), o(this, k).writeEBMLVarInt(t, Vs), o(this, k).seek(e);
3668
+ }
3669
+ if (o(this, k) instanceof qe && o(this, k).target.options.onCluster) {
3670
+ let { data: t, start: e } = o(this, k).getTrackedWrites();
3671
+ o(this, k).target.options.onCluster(t, e, o(this, He));
3672
+ }
3673
+ };
3674
+ Ce = /* @__PURE__ */ new WeakSet();
3675
+ di = function() {
3676
+ if (o(this, Ue))
3677
+ throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
3678
+ };
3679
+ new TextEncoder();
3680
+ async function co(t, e = {}) {
3681
+ if (!t.frames.length) throw new Error("[p5.export] encodeGIF: no frames to encode");
3682
+ const i = ls(), r = Math.round(1e3 / t.fps), s = e.maxColors ?? 256, n = t.frames.length;
3683
+ for (let a = 0; a < n; a++) {
3684
+ const l = t.frames[a], u = os(l, s), g = hs(l, u);
3685
+ i.writeFrame(g, t.width, t.height, { palette: u, delay: r }), e.onProgress && e.onProgress((a + 1) / n), (a & 15) === 15 && await new Promise((v) => setTimeout(v, 0));
3686
+ }
3687
+ return i.finish(), new Blob([i.bytes()], { type: "image/gif" });
3688
+ }
3689
+ function fo() {
3690
+ return typeof window < "u" && typeof window.VideoEncoder == "function" && typeof window.VideoFrame == "function";
3691
+ }
3692
+ const uo = {
3693
+ mp4: [
3694
+ "avc1.640028",
3695
+ // H.264 High @ 4.0 — most modern devices
3696
+ "avc1.4d0028",
3697
+ // H.264 Main @ 4.0
3698
+ "avc1.42001f",
3699
+ // H.264 Baseline 3.1 — broadest compat
3700
+ "av01.0.04M.08"
3701
+ // AV1 fallback
3702
+ ],
3703
+ webm: [
3704
+ "vp09.00.10.08",
3705
+ // VP9 Profile 0
3706
+ "vp8",
3707
+ "av01.0.04M.08"
3708
+ ]
3709
+ }, po = { avc1: "avc", av01: "av1", hvc1: "hevc", hev1: "hevc" }, mo = { vp09: "V_VP9", vp9: "V_VP9", vp8: "V_VP8", av01: "V_AV1" };
3710
+ function wo(t, e) {
3711
+ const i = e.split(".")[0].toLowerCase();
3712
+ return (t === "mp4" ? po : mo)[i] || (t === "mp4" ? "avc" : "V_VP9");
3713
+ }
3714
+ async function go(t, { width: e, height: i, fps: r, bitrate: s }) {
3715
+ for (const n of uo[t] || [])
3716
+ for (const a of [{ hardwareAcceleration: "prefer-hardware" }, {}])
3717
+ try {
3718
+ const l = await VideoEncoder.isConfigSupported({
3719
+ codec: n,
3720
+ width: e,
3721
+ height: i,
3722
+ bitrate: s,
3723
+ framerate: r,
3724
+ ...a
3725
+ });
3726
+ if (l && l.supported) return n;
3727
+ } catch {
3728
+ }
3729
+ return null;
3730
+ }
3731
+ async function vo(t, e) {
3732
+ const i = e.format === "mp4" ? "mp4" : "webm", r = t.width, s = t.height, n = t.fps, a = e.bitsPerSecond ?? Math.min(4e7, Math.max(15e5, Math.round(r * s * n * 0.2))), l = await go(i, { width: r, height: s, fps: n, bitrate: a });
3733
+ if (!l)
3734
+ throw new Error(`[p5.export] WebCodecs: no supported ${i.toUpperCase()} codec for ${r}×${s} @ ${n}fps`);
3735
+ const u = i === "mp4" ? new ws() : new Ms(), g = wo(i, l), v = i === "mp4" ? new Ja({
3736
+ target: u,
3737
+ video: { codec: g, width: r, height: s, frameRate: n },
3738
+ fastStart: "in-memory"
3739
+ }) : new lo({
3740
+ target: u,
3741
+ video: { codec: g, width: r, height: s, frameRate: n }
3742
+ });
3743
+ let p = null;
3744
+ const h = new VideoEncoder({
3745
+ output: (M, $) => v.addVideoChunk(M, $),
3746
+ error: (M) => {
3747
+ p = p || M;
3748
+ }
3749
+ }), d = { codec: l, width: r, height: s, bitrate: a, framerate: n };
3750
+ l.startsWith("avc1") && (d.avc = { format: "avc" });
3751
+ const f = [
3752
+ { ...d, hardwareAcceleration: "prefer-hardware" },
3753
+ { ...d }
3754
+ // no hint at all
3755
+ ];
3756
+ let m = null;
3757
+ for (const M of f)
3758
+ try {
3759
+ h.configure(M), m = M;
3760
+ break;
3761
+ } catch {
3762
+ }
3763
+ if (!m)
3764
+ throw new Error(`[p5.export] could not configure VideoEncoder for ${l}`);
3765
+ const w = 1e6 / n, y = t.frames.length, C = Math.max(1, Math.round(n * 2)), x = 16;
3766
+ for (let M = 0; M < y; M++) {
3767
+ if (p) throw p;
3768
+ for (; h.encodeQueueSize > x; )
3769
+ if (await new Promise((B) => setTimeout(B, 0)), p) throw p;
3770
+ const $ = new VideoFrame(t.frames[M], {
3771
+ format: "RGBA",
3772
+ codedWidth: r,
3773
+ codedHeight: s,
3774
+ timestamp: Math.round(M * w),
3775
+ duration: Math.round(w)
3776
+ });
3777
+ h.encode($, { keyFrame: M % C === 0 }), $.close(), e.onProgress && e.onProgress((M + 1) / y), (M & 31) === 31 && await new Promise((B) => setTimeout(B, 0));
3778
+ }
3779
+ if (await h.flush(), p) throw p;
3780
+ v.finalize();
3781
+ const _ = new Blob([u.buffer], {
3782
+ type: i === "mp4" ? "video/mp4" : "video/webm"
3783
+ });
3784
+ return _.__ext = i, _;
3785
+ }
3786
+ const Ke = {
3787
+ webm: ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"],
3788
+ mp4: ["video/mp4;codecs=avc1", "video/mp4;codecs=h264", "video/mp4"]
3789
+ };
3790
+ function yo(t) {
3791
+ const e = t === "mp4" ? [...Ke.mp4, ...Ke.webm] : [...Ke.webm, ...Ke.mp4];
3792
+ for (const i of e)
3793
+ if (typeof MediaRecorder < "u" && MediaRecorder.isTypeSupported(i))
3794
+ return { mime: i, ext: i.startsWith("video/mp4") ? "mp4" : "webm" };
3795
+ return null;
3796
+ }
3797
+ function bo(t, e) {
3798
+ return new Promise((i, r) => {
3799
+ const s = e.format || "webm", n = yo(s);
3800
+ if (!n) return r(new Error("[p5.export] MediaRecorder fallback: no supported mime"));
3801
+ s === "mp4" && n.ext !== "mp4" && console.warn("[p5.export] MP4 unsupported here — falling back to WebM.");
3802
+ const a = document.createElement("canvas");
3803
+ a.width = t.width, a.height = t.height;
3804
+ const l = a.getContext("2d"), u = a.captureStream(t.fps), g = { mimeType: n.mime };
3805
+ e.bitsPerSecond && (g.videoBitsPerSecond = e.bitsPerSecond);
3806
+ const v = new MediaRecorder(u, g), p = [];
3807
+ v.ondataavailable = (m) => {
3808
+ m.data && m.data.size && p.push(m.data);
3809
+ }, v.onerror = (m) => r(m.error || new Error("MediaRecorder error")), v.onstop = () => {
3810
+ u.getTracks().forEach((w) => w.stop());
3811
+ const m = new Blob(p, { type: n.mime });
3812
+ m.__ext = n.ext, i(m);
3813
+ }, l.putImageData(new ImageData(t.frames[0], t.width, t.height), 0, 0), v.start();
3814
+ const h = 1e3 / t.fps;
3815
+ let d = 1;
3816
+ const f = () => {
3817
+ if (d >= t.frames.length) {
3818
+ setTimeout(() => v.stop(), 100);
3819
+ return;
3820
+ }
3821
+ l.putImageData(new ImageData(t.frames[d], t.width, t.height), 0, 0), e.onProgress && e.onProgress((d + 1) / t.frames.length), d++, setTimeout(f, h);
3822
+ };
3823
+ setTimeout(f, h);
3824
+ });
3825
+ }
3826
+ async function _o(t, e = {}) {
3827
+ if (!t.frames.length) throw new Error("[p5.export] encodeVideo: no frames to encode");
3828
+ if (fo()) {
3829
+ const i = performance.now();
3830
+ try {
3831
+ const r = await vo(t, e), s = performance.now() - i | 0;
3832
+ return console.info(`[p5.export] WebCodecs encoded ${t.frames.length} frames in ${s}ms (${t.frames.length / (s / 1e3) | 0} fps).`), r;
3833
+ } catch (r) {
3834
+ console.warn(
3835
+ "[p5.export] WebCodecs encode failed; falling back to MediaRecorder (real-time, much slower). Cause:",
3836
+ r
3837
+ );
3838
+ }
3839
+ } else
3840
+ console.info("[p5.export] WebCodecs not available in this browser; using MediaRecorder (real-time).");
3841
+ return bo(t, e);
3842
+ }
3843
+ async function xo(t, e = {}) {
3844
+ if (!t || !t.frames.length)
3845
+ throw new Error("[p5.export] encodeAnimatedWebP: buffer has no frames");
3846
+ const { width: i, height: r, fps: s, frames: n } = t, a = Io(e.quality ?? 0.85), l = Math.max(0, e.loop ?? 0), u = Math.max(1, Math.round(1e3 / (s || 30)));
3847
+ await So(i, r);
3848
+ const g = document.createElement("canvas");
3849
+ g.width = i, g.height = r;
3850
+ const v = g.getContext("2d"), p = v.createImageData(i, r), h = [];
3851
+ for (let m = 0; m < n.length; m++) {
3852
+ p.data.set(n[m]), v.putImageData(p, 0, 0);
3853
+ const w = await Zs(g, a), y = new Uint8Array(await w.arrayBuffer());
3854
+ h.push(Co(y)), e.onProgress && e.onProgress((m + 1) / n.length);
3855
+ }
3856
+ const d = Ao([
3857
+ Bi("VP8X", Eo(i, r)),
3858
+ Bi("ANIM", To(l)),
3859
+ ...h.map((m) => Bi("ANMF", ko(i, r, u, m)))
3860
+ ]), f = new Uint8Array(12 + d.length);
3861
+ return rr(f, 0, "RIFF"), Qs(f, 4, 4 + d.length), rr(f, 8, "WEBP"), f.set(d, 12), new Blob([f], { type: "image/webp" });
3862
+ }
3863
+ async function So(t, e) {
3864
+ const i = document.createElement("canvas");
3865
+ i.width = Math.min(8, t), i.height = Math.min(8, e);
3866
+ const r = await Zs(i, 0.9);
3867
+ if (!r || r.type !== "image/webp")
3868
+ throw new Error(
3869
+ "[p5.export] This browser doesn't encode WebP from canvas — animated WebP export is unavailable. Use MP4 or WebM instead, or try the latest Chrome/Firefox/Safari."
3870
+ );
3871
+ }
3872
+ function Zs(t, e) {
3873
+ return new Promise((i, r) => {
3874
+ t.toBlob(
3875
+ (s) => s ? i(s) : r(new Error("canvas.toBlob returned null")),
3876
+ "image/webp",
3877
+ e
3878
+ );
3879
+ });
3880
+ }
3881
+ function Co(t) {
3882
+ let e = 12;
3883
+ for (; e + 8 <= t.length; ) {
3884
+ const i = String.fromCharCode(t[e], t[e + 1], t[e + 2], t[e + 3]), r = Po(t, e + 4), s = r + (r & 1);
3885
+ if (i === "VP8 " || i === "VP8L")
3886
+ return t.slice(e, e + 8 + s);
3887
+ e += 8 + s;
3888
+ }
3889
+ throw new Error("[p5.export] no VP8/VP8L chunk found in encoded WebP frame");
3890
+ }
3891
+ function Eo(t, e) {
3892
+ const i = new Uint8Array(10);
3893
+ return i[0] = 2, We(i, 4, t - 1), We(i, 7, e - 1), i;
3894
+ }
3895
+ function To(t) {
3896
+ const e = new Uint8Array(6);
3897
+ return Mo(e, 4, t), e;
3898
+ }
3899
+ function ko(t, e, i, r) {
3900
+ const s = new Uint8Array(16);
3901
+ We(s, 6, t - 1), We(s, 9, e - 1), We(s, 12, i), s[15] = 0;
3902
+ const n = new Uint8Array(s.length + r.length);
3903
+ return n.set(s, 0), n.set(r, s.length), n;
3904
+ }
3905
+ function Bi(t, e) {
3906
+ const i = e.length & 1, r = new Uint8Array(8 + e.length + i);
3907
+ return rr(r, 0, t), Qs(r, 4, e.length), r.set(e, 8), r;
3908
+ }
3909
+ function Ao(t) {
3910
+ let e = 0;
3911
+ for (const s of t) e += s.length;
3912
+ const i = new Uint8Array(e);
3913
+ let r = 0;
3914
+ for (const s of t)
3915
+ i.set(s, r), r += s.length;
3916
+ return i;
3917
+ }
3918
+ function rr(t, e, i) {
3919
+ for (let r = 0; r < i.length; r++) t[e + r] = i.charCodeAt(r);
3920
+ }
3921
+ function Mo(t, e, i) {
3922
+ t[e] = i & 255, t[e + 1] = i >> 8 & 255;
3923
+ }
3924
+ function We(t, e, i) {
3925
+ t[e] = i & 255, t[e + 1] = i >> 8 & 255, t[e + 2] = i >> 16 & 255;
3926
+ }
3927
+ function Qs(t, e, i) {
3928
+ t[e] = i & 255, t[e + 1] = i >> 8 & 255, t[e + 2] = i >> 16 & 255, t[e + 3] = i >> 24 & 255;
3929
+ }
3930
+ function Po(t, e) {
3931
+ return t[e] | t[e + 1] << 8 | t[e + 2] << 16 | t[e + 3] << 24 >>> 0;
3932
+ }
3933
+ function Io(t) {
3934
+ return Math.max(0, Math.min(1, t));
3935
+ }
3936
+ const Ze = {
3937
+ webm: ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"],
3938
+ mp4: ["video/mp4;codecs=avc1", "video/mp4;codecs=h264", "video/mp4"]
3939
+ };
3940
+ function Ro(t) {
3941
+ const e = t === "mp4" ? [...Ze.mp4, ...Ze.webm] : [...Ze.webm, ...Ze.mp4];
3942
+ for (const i of e)
3943
+ if (typeof MediaRecorder < "u" && MediaRecorder.isTypeSupported(i))
3944
+ return { mime: i, ext: i.startsWith("video/mp4") ? "mp4" : "webm" };
3945
+ return null;
3946
+ }
3947
+ class Bo {
3948
+ /**
3949
+ * @param {object} opts
3950
+ * @param {HTMLCanvasElement} opts.canvas
3951
+ * @param {'webm'|'mp4'} [opts.format='webm']
3952
+ * @param {number} [opts.fps=60]
3953
+ * @param {number} [opts.bitsPerSecond]
3954
+ * @param {number} [opts.duration] seconds; auto-stop when reached
3955
+ * @param {string} [opts.filename]
3956
+ */
3957
+ constructor(e) {
3958
+ const i = Ro(e.format || "webm");
3959
+ if (!i) throw new Error("[p5.export] no supported MediaRecorder mime type found");
3960
+ this.ext = i.ext, e.format === "mp4" && this.ext !== "mp4" && console.warn("[p5.export] MP4 not supported by this browser — falling back to WebM"), this.stream = e.canvas.captureStream(e.fps || 60);
3961
+ const r = { mimeType: i.mime };
3962
+ e.bitsPerSecond && (r.videoBitsPerSecond = e.bitsPerSecond), this.recorder = new MediaRecorder(this.stream, r), this.chunks = [], this.recorder.ondataavailable = (s) => {
3963
+ s.data && s.data.size && this.chunks.push(s.data);
3964
+ }, this.filename = e.filename, this.duration = e.duration, this._mime = i.mime, this._stopPromise = null;
3965
+ }
3966
+ start() {
3967
+ this.recorder.start(), this.duration && setTimeout(() => this.stop(), this.duration * 1e3);
3968
+ }
3969
+ /** Stop the recorder and resolve with a downloaded Blob. */
3970
+ stop() {
3971
+ return this._stopPromise ? this._stopPromise : (this._stopPromise = new Promise((e) => {
3972
+ this.recorder.onstop = () => {
3973
+ const i = new Blob(this.chunks, { type: this._mime }), r = this.filename ? St(this.filename, this.ext) : xt(this.ext);
3974
+ _t(i, r), this.stream.getTracks().forEach((s) => s.stop()), e(i);
3975
+ }, this.recorder.state !== "inactive" && this.recorder.stop();
3976
+ }), this._stopPromise);
3977
+ }
3978
+ get state() {
3979
+ return this.recorder.state;
3980
+ }
3981
+ }
3982
+ function Fo(t, e, i) {
3983
+ if (e.recordVideo = function(r = {}) {
3984
+ const s = Tt(this);
3985
+ if (!s) throw new Error("[p5.export] recordVideo: no canvas found");
3986
+ if (this._p5ExportVideo && this._p5ExportVideo.state === "recording")
3987
+ throw new Error("[p5.export] a video recording is already in progress");
3988
+ const n = new Bo({ canvas: s, ...r });
3989
+ return n.start(), this._p5ExportVideo = n, n;
3990
+ }, e.recordWebM = function(r = {}) {
3991
+ return e.recordVideo.call(this, { ...r, format: "webm" });
3992
+ }, e.recordMP4 = function(r = {}) {
3993
+ return e.recordVideo.call(this, { ...r, format: "mp4" });
3994
+ }, e.stopVideo = function() {
3995
+ const r = this._p5ExportVideo;
3996
+ return r ? (this._p5ExportVideo = null, r.stop()) : null;
3997
+ }, e.createVideoBuffer = function(r = {}) {
3998
+ const s = Tt(this);
3999
+ if (!s) throw new Error("[p5.export] createVideoBuffer: no canvas found");
4000
+ if (this._p5ExportBuffer && this._p5ExportBuffer.recording)
4001
+ throw new Error("[p5.export] a video buffer is already recording");
4002
+ const n = this, a = r.scale, l = typeof n.pixelDensity == "function" ? n.pixelDensity() : 1, u = a && a > 0 && a !== l;
4003
+ u && (n.pixelDensity(a), typeof n.redraw == "function" && n.redraw());
4004
+ const g = new Nn({ canvas: s, ...r }), v = g.stop.bind(g);
4005
+ let p = !u;
4006
+ return g.stop = function() {
4007
+ v(), p || (p = !0, n.pixelDensity(l), typeof n.redraw == "function" && n.redraw());
4008
+ }, g.start(), this._p5ExportBuffer = g, g;
4009
+ }, e.stopVideoBuffer = function() {
4010
+ const r = this._p5ExportBuffer;
4011
+ return r && r.stop(), r || null;
4012
+ }, e.exportVideoBuffer = async function(r, s = {}) {
4013
+ if (!r || !r.frames.length)
4014
+ throw new Error("[p5.export] exportVideoBuffer: buffer has no frames");
4015
+ const n = (s.format || "webm").toLowerCase();
4016
+ let a, l;
4017
+ if (n === "gif")
4018
+ a = await co(r, s), l = "gif";
4019
+ else if (n === "webp")
4020
+ a = await xo(r, s), l = "webp";
4021
+ else if (n === "webm" || n === "mp4")
4022
+ a = await _o(r, { ...s, format: n }), l = a.__ext || (n === "mp4" ? "mp4" : "webm");
4023
+ else
4024
+ throw new Error(`[p5.export] unsupported video format: ${n}`);
4025
+ const u = s.filename ? St(s.filename, l) : xt(l);
4026
+ return _t(a, u), a;
4027
+ }, i && typeof i == "object") {
4028
+ const r = i.postdraw;
4029
+ i.postdraw = function() {
4030
+ typeof r == "function" && r.call(this);
4031
+ const s = this._p5ExportBuffer;
4032
+ s && s.recording && s.tick();
4033
+ };
4034
+ }
4035
+ }
4036
+ function qr(t, e) {
4037
+ return e && Array.isArray(e.vertices) && Array.isArray(e.faces) ? e : typeof e == "function" && typeof t.buildGeometry == "function" ? t.buildGeometry(e) : null;
4038
+ }
4039
+ function Uo(t, e) {
4040
+ e.saveSTL = function(i, r, s = {}) {
4041
+ const n = qr(this, i);
4042
+ if (!n || typeof n.saveStl != "function") {
4043
+ const l = Di(this) ? "Pass a p5.Geometry (from buildGeometry / loadModel) or a buildGeometry-style callback." : "STL is a 3D format; this sketch is P2D. Use a WEBGL renderer (createCanvas(w, h, WEBGL)) and pass a p5.Geometry.";
4044
+ throw new Error("[p5.export] saveSTL: no exportable geometry. " + l);
4045
+ }
4046
+ const a = r || "sketch.stl";
4047
+ n.saveStl(a, { binary: !!s.binary });
4048
+ }, e.saveOBJ = function(i, r) {
4049
+ const s = qr(this, i);
4050
+ if (!s || typeof s.saveObj != "function") {
4051
+ const a = Di(this) ? "Pass a p5.Geometry (from buildGeometry / loadModel) or a buildGeometry-style callback." : "OBJ is a 3D format; this sketch is P2D. Use a WEBGL renderer and pass a p5.Geometry.";
4052
+ throw new Error("[p5.export] saveOBJ: no exportable geometry. " + a);
4053
+ }
4054
+ const n = r || "sketch.obj";
4055
+ s.saveObj(n);
4056
+ };
4057
+ }
4058
+ const Do = ".p5export-panel{position:fixed;top:16px;right:16px;z-index:99999;width:240px;font:12px ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:#1c1d20;background:#fff;border:1px solid #ebebee;border-radius:8px;box-shadow:0 4px 16px -6px #14161c14;-webkit-user-select:none;user-select:none;overflow:hidden}.p5export-panel *,.p5export-panel *:before,.p5export-panel *:after{box-sizing:border-box}.p5export-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;cursor:grab}.p5export-title{font-weight:500}.p5export-toggle{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;border:0;cursor:pointer;color:#7a7c82;font:inherit;font-size:14px;padding:0 4px}.p5export-tabs{display:flex;gap:16px;padding:0 12px;border-bottom:1px solid #ebebee}.p5export-tab{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;border:0;border-bottom:1px solid transparent;margin-bottom:-1px;padding:6px 0;color:#7a7c82;font:inherit;cursor:pointer}.p5export-tab.is-active{color:#1c1d20;border-bottom-color:#1c1d20}.p5export-body{padding:12px}.p5export-panel.is-collapsed .p5export-body,.p5export-panel.is-collapsed .p5export-tabs{display:none}.p5export-view:not([hidden]){display:flex;flex-direction:column;gap:8px}.p5export-row{display:grid;grid-template-columns:60px 1fr;align-items:center;gap:8px}.p5export-row label{color:#7a7c82}.p5export-input,.p5export-select{width:100%;padding:6px 8px;border:1px solid #ebebee;border-radius:4px;background:#fff;font:inherit;color:inherit}.p5export-input::placeholder{color:#7a7c82}.p5export-select{cursor:pointer}.p5export-btn{padding:8px;border:0;border-radius:4px;background:#1c1d20;color:#fff;font:inherit;cursor:pointer}.p5export-btn.is-ghost{background:transparent;color:#1c1d20;border:1px solid #ebebee}.p5export-btn.is-danger{background:#b9322a}.p5export-btn:disabled{opacity:.35;cursor:not-allowed}.p5export-status{color:#7a7c82}.p5export-status.is-error{color:#b9322a}.p5export-status[hidden]{display:none}.p5export-preview:not([hidden]){display:flex;flex-direction:column;gap:6px}.p5export-preview-canvas{display:block;width:100%;border:1px solid #ebebee;border-radius:4px;image-rendering:pixelated}.p5export-preview-controls{display:flex;align-items:center;gap:8px;padding:6px 0}.p5export-play{width:11px;height:11px;border:0;background:transparent;color:#1c1d20;cursor:pointer;padding:0;opacity:.7}.p5export-play:hover{opacity:1}.p5export-play svg{width:100%;height:100%;display:block}.p5export-timeline{flex:1;height:2px;-moz-appearance:none;appearance:none;-webkit-appearance:none;background:#ebebee;border-radius:999px;cursor:pointer;outline:0}.p5export-timeline::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:8px;height:8px;border:0;border-radius:50%;background:#1c1d20;cursor:grab}.p5export-timeline::-moz-range-thumb{width:8px;height:8px;border:0;border-radius:50%;background:#1c1d20;cursor:grab}.p5export-time{color:#7a7c82;font-variant-numeric:tabular-nums}";
4059
+ let Hr = !1;
4060
+ function Wo() {
4061
+ if (Hr || typeof document > "u") return;
4062
+ Hr = !0;
4063
+ const t = document.createElement("style");
4064
+ t.setAttribute("data-p5-export", ""), t.textContent = Do, document.head.appendChild(t);
4065
+ }
4066
+ const Xr = [
4067
+ { value: "png", label: "PNG (image)" },
4068
+ { value: "jpg", label: "JPG (image)" },
4069
+ { value: "webp", label: "WebP (image)" },
4070
+ { value: "svg", label: "SVG (vector)" },
4071
+ { value: "pdf", label: "PDF (vector)" }
4072
+ ], zo = [
4073
+ { value: "stl", label: "STL (3D)" },
4074
+ { value: "obj", label: "OBJ (3D)" }
4075
+ ], Vo = [
4076
+ { value: "webm", label: "WebM (video)" },
4077
+ { value: "mp4", label: "MP4 (video)" },
4078
+ { value: "webp", label: "WebP (animation)" },
4079
+ { value: "gif", label: "GIF (animation)" }
4080
+ ], Lo = [
4081
+ { value: "1", label: "1×" },
4082
+ { value: "2", label: "2×" },
4083
+ { value: "3", label: "3×" },
4084
+ { value: "4", label: "4×" }
4085
+ ], Yr = /* @__PURE__ */ new Set(["png", "jpg", "webp", "pdf"]), sr = '<path d="M2 1.2 L9 5 L2 8.8 Z" fill="currentColor"/>', Oo = '<rect x="2" y="1.5" width="2" height="7" rx="0.5" fill="currentColor"/><rect x="6" y="1.5" width="2" height="7" rx="0.5" fill="currentColor"/>', Go = `
4086
+ <div class="p5export-panel">
4087
+ <div class="p5export-header" data-el="header">
4088
+ <span class="p5export-title" data-el="title">p5.export</span>
4089
+ <button class="p5export-toggle" data-action="toggleCollapsed" title="Collapse">−</button>
4090
+ </div>
4091
+
4092
+ <div class="p5export-tabs">
4093
+ <button class="p5export-tab is-active" data-tab="image">Image</button>
4094
+ <button class="p5export-tab" data-tab="video">Video</button>
4095
+ </div>
4096
+
4097
+ <div class="p5export-body">
4098
+ <!-- IMAGE TAB ─────────────────────────────────────────────────── -->
4099
+ <div class="p5export-view" data-view="image">
4100
+ <div class="p5export-row">
4101
+ <label>Format</label>
4102
+ <select class="p5export-select" data-el="imageFormat"></select>
4103
+ </div>
4104
+ <div class="p5export-row" data-el="imageScaleRow">
4105
+ <label>Scale</label>
4106
+ <select class="p5export-select" data-el="imageScale"></select>
4107
+ </div>
4108
+ <div class="p5export-row">
4109
+ <label>Name</label>
4110
+ <input class="p5export-input" type="text" placeholder="filename" data-el="imageFilename">
4111
+ </div>
4112
+ <button class="p5export-btn" data-action="saveImage">Export</button>
4113
+ <div class="p5export-status" data-el="imageStatus" hidden></div>
4114
+ </div>
4115
+
4116
+ <!-- VIDEO TAB ─────────────────────────────────────────────────── -->
4117
+ <div class="p5export-view" data-view="video" hidden>
4118
+ <div class="p5export-row">
4119
+ <label>Format</label>
4120
+ <select class="p5export-select" data-el="videoFormat"></select>
4121
+ </div>
4122
+ <div class="p5export-row">
4123
+ <label>Duration</label>
4124
+ <input class="p5export-input" type="number" min="0.5" step="0.5" value="3" data-el="videoDuration">
4125
+ </div>
4126
+ <div class="p5export-row">
4127
+ <label>Name</label>
4128
+ <input class="p5export-input" type="text" placeholder="filename" data-el="videoFilename">
4129
+ </div>
4130
+ <div class="p5export-preview" data-el="previewWrap" hidden>
4131
+ <canvas class="p5export-preview-canvas" data-el="previewCanvas"></canvas>
4132
+ <div class="p5export-preview-controls">
4133
+ <button class="p5export-play" data-action="togglePreview" title="Play / pause">
4134
+ <svg viewBox="0 0 10 10" data-el="playIcon">${sr}</svg>
4135
+ </button>
4136
+ <input class="p5export-timeline" type="range" min="0" max="0" step="1" value="0" data-el="timeline">
4137
+ <span class="p5export-time" data-el="timeLabel">0:00</span>
4138
+ </div>
4139
+ </div>
4140
+ <button class="p5export-btn" data-action="videoPrimary" data-el="videoPrimaryBtn">Record</button>
4141
+ <button class="p5export-btn is-ghost" data-action="resetVideo" data-el="rerecordBtn" hidden>Re-record</button>
4142
+ <div class="p5export-status" data-el="recordedStatus" hidden></div>
4143
+ </div>
4144
+ </div>
4145
+ </div>`.trim();
4146
+ class No {
4147
+ constructor(e, i = {}) {
4148
+ Wo(), this.p = e, this.opts = i, this.tab = "image", this.videoState = "idle", this.buffer = null, this._statusTimer = null, this.el = document.createRange().createContextualFragment(Go).firstElementChild;
4149
+ for (const r of this.el.querySelectorAll("[data-el]"))
4150
+ this[r.dataset.el] = r;
4151
+ for (const r of this.el.querySelectorAll("[data-action]"))
4152
+ r.addEventListener("click", () => {
4153
+ const s = this[`_${r.dataset.action}`];
4154
+ typeof s == "function" && s.call(this);
4155
+ });
4156
+ for (const r of this.el.querySelectorAll("[data-tab]"))
4157
+ r.addEventListener("click", () => this._switchTab(r.dataset.tab));
4158
+ this._populateOptions(), this._wireExtras(), this.opts.title && (this.title.textContent = this.opts.title), this.opts.collapsed && this.el.classList.add("is-collapsed"), (i.parent || document.body).appendChild(this.el), this._wireDrag();
4159
+ }
4160
+ // ─── Bootstrapping helpers ─────────────────────────────────────────────
4161
+ _populateOptions() {
4162
+ const e = Di(this.p) ? [...Xr, ...zo] : Xr;
4163
+ this.imageFormat.innerHTML = Fi(e), this.imageScale.innerHTML = Fi(Lo), this.videoFormat.innerHTML = Fi(Vo), this.opts.filename && (this.imageFilename.value = this.opts.filename, this.videoFilename.value = this.opts.filename);
4164
+ }
4165
+ _wireExtras() {
4166
+ this.imageFormat.addEventListener("change", () => this._refreshImageScaleEnabled()), this._refreshImageScaleEnabled(), this.timeline.addEventListener("input", () => {
4167
+ this._pausePreview(), this._previewFrame = Number(this.timeline.value), this._renderPreviewFrame();
4168
+ });
4169
+ }
4170
+ _toggleCollapsed() {
4171
+ this.el.classList.toggle("is-collapsed");
4172
+ }
4173
+ _switchTab(e) {
4174
+ this.tab = e;
4175
+ for (const i of this.el.querySelectorAll("[data-tab]"))
4176
+ i.classList.toggle("is-active", i.dataset.tab === e);
4177
+ for (const i of this.el.querySelectorAll("[data-view]"))
4178
+ i.toggleAttribute("hidden", i.dataset.view !== e);
4179
+ }
4180
+ // ─── Image tab ─────────────────────────────────────────────────────────
4181
+ /** Scale only applies to raster formats; grey it out for SVG. */
4182
+ _refreshImageScaleEnabled() {
4183
+ const e = Yr.has(this.imageFormat.value);
4184
+ this.imageScale.disabled = !e, this.imageScaleRow.style.opacity = e ? "" : "0.45";
4185
+ }
4186
+ async _saveImage() {
4187
+ const e = this.imageFormat.value, i = this.imageFilename.value || void 0, r = Number(this.imageScale.value) || 1, s = Yr.has(e) ? { scale: r } : void 0, n = `${e.toUpperCase()}${s && r > 1 ? ` @ ${r}×` : ""}`;
4188
+ this._setStatus(this.imageStatus, `Saving ${n}…`);
4189
+ try {
4190
+ if (e === "png") await this.p.savePNG(i, s);
4191
+ else if (e === "jpg") await this.p.saveJPG(i, s);
4192
+ else if (e === "webp") await this.p.saveWebP(i, s);
4193
+ else if (e === "svg") this.p.saveSVG(i);
4194
+ else if (e === "pdf") await this.p.savePDF(i, s);
4195
+ else if (e === "stl" || e === "obj") {
4196
+ this._setStatus(
4197
+ this.imageStatus,
4198
+ `${e.toUpperCase()} needs a p5.Geometry — call saveSTL(myGeometry) from your sketch.`,
4199
+ "error"
4200
+ );
4201
+ return;
4202
+ }
4203
+ this._setStatus(this.imageStatus, `Saved ${n}.`, "", 2e3);
4204
+ } catch (a) {
4205
+ console.error(a), this._setStatus(this.imageStatus, `Error: ${a.message}`, "error");
4206
+ }
4207
+ }
4208
+ // ─── Video tab ─────────────────────────────────────────────────────────
4209
+ /** Cycle: idle → recording → recorded → encoding → recorded. */
4210
+ _videoPrimary() {
4211
+ if (this.videoState === "idle") return this._startRecording();
4212
+ if (this.videoState === "recording") return this._stopRecording();
4213
+ if (this.videoState === "recorded") return this._export(this.videoFormat.value);
4214
+ }
4215
+ _startRecording() {
4216
+ const e = Number(this.videoDuration.value) || void 0;
4217
+ try {
4218
+ this.buffer = this.p.createVideoBuffer({ duration: e, fps: 30, scale: 1 });
4219
+ } catch (r) {
4220
+ console.error(r), this._setStatus(this.recordedStatus, `Error: ${r.message}`, "error");
4221
+ return;
4222
+ }
4223
+ this.videoState = "recording", this._updateVideoState();
4224
+ const i = performance.now();
4225
+ this._statusTimer = setInterval(() => {
4226
+ const r = (performance.now() - i) / 1e3, s = e ? ` / ${e.toFixed(1)}s` : "";
4227
+ this._setStatus(
4228
+ this.recordedStatus,
4229
+ `Recording ${r.toFixed(1)}s${s} · ${this.buffer.framesRecorded} frames`
4230
+ ), this.buffer.recording || this._finishRecording();
4231
+ }, 100);
4232
+ }
4233
+ _stopRecording() {
4234
+ this.buffer && this.buffer.stop(), this._finishRecording();
4235
+ }
4236
+ _finishRecording() {
4237
+ clearInterval(this._statusTimer), this._statusTimer = null, this.buffer && (this.videoState = "recorded", this._setStatus(this.recordedStatus, ""), this._initPreview(), this._updateVideoState());
4238
+ }
4239
+ async _export(e) {
4240
+ if (!this.buffer) return;
4241
+ const i = this.videoFilename.value || void 0, r = this.videoState;
4242
+ this.videoState = "encoding", this._updateVideoState(), this._setStatus(this.recordedStatus, `Encoding ${e.toUpperCase()}…`);
4243
+ try {
4244
+ await this.p.exportVideoBuffer(this.buffer, {
4245
+ format: e,
4246
+ filename: i,
4247
+ onProgress: (s) => this._setStatus(
4248
+ this.recordedStatus,
4249
+ `Encoding ${e.toUpperCase()}… ${Math.round(s * 100)}%`
4250
+ )
4251
+ }), this._setStatus(this.recordedStatus, `Saved ${e.toUpperCase()}.`, "", 2e3);
4252
+ } catch (s) {
4253
+ console.error(s), this._setStatus(this.recordedStatus, `Error: ${s.message}`, "error");
4254
+ } finally {
4255
+ this.videoState = r, this._updateVideoState();
4256
+ }
4257
+ }
4258
+ _resetVideo() {
4259
+ this._pausePreview(), this.buffer && this.buffer.clear(), this.buffer = null, this._setStatus(this.recordedStatus, ""), this.videoState = "idle", this._updateVideoState();
4260
+ }
4261
+ /** Drive every video-tab visual difference from one place. */
4262
+ _updateVideoState() {
4263
+ const e = this.videoState, i = e === "recorded" || e === "encoding", r = e === "recording";
4264
+ this.videoFormat.disabled = r, this.videoDuration.disabled = r, this.videoFilename.disabled = r, this.previewWrap.toggleAttribute("hidden", !i), this.rerecordBtn.toggleAttribute("hidden", !i), this.videoPrimaryBtn.className = "p5export-btn" + (e === "recording" ? " is-danger" : ""), this.videoPrimaryBtn.textContent = e === "recording" ? "Stop" : i ? "Export" : "Record";
4265
+ const s = e === "encoding";
4266
+ this.videoPrimaryBtn.disabled = s, this.rerecordBtn.disabled = s;
4267
+ }
4268
+ // ─── Preview player ────────────────────────────────────────────────────
4269
+ _initPreview() {
4270
+ if (!this.buffer || !this.buffer.frames.length) return;
4271
+ const e = 320, i = this.buffer.width, r = this.buffer.height, s = Math.min(1, e / Math.max(i, r));
4272
+ this.previewCanvas.width = Math.max(1, Math.round(i * s)), this.previewCanvas.height = Math.max(1, Math.round(r * s)), this._previewCtx = this.previewCanvas.getContext("2d"), this._previewSrc = document.createElement("canvas"), this._previewSrc.width = i, this._previewSrc.height = r, this._previewSrcCtx = this._previewSrc.getContext("2d"), this._previewImageData = this._previewSrcCtx.createImageData(i, r), this._previewFrame = 0, this._previewPlaying = !1, this._previewRaf = null, this.timeline.min = "0", this.timeline.max = String(this.buffer.frames.length - 1), this.timeline.value = "0", this.playIcon.innerHTML = sr, this._renderPreviewFrame();
4273
+ }
4274
+ _renderPreviewFrame() {
4275
+ if (!this.buffer || !this._previewCtx) return;
4276
+ const e = Math.max(0, Math.min(this.buffer.frames.length - 1, this._previewFrame)), i = this.buffer.frames[e];
4277
+ if (!i) return;
4278
+ this._previewImageData.data.set(i), this._previewSrcCtx.putImageData(this._previewImageData, 0, 0), this._previewCtx.clearRect(0, 0, this.previewCanvas.width, this.previewCanvas.height), this._previewCtx.drawImage(
4279
+ this._previewSrc,
4280
+ 0,
4281
+ 0,
4282
+ this._previewSrc.width,
4283
+ this._previewSrc.height,
4284
+ 0,
4285
+ 0,
4286
+ this.previewCanvas.width,
4287
+ this.previewCanvas.height
4288
+ ), this.timeline.value = String(e);
4289
+ const r = this.buffer.fps || 30;
4290
+ this.timeLabel.textContent = `${(e / r).toFixed(1)}s`;
4291
+ }
4292
+ _togglePreview() {
4293
+ this.buffer && (this._previewPlaying ? this._pausePreview() : this._playPreview());
4294
+ }
4295
+ _playPreview() {
4296
+ if (!this.buffer || !this.buffer.frames.length) return;
4297
+ this._previewPlaying = !0, this.playIcon.innerHTML = Oo;
4298
+ const i = 1e3 / (this.buffer.fps || 30);
4299
+ let r = performance.now();
4300
+ const s = (n) => {
4301
+ if (!this._previewPlaying) return;
4302
+ const a = n - r;
4303
+ a >= i && (r = n - a % i, this._previewFrame++, this._previewFrame >= this.buffer.frames.length && (this._previewFrame = 0), this._renderPreviewFrame()), this._previewRaf = requestAnimationFrame(s);
4304
+ };
4305
+ this._previewRaf = requestAnimationFrame(s);
4306
+ }
4307
+ _pausePreview() {
4308
+ this._previewPlaying && (this._previewPlaying = !1, this._previewRaf && cancelAnimationFrame(this._previewRaf), this._previewRaf = null, this.playIcon.innerHTML = sr);
4309
+ }
4310
+ // ─── Status helper ─────────────────────────────────────────────────────
4311
+ /**
4312
+ * Update a status element. Empty message → element hidden (so it
4313
+ * doesn't reserve vertical space). `kind === 'error'` paints it red;
4314
+ * any other value clears existing modifier classes.
4315
+ */
4316
+ _setStatus(e, i, r = "", s = 0) {
4317
+ e.textContent = i || "", e.toggleAttribute("hidden", !i), e.classList.toggle("is-error", r === "error"), s && i && setTimeout(() => {
4318
+ e.textContent === i && this._setStatus(e, "");
4319
+ }, s);
4320
+ }
4321
+ // ─── Dragging ──────────────────────────────────────────────────────────
4322
+ _wireDrag() {
4323
+ let e = 0, i = 0, r = 0, s = 0, n = !1;
4324
+ const a = (u) => {
4325
+ n && (this.el.style.left = r + u.clientX - e + "px", this.el.style.top = s + u.clientY - i + "px");
4326
+ }, l = () => {
4327
+ n = !1, document.removeEventListener("mousemove", a);
4328
+ };
4329
+ this.header.addEventListener("mousedown", (u) => {
4330
+ if (u.target.closest(".p5export-toggle")) return;
4331
+ n = !0, e = u.clientX, i = u.clientY;
4332
+ const g = this.el.getBoundingClientRect();
4333
+ r = g.left, s = g.top, this.el.style.left = r + "px", this.el.style.top = s + "px", this.el.style.right = "auto", document.addEventListener("mousemove", a), document.addEventListener("mouseup", l, { once: !0 });
4334
+ });
4335
+ }
4336
+ destroy() {
4337
+ clearInterval(this._statusTimer), this._pausePreview(), this.buffer && this.buffer.clear(), this.el.remove();
4338
+ }
4339
+ }
4340
+ function Fi(t) {
4341
+ return t.map((e) => `<option value="${e.value}">${e.label}</option>`).join("");
4342
+ }
4343
+ function $o(t, e, i) {
4344
+ if (e.createExportGUI = function(r = {}) {
4345
+ if (this._p5ExportPanel)
4346
+ return Object.assign(this._p5ExportPanel.opts, r), this._p5ExportPanel;
4347
+ const s = new No(this, r);
4348
+ return this._p5ExportPanel = s, s;
4349
+ }, e.removeExportGUI = function() {
4350
+ this._p5ExportPanel && (this._p5ExportPanel.destroy(), this._p5ExportPanel = null);
4351
+ }, i && typeof i == "object") {
4352
+ const r = i.postsetup;
4353
+ i.postsetup = function() {
4354
+ typeof r == "function" && r.call(this), (typeof window < "u" && window.p5ExportConfig || {}).autoGUI !== !1 && (this._p5ExportPanel || this.createExportGUI());
4355
+ };
4356
+ }
4357
+ }
4358
+ function Br(t, e, i) {
4359
+ sn(t, e), Cn(t, e, i), kn(t, e), Gn(t, e, i), Fo(t, e, i), Uo(t, e), $o(t, e, i), jo(t), e.downloadBlob = function(r, s) {
4360
+ return _t(r, s);
4361
+ };
4362
+ }
4363
+ function jo(t) {
4364
+ const e = t && t.Graphics;
4365
+ if (!e || !e.prototype || e.prototype.__p5ExportGraphicsRandomPatched) return;
4366
+ const i = t.prototype;
4367
+ for (const r of ["random", "randomSeed", "noise", "noiseSeed", "randomGaussian"])
4368
+ typeof e.prototype[r] != "function" && typeof i[r] == "function" && (e.prototype[r] = function(...s) {
4369
+ const n = typeof window < "u" && window.p5 && window.p5.instance || this;
4370
+ return i[r].apply(n, s);
4371
+ });
4372
+ e.prototype.__p5ExportGraphicsRandomPatched = !0;
4373
+ }
4374
+ function tn(t) {
4375
+ if (!t || !t.prototype) return !1;
4376
+ if (t.prototype.__p5ExportInstalled) return !0;
4377
+ t.prototype.__p5ExportInstalled = !0;
4378
+ const e = {};
4379
+ Br(t, t.prototype, e);
4380
+ const i = (r, s) => typeof s == "function" && typeof t.prototype.registerMethod == "function" && t.prototype.registerMethod(r, s);
4381
+ return i("beforeSetup", e.presetup), i("afterSetup", e.postsetup), i("pre", e.predraw), i("post", e.postdraw), console.info("[p5.export] Registered against p5 1.x — vector SVG, image, GIF, video, PDF exports available. Use p5 2.0 for full feature parity."), !0;
4382
+ }
4383
+ function eh(t) {
4384
+ if (!t) throw new Error("[p5.export] register() called with no p5 constructor");
4385
+ if (typeof t.registerAddon == "function") {
4386
+ t.registerAddon(Br);
4387
+ return;
4388
+ }
4389
+ if (!tn(t))
4390
+ throw new Error("[p5.export] Could not register — no registerAddon and no prototype.registerMethod.");
4391
+ }
4392
+ function Ui() {
4393
+ return typeof window > "u" || !window.p5 ? !1 : window.p5.prototype && window.p5.prototype.__p5ExportInstalled || window.p5.__p5ExportAutoRegistered ? !0 : typeof window.p5.registerAddon == "function" ? (window.p5.registerAddon(Br), window.p5.__p5ExportAutoRegistered = !0, !0) : tn(window.p5);
4394
+ }
4395
+ if (typeof window < "u" && !Ui()) {
4396
+ const t = setInterval(() => {
4397
+ Ui() && clearInterval(t);
4398
+ }, 10);
4399
+ setTimeout(() => clearInterval(t), 5e3), window.addEventListener("p5Ready", Ui, { once: !0 });
4400
+ }
4401
+ export {
4402
+ Br as default,
4403
+ Br as p5ExportAddon,
4404
+ eh as register
4405
+ };
4406
+ //# sourceMappingURL=p5.export.js.map