@munusshih/p5.export 0.1.0-beta.5 → 0.1.0-beta.7

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.
@@ -1,4 +1,5 @@
1
- (function(kt,rt){typeof exports=="object"&&typeof module<"u"?rt(exports):typeof define=="function"&&define.amd?define(["exports"],rt):(kt=typeof globalThis<"u"?globalThis:kt||self,rt(kt.p5Export={}))})(this,function(kt){"use strict";function rt(t,e){const i=URL.createObjectURL(t),r=document.createElement("a");r.href=i,r.download=e,r.style.display="none",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),0)}function vt(t,e="sketch"){const i=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");return`${e}-${i}.${t}`}function yt(t,e){return t.toLowerCase().endsWith("."+e.toLowerCase())?t:`${t}.${e}`}function bt(t){return t?t instanceof HTMLCanvasElement?t:t.canvas instanceof HTMLCanvasElement?t.canvas:t.elt instanceof HTMLCanvasElement?t.elt:Ur():Ur()}function Ur(){const t=document.querySelector("canvas.p5Canvas");return t||document.querySelector("canvas")}function Mi(t){if(!t)return!1;const e=t._renderer;if(!e)return!1;const i=e.drawingContext;return!!(i&&typeof i.fillRect!="function"||e.GL)}const sn={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};async function Dr(t,e,i,r){const s=t&&t._p5ExportSVGRecorder;if(!s||!s.ops||s.ops.length===0)return null;const n=bt(t);if(!n)return null;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");p.width=g,p.height=v;const h=p.getContext("2d");if(!h)return null;const d=e/a,f=s.ops;for(let w=0;w<f.length;w++){const y=f[w];try{if(y[0]===0){const C=y[1];if(C==="setTransform"){const S=y[2];h.setTransform(S[0]*d,S[1]*d,S[2]*d,S[3]*d,S[4]*d,S[5]*d)}else h[C](...y[2])}else h[y[1]]=y[2]}catch{}}const m=sn[i]||"image/png";return new Promise((w,y)=>{p.toBlob(C=>C?w(C):y(new Error("[p5.export] toBlob returned null")),m,r)})}async function Wr(t,e,i){if(!e||e<=1)return i();const r=typeof t.pixelDensity=="function"?t.pixelDensity():1;if(e<=r)return i();const s=typeof t.isLooping=="function"?t.isLooping():!0;s&&typeof t.noLoop=="function"&&t.noLoop();try{return t.pixelDensity(e),typeof t.redraw=="function"&&await t.redraw(),await new Promise(n=>requestAnimationFrame(n)),await i()}finally{t.pixelDensity(r),typeof t.redraw=="function"&&await t.redraw(),s&&typeof t.loop=="function"&&t.loop()}}const nn={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};function Ii(t,e,i){const r=bt(t);if(!r)return Promise.reject(new Error("[p5.export] no canvas found"));const s=nn[e];return s?new Promise((n,a)=>{r.toBlob(l=>l?n(l):a(new Error("[p5.export] toBlob returned null")),s,i)}):Promise.reject(new Error(`[p5.export] unknown image format: ${e}`))}async function Je(t,e,i,r){if(!e||e<=1)return Ii(t,i,r);const s=typeof t.pixelDensity=="function"?t.pixelDensity():1;if(e<=s)return Ii(t,i,r);const n=await Dr(t,e,i,r);return n||Wr(t,e,()=>Ii(t,i,r))}function an(t,e){e.savePNG=async function(i,r={}){const s=await Je(this,r.scale,"png");return rt(s,i?yt(i,"png"):vt("png")),s},e.saveJPG=async function(i,r={}){const s=r.quality??.92,n=await Je(this,r.scale,"jpg",s);return rt(n,i?yt(i,"jpg"):vt("jpg")),n},e.saveJPEG=e.saveJPG,e.saveWebP=async function(i,r={}){const s=r.quality??.92,n=await Je(this,r.scale,"webp",s);return rt(n,i?yt(i,"webp"):vt("webp")),n},e.saveImage=async function(i,r,s={}){i=(i||"png").toLowerCase(),i==="jpeg"&&(i="jpg");const n=await Je(this,s.scale,i,s.quality);return rt(n,r?yt(r,i):vt(i)),n}}function on(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var zr={exports:{}};/*!!
1
+ /*! @munusshih/p5.export v0.1.0-beta.7 | Created by Munus Shih | MIT License | https://github.com/munusshih/p5.export */
2
+ (function(Mt,rt){typeof exports=="object"&&typeof module<"u"?rt(exports):typeof define=="function"&&define.amd?define(["exports"],rt):(Mt=typeof globalThis<"u"?globalThis:Mt||self,rt(Mt.p5Export={}))})(this,function(Mt){"use strict";function rt(t,e){const i=URL.createObjectURL(t),r=document.createElement("a");r.href=i,r.download=e,r.style.display="none",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),0)}function bt(t,e="sketch"){const i=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");return`${e}-${i}.${t}`}function _t(t,e){return t.toLowerCase().endsWith("."+e.toLowerCase())?t:`${t}.${e}`}function xt(t){return t?t instanceof HTMLCanvasElement?t:t.canvas instanceof HTMLCanvasElement?t.canvas:t.elt instanceof HTMLCanvasElement?t.elt:Vr():Vr()}function Vr(){const t=document.querySelector("canvas.p5Canvas");return t||document.querySelector("canvas")}function Fi(t){if(!t)return!1;const e=t._renderer;if(!e)return!1;const i=e.drawingContext;return!!(i&&typeof i.fillRect!="function"||e.GL)}const ds={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};async function Lr(t,e,i,r){const n=t&&t._p5ExportSVGRecorder;if(!n||!n.ops||n.ops.length===0)return null;const s=xt(t);if(!s)return null;const a=typeof t.pixelDensity=="function"?t.pixelDensity():1,l=Math.max(1,Math.round(s.width/a)),u=Math.max(1,Math.round(s.height/a)),m=l*e,v=u*e,p=document.createElement("canvas");p.width=m,p.height=v;const h=p.getContext("2d");if(!h)return null;const d=e/a,c=n.ops;for(let g=0;g<c.length;g++){const y=c[g];try{if(y[0]===0){const M=y[1];if(M==="setTransform"){const C=y[2];h.setTransform(C[0]*d,C[1]*d,C[2]*d,C[3]*d,C[4]*d,C[5]*d)}else h[M](...y[2])}else h[y[1]]=y[2]}catch{}}const w=ds[i]||"image/png";return new Promise((g,y)=>{p.toBlob(M=>M?g(M):y(new Error("[p5.export] toBlob returned null")),w,r)})}async function Gr(t,e,i){if(!e||e<=1)return i();const r=typeof t.pixelDensity=="function"?t.pixelDensity():1;if(e<=r)return i();const n=typeof t.isLooping=="function"?t.isLooping():!0;n&&typeof t.noLoop=="function"&&t.noLoop();try{return t.pixelDensity(e),typeof t.redraw=="function"&&await t.redraw(),await new Promise(s=>requestAnimationFrame(s)),await i()}finally{t.pixelDensity(r),typeof t.redraw=="function"&&await t.redraw(),n&&typeof t.loop=="function"&&t.loop()}}const cs={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};function Di(t,e,i){const r=xt(t);if(!r)return Promise.reject(new Error("[p5.export] no canvas found"));const n=cs[e];return n?new Promise((s,a)=>{r.toBlob(l=>l?s(l):a(new Error("[p5.export] toBlob returned null")),n,i)}):Promise.reject(new Error(`[p5.export] unknown image format: ${e}`))}async function ti(t,e,i,r){if(!e||e<=1)return Di(t,i,r);const n=typeof t.pixelDensity=="function"?t.pixelDensity():1;if(e<=n)return Di(t,i,r);const s=await Lr(t,e,i,r);return s||Gr(t,e,()=>Di(t,i,r))}function fs(t,e){e.savePNG=async function(i,r={}){const n=await ti(this,r.scale,"png");return rt(n,i?_t(i,"png"):bt("png")),n},e.saveJPG=async function(i,r={}){const n=r.quality??.92,s=await ti(this,r.scale,"jpg",n);return rt(s,i?_t(i,"jpg"):bt("jpg")),s},e.saveJPEG=e.saveJPG,e.saveWebP=async function(i,r={}){const n=r.quality??.92,s=await ti(this,r.scale,"webp",n);return rt(s,i?_t(i,"webp"):bt("webp")),s},e.saveImage=async function(i,r,n={}){i=(i||"png").toLowerCase(),i==="jpeg"&&(i="jpg");const s=await ti(this,n.scale,i,n.quality);return rt(s,r?_t(r,i):bt(i)),s}}function us(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Nr={exports:{}};/*!!
2
3
  * Canvas 2 Svg v1.0.15
3
4
  * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document.
4
5
  *
@@ -9,9 +10,9 @@
9
10
  * Kerry Liu
10
11
  *
11
12
  * Copyright (c) 2014 Gliffy Inc.
12
- */(function(t){(function(){var e,i,r,s,n;function a(h,d){var f=Object.keys(d),m;for(m=0;m<f.length;m++)h=h.replace(new RegExp("\\{"+f[m]+"\\}","gi"),d[f[m]]);return h}function l(h){var d,f,m;if(!h)throw new Error("cannot create a random attribute name for an undefined object");d="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",f="";do for(f="",m=0;m<12;m++)f+=d[Math.floor(Math.random()*d.length)];while(h[f]);return f}function u(h,d){var f,m,w={},y;for(h=h.split(","),d=d||10,f=0;f<h.length;f+=2)m="&"+h[f+1]+";",y=parseInt(h[f],d),w[m]="&#"+y+";";return w["\\xa0"]="&#160;",w}function g(h){var d={left:"start",right:"end",center:"middle",start:"start",end:"end"};return d[h]||d.start}function v(h){var d={alphabetic:"alphabetic",hanging:"hanging",top:"text-before-edge",bottom:"text-after-edge",middle:"central"};return d[h]||d.alphabetic}n=u("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",32),e={strokeStyle:{svgAttr:"stroke",canvas:"#000000",svg:"none",apply:"stroke"},fillStyle:{svgAttr:"fill",canvas:"#000000",svg:null,apply:"fill"},lineCap:{svgAttr:"stroke-linecap",canvas:"butt",svg:"butt",apply:"stroke"},lineJoin:{svgAttr:"stroke-linejoin",canvas:"miter",svg:"miter",apply:"stroke"},miterLimit:{svgAttr:"stroke-miterlimit",canvas:10,svg:4,apply:"stroke"},lineWidth:{svgAttr:"stroke-width",canvas:1,svg:1,apply:"stroke"},globalAlpha:{svgAttr:"opacity",canvas:1,svg:1,apply:"fill stroke"},font:{canvas:"10px sans-serif"},shadowColor:{canvas:"#000000"},shadowOffsetX:{canvas:0},shadowOffsetY:{canvas:0},shadowBlur:{canvas:0},textAlign:{canvas:"start"},textBaseline:{canvas:"alphabetic"}},r=function(h,d){this.__root=h,this.__ctx=d},r.prototype.addColorStop=function(h,d){var f=this.__ctx.__createElement("stop"),m,w;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)},s=function(h,d){this.__root=h,this.__ctx=d},i=function(h){var d={width:500,height:500,enableMirroring:!1},f;if(arguments.length>1?(f=d,f.width=arguments[0],f.height=arguments[1]):h?f=h:f=d,!(this instanceof i))return new i(f);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)},i.prototype.__createElement=function(h,d,f){typeof d>"u"&&(d={});var m=this.__document.createElementNS("http://www.w3.org/2000/svg",h),w=Object.keys(d),y,C;for(f&&(m.setAttribute("fill","none"),m.setAttribute("stroke","none")),y=0;y<w.length;y++)C=w[y],m.setAttribute(C,d[C]);return m},i.prototype.__setDefaultStyles=function(){var h=Object.keys(e),d,f;for(d=0;d<h.length;d++)f=h[d],this[f]=e[f].canvas},i.prototype.__applyStyleState=function(h){var d=Object.keys(h),f,m;for(f=0;f<d.length;f++)m=d[f],this[m]=h[m]},i.prototype.__getStyleState=function(){var h,d={},f=Object.keys(e),m;for(h=0;h<f.length;h++)m=f[h],d[m]=this[m];return d},i.prototype.__applyStyleToCurrentElement=function(h){var d=Object.keys(e),f,m,w,y,C,S;for(f=0;f<d.length;f++)if(m=e[d[f]],w=this[d[f]],m.apply)if(m.apply.indexOf("fill")!==-1&&w instanceof s){if(w.__ctx)for(;w.__ctx.__defs.childNodes.length;)y=w.__ctx.__defs.childNodes[0].getAttribute("id"),this.__ids[y]=y,this.__defs.appendChild(w.__ctx.__defs.childNodes[0]);this.__currentElement.setAttribute("fill",a("url(#{id})",{id:w.__root.getAttribute("id")}))}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,S=C.exec(w),this.__currentElement.setAttribute(m.svgAttr,a("rgb({r},{g},{b})",{r:S[1],g:S[2],b:S[3]})),this.__currentElement.setAttribute(m.svgAttr+"-opacity",S[4])):this.__currentElement.setAttribute(m.svgAttr,w))},i.prototype.__closestGroupOrSvg=function(h){return h=h||this.__currentElement,h.nodeName==="g"||h.nodeName==="svg"?h:this.__closestGroupOrSvg(h.parentNode)},i.prototype.getSerializedSvg=function(h){var d=new XMLSerializer().serializeToString(this.__root),f,m,w,y,C,S;if(S=/xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi,S.test(d)&&(d=d.replace('xmlns="http://www.w3.org/2000/svg','xmlns:xlink="http://www.w3.org/1999/xlink')),h)for(f=Object.keys(n),m=0;m<f.length;m++)w=f[m],y=n[w],C=new RegExp(w,"gi"),C.test(d)&&(d=d.replace(C,y));return d},i.prototype.getSvg=function(){return this.__root},i.prototype.save=function(){var h=this.__createElement("g"),d=this.__closestGroupOrSvg();this.__groupStack.push(d),d.appendChild(h),this.__currentElement=h,this.__stack.push(this.__getStyleState())},i.prototype.restore=function(){this.__currentElement=this.__groupStack.pop();var h=this.__stack.pop();this.__applyStyleState(h)},i.prototype.__addTransform=function(h){var d=this.__closestGroupOrSvg();if(d.childNodes.length>0){var f=this.__createElement("g");d.appendChild(f),this.__currentElement=f}var m=this.__currentElement.getAttribute("transform");m?m+=" ":m="",m+=h,this.__currentElement.setAttribute("transform",m)},i.prototype.scale=function(h,d){d===void 0&&(d=h),this.__addTransform(a("scale({x},{y})",{x:h,y:d}))},i.prototype.rotate=function(h){var d=h*180/Math.PI;this.__addTransform(a("rotate({angle},{cx},{cy})",{angle:d,cx:0,cy:0}))},i.prototype.translate=function(h,d){this.__addTransform(a("translate({x},{y})",{x:h,y:d}))},i.prototype.transform=function(h,d,f,m,w,y){this.__addTransform(a("matrix({a},{b},{c},{d},{e},{f})",{a:h,b:d,c:f,d:m,e:w,f:y}))},i.prototype.beginPath=function(){var h,d;this.__currentDefaultPath="",this.__currentPosition={},h=this.__createElement("path",{},!0),d=this.__closestGroupOrSvg(),d.appendChild(h),this.__currentElement=h},i.prototype.__applyCurrentDefaultPath=function(){if(this.__currentElement.nodeName==="path"){var h=this.__currentDefaultPath;this.__currentElement.setAttribute("d",h)}else throw new Error("Attempted to apply path command to node "+this.__currentElement.nodeName)},i.prototype.__addPathCommand=function(h){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=h},i.prototype.moveTo=function(h,d){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.__currentPosition={x:h,y:d},this.__addPathCommand(a("M {x} {y}",{x:h,y:d}))},i.prototype.closePath=function(){this.__addPathCommand("Z")},i.prototype.lineTo=function(h,d){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}))},i.prototype.bezierCurveTo=function(h,d,f,m,w,y){this.__currentPosition={x:w,y},this.__addPathCommand(a("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:h,cp1y:d,cp2x:f,cp2y:m,x:w,y}))},i.prototype.quadraticCurveTo=function(h,d,f,m){this.__currentPosition={x:f,y:m},this.__addPathCommand(a("Q {cpx} {cpy} {x} {y}",{cpx:h,cpy:d,x:f,y:m}))};var p=function(h){var d=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return[h[0]/d,h[1]/d]};i.prototype.arcTo=function(h,d,f,m,w){var y=this.__currentPosition&&this.__currentPosition.x,C=this.__currentPosition&&this.__currentPosition.y;if(!(typeof y>"u"||typeof C>"u")){if(w<0)throw new Error("IndexSizeError: The radius provided ("+w+") is negative.");if(y===h&&C===d||h===f&&d===m||w===0){this.lineTo(h,d);return}var S=p([y-h,C-d]),_=p([f-h,m-d]);if(S[0]*_[1]===S[1]*_[0]){this.lineTo(h,d);return}var M=S[0]*_[0]+S[1]*_[1],j=Math.acos(Math.abs(M)),B=p([S[0]+_[0],S[1]+_[1]]),O=w/Math.sin(j/2),G=h+O*B[0],tt=d+O*B[1],X=[-S[1],S[0]],q=[_[1],-_[0]],ht=function(A){var F=A[0],b=A[1];return b>=0?Math.acos(F):-Math.acos(F)},Y=ht(X),L=ht(q);this.lineTo(G+X[0]*w,tt+X[1]*w),this.arc(G,tt,w,Y,L)}},i.prototype.stroke=function(){this.__currentElement.nodeName==="path"&&this.__currentElement.setAttribute("paint-order","fill stroke markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("stroke")},i.prototype.fill=function(){this.__currentElement.nodeName==="path"&&this.__currentElement.setAttribute("paint-order","stroke fill markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("fill")},i.prototype.rect=function(h,d,f,m){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()},i.prototype.fillRect=function(h,d,f,m){var w,y;w=this.__createElement("rect",{x:h,y:d,width:f,height:m},!0),y=this.__closestGroupOrSvg(),y.appendChild(w),this.__currentElement=w,this.__applyStyleToCurrentElement("fill")},i.prototype.strokeRect=function(h,d,f,m){var w,y;w=this.__createElement("rect",{x:h,y:d,width:f,height:m},!0),y=this.__closestGroupOrSvg(),y.appendChild(w),this.__currentElement=w,this.__applyStyleToCurrentElement("stroke")},i.prototype.clearRect=function(h,d,f,m){var w,y=this.__closestGroupOrSvg();w=this.__createElement("rect",{x:h,y:d,width:f,height:m,fill:"#FFFFFF"},!0),y.appendChild(w)},i.prototype.createLinearGradient=function(h,d,f,m){var w=this.__createElement("linearGradient",{id:l(this.__ids),x1:h+"px",x2:f+"px",y1:d+"px",y2:m+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(w),new r(w,this)},i.prototype.createRadialGradient=function(h,d,f,m,w,y){var C=this.__createElement("radialGradient",{id:l(this.__ids),cx:m+"px",cy:w+"px",r:y+"px",fx:h+"px",fy:d+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(C),new r(C,this)},i.prototype.__parseFont=function(){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={style:d[1]||"normal",size:d[4]||"10px",family:d[6]||"sans-serif",weight:d[3]||"normal",decoration:d[2]||"normal",href:null};return this.__fontUnderline==="underline"&&(f.decoration="underline"),this.__fontHref&&(f.href=this.__fontHref),f},i.prototype.__wrapTextLink=function(h,d){if(h.href){var f=this.__createElement("a");return f.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h.href),f.appendChild(d),f}return d},i.prototype.__applyText=function(h,d,f,m){var w=this.__parseFont(),y=this.__closestGroupOrSvg(),C=this.__createElement("text",{"font-family":w.family,"font-size":w.size,"font-style":w.style,"font-weight":w.weight,"text-decoration":w.decoration,x:d,y:f,"text-anchor":g(this.textAlign),"dominant-baseline":v(this.textBaseline)},!0);C.appendChild(this.__document.createTextNode(h)),this.__currentElement=C,this.__applyStyleToCurrentElement(m),y.appendChild(this.__wrapTextLink(w,C))},i.prototype.fillText=function(h,d,f){this.__applyText(h,d,f,"fill")},i.prototype.strokeText=function(h,d,f){this.__applyText(h,d,f,"stroke")},i.prototype.measureText=function(h){return this.__ctx.font=this.font,this.__ctx.measureText(h)},i.prototype.arc=function(h,d,f,m,w,y){if(m!==w){m=m%(2*Math.PI),w=w%(2*Math.PI),m===w&&(w=(w+2*Math.PI-.001*(y?-1:1))%(2*Math.PI));var C=h+f*Math.cos(w),S=d+f*Math.sin(w),_=h+f*Math.cos(m),M=d+f*Math.sin(m),j=y?0:1,B=0,O=w-m;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("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:f,ry:f,xAxisRotation:0,largeArcFlag:B,sweepFlag:j,endX:C,endY:S})),this.__currentPosition={x:C,y:S}}},i.prototype.clip=function(){var h=this.__closestGroupOrSvg(),d=this.__createElement("clipPath"),f=l(this.__ids),m=this.__createElement("g");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},i.prototype.drawImage=function(){var h=Array.prototype.slice.call(arguments),d=h[0],f,m,w,y,C=0,S=0,_,M,j,B,O,G,tt,X,q,ht,Y;if(h.length===3)f=h[1],m=h[2],_=d.width,M=d.height,w=_,y=M;else if(h.length===5)f=h[1],m=h[2],w=h[3],y=h[4],_=d.width,M=d.height;else if(h.length===9)C=h[1],S=h[2],_=h[3],M=h[4],f=h[5],m=h[6],w=h[7],y=h[8];else throw new Error("Inavlid number of arguments passed to drawImage: "+arguments.length);if(j=this.__closestGroupOrSvg(),tt=this.__currentElement,d instanceof i){for(B=d.getSvg(),O=B.childNodes[0];O.childNodes.length;)Y=O.childNodes[0].getAttribute("id"),this.__ids[Y]=Y,this.__defs.appendChild(O.childNodes[0]);G=B.childNodes[1],j.appendChild(G),this.__currentElement=G,this.translate(f,m),this.__currentElement=tt}else(d.nodeName==="CANVAS"||d.nodeName==="IMG")&&(X=this.__createElement("image"),X.setAttribute("width",w),X.setAttribute("height",y),X.setAttribute("preserveAspectRatio","none"),(C||S||_!==d.width||M!==d.height)&&(q=this.__document.createElement("canvas"),q.width=w,q.height=y,ht=q.getContext("2d"),ht.drawImage(d,C,S,_,M,0,0,w,y),d=q),X.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",d.nodeName==="CANVAS"?d.toDataURL():d.getAttribute("src")),j.appendChild(X),this.__currentElement=X,this.translate(f,m),this.__currentElement=tt)},i.prototype.createPattern=function(h,d){var f=this.__document.createElementNS("http://www.w3.org/2000/svg","pattern"),m=l(this.__ids),w;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("http://www.w3.org/1999/xlink","xlink:href",h.nodeName==="CANVAS"?h.toDataURL():h.getAttribute("src")),f.appendChild(w),this.__defs.appendChild(f)):h instanceof i&&(f.appendChild(h.__root.childNodes[1]),this.__defs.appendChild(f)),new s(f,this)},i.prototype.drawFocusRing=function(){},i.prototype.createImageData=function(){},i.prototype.getImageData=function(){},i.prototype.putImageData=function(){},i.prototype.globalCompositeOperation=function(){},i.prototype.setTransform=function(){},typeof window=="object"&&(window.C2S=i),t.exports=i})()})(zr);var hn=zr.exports;const _t=on(hn),ln=Math.PI*2;let dn=0;function cn(){return`p5ExportPattern_${++dn}`}function fn(t){const e=t._patternControler,i=e&&Array.isArray(e.colors)?e.colors:null;if(!i||i.length===0)return"#888888";const r=i[i.length-1];return typeof r=="string"?r:r&&typeof r.toString=="function"?r.toString():"#888888"}function ge(t,e,i,r,s){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*.5,y:e-r*.5,w:i,h:r}:{x:t,y:e,w:i,h:r}}function Vr(t){return t._renderer&&t._renderer.states&&t._renderer.states.rectMode||"corner"}function Pi(t){return t._renderer&&t._renderer.states&&t._renderer.states.ellipseMode||"center"}function un(t,e,i){const r=t._p5ExportSVGRecorder;r&&r.ops.push([3,e,i])}function pn(t,e){const i=t._p5ExportSVGRecorder;i&&i.ops.push([2,"beginRaster",e])}function mn(t){const e=t._p5ExportSVGRecorder;e&&e.ops.push([2,"endRaster"])}function Dt(t,e,i){const r=t[e];typeof r!="function"||r.__p5ExportWrapped||(t[e]=function(...s){let n,a;try{if(a=i(this,s),a){n=cn();const u=fn(this);un(this,a.kind,{...a,color:u,patternId:n})}}catch{}const l=!!this._p5ExportSVGRecorder&&!!n&&!!a;l&&pn(this,{bbox:a,patternId:n});try{return r.apply(this,s)}finally{l&&mn(this)}},t[e].__p5ExportWrapped=!0)}const wn=["rectPattern","squarePattern","ellipsePattern","circlePattern","arcPattern","trianglePattern","quadPattern"];function Lr(t,e){if(!t||!t.prototype)return!1;const i=t.prototype;if(typeof i.rectPattern!="function")return!1;const r=!!i.__p5ExportPatternHooksInstalled;if(r||(i.__p5ExportPatternHooksInstalled=!0),e&&e._renderer&&e._renderer.states){const n=t.Renderer||e._renderer.constructor;if(n&&n.prototype&&!n.prototype.__p5ExportModeBridged){n.prototype.__p5ExportModeBridged=!0;for(const a of["rectMode","ellipseMode","imageMode","colorMode"])Object.defineProperty(n.prototype,"_"+a,{configurable:!0,get(){return this.states&&this.states[a]},set(l){this.states&&(this.states[a]=l)}})}}r||(Dt(i,"rectPattern",(n,a)=>({kind:"rect",...ge(a[0],a[1],a[2],a[3],Vr(n))})),Dt(i,"squarePattern",(n,a)=>({kind:"rect",...ge(a[0],a[1],a[2],a[2],Vr(n))})),Dt(i,"ellipsePattern",(n,a)=>({kind:"ellipse",...ge(a[0],a[1],a[2],a[3],Pi(n))})),Dt(i,"circlePattern",(n,a)=>({kind:"ellipse",...ge(a[0],a[1],a[2],a[2],Pi(n))})),Dt(i,"arcPattern",(n,a)=>({kind:"ellipse",...ge(a[0],a[1],a[2],a[3],Pi(n))})),Dt(i,"trianglePattern",(n,a)=>{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);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]]],x:g,y:p,w:v-g,h:h-p}}),Dt(i,"quadPattern",(n,a)=>{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);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]],[a[6],a[7]]],x:g,y:p,w:v-g,h:h-p}}));const s=e&&e._isGlobal&&e||typeof window<"u"&&window.p5&&window.p5.instance||null;if(s&&s._isGlobal&&typeof window<"u")for(const n of wn){const a=i[n];if(typeof a=="function")try{let l=a.bind(s);Object.defineProperty(window,n,{configurable:!0,enumerable:!0,get(){return l},set(u){}})}catch{}}return!0}const Or="p5ExportSharedRaster";function gn(t,e,i,r){if(!i||!t)return;const s=t.fillStyle;i.patternId?t.fillStyle=`url(#${i.patternId})`:t.fillStyle=`url(#${Or})`;try{if(e==="rect")t.beginPath(),t.rect(i.x,i.y,i.w,i.h),t.fill();else if(e==="ellipse"){const n=i.w/2,a=i.h/2,l=i.x+n,u=i.y+a;t.beginPath(),t.ellipse(l,u,n,a,0,0,ln),t.fill()}else if(e==="polygon"){const n=i.points||[];if(n.length>=2){t.beginPath(),t.moveTo(n[0][0],n[0][1]);for(let a=1;a<n.length;a++)t.lineTo(n[a][0],n[a][1]);t.closePath(),t.fill()}}}finally{t.fillStyle=s}}let Gr=!1;function vn(){if(Gr)return;Gr=!0,_t.prototype.setTransform=function(r,s,n,a,l,u){const v=this.__groupStack&&this.__groupStack.length>0?this.__closestGroupOrSvg():this.__root,p=this.__createElement("g");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})`)},_t.prototype.resetTransform=function(){this.setTransform(1,0,0,1,0,0)},_t.prototype.ellipse=function(r,s,n,a,l,u,g,v){if(u===g)return;l=l||0;const p=Math.PI*2;u=u%p,g=g%p,u===g&&(g=(g+p-.001*(v?-1:1))%p);const h=Math.cos(l),d=Math.sin(l),f=M=>{const j=n*Math.cos(M),B=a*Math.sin(M);return{x:r+j*h-B*d,y:s+j*d+B*h}},m=f(u),w=f(g);let y=g-u;y<0&&(y+=p);const C=v?0:1,S=v?y>Math.PI?0:1:y>Math.PI?1:0,_=l*180/Math.PI;this.lineTo(m.x,m.y),this.__addPathCommand("A "+n+" "+a+" "+_+" "+S+" "+C+" "+w.x+" "+w.y),this.__currentPosition={x:w.x,y:w.y}},typeof _t.prototype.roundRect!="function"&&(_t.prototype.roundRect=function(r,s,n,a,l){let u,g,v,p;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;const h=Math.min(Math.abs(n),Math.abs(a))/2;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)}),delete _t.prototype.globalCompositeOperation;const t=_t.prototype.__applyStyleToCurrentElement,e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,i=r=>{if(typeof r!="string")return r;const s=e.exec(r);if(!s)return r;const n=Math.round(parseInt(s[4],16)/255*1e3)/1e3;return`rgba(${parseInt(s[1],16)},${parseInt(s[2],16)},${parseInt(s[3],16)},${n})`};_t.prototype.__applyStyleToCurrentElement=function(r){const s=this.fillStyle,n=this.strokeStyle;typeof s=="string"&&(this.fillStyle=i(s)),typeof n=="string"&&(this.strokeStyle=i(n));try{return t.call(this,r)}finally{this.fillStyle=s,this.strokeStyle=n}}}const yn=60,Nr=new Set(["fillStyle","strokeStyle","lineWidth","lineCap","lineJoin","miterLimit","globalAlpha","font","textAlign","textBaseline","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]);let bn=0;const $r=new Map;function _n(){return`p5ExportGrad_${++bn}`}function xn(t){const e=[],i=[0],r={proxy:null,ops:e,maxFrames:yn,clear(){e.length=0,i.length=1,i[0]=0},markFrameBoundary(){if(this.maxFrames===1/0){i.push(e.length);return}for(i.push(e.length);i.length>this.maxFrames+1;){const a=i[1];if(a>0){const l={};for(let v=0;v<a;v++){const p=e[v];p[0]===1&&Nr.has(p[1])&&(l[p[1]]=p[2])}e.splice(0,a);const u=[];for(const v in l)u.push([1,v,l[v]]);u.length&&e.unshift(...u);const g=u.length-a;for(let v=1;v<i.length;v++)i[v]+=g}i.shift()}}},s=new Set(["createLinearGradient","createRadialGradient","createConicGradient"]),n=(a,l,u)=>{if(!a)return a;const g=_n(),v={id:g,kind:l,args:Array.from(u),stops:[]};$r.set(g,v);try{a.__p5ExportGradId=g}catch{}return new Proxy(a,{get(p,h){if(h==="__p5ExportRealGrad")return p;if(h==="addColorStop"&&typeof p[h]=="function")return function(f,m){return v.stops.push({offset:f,color:m}),p[h].call(p,f,m)};const d=p[h];return typeof d=="function"?d.bind(p):d}})};return r.proxy=new Proxy(t,{get(a,l){const u=a[l];return typeof u=="function"?function(...g){e.push([0,l,g]);const v=u.apply(a,g);return s.has(l)?n(v,l,g):v}:u},set(a,l,u){if((l==="fillStyle"||l==="strokeStyle")&&u&&typeof u=="object"){const g=u.__p5ExportGradId;e.push([1,l,g?{__p5ExportGradId:g}:u]),a[l]=u.__p5ExportRealGrad||u}else e.push([1,l,u]),a[l]=u;return!0}}),r}function Sn(t){return!!(t&&typeof t.fillRect=="function")}function jr(t){if(!t||t._p5ExportSVGRecorder)return;const e=t._renderer;if(!e)return;const i=e.drawingContext;if(!Sn(i))return;const r=xn(i),s=typeof window<"u"&&window.p5ExportConfig||{};typeof s.svgMaxFrames=="number"&&(r.maxFrames=s.svgMaxFrames>0?s.svgMaxFrames:1/0),t._p5ExportSVGRecorder=r;const n={value:r.proxy,configurable:!0,writable:!0,enumerable:!0};Object.defineProperty(e,"drawingContext",n),Object.defineProperty(t,"drawingContext",n)}function qr(t){if(typeof t!="string")return t;const e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!e)return t;const i=parseInt(e[4],16)/255;return`rgba(${parseInt(e[1],16)},${parseInt(e[2],16)},${parseInt(e[3],16)},${i})`}function Cn(t){if(typeof t!="string")return!0;let e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);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))}function Hr(t,e,i){let r=-1,s="#000000";const n=.5;let a=!1;for(let l=0;l<t.length;l++){const u=t[l];if(u[0]===2){u[1]==="beginRaster"?a=!0:u[1]==="endRaster"&&(a=!1);continue}if(!a){if(u[0]===1&&u[1]==="fillStyle")s=u[2];else if(u[0]===0&&(u[1]==="fillRect"||u[1]==="clearRect")){const g=u[2],v=g[0],p=g[1],h=g[2],d=g[3];Math.abs(v)<=n&&Math.abs(p)<=n&&Math.abs(h-e)<=n&&Math.abs(d-i)<=n&&(u[1]==="clearRect"||Cn(s))&&(r=l)}}}return r}function Xr(t){vn();const e=t._p5ExportSVGRecorder,i=t.width||100,r=t.height||100,s=new _t(i,r);if(s.setTransform(1,0,0,1,0,0),!e)return s.getSerializedSvg();let n="#000000",a="#000000";const l=new Set,u="http://www.w3.org/2000/svg",g=L=>{if(!L||l.has(L.id))return!0;const A=s.__defs,F=s.__document;let b;if(L.kind==="createLinearGradient"){const[W,et,lt,Bt]=L.args;b=F.createElementNS(u,"linearGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("x1",String(W)),b.setAttribute("y1",String(et)),b.setAttribute("x2",String(lt)),b.setAttribute("y2",String(Bt))}else if(L.kind==="createRadialGradient"){const[W,et,lt,Bt,Xe,Fr]=L.args;b=F.createElementNS(u,"radialGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("fx",String(W)),b.setAttribute("fy",String(et)),b.setAttribute("fr",String(lt)),b.setAttribute("cx",String(Bt)),b.setAttribute("cy",String(Xe)),b.setAttribute("r",String(Fr))}else return!1;b.setAttribute("id",L.id);for(const W of L.stops){const et=F.createElementNS(u,"stop");et.setAttribute("offset",String(W.offset)),et.setAttribute("stop-color",String(W.color)),b.appendChild(et)}return A.appendChild(b),l.add(L.id),!0},v=typeof t.pixelDensity=="function"?t.pixelDensity():1,p=1/v,h=e.ops.slice(),d=Hr(h,i,r);let f=0;if(d>0){let L=0,A=-1;for(let b=d-1;b>=0;b--)if(h[b][0]===0){if(h[b][1]==="restore")L++;else if(h[b][1]==="save"){if(L===0){A=b;break}L--}}f=A>=0?A:d;const F={};for(let b=0;b<f;b++){const W=h[b];W[0]===1&&Nr.has(W[1])&&(F[W[1]]=W[2])}for(const b in F){const W=F[b];b==="fillStyle"||b==="strokeStyle"?typeof W=="string"?(b==="fillStyle"?n=W:a=W,s[b]=qr(W)):s[b]=b==="fillStyle"?n:a:s[b]=W}}const m=bt(t),w=m?m.width:i*v,y=m?m.height:r*v;let C=null,S=null,_=null,M=null,j=null,B=!1;const O="http://www.w3.org/2000/svg",G="http://www.w3.org/1999/xlink",tt=()=>{C||(C=document.createElement("canvas"),C.width=w,C.height=y,S=C.getContext("2d")),S.setTransform(1,0,0,1,0,0),S.clearRect(0,0,C.width,C.height),S.setTransform(v,0,0,v,0,0)},X=()=>{M||(M=document.createElement("canvas"),M.width=w,M.height=y,j=M.getContext("2d"),j.setTransform(v,0,0,v,0,0))},q=L=>{if(!L||!L.hasContent||!C)return;const A=L.bbox;if(!A)return;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)),et=Math.min(C.height,Math.ceil((A.y+A.h)*v)),lt=W-F,Bt=et-b;if(lt<=0||Bt<=0)return;let Xe;try{const Ye=document.createElement("canvas");Ye.width=lt,Ye.height=Bt,Ye.getContext("2d").drawImage(C,F,b,lt,Bt,0,0,lt,Bt),Xe=Ye.toDataURL()}catch{return}const Fr=s.__defs,Ft=s.__document.createElementNS(O,"pattern");Ft.setAttribute("id",L.patternId),Ft.setAttribute("patternUnits","userSpaceOnUse"),Ft.setAttribute("x",String(A.x)),Ft.setAttribute("y",String(A.y)),Ft.setAttribute("width",String(A.w)),Ft.setAttribute("height",String(A.h));const Ut=s.__document.createElementNS(O,"image");Ut.setAttribute("x","0"),Ut.setAttribute("y","0"),Ut.setAttribute("width",String(A.w)),Ut.setAttribute("height",String(A.h)),Ut.setAttributeNS(G,"xlink:href",Xe),Ut.setAttribute("href",Xe),Ut.setAttribute("preserveAspectRatio","none"),Ft.appendChild(Ut),Fr.appendChild(Ft)},ht=()=>{if(!(!M||!B))try{const L=M.toDataURL(),A=s.__defs,F=s.__document.createElementNS(O,"pattern");F.setAttribute("id",Or),F.setAttribute("patternUnits","userSpaceOnUse"),F.setAttribute("x","0"),F.setAttribute("y","0"),F.setAttribute("width",String(i)),F.setAttribute("height",String(r));const b=s.__document.createElementNS(O,"image");b.setAttribute("x","0"),b.setAttribute("y","0"),b.setAttribute("width",String(i)),b.setAttribute("height",String(r)),b.setAttributeNS(G,"xlink:href",L),b.setAttribute("href",L),F.appendChild(b),A.appendChild(F);const W=s.__document.createElementNS(O,"image");W.setAttribute("x","0"),W.setAttribute("y","0"),W.setAttribute("width",String(i)),W.setAttribute("height",String(r)),W.setAttributeNS(G,"xlink:href",L),W.setAttribute("href",L),s.__root.appendChild(W)}catch{}};let Y=!1;for(let L=f;L<h.length;L++){const A=h[L];if(A[0]===2){if(A[1]==="beginRaster"){const b=A[2];b&&b.bbox&&b.patternId?(tt(),_={bbox:b.bbox,patternId:b.patternId,hasContent:!1}):(X(),_=null),Y=!0}else A[1]==="endRaster"&&(_&&(q(_),_=null),Y=!1);continue}if(A[0]===3){try{gn(s,A[1],A[2],!0)}catch{}continue}const F=Y?_?S:j:s;Y&&A[0]===0&&(_?_.hasContent=!0:B=!0);try{if(A[0]===0)if(A[1]==="setTransform"){const b=A[2];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])}else{const b=F[A[1]];typeof b=="function"&&b.apply(F,A[2])}else if(A[1]==="fillStyle"||A[1]==="strokeStyle"){const b=A[2],W=A[1]==="fillStyle";if(typeof b=="string")W?n=b:a=b,F[A[1]]=F===s?qr(b):b;else if(b&&typeof b=="object"&&b.__p5ExportGradId){const et=$r.get(b.__p5ExportGradId);F===s&&g(et)?F[A[1]]=`url(#${et.id})`:F===s&&(F[A[1]]=W?n:a)}else if(F===s)F[A[1]]=W?n:a;else try{F[A[1]]=b}catch{}}else if(A[1]==="globalCompositeOperation"){if(F[A[1]]=A[2],F===s){const b=A[2],W=s.__currentElement;if(W&&W.setAttribute&&b&&b!=="source-over"){const et=W.getAttribute("style")||"";if(et.indexOf("mix-blend-mode")===-1){const lt=et&&!et.trim().endsWith(";")?";":"";W.setAttribute("style",et+lt+"mix-blend-mode:"+b)}}}}else F[A[1]]=A[2]}catch{}}return _&&q(_),ht(),s.getSerializedSvg()}function En(t){const e=t.toDataURL("image/png"),i=t.width,r=t.height;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>`}function Tn(t,e,i){e.saveSVG=function(s,n={}){let a;const l=!!this._p5ExportSVGRecorder,u=2e6;let g=0;if(l){const d=this._p5ExportSVGRecorder.ops.slice(),f=this.width||100,m=this.height||100,w=Hr(d,f,m);let y=0;if(w>0){let S=0;for(let _=w-1;_>=0;_--)if(d[_][0]===0){if(d[_][1]==="restore")S++;else if(d[_][1]==="save"){if(S===0){y=_;break}S--}}}let C=!1;for(let S=y;S<d.length;S++){const _=d[S];if(_[0]===2){_[1]==="beginRaster"?C=!0:_[1]==="endRaster"&&(C=!1);continue}C||g++}}const v=l&&!n.forceVector&&g>u;if(!n.raster&&(!l||v)&&!n.silent&&typeof window<"u"&&typeof window.confirm=="function"){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.";if(!window.confirm(`[p5.export] SVG export problem
13
+ */(function(t){(function(){var e,i,r,n,s;function a(h,d){var c=Object.keys(d),w;for(w=0;w<c.length;w++)h=h.replace(new RegExp("\\{"+c[w]+"\\}","gi"),d[c[w]]);return h}function l(h){var d,c,w;if(!h)throw new Error("cannot create a random attribute name for an undefined object");d="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",c="";do for(c="",w=0;w<12;w++)c+=d[Math.floor(Math.random()*d.length)];while(h[c]);return c}function u(h,d){var c,w,g={},y;for(h=h.split(","),d=d||10,c=0;c<h.length;c+=2)w="&"+h[c+1]+";",y=parseInt(h[c],d),g[w]="&#"+y+";";return g["\\xa0"]="&#160;",g}function m(h){var d={left:"start",right:"end",center:"middle",start:"start",end:"end"};return d[h]||d.start}function v(h){var d={alphabetic:"alphabetic",hanging:"hanging",top:"text-before-edge",bottom:"text-after-edge",middle:"central"};return d[h]||d.alphabetic}s=u("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",32),e={strokeStyle:{svgAttr:"stroke",canvas:"#000000",svg:"none",apply:"stroke"},fillStyle:{svgAttr:"fill",canvas:"#000000",svg:null,apply:"fill"},lineCap:{svgAttr:"stroke-linecap",canvas:"butt",svg:"butt",apply:"stroke"},lineJoin:{svgAttr:"stroke-linejoin",canvas:"miter",svg:"miter",apply:"stroke"},miterLimit:{svgAttr:"stroke-miterlimit",canvas:10,svg:4,apply:"stroke"},lineWidth:{svgAttr:"stroke-width",canvas:1,svg:1,apply:"stroke"},globalAlpha:{svgAttr:"opacity",canvas:1,svg:1,apply:"fill stroke"},font:{canvas:"10px sans-serif"},shadowColor:{canvas:"#000000"},shadowOffsetX:{canvas:0},shadowOffsetY:{canvas:0},shadowBlur:{canvas:0},textAlign:{canvas:"start"},textBaseline:{canvas:"alphabetic"}},r=function(h,d){this.__root=h,this.__ctx=d},r.prototype.addColorStop=function(h,d){var c=this.__ctx.__createElement("stop"),w,g;c.setAttribute("offset",h),d.indexOf("rgba")!==-1?(w=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,g=w.exec(d),c.setAttribute("stop-color",a("rgb({r},{g},{b})",{r:g[1],g:g[2],b:g[3]})),c.setAttribute("stop-opacity",g[4])):c.setAttribute("stop-color",d),this.__root.appendChild(c)},n=function(h,d){this.__root=h,this.__ctx=d},i=function(h){var d={width:500,height:500,enableMirroring:!1},c;if(arguments.length>1?(c=d,c.width=arguments[0],c.height=arguments[1]):h?c=h:c=d,!(this instanceof i))return new i(c);this.width=c.width||d.width,this.height=c.height||d.height,this.enableMirroring=c.enableMirroring!==void 0?c.enableMirroring:d.enableMirroring,this.canvas=this,this.__document=c.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)},i.prototype.__createElement=function(h,d,c){typeof d>"u"&&(d={});var w=this.__document.createElementNS("http://www.w3.org/2000/svg",h),g=Object.keys(d),y,M;for(c&&(w.setAttribute("fill","none"),w.setAttribute("stroke","none")),y=0;y<g.length;y++)M=g[y],w.setAttribute(M,d[M]);return w},i.prototype.__setDefaultStyles=function(){var h=Object.keys(e),d,c;for(d=0;d<h.length;d++)c=h[d],this[c]=e[c].canvas},i.prototype.__applyStyleState=function(h){var d=Object.keys(h),c,w;for(c=0;c<d.length;c++)w=d[c],this[w]=h[w]},i.prototype.__getStyleState=function(){var h,d={},c=Object.keys(e),w;for(h=0;h<c.length;h++)w=c[h],d[w]=this[w];return d},i.prototype.__applyStyleToCurrentElement=function(h){var d=Object.keys(e),c,w,g,y,M,C;for(c=0;c<d.length;c++)if(w=e[d[c]],g=this[d[c]],w.apply)if(w.apply.indexOf("fill")!==-1&&g instanceof n){if(g.__ctx)for(;g.__ctx.__defs.childNodes.length;)y=g.__ctx.__defs.childNodes[0].getAttribute("id"),this.__ids[y]=y,this.__defs.appendChild(g.__ctx.__defs.childNodes[0]);this.__currentElement.setAttribute("fill",a("url(#{id})",{id:g.__root.getAttribute("id")}))}else w.apply.indexOf("fill")!==-1&&g instanceof r?this.__currentElement.setAttribute("fill",a("url(#{id})",{id:g.__root.getAttribute("id")})):w.apply.indexOf(h)!==-1&&w.svg!==g&&((w.svgAttr==="stroke"||w.svgAttr==="fill")&&g.indexOf("rgba")!==-1?(M=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,C=M.exec(g),this.__currentElement.setAttribute(w.svgAttr,a("rgb({r},{g},{b})",{r:C[1],g:C[2],b:C[3]})),this.__currentElement.setAttribute(w.svgAttr+"-opacity",C[4])):this.__currentElement.setAttribute(w.svgAttr,g))},i.prototype.__closestGroupOrSvg=function(h){return h=h||this.__currentElement,h.nodeName==="g"||h.nodeName==="svg"?h:this.__closestGroupOrSvg(h.parentNode)},i.prototype.getSerializedSvg=function(h){var d=new XMLSerializer().serializeToString(this.__root),c,w,g,y,M,C;if(C=/xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi,C.test(d)&&(d=d.replace('xmlns="http://www.w3.org/2000/svg','xmlns:xlink="http://www.w3.org/1999/xlink')),h)for(c=Object.keys(s),w=0;w<c.length;w++)g=c[w],y=s[g],M=new RegExp(g,"gi"),M.test(d)&&(d=d.replace(M,y));return d},i.prototype.getSvg=function(){return this.__root},i.prototype.save=function(){var h=this.__createElement("g"),d=this.__closestGroupOrSvg();this.__groupStack.push(d),d.appendChild(h),this.__currentElement=h,this.__stack.push(this.__getStyleState())},i.prototype.restore=function(){this.__currentElement=this.__groupStack.pop();var h=this.__stack.pop();this.__applyStyleState(h)},i.prototype.__addTransform=function(h){var d=this.__closestGroupOrSvg();if(d.childNodes.length>0){var c=this.__createElement("g");d.appendChild(c),this.__currentElement=c}var w=this.__currentElement.getAttribute("transform");w?w+=" ":w="",w+=h,this.__currentElement.setAttribute("transform",w)},i.prototype.scale=function(h,d){d===void 0&&(d=h),this.__addTransform(a("scale({x},{y})",{x:h,y:d}))},i.prototype.rotate=function(h){var d=h*180/Math.PI;this.__addTransform(a("rotate({angle},{cx},{cy})",{angle:d,cx:0,cy:0}))},i.prototype.translate=function(h,d){this.__addTransform(a("translate({x},{y})",{x:h,y:d}))},i.prototype.transform=function(h,d,c,w,g,y){this.__addTransform(a("matrix({a},{b},{c},{d},{e},{f})",{a:h,b:d,c,d:w,e:g,f:y}))},i.prototype.beginPath=function(){var h,d;this.__currentDefaultPath="",this.__currentPosition={},h=this.__createElement("path",{},!0),d=this.__closestGroupOrSvg(),d.appendChild(h),this.__currentElement=h},i.prototype.__applyCurrentDefaultPath=function(){if(this.__currentElement.nodeName==="path"){var h=this.__currentDefaultPath;this.__currentElement.setAttribute("d",h)}else throw new Error("Attempted to apply path command to node "+this.__currentElement.nodeName)},i.prototype.__addPathCommand=function(h){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=h},i.prototype.moveTo=function(h,d){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.__currentPosition={x:h,y:d},this.__addPathCommand(a("M {x} {y}",{x:h,y:d}))},i.prototype.closePath=function(){this.__addPathCommand("Z")},i.prototype.lineTo=function(h,d){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}))},i.prototype.bezierCurveTo=function(h,d,c,w,g,y){this.__currentPosition={x:g,y},this.__addPathCommand(a("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:h,cp1y:d,cp2x:c,cp2y:w,x:g,y}))},i.prototype.quadraticCurveTo=function(h,d,c,w){this.__currentPosition={x:c,y:w},this.__addPathCommand(a("Q {cpx} {cpy} {x} {y}",{cpx:h,cpy:d,x:c,y:w}))};var p=function(h){var d=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return[h[0]/d,h[1]/d]};i.prototype.arcTo=function(h,d,c,w,g){var y=this.__currentPosition&&this.__currentPosition.x,M=this.__currentPosition&&this.__currentPosition.y;if(!(typeof y>"u"||typeof M>"u")){if(g<0)throw new Error("IndexSizeError: The radius provided ("+g+") is negative.");if(y===h&&M===d||h===c&&d===w||g===0){this.lineTo(h,d);return}var C=p([y-h,M-d]),x=p([c-h,w-d]);if(C[0]*x[1]===C[1]*x[0]){this.lineTo(h,d);return}var E=C[0]*x[0]+C[1]*x[1],W=Math.acos(Math.abs(E)),I=p([C[0]+x[0],C[1]+x[1]]),j=g/Math.sin(W/2),N=h+j*I[0],Y=d+j*I[1],X=[-C[1],C[0]],q=[x[1],-x[0]],ht=function(dt){var ot=dt[0],L=dt[1];return L>=0?Math.acos(ot):-Math.acos(ot)},K=ht(X),Qt=ht(q);this.lineTo(N+X[0]*g,Y+X[1]*g),this.arc(N,Y,g,K,Qt)}},i.prototype.stroke=function(){this.__currentElement.nodeName==="path"&&this.__currentElement.setAttribute("paint-order","fill stroke markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("stroke")},i.prototype.fill=function(){this.__currentElement.nodeName==="path"&&this.__currentElement.setAttribute("paint-order","stroke fill markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("fill")},i.prototype.rect=function(h,d,c,w){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.moveTo(h,d),this.lineTo(h+c,d),this.lineTo(h+c,d+w),this.lineTo(h,d+w),this.lineTo(h,d),this.closePath()},i.prototype.fillRect=function(h,d,c,w){var g,y;g=this.__createElement("rect",{x:h,y:d,width:c,height:w},!0),y=this.__closestGroupOrSvg(),y.appendChild(g),this.__currentElement=g,this.__applyStyleToCurrentElement("fill")},i.prototype.strokeRect=function(h,d,c,w){var g,y;g=this.__createElement("rect",{x:h,y:d,width:c,height:w},!0),y=this.__closestGroupOrSvg(),y.appendChild(g),this.__currentElement=g,this.__applyStyleToCurrentElement("stroke")},i.prototype.clearRect=function(h,d,c,w){var g,y=this.__closestGroupOrSvg();g=this.__createElement("rect",{x:h,y:d,width:c,height:w,fill:"#FFFFFF"},!0),y.appendChild(g)},i.prototype.createLinearGradient=function(h,d,c,w){var g=this.__createElement("linearGradient",{id:l(this.__ids),x1:h+"px",x2:c+"px",y1:d+"px",y2:w+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(g),new r(g,this)},i.prototype.createRadialGradient=function(h,d,c,w,g,y){var M=this.__createElement("radialGradient",{id:l(this.__ids),cx:w+"px",cy:g+"px",r:y+"px",fx:h+"px",fy:d+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(M),new r(M,this)},i.prototype.__parseFont=function(){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),c={style:d[1]||"normal",size:d[4]||"10px",family:d[6]||"sans-serif",weight:d[3]||"normal",decoration:d[2]||"normal",href:null};return this.__fontUnderline==="underline"&&(c.decoration="underline"),this.__fontHref&&(c.href=this.__fontHref),c},i.prototype.__wrapTextLink=function(h,d){if(h.href){var c=this.__createElement("a");return c.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h.href),c.appendChild(d),c}return d},i.prototype.__applyText=function(h,d,c,w){var g=this.__parseFont(),y=this.__closestGroupOrSvg(),M=this.__createElement("text",{"font-family":g.family,"font-size":g.size,"font-style":g.style,"font-weight":g.weight,"text-decoration":g.decoration,x:d,y:c,"text-anchor":m(this.textAlign),"dominant-baseline":v(this.textBaseline)},!0);M.appendChild(this.__document.createTextNode(h)),this.__currentElement=M,this.__applyStyleToCurrentElement(w),y.appendChild(this.__wrapTextLink(g,M))},i.prototype.fillText=function(h,d,c){this.__applyText(h,d,c,"fill")},i.prototype.strokeText=function(h,d,c){this.__applyText(h,d,c,"stroke")},i.prototype.measureText=function(h){return this.__ctx.font=this.font,this.__ctx.measureText(h)},i.prototype.arc=function(h,d,c,w,g,y){if(w!==g){w=w%(2*Math.PI),g=g%(2*Math.PI),w===g&&(g=(g+2*Math.PI-.001*(y?-1:1))%(2*Math.PI));var M=h+c*Math.cos(g),C=d+c*Math.sin(g),x=h+c*Math.cos(w),E=d+c*Math.sin(w),W=y?0:1,I=0,j=g-w;j<0&&(j+=2*Math.PI),y?I=j>Math.PI?0:1:I=j>Math.PI?1:0,this.lineTo(x,E),this.__addPathCommand(a("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:c,ry:c,xAxisRotation:0,largeArcFlag:I,sweepFlag:W,endX:M,endY:C})),this.__currentPosition={x:M,y:C}}},i.prototype.clip=function(){var h=this.__closestGroupOrSvg(),d=this.__createElement("clipPath"),c=l(this.__ids),w=this.__createElement("g");h.removeChild(this.__currentElement),d.setAttribute("id",c),d.appendChild(this.__currentElement),this.__defs.appendChild(d),h.setAttribute("clip-path",a("url(#{id})",{id:c})),h.appendChild(w),this.__currentElement=w},i.prototype.drawImage=function(){var h=Array.prototype.slice.call(arguments),d=h[0],c,w,g,y,M=0,C=0,x,E,W,I,j,N,Y,X,q,ht,K;if(h.length===3)c=h[1],w=h[2],x=d.width,E=d.height,g=x,y=E;else if(h.length===5)c=h[1],w=h[2],g=h[3],y=h[4],x=d.width,E=d.height;else if(h.length===9)M=h[1],C=h[2],x=h[3],E=h[4],c=h[5],w=h[6],g=h[7],y=h[8];else throw new Error("Inavlid number of arguments passed to drawImage: "+arguments.length);if(W=this.__closestGroupOrSvg(),Y=this.__currentElement,d instanceof i){for(I=d.getSvg(),j=I.childNodes[0];j.childNodes.length;)K=j.childNodes[0].getAttribute("id"),this.__ids[K]=K,this.__defs.appendChild(j.childNodes[0]);N=I.childNodes[1],W.appendChild(N),this.__currentElement=N,this.translate(c,w),this.__currentElement=Y}else(d.nodeName==="CANVAS"||d.nodeName==="IMG")&&(X=this.__createElement("image"),X.setAttribute("width",g),X.setAttribute("height",y),X.setAttribute("preserveAspectRatio","none"),(M||C||x!==d.width||E!==d.height)&&(q=this.__document.createElement("canvas"),q.width=g,q.height=y,ht=q.getContext("2d"),ht.drawImage(d,M,C,x,E,0,0,g,y),d=q),X.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",d.nodeName==="CANVAS"?d.toDataURL():d.getAttribute("src")),W.appendChild(X),this.__currentElement=X,this.translate(c,w),this.__currentElement=Y)},i.prototype.createPattern=function(h,d){var c=this.__document.createElementNS("http://www.w3.org/2000/svg","pattern"),w=l(this.__ids),g;return c.setAttribute("id",w),c.setAttribute("width",h.width),c.setAttribute("height",h.height),h.nodeName==="CANVAS"||h.nodeName==="IMG"?(g=this.__document.createElementNS("http://www.w3.org/2000/svg","image"),g.setAttribute("width",h.width),g.setAttribute("height",h.height),g.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h.nodeName==="CANVAS"?h.toDataURL():h.getAttribute("src")),c.appendChild(g),this.__defs.appendChild(c)):h instanceof i&&(c.appendChild(h.__root.childNodes[1]),this.__defs.appendChild(c)),new n(c,this)},i.prototype.drawFocusRing=function(){},i.prototype.createImageData=function(){},i.prototype.getImageData=function(){},i.prototype.putImageData=function(){},i.prototype.globalCompositeOperation=function(){},i.prototype.setTransform=function(){},typeof window=="object"&&(window.C2S=i),t.exports=i})()})(Nr);var ps=Nr.exports;const St=us(ps),ms=Math.PI*2;let ws=0;function gs(){return`p5ExportPattern_${++ws}`}function vs(t){const e=t._patternControler,i=e&&Array.isArray(e.colors)?e.colors:null;if(!i||i.length===0)return"#888888";const r=i[i.length-1];return typeof r=="string"?r:r&&typeof r.toString=="function"?r.toString():"#888888"}function _e(t,e,i,r,n){return n==="corners"?{x:t,y:e,w:i-t,h:r-e}:n==="radius"?{x:t-i,y:e-r,w:2*i,h:2*r}:n==="center"?{x:t-i*.5,y:e-r*.5,w:i,h:r}:{x:t,y:e,w:i,h:r}}function $r(t){return t._renderer&&t._renderer.states&&t._renderer.states.rectMode||"corner"}function Ui(t){return t._renderer&&t._renderer.states&&t._renderer.states.ellipseMode||"center"}function ys(t,e,i){const r=t._p5ExportSVGRecorder;r&&r.ops.push([3,e,i])}function bs(t,e){const i=t._p5ExportSVGRecorder;i&&i.ops.push([2,"beginRaster",e])}function _s(t){const e=t._p5ExportSVGRecorder;e&&e.ops.push([2,"endRaster"])}function zt(t,e,i){const r=t[e];typeof r!="function"||r.__p5ExportWrapped||(t[e]=function(...n){let s,a;try{if(a=i(this,n),a){s=gs();const u=vs(this);ys(this,a.kind,{...a,color:u,patternId:s})}}catch{}const l=!!this._p5ExportSVGRecorder&&!!s&&!!a;l&&bs(this,{bbox:a,patternId:s});try{return r.apply(this,n)}finally{l&&_s(this)}},t[e].__p5ExportWrapped=!0)}const xs=["rectPattern","squarePattern","ellipsePattern","circlePattern","arcPattern","trianglePattern","quadPattern"];function jr(t,e){if(!t||!t.prototype)return!1;const i=t.prototype;if(typeof i.rectPattern!="function")return!1;const r=!!i.__p5ExportPatternHooksInstalled;if(r||(i.__p5ExportPatternHooksInstalled=!0),e&&e._renderer&&e._renderer.states){const s=t.Renderer||e._renderer.constructor;if(s&&s.prototype&&!s.prototype.__p5ExportModeBridged){s.prototype.__p5ExportModeBridged=!0;for(const a of["rectMode","ellipseMode","imageMode","colorMode"])Object.defineProperty(s.prototype,"_"+a,{configurable:!0,get(){return this.states&&this.states[a]},set(l){this.states&&(this.states[a]=l)}})}}r||(zt(i,"rectPattern",(s,a)=>({kind:"rect",..._e(a[0],a[1],a[2],a[3],$r(s))})),zt(i,"squarePattern",(s,a)=>({kind:"rect",..._e(a[0],a[1],a[2],a[2],$r(s))})),zt(i,"ellipsePattern",(s,a)=>({kind:"ellipse",..._e(a[0],a[1],a[2],a[3],Ui(s))})),zt(i,"circlePattern",(s,a)=>({kind:"ellipse",..._e(a[0],a[1],a[2],a[2],Ui(s))})),zt(i,"arcPattern",(s,a)=>({kind:"ellipse",..._e(a[0],a[1],a[2],a[3],Ui(s))})),zt(i,"trianglePattern",(s,a)=>{const l=[a[0],a[2],a[4]],u=[a[1],a[3],a[5]],m=Math.min(...l),v=Math.max(...l),p=Math.min(...u),h=Math.max(...u);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]]],x:m,y:p,w:v-m,h:h-p}}),zt(i,"quadPattern",(s,a)=>{const l=[a[0],a[2],a[4],a[6]],u=[a[1],a[3],a[5],a[7]],m=Math.min(...l),v=Math.max(...l),p=Math.min(...u),h=Math.max(...u);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]],[a[6],a[7]]],x:m,y:p,w:v-m,h:h-p}}));const n=e&&e._isGlobal&&e||typeof window<"u"&&window.p5&&window.p5.instance||null;if(n&&n._isGlobal&&typeof window<"u")for(const s of xs){const a=i[s];if(typeof a=="function")try{let l=a.bind(n);Object.defineProperty(window,s,{configurable:!0,enumerable:!0,get(){return l},set(u){}})}catch{}}return!0}const qr="p5ExportSharedRaster";function Ss(t,e,i,r){if(!i||!t)return;const n=t.fillStyle;i.patternId?t.fillStyle=`url(#${i.patternId})`:t.fillStyle=`url(#${qr})`;try{if(e==="rect")t.beginPath(),t.rect(i.x,i.y,i.w,i.h),t.fill();else if(e==="ellipse"){const s=i.w/2,a=i.h/2,l=i.x+s,u=i.y+a;t.beginPath(),t.ellipse(l,u,s,a,0,0,ms),t.fill()}else if(e==="polygon"){const s=i.points||[];if(s.length>=2){t.beginPath(),t.moveTo(s[0][0],s[0][1]);for(let a=1;a<s.length;a++)t.lineTo(s[a][0],s[a][1]);t.closePath(),t.fill()}}}finally{t.fillStyle=n}}let Hr=!1;function Cs(){if(Hr)return;Hr=!0,St.prototype.setTransform=function(r,n,s,a,l,u){const v=this.__groupStack&&this.__groupStack.length>0?this.__closestGroupOrSvg():this.__root,p=this.__createElement("g");v.appendChild(p),this.__currentElement=p,r===1&&n===0&&s===0&&a===1&&l===0&&u===0||this.__currentElement.setAttribute("transform",`matrix(${r},${n},${s},${a},${l},${u})`)},St.prototype.resetTransform=function(){this.setTransform(1,0,0,1,0,0)},St.prototype.ellipse=function(r,n,s,a,l,u,m,v){if(u===m)return;l=l||0;const p=Math.PI*2;u=u%p,m=m%p,u===m&&(m=(m+p-.001*(v?-1:1))%p);const h=Math.cos(l),d=Math.sin(l),c=E=>{const W=s*Math.cos(E),I=a*Math.sin(E);return{x:r+W*h-I*d,y:n+W*d+I*h}},w=c(u),g=c(m);let y=m-u;y<0&&(y+=p);const M=v?0:1,C=v?y>Math.PI?0:1:y>Math.PI?1:0,x=l*180/Math.PI;this.lineTo(w.x,w.y),this.__addPathCommand("A "+s+" "+a+" "+x+" "+C+" "+M+" "+g.x+" "+g.y),this.__currentPosition={x:g.x,y:g.y}},typeof St.prototype.roundRect!="function"&&(St.prototype.roundRect=function(r,n,s,a,l){let u,m,v,p;typeof l=="number"?u=m=v=p=l:Array.isArray(l)?l.length===1?u=m=v=p=l[0]:l.length===2?(u=v=l[0],m=p=l[1]):[u,m,v,p]=[l[0],l[1],l[2],l[3]??l[1]]:u=m=v=p=0;const h=Math.min(Math.abs(s),Math.abs(a))/2;u=Math.min(u,h),m=Math.min(m,h),v=Math.min(v,h),p=Math.min(p,h),this.moveTo(r+u,n),this.lineTo(r+s-m,n),this.ellipse(r+s-m,n+m,m,m,0,-Math.PI/2,0),this.lineTo(r+s,n+a-v),this.ellipse(r+s-v,n+a-v,v,v,0,0,Math.PI/2),this.lineTo(r+p,n+a),this.ellipse(r+p,n+a-p,p,p,0,Math.PI/2,Math.PI),this.lineTo(r,n+u),this.ellipse(r+u,n+u,u,u,0,Math.PI,Math.PI*1.5)}),delete St.prototype.globalCompositeOperation;const t=St.prototype.__applyStyleToCurrentElement,e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,i=r=>{if(typeof r!="string")return r;const n=e.exec(r);if(!n)return r;const s=Math.round(parseInt(n[4],16)/255*1e3)/1e3;return`rgba(${parseInt(n[1],16)},${parseInt(n[2],16)},${parseInt(n[3],16)},${s})`};St.prototype.__applyStyleToCurrentElement=function(r){const n=this.fillStyle,s=this.strokeStyle;typeof n=="string"&&(this.fillStyle=i(n)),typeof s=="string"&&(this.strokeStyle=i(s));try{return t.call(this,r)}finally{this.fillStyle=n,this.strokeStyle=s}}}const Es=60,te=new WeakMap;let Xr=!1;function Ts(){if(Xr||typeof Path2D>"u")return;Xr=!0;const t=Path2D.prototype,e=["moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath"];for(const r of e){const n=t[r];if(typeof n!="function"||n.__p5ExportWrapped)continue;const s=function(...a){let l=te.get(this);return l||(l=[],te.set(this,l)),l.push([r,a.map(u=>Array.isArray(u)?u.slice():u)]),n.apply(this,a)};s.__p5ExportWrapped=!0;try{t[r]=s}catch{}}const i=t.addPath;if(typeof i=="function"&&!i.__p5ExportWrapped){const r=function(n,s){const a=te.get(n);if(a&&a.length){let l=te.get(this);l||(l=[],te.set(this,l));const u=s?[s.a,s.b,s.c,s.d,s.e,s.f]:null;l.push(["addPath",a.map(([m,v])=>[m,v.slice()]),u])}return i.apply(this,arguments)};r.__p5ExportWrapped=!0;try{t.addPath=r}catch{}}}function ks(t){if(!t||typeof t!="object")return null;const e=te.get(t);return e?{__p5ExportPath2D:e.map(i=>i[0]==="addPath"?["addPath",i[1].map(([r,n])=>[r,n.slice()]),i[2]&&i[2].slice()]:[i[0],i[1].map(r=>Array.isArray(r)?r.slice():r)])}:null}function As(t,e){const i=e&&e.__p5ExportPath2D;if(!i)return!1;t.beginPath();const r=n=>{for(const s of n){const a=s[0];if(a==="addPath"){r(s[1]);continue}const l=t[a];typeof l=="function"&&l.apply(t,s[1])}};return r(i),!0}const Yr=new Set(["fillStyle","strokeStyle","lineWidth","lineCap","lineJoin","miterLimit","globalAlpha","font","textAlign","textBaseline","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]);let Ms=0;const Jr=new Map;function Ps(){return`p5ExportGrad_${++Ms}`}function Is(t){const e=[],i=[0],r={proxy:null,ops:e,maxFrames:Es,paused:!1,textOutline:null,clear(){e.length=0,i.length=1,i[0]=0},markFrameBoundary(){if(this.maxFrames===1/0){i.push(e.length);return}for(i.push(e.length);i.length>this.maxFrames+1;){const a=i[1];if(a>0){const l={};for(let v=0;v<a;v++){const p=e[v];p[0]===1&&Yr.has(p[1])&&(l[p[1]]=p[2])}e.splice(0,a);const u=[];for(const v in l)u.push([1,v,l[v]]);u.length&&e.unshift(...u);const m=u.length-a;for(let v=1;v<i.length;v++)i[v]+=m}i.shift()}}},n=new Set(["createLinearGradient","createRadialGradient","createConicGradient"]),s=(a,l,u)=>{if(!a)return a;const m=Ps(),v={id:m,kind:l,args:Array.from(u),stops:[]};Jr.set(m,v);try{a.__p5ExportGradId=m}catch{}return new Proxy(a,{get(p,h){if(h==="__p5ExportRealGrad")return p;if(h==="addColorStop"&&typeof p[h]=="function")return function(c,w){return v.stops.push({offset:c,color:w}),p[h].call(p,c,w)};const d=p[h];return typeof d=="function"?d.bind(p):d}})};return r.proxy=new Proxy(t,{get(a,l){const u=a[l];return typeof u=="function"?function(...m){if(!r.paused){const p=m.map(h=>ks(h)||h);e.push([0,l,p])}const v=u.apply(a,m);return n.has(l)?s(v,l,m):v}:u},set(a,l,u){if((l==="fillStyle"||l==="strokeStyle")&&u&&typeof u=="object"){const m=u.__p5ExportGradId;r.paused||e.push([1,l,m?{__p5ExportGradId:m}:u]),a[l]=u.__p5ExportRealGrad||u}else r.paused||e.push([1,l,u]),a[l]=u;return!0}}),r}function Rs(t){return!!(t&&typeof t.fillRect=="function")}function Kr(t){if(!t||t._p5ExportSVGRecorder)return;const e=t._renderer;if(!e)return;const i=e.drawingContext;if(!Rs(i))return;const r=Is(i),n=typeof window<"u"&&window.p5ExportConfig||{};typeof n.svgMaxFrames=="number"&&(r.maxFrames=n.svgMaxFrames>0?n.svgMaxFrames:1/0),t._p5ExportSVGRecorder=r;const s={value:r.proxy,configurable:!0,writable:!0,enumerable:!0};Object.defineProperty(e,"drawingContext",s),Object.defineProperty(t,"drawingContext",s)}function ei(t){if(typeof t!="string")return t;const e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!e)return t;const i=parseInt(e[4],16)/255;return`rgba(${parseInt(e[1],16)},${parseInt(e[2],16)},${parseInt(e[3],16)},${i})`}function Bs(t){if(typeof t!="string")return!0;let e=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);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))}function Zr(t,e,i){let r=-1,n="#000000";const s=.5;let a=!1;for(let l=0;l<t.length;l++){const u=t[l];if(u[0]===2){u[1]==="beginRaster"?a=!0:u[1]==="endRaster"&&(a=!1);continue}if(!a){if(u[0]===1&&u[1]==="fillStyle")n=u[2];else if(u[0]===0&&(u[1]==="fillRect"||u[1]==="clearRect")){const m=u[2],v=m[0],p=m[1],h=m[2],d=m[3];Math.abs(v)<=s&&Math.abs(p)<=s&&Math.abs(h-e)<=s&&Math.abs(d-i)<=s&&(u[1]==="clearRect"||Bs(n))&&(r=l)}}}return r}function Qr(t,e){if(e&&typeof e.outlineText=="boolean")return e.outlineText;const i=t._p5ExportSVGRecorder;if(i&&typeof i.textOutline=="boolean")return i.textOutline;const r=typeof window<"u"&&window.p5ExportConfig||{};return typeof r.svgTextOutlines=="boolean"?r.svgTextOutlines:!0}function Fs(t,e,i,r){const n=i&&i.font;if(!n||typeof n.textToPaths!="function"||!n.data)return!1;const s=e._renderer;if(!s)return!1;let a;const l=r.paused;r.paused=!0;try{s.push();try{i.textSize!=null&&(s.states.textSize=i.textSize),i.textAlign!=null&&(s.states.textAlign=i.textAlign),i.textBaseline!=null&&(s.states.textBaseline=i.textBaseline),i.textLeading!=null&&(s.states.textLeading=i.textLeading),i.rectMode!=null&&(s.states.rectMode=i.rectMode),a=n.textToPaths(i.str,i.x,i.y,i.w,i.h)}finally{s.pop()}}catch{return!1}finally{r.paused=l}if(!a||!a.length)return!0;t.save(),t.beginPath();for(let u=0;u<a.length;u++){const m=a[u];switch(m[0]){case"M":t.moveTo(m[1],m[2]);break;case"L":t.lineTo(m[1],m[2]);break;case"C":t.bezierCurveTo(m[1],m[2],m[3],m[4],m[5],m[6]);break;case"Q":t.quadraticCurveTo(m[1],m[2],m[3],m[4]);break;case"Z":t.closePath();break}}return i.fill&&(t.fillStyle=ei(i.fill),t.fill()),i.hasStroke&&i.stroke&&(t.strokeStyle=ei(i.stroke),i.strokeWeight!=null&&(t.lineWidth=i.strokeWeight),t.stroke()),t.restore(),!0}function tn(t,e={}){Cs();const i=!!e.outlineText,r=t._p5ExportSVGRecorder,n=t.width||100,s=t.height||100,a=new St(n,s);if(a.setTransform(1,0,0,1,0,0),!r)return a.getSerializedSvg();let l="#000000",u="#000000";const m=new Set,v="http://www.w3.org/2000/svg",p=L=>{if(!L||m.has(L.id))return!0;const T=a.__defs,U=a.__document;let b;if(L.kind==="createLinearGradient"){const[O,et,ct,Dt]=L.args;b=U.createElementNS(v,"linearGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("x1",String(O)),b.setAttribute("y1",String(et)),b.setAttribute("x2",String(ct)),b.setAttribute("y2",String(Dt))}else if(L.kind==="createRadialGradient"){const[O,et,ct,Dt,Ze,Or]=L.args;b=U.createElementNS(v,"radialGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("fx",String(O)),b.setAttribute("fy",String(et)),b.setAttribute("fr",String(ct)),b.setAttribute("cx",String(Dt)),b.setAttribute("cy",String(Ze)),b.setAttribute("r",String(Or))}else return!1;b.setAttribute("id",L.id);for(const O of L.stops){const et=U.createElementNS(v,"stop");et.setAttribute("offset",String(O.offset)),et.setAttribute("stop-color",String(O.color)),b.appendChild(et)}return T.appendChild(b),m.add(L.id),!0},h=typeof t.pixelDensity=="function"?t.pixelDensity():1,d=1/h,c=r.ops.slice(),w=Zr(c,n,s);let g=0;if(w>0){let L=0,T=-1;for(let b=w-1;b>=0;b--)if(c[b][0]===0){if(c[b][1]==="restore")L++;else if(c[b][1]==="save"){if(L===0){T=b;break}L--}}g=T>=0?T:w;const U={};for(let b=0;b<g;b++){const O=c[b];O[0]===1&&Yr.has(O[1])&&(U[O[1]]=O[2])}for(const b in U){const O=U[b];b==="fillStyle"||b==="strokeStyle"?typeof O=="string"?(b==="fillStyle"?l=O:u=O,a[b]=ei(O)):a[b]=b==="fillStyle"?l:u:a[b]=O}}const y=xt(t),M=y?y.width:n*h,C=y?y.height:s*h;let x=null,E=null,W=null,I=null,j=null,N=!1;const Y="http://www.w3.org/2000/svg",X="http://www.w3.org/1999/xlink",q=()=>{x||(x=document.createElement("canvas"),x.width=M,x.height=C,E=x.getContext("2d")),E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,x.width,x.height),E.setTransform(h,0,0,h,0,0)},ht=()=>{I||(I=document.createElement("canvas"),I.width=M,I.height=C,j=I.getContext("2d"),j.setTransform(h,0,0,h,0,0))},K=L=>{if(!L||!L.hasContent||!x)return;const T=L.bbox;if(!T)return;const U=Math.max(0,Math.floor(T.x*h)),b=Math.max(0,Math.floor(T.y*h)),O=Math.min(x.width,Math.ceil((T.x+T.w)*h)),et=Math.min(x.height,Math.ceil((T.y+T.h)*h)),ct=O-U,Dt=et-b;if(ct<=0||Dt<=0)return;let Ze;try{const Qe=document.createElement("canvas");Qe.width=ct,Qe.height=Dt,Qe.getContext("2d").drawImage(x,U,b,ct,Dt,0,0,ct,Dt),Ze=Qe.toDataURL()}catch{return}const Or=a.__defs,Ut=a.__document.createElementNS(Y,"pattern");Ut.setAttribute("id",L.patternId),Ut.setAttribute("patternUnits","userSpaceOnUse"),Ut.setAttribute("x",String(T.x)),Ut.setAttribute("y",String(T.y)),Ut.setAttribute("width",String(T.w)),Ut.setAttribute("height",String(T.h));const Wt=a.__document.createElementNS(Y,"image");Wt.setAttribute("x","0"),Wt.setAttribute("y","0"),Wt.setAttribute("width",String(T.w)),Wt.setAttribute("height",String(T.h)),Wt.setAttributeNS(X,"xlink:href",Ze),Wt.setAttribute("href",Ze),Wt.setAttribute("preserveAspectRatio","none"),Ut.appendChild(Wt),Or.appendChild(Ut)},Qt=()=>{if(!(!I||!N))try{const L=I.toDataURL(),T=a.__defs,U=a.__document.createElementNS(Y,"pattern");U.setAttribute("id",qr),U.setAttribute("patternUnits","userSpaceOnUse"),U.setAttribute("x","0"),U.setAttribute("y","0"),U.setAttribute("width",String(n)),U.setAttribute("height",String(s));const b=a.__document.createElementNS(Y,"image");b.setAttribute("x","0"),b.setAttribute("y","0"),b.setAttribute("width",String(n)),b.setAttribute("height",String(s)),b.setAttributeNS(X,"xlink:href",L),b.setAttribute("href",L),U.appendChild(b),T.appendChild(U);const O=a.__document.createElementNS(Y,"image");O.setAttribute("x","0"),O.setAttribute("y","0"),O.setAttribute("width",String(n)),O.setAttribute("height",String(s)),O.setAttributeNS(X,"xlink:href",L),O.setAttribute("href",L),a.__root.appendChild(O)}catch{}};let dt=!1,ot=!1;for(let L=g;L<c.length;L++){const T=c[L];if(T[0]===5){T[1]==="textStart"?ot=i?Fs(a,t,T[2],r):!1:T[1]==="textEnd"&&(ot=!1);continue}if(ot)continue;if(T[0]===2){if(T[1]==="beginRaster"){const b=T[2];b&&b.bbox&&b.patternId?(q(),W={bbox:b.bbox,patternId:b.patternId,hasContent:!1}):(ht(),W=null),dt=!0}else T[1]==="endRaster"&&(W&&(K(W),W=null),dt=!1);continue}if(T[0]===3){try{Ss(a,T[1],T[2],!0)}catch{}continue}const U=dt?W?E:j:a;dt&&T[0]===0&&(W?W.hasContent=!0:N=!0);try{if(T[0]===0)if(T[1]==="setTransform"){const b=T[2];U===a?U.setTransform(b[0]*d,b[1]*d,b[2]*d,b[3]*d,b[4]*d,b[5]*d):U.setTransform(b[0],b[1],b[2],b[3],b[4],b[5])}else if((T[1]==="fill"||T[1]==="stroke"||T[1]==="clip")&&T[2]&&T[2][0]&&T[2][0].__p5ExportPath2D){As(U,T[2][0]);const b=U[T[1]];typeof b=="function"&&b.apply(U,T[2].slice(1))}else{const b=U[T[1]];typeof b=="function"&&b.apply(U,T[2])}else if(T[1]==="fillStyle"||T[1]==="strokeStyle"){const b=T[2],O=T[1]==="fillStyle";if(typeof b=="string")O?l=b:u=b,U[T[1]]=U===a?ei(b):b;else if(b&&typeof b=="object"&&b.__p5ExportGradId){const et=Jr.get(b.__p5ExportGradId);U===a&&p(et)?U[T[1]]=`url(#${et.id})`:U===a&&(U[T[1]]=O?l:u)}else if(U===a)U[T[1]]=O?l:u;else try{U[T[1]]=b}catch{}}else if(T[1]==="globalCompositeOperation"){if(U[T[1]]=T[2],U===a){const b=T[2],O=a.__currentElement;if(O&&O.setAttribute&&b&&b!=="source-over"){const et=O.getAttribute("style")||"";if(et.indexOf("mix-blend-mode")===-1){const ct=et&&!et.trim().endsWith(";")?";":"";O.setAttribute("style",et+ct+"mix-blend-mode:"+b)}}}}else U[T[1]]=T[2]}catch{}}return W&&K(W),Qt(),a.getSerializedSvg()}function Ds(t){const e=t.toDataURL("image/png"),i=t.width,r=t.height;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>`}function Us(t,e,i){Ts(),e.saveSVG=function(s,a={}){let l;const u=!!this._p5ExportSVGRecorder,m=2e6;let v=0;if(u){const c=this._p5ExportSVGRecorder.ops.slice(),w=this.width||100,g=this.height||100,y=Zr(c,w,g);let M=0;if(y>0){let x=0;for(let E=y-1;E>=0;E--)if(c[E][0]===0){if(c[E][1]==="restore")x++;else if(c[E][1]==="save"){if(x===0){M=E;break}x--}}}let C=!1;for(let x=M;x<c.length;x++){const E=c[x];if(E[0]===2){E[1]==="beginRaster"?C=!0:E[1]==="endRaster"&&(C=!1);continue}E[0]!==5&&(C||v++)}}const p=u&&!a.forceVector&&v>m;if(!a.raster&&(!u||p)&&!a.silent&&typeof window<"u"&&typeof window.confirm=="function"){const c=p?`This sketch produced ${v.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.";if(!window.confirm(`[p5.export] SVG export problem
13
14
 
14
- ${d}
15
+ ${c}
15
16
 
16
17
  Click OK to export a raster-only SVG anyway (a single <image> tag) — useful for archival.
17
18
  Click Cancel to abort the download.
@@ -19,14 +20,14 @@ Click Cancel to abort the download.
19
20
  Tips:
20
21
  • Wrap expensive draws in beginRasterRegion()/endRasterRegion() for hybrid output.
21
22
  • saveSVG('out', { forceVector: true }) — force vector despite the size.
22
- • saveSVG('out', { silent: true }) — never prompt; matches old behavior.`))return console.info("[p5.export] saveSVG cancelled by user"),null}if(n.raster||!l||v){const d=bt(this);if(!d)throw new Error("[p5.export] saveSVG: no canvas found");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=En(d)}else a=Xr(this);const h=new Blob([a],{type:"image/svg+xml"});return rt(h,s?yt(s,"svg"):vt("svg")),h},e.getSVG=function(){return this._p5ExportSVGRecorder?Xr(this):""},e.clearSVGRecording=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.clear()},e.beginRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"beginRaster"])},e.endRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"endRaster"])},e.rasterize=function(s){this.beginRasterRegion();try{return s.call(this)}finally{this.endRasterRegion()}},e.setSVGRecordingFrames=function(s){this._p5ExportSVGRecorder&&(s===1/0||s<0?this._p5ExportSVGRecorder.maxFrames=1/0:this._p5ExportSVGRecorder.maxFrames=Math.max(1,Math.floor(s)))};const r=e.createCanvas;if(typeof r=="function"&&(e.createCanvas=function(...s){const n=r.apply(this,s);this._p5ExportSVGRecorder=null,jr(this);try{Lr(t,this)}catch{}return n}),i&&typeof i=="object"){const s=i.presetup;i.presetup=function(){typeof s=="function"&&s.call(this);try{Lr(t,this)}catch{}};const n=i.postsetup;i.postsetup=function(){typeof n=="function"&&n.call(this),jr(this)};const a=i.predraw;i.predraw=function(){typeof a=="function"&&a.call(this),this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.markFrameBoundary()}}}function kn(t){return new Promise((e,i)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=i,r.readAsDataURL(t)})}let Ke=null;function An(){return Ke||(Ke=(async()=>{if(typeof window<"u"){if(window.jspdf&&window.jspdf.jsPDF)return window.jspdf.jsPDF;if(window.jsPDF)return window.jsPDF}try{const t=await import("jspdf");if(t&&t.jsPDF)return t.jsPDF}catch{}throw new Error('[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.')})(),Ke)}function Mn(t,e){e.savePDF=async function(i,r={}){const s=bt(this);if(!s)throw new Error("[p5.export] savePDF: no canvas found");const n=await An(),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;let h;if(!p||p<=1||p<=(this.pixelDensity?this.pixelDensity():1))h=s.toDataURL(l,r.quality);else{const O=await Dr(this,p,v,r.quality);O?h=await kn(O):h=await Wr(this,p,()=>bt(this).toDataURL(l,r.quality))}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(),S=Math.min(y/u,C/g),_=u*S,M=g*S,j=(y-_)/2,B=(C-M)/2;return w.addImage(h,a,j,B,_,M),w.save(i?yt(i,"pdf"):vt("pdf")),w}}var In={trailer:59};function Yr(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView(){return i.subarray(0,e)},bytes(){return i.slice(0,e)},writeByte(s){r(e+1),i[e]=s,e++},writeBytes(s,n=0,a=s.length){r(e+a);for(let l=0;l<a;l++)i[e++]=s[l+n]},writeBytesView(s,n=0,a=s.byteLength){r(e+a),i.set(s.subarray(n,n+a),e),e+=a}};function r(s){var n=i.length;if(n>=s)return;var a=1024*1024;s=Math.max(s,n*(n<a?2:1.125)>>>0),n!=0&&(s=Math.max(s,256));let l=i;i=new Uint8Array(s),e>0&&i.set(l.subarray(0,e),0)}}var Ri=12,Jr=5003,Pn=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function Rn(t,e,i,r,s=Yr(512),n=new Uint8Array(256),a=new Int32Array(Jr),l=new Int32Array(Jr)){let u=a.length,g=Math.max(2,r);n.fill(0),l.fill(0),a.fill(-1);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,S=y+2,_=0,M=i[0],j=0;for(let G=u;G<65536;G*=2)++j;j=8-j,s.writeByte(g),O(y);let B=i.length;for(let G=1;G<B;G++)t:{let tt=i[G],X=(tt<<Ri)+M,q=tt<<j^M;if(a[q]===X){M=l[q];break t}let ht=q===0?1:u-q;for(;a[q]>=0;)if(q-=ht,q<0&&(q+=u),a[q]===X){M=l[q];break t}O(M),M=tt,S<1<<Ri?(l[q]=S++,a[q]=X):(a.fill(-1),S=y+2,f=!0,O(y))}return O(M),O(C),s.writeByte(0),s.bytesView();function O(G){for(v&=Pn[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;if((S>w||f)&&(f?(m=d,w=(1<<m)-1,f=!1):(++m,w=m===Ri?1<<m:(1<<m)-1)),G==C){for(;p>0;)n[_++]=v&255,_>=254&&(s.writeByte(_),s.writeBytesView(n,0,_),_=0),v>>=8,p-=8;_>0&&(s.writeByte(_),s.writeBytesView(n,0,_),_=0)}}}var Bn=Rn;function Kr(t,e,i){return t<<8&63488|e<<2&992|i>>3}function Zr(t,e,i,r){return t>>4|e&240|(i&240)<<4|(r&240)<<8}function Qr(t,e,i){return t>>4<<8|e&240|i>>4}function Ze(t,e,i){return t<e?e:t>i?i:t}function Qe(t){return t*t}function ts(t,e,i){var r=0,s=1e100;let n=t[e],a=n.cnt;n.ac;let l=n.rc,u=n.gc,g=n.bc;for(var v=n.fw;v!=0;v=t[v].fw){let h=t[v],d=h.cnt,f=a*d/(a+d);if(!(f>=s)){var p=0;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)))}}n.err=s,n.nn=r}function Bi(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function Fn(t,e){let i=e==="rgb444"?4096:65536,r=new Array(i),s=t.length;if(e==="rgba4444")for(let n=0;n<s;++n){let a=t[n],l=a>>24&255,u=a>>16&255,g=a>>8&255,v=a&255,p=Zr(v,g,u,l),h=p in r?r[p]:r[p]=Bi();h.rc+=v,h.gc+=g,h.bc+=u,h.ac+=l,h.cnt++}else if(e==="rgb444")for(let n=0;n<s;++n){let a=t[n],l=a>>16&255,u=a>>8&255,g=a&255,v=Qr(g,u,l),p=v in r?r[v]:r[v]=Bi();p.rc+=g,p.gc+=u,p.bc+=l,p.cnt++}else for(let n=0;n<s;++n){let a=t[n],l=a>>16&255,u=a>>8&255,g=a&255,v=Kr(g,u,l),p=v in r?r[v]:r[v]=Bi();p.rc+=g,p.gc+=u,p.bc+=l,p.cnt++}return r}function es(t,e,i={}){let{format:r="rgb565",clearAlpha:s=!0,clearAlphaColor:n=0,clearAlphaThreshold:a=0,oneBitAlpha:l=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let u=new Uint32Array(t.buffer),g=i.useSqrt!==!1,v=r==="rgba4444",p=Fn(u,r),h=p.length,d=h-1,f=new Uint32Array(h+1);for(var m=0,w=0;w<h;++w){let Y=p[w];if(Y!=null){var y=1/Y.cnt;v&&(Y.ac*=y),Y.rc*=y,Y.gc*=y,Y.bc*=y,p[m++]=Y}}Qe(e)/m<.022&&(g=!1);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));g&&(p[w].cnt=Math.sqrt(p[w].cnt));var C,S,_;for(w=0;w<m;++w){ts(p,w);var M=p[w].err;for(S=++f[0];S>1&&(_=S>>1,!(p[C=f[_]].err<=M));S=_)f[S]=C;f[S]=w}var j=m-e;for(w=0;w<j;){for(var B;;){var O=f[1];if(B=p[O],B.tm>=B.mtm&&p[B.nn].mtm<=B.tm)break;B.mtm==d?O=f[1]=f[f[0]--]:(ts(p,O),B.tm=w);var M=p[O].err;for(S=1;(_=S+S)<=f[0]&&(_<f[0]&&p[f[_]].err>p[f[_+1]].err&&_++,!(M<=p[C=f[_]].err));S=_)f[S]=C;f[S]=O}var G=p[B.nn],tt=B.cnt,X=G.cnt,y=1/(tt+X);v&&(B.ac=y*(tt*B.ac+X*G.ac)),B.rc=y*(tt*B.rc+X*G.rc),B.gc=y*(tt*B.gc+X*G.gc),B.bc=y*(tt*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}let q=[];var ht=0;for(w=0;;++ht){let Y=Ze(Math.round(p[w].rc),0,255),L=Ze(Math.round(p[w].gc),0,255),A=Ze(Math.round(p[w].bc),0,255),F=255;v&&(F=Ze(Math.round(p[w].ac),0,255),l&&(F=F<=(typeof l=="number"?l:127)?0:255),s&&F<=a&&(Y=L=A=n,F=0));let b=v?[Y,L,A,F]:[Y,L,A];if(Un(q,b)||q.push(b),(w=p[w].fw)==0)break}return q}function Un(t,e){for(let i=0;i<t.length;i++){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;if(s&&n)return!0}return!1}function is(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");let r=new Uint32Array(t.buffer),s=r.length,n=i==="rgb444"?4096:65536,a=new Uint8Array(s),l=new Array(n);if(i==="rgba4444")for(let u=0;u<s;u++){let g=r[u],v=g>>24&255,p=g>>16&255,h=g>>8&255,d=g&255,f=Zr(d,h,p,v),m=f in l?l[f]:l[f]=Dn(d,h,p,v,e);a[u]=m}else{let u=i==="rgb444"?Qr:Kr;for(let g=0;g<s;g++){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]=Wn(d,h,p,e);a[g]=m}}return a}function Dn(t,e,i,r,s){let n=0,a=1e100;for(let l=0;l<s.length;l++){let u=s[l],g=u[3],v=Wt(g-r);if(v>a)continue;let p=u[0];if(v+=Wt(p-t),v>a)continue;let h=u[1];if(v+=Wt(h-e),v>a)continue;let d=u[2];v+=Wt(d-i),!(v>a)&&(a=v,n=l)}return n}function Wn(t,e,i,r){let s=0,n=1e100;for(let a=0;a<r.length;a++){let l=r[a],u=l[0],g=Wt(u-t);if(g>n)continue;let v=l[1];if(g+=Wt(v-e),g>n)continue;let p=l[2];g+=Wt(p-i),!(g>n)&&(n=g,s=a)}return s}function Wt(t){return t*t}function rs(t={}){let{initialCapacity:e=4096,auto:i=!0}=t,r=Yr(e),s=5003,n=new Uint8Array(256),a=new Int32Array(s),l=new Int32Array(s),u=!1;return{reset(){r.reset(),u=!1},finish(){r.writeByte(In.trailer)},bytes(){return r.bytes()},bytesView(){return r.bytesView()},get buffer(){return r.buffer},get stream(){return r},writeHeader:g,writeFrame(v,p,h,d={}){let{transparent:f=!1,transparentIndex:m=0,delay:w=0,palette:y=null,repeat:C=0,colorDepth:S=8,dispose:_=-1}=d,M=!1;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){if(!y)throw new Error("First frame must include a { palette } option");Vn(r,p,h,y,S),ss(r,y),C>=0&&Ln(r,C)}let j=Math.round(w/10);zn(r,_,j,f,m);let B=!!y&&!M;On(r,p,h,B?y:null),B&&ss(r,y),Gn(r,v,p,h,S,n,a,l)}};function g(){ns(r,"GIF89a")}}function zn(t,e,i,r,s){t.writeByte(33),t.writeByte(249),t.writeByte(4),s<0&&(s=0,r=!1);var n,a;r?(n=1,a=2):(n=0,a=0),e>=0&&(a=e&7),a<<=2,t.writeByte(0|a|0|n),At(t,i),t.writeByte(s||0),t.writeByte(0)}function Vn(t,e,i,r,s=8){let n=1,a=0,l=Fi(r.length)-1,u=n<<7|s-1<<4|a<<3|l;At(t,e),At(t,i),t.writeBytes([u,0,0])}function Ln(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),ns(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),At(t,e),t.writeByte(0)}function ss(t,e){let i=1<<Fi(e.length);for(let r=0;r<i;r++){let s=[0,0,0];r<e.length&&(s=e[r]),t.writeByte(s[0]),t.writeByte(s[1]),t.writeByte(s[2])}}function On(t,e,i,r){if(t.writeByte(44),At(t,0),At(t,0),At(t,e),At(t,i),r){let s=0,n=0,a=Fi(r.length)-1;t.writeByte(128|s|n|0|a)}else t.writeByte(0)}function Gn(t,e,i,r,s=8,n,a,l){Bn(i,r,e,s,t,n,a,l)}function At(t,e){t.writeByte(e&255),t.writeByte(e>>8&255)}function ns(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function Fi(t){return Math.max(Math.ceil(Math.log2(t)),1)}class Nn{constructor(e){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||(()=>{}),this.frames=[],this.startTime=0,this.active=!1,this.framesRecorded=0}start(){this.active||(this.frames=[],this.framesRecorded=0,this.startTime=performance.now(),this.active=!0,this._nextFrameAt=this.startTime)}tick(){if(!this.active)return;const e=performance.now();if(e<this._nextFrameAt)return;const i=this.canvas.getContext("2d",{willReadFrequently:!0})||this.canvas.getContext("webgl2")||this.canvas.getContext("webgl");let r;if(i&&i.getImageData)r=i.getImageData(0,0,this.canvas.width,this.canvas.height).data;else{const s=document.createElement("canvas");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}this.frames.push({data:new Uint8ClampedArray(r),width:this.canvas.width,height:this.canvas.height}),this.framesRecorded++,this._nextFrameAt+=1e3/this.fps,this.duration&&e-this.startTime>=this.duration*1e3&&this.stop()}async stop(){if(!this.active)return null;this.active=!1;const e=await this._encode(),i=this.filename?yt(this.filename,"gif"):vt("gif");return rt(e,i),e}async encode(){return this.active=!1,this._encode()}async _encode(){const e=rs(),i=Math.round(1e3/this.fps),r=this.frames.length;for(let s=0;s<r;s++){const n=this.frames[s],a=es(n.data,this.maxColors),l=is(n.data,a);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))}return e.finish(),new Blob([e.bytes()],{type:"image/gif"})}}function $n(t,e,i){if(e.recordGIF=function(r={}){const s=bt(this);if(!s)throw new Error("[p5.export] recordGIF: no canvas found");if(this._p5ExportGIF&&this._p5ExportGIF.active)throw new Error("[p5.export] a GIF recording is already in progress");const n=new Nn({canvas:s,...r});return n.start(),this._p5ExportGIF=n,n},e.stopGIF=function(){const r=this._p5ExportGIF;return r?(this._p5ExportGIF=null,r.stop()):null},i&&typeof i=="object"){const r=i.postdraw;i.postdraw=function(){typeof r=="function"&&r.call(this),this._p5ExportGIF&&this._p5ExportGIF.active&&this._p5ExportGIF.tick()}}}class jn{constructor({canvas:e,fps:i=30,duration:r,maxFrames:s=900}){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}start(){this.frames=[],this.recording=!0,this.startTime=performance.now(),this._nextFrameAt=this.startTime}tick(){if(!this.recording)return;const e=performance.now();if(e<this._nextFrameAt)return;if(this.frames.length>=this.maxFrames){this.stop();return}let i;const r=this.canvas.getContext("2d",{willReadFrequently:!0});if(r&&typeof r.getImageData=="function")i=r.getImageData(0,0,this.width,this.height).data;else{const s=document.createElement("canvas");s.width=this.width,s.height=this.height;const n=s.getContext("2d");n.drawImage(this.canvas,0,0),i=n.getImageData(0,0,this.width,this.height).data}this.frames.push(new Uint8ClampedArray(i)),this._nextFrameAt+=1e3/this.fps,this.duration&&e-this.startTime>=this.duration*1e3&&this.stop()}stop(){this.recording=!1}clear(){this.frames=[]}get framesRecorded(){return this.frames.length}get capturedSeconds(){return this.frames.length/this.fps}}var Ui=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},c=(t,e,i)=>(Ui(t,e,"read from private field"),i?i.call(t):e.get(t)),D=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},Z=(t,e,i,r)=>(Ui(t,e,"write to private field"),e.set(t,i),i),qn=(t,e,i,r)=>({set _(s){Z(t,e,s)},get _(){return c(t,e,r)}}),z=(t,e,i)=>(Ui(t,e,"access private method"),i),V=new Uint8Array(8),dt=new DataView(V.buffer),K=t=>[(t%256+256)%256],$=t=>(dt.setUint16(0,t,!1),[V[0],V[1]]),Hn=t=>(dt.setInt16(0,t,!1),[V[0],V[1]]),as=t=>(dt.setUint32(0,t,!1),[V[1],V[2],V[3]]),E=t=>(dt.setUint32(0,t,!1),[V[0],V[1],V[2],V[3]]),Xn=t=>(dt.setInt32(0,t,!1),[V[0],V[1],V[2],V[3]]),zt=t=>(dt.setUint32(0,Math.floor(t/2**32),!1),dt.setUint32(4,t,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Di=t=>(dt.setInt16(0,2**8*t,!1),[V[0],V[1]]),ct=t=>(dt.setInt32(0,2**16*t,!1),[V[0],V[1],V[2],V[3]]),Wi=t=>(dt.setInt32(0,2**30*t,!1),[V[0],V[1],V[2],V[3]]),ot=(t,e=!1)=>{let i=Array(t.length).fill(null).map((r,s)=>t.charCodeAt(s));return e&&i.push(0),i},ti=t=>t&&t[t.length-1],zi=t=>{let e;for(let i of t)(!e||i.presentationTimestamp>e.presentationTimestamp)&&(e=i);return e},ft=(t,e,i=!0)=>{let r=t*e;return i?Math.round(r):r},os=t=>{let e=t*(Math.PI/180),i=Math.cos(e),r=Math.sin(e);return[i,r,0,-r,i,0,0,0,1]},hs=os(0),ls=t=>[ct(t[0]),ct(t[1]),Wi(t[2]),ct(t[3]),ct(t[4]),Wi(t[5]),ct(t[6]),ct(t[7]),Wi(t[8])],ve=t=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(ve):Object.fromEntries(Object.entries(t).map(([e,i])=>[e,ve(i)])),Kt=t=>t>=0&&t<2**32,J=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),H=(t,e,i,r,s)=>J(t,[K(e),as(i),r??[]],s),Yn=t=>{let e=512;return t.fragmented?J("ftyp",[ot("iso5"),E(e),ot("iso5"),ot("iso6"),ot("mp41")]):J("ftyp",[ot("isom"),E(e),ot("isom"),t.holdsAvc?ot("avc1"):[],ot("mp41")])},Vi=t=>({type:"mdat",largeSize:t}),Jn=t=>({type:"free",size:t}),ei=(t,e,i=!1)=>J("moov",null,[Kn(e,t),...t.map(r=>Zn(r,e)),i?Ma(t):null]),Kn=(t,e)=>{let i=ft(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const l=zi(a.samples);return l.presentationTimestamp+l.duration})),ji),r=Math.max(...e.map(a=>a.id))+1,s=!Kt(t)||!Kt(i),n=s?zt:E;return H("mvhd",+s,0,[n(t),n(t),E(ji),n(i),ct(1),Di(1),Array(10).fill(0),ls(hs),Array(24).fill(0),E(r)])},Zn=(t,e)=>J("trak",null,[Qn(t,e),ta(t,e)]),Qn=(t,e)=>{let i=zi(t.samples),r=ft(i?i.presentationTimestamp+i.duration:0,ji),s=!Kt(e)||!Kt(r),n=s?zt:E,a;return t.info.type==="video"?a=typeof t.info.rotation=="number"?os(t.info.rotation):t.info.rotation:a=hs,H("tkhd",+s,3,[n(e),n(e),E(t.id),E(0),n(r),Array(8).fill(0),$(0),$(0),Di(t.info.type==="audio"?1:0),$(0),ls(a),ct(t.info.type==="video"?t.info.width:0),ct(t.info.type==="video"?t.info.height:0)])},ta=(t,e)=>J("mdia",null,[ea(t,e),ia(t.info.type==="video"?"vide":"soun"),ra(t)]),ea=(t,e)=>{let i=zi(t.samples),r=ft(i?i.presentationTimestamp+i.duration:0,t.timescale),s=!Kt(e)||!Kt(r),n=s?zt:E;return H("mdhd",+s,0,[n(e),n(e),E(t.timescale),n(r),$(21956),$(0)])},ia=t=>H("hdlr",0,0,[ot("mhlr"),ot(t),E(0),E(0),E(0),ot("mp4-muxer-hdlr",!0)]),ra=t=>J("minf",null,[t.info.type==="video"?sa():na(),aa(),la(t)]),sa=()=>H("vmhd",0,1,[$(0),$(0),$(0),$(0)]),na=()=>H("smhd",0,0,[$(0),$(0)]),aa=()=>J("dinf",null,[oa()]),oa=()=>H("dref",0,0,[E(1)],[ha()]),ha=()=>H("url ",0,1),la=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(i=>i.sampleCompositionTimeOffset!==0);return J("stbl",null,[da(t),Sa(t),Ca(t),Ea(t),Ta(t),ka(t),e?Aa(t):null])},da=t=>H("stsd",0,0,[E(1)],[t.info.type==="video"?ca(Va[t.info.codec],t):ba(Oa[t.info.codec],t)]),ca=(t,e)=>J(t,[Array(6).fill(0),$(1),$(0),$(0),Array(12).fill(0),$(e.info.width),$(e.info.height),E(4718592),E(4718592),E(0),$(1),Array(32).fill(0),$(24),Hn(65535)],[La[e.info.codec](e),e.info.decoderConfig.colorSpace?ma(e):null]),fa={bt709:1,bt470bg:5,smpte170m:6},ua={bt709:1,smpte170m:6,"iec61966-2-1":13},pa={rgb:0,bt709:1,bt470bg:5,smpte170m:6},ma=t=>J("colr",[ot("nclx"),$(fa[t.info.decoderConfig.colorSpace.primaries]),$(ua[t.info.decoderConfig.colorSpace.transfer]),$(pa[t.info.decoderConfig.colorSpace.matrix]),K((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),wa=t=>t.info.decoderConfig&&J("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),ga=t=>t.info.decoderConfig&&J("hvcC",[...new Uint8Array(t.info.decoderConfig.description)]),va=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig;if(!e.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let i=e.codec.split("."),r=Number(i[1]),s=Number(i[2]),l=(Number(i[3])<<4)+(0<<1)+Number(e.colorSpace.fullRange);return H("vpcC",1,0,[K(r),K(s),K(l),K(2),K(2),K(2),$(0)])},ya=()=>{let i=(1<<7)+1;return J("av1C",[i,0,0,0])},ba=(t,e)=>J(t,[Array(6).fill(0),$(1),$(0),$(0),E(0),$(e.info.numberOfChannels),$(16),$(0),$(0),ct(e.info.sampleRate)],[Ga[e.info.codec](e)]),_a=t=>{let e=new Uint8Array(t.info.decoderConfig.description);return H("esds",0,0,[E(58753152),K(32+e.byteLength),$(1),K(0),E(75530368),K(18+e.byteLength),K(64),K(21),as(0),E(130071),E(130071),E(92307584),K(e.byteLength),...e,E(109084800),K(1),K(2)])},xa=t=>{var s;let e=3840,i=0;const r=(s=t.info.decoderConfig)==null?void 0:s.description;if(r){if(r.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const n=ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r);e=n.getUint16(10,!0),i=n.getInt16(14,!0)}return J("dOps",[K(0),K(t.info.numberOfChannels),$(e),E(t.info.sampleRate),Di(i),K(0)])},Sa=t=>H("stts",0,0,[E(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[E(e.sampleCount),E(e.sampleDelta)])]),Ca=t=>{if(t.samples.every(i=>i.type==="key"))return null;let e=[...t.samples.entries()].filter(([,i])=>i.type==="key");return H("stss",0,0,[E(e.length),e.map(([i])=>E(i+1))])},Ea=t=>H("stsc",0,0,[E(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[E(e.firstChunk),E(e.samplesPerChunk),E(1)])]),Ta=t=>H("stsz",0,0,[E(0),E(t.samples.length),t.samples.map(e=>E(e.size))]),ka=t=>t.finalizedChunks.length>0&&ti(t.finalizedChunks).offset>=2**32?H("co64",0,0,[E(t.finalizedChunks.length),t.finalizedChunks.map(e=>zt(e.offset))]):H("stco",0,0,[E(t.finalizedChunks.length),t.finalizedChunks.map(e=>E(e.offset))]),Aa=t=>H("ctts",0,0,[E(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[E(e.sampleCount),E(e.sampleCompositionTimeOffset)])]),Ma=t=>J("mvex",null,t.map(Ia)),Ia=t=>H("trex",0,0,[E(t.id),E(1),E(0),E(0),E(0)]),ds=(t,e)=>J("moof",null,[Pa(t),...e.map(Ra)]),Pa=t=>H("mfhd",0,0,[E(t)]),cs=t=>{let e=0,i=0,r=0,s=0,n=t.type==="delta";return i|=+n,n?e|=1:e|=2,e<<24|i<<16|r<<8|s},Ra=t=>J("traf",null,[Ba(t),Fa(t),Ua(t)]),Ba=t=>{let e=0;e|=8,e|=16,e|=32,e|=131072;let i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:cs(i)};return H("tfhd",0,e,[E(t.id),E(r.duration),E(r.size),E(r.flags)])},Fa=t=>H("tfdt",1,0,[zt(ft(t.currentChunk.startTimestamp,t.timescale))]),Ua=t=>{let e=t.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(m=>m.size),r=t.currentChunk.samples.map(cs),s=t.currentChunk.samples.map(m=>ft(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;return f|=1,f|=4*+g,f|=256*+v,f|=512*+p,f|=1024*+h,f|=2048*+d,H("trun",1,f,[E(t.currentChunk.samples.length),E(t.currentChunk.offset-t.currentChunk.moofOffset||0),g?E(r[0]):[],t.currentChunk.samples.map((m,w)=>[v?E(e[w]):[],p?E(i[w]):[],h?E(r[w]):[],d?Xn(s[w]):[]])])},Da=t=>J("mfra",null,[...t.map(Wa),za()]),Wa=(t,e)=>H("tfra",1,0,[E(t.id),E(63),E(t.finalizedChunks.length),t.finalizedChunks.map(r=>[zt(ft(r.startTimestamp,t.timescale)),zt(r.moofOffset),E(e+1),E(1),E(1)])]),za=()=>H("mfro",0,0,[E(0)]),Va={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},La={avc:wa,hevc:ga,vp9:va,av1:ya},Oa={aac:"mp4a",opus:"Opus"},Ga={aac:_a,opus:xa},ii=class{},fs=class extends ii{constructor(){super(...arguments),this.buffer=null}},us=class extends ii{constructor(e){if(super(),this.options=e,typeof e!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(e.onData){if(typeof e.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(e.onData.length<2)throw new TypeError("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.")}if(e.chunked!==void 0&&typeof e.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},Na=class extends ii{constructor(e,i){if(super(),this.stream=e,this.options=i,!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(i!==void 0&&typeof i!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(i&&i.chunkSize!==void 0&&(!Number.isInteger(i.chunkSize)||i.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},Vt,Zt,ps=class{constructor(){this.pos=0,D(this,Vt,new Uint8Array(8)),D(this,Zt,new DataView(c(this,Vt).buffer)),this.offsets=new WeakMap}seek(e){this.pos=e}writeU32(e){c(this,Zt).setUint32(0,e,!1),this.write(c(this,Vt).subarray(0,4))}writeU64(e){c(this,Zt).setUint32(0,Math.floor(e/2**32),!1),c(this,Zt).setUint32(4,e,!1),this.write(c(this,Vt).subarray(0,8))}writeAscii(e){for(let i=0;i<e.length;i++)c(this,Zt).setUint8(i%8,e.charCodeAt(i)),i%8===7&&this.write(c(this,Vt));e.length%8!==0&&this.write(c(this,Vt).subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.pos),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.write(e.contents);else{let i=this.pos;if(this.writeBoxHeader(e,0),e.contents&&this.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let r=this.pos,s=e.size??r-i;this.seek(i),this.writeBoxHeader(e,s),this.seek(r)}}writeBoxHeader(e,i){this.writeU32(e.largeSize?1:i),this.writeAscii(e.type),e.largeSize&&this.writeU64(i)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let i=this.pos;this.seek(this.offsets.get(e)),this.writeBox(e),this.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let i=this.measureBoxHeader(e);if(e.contents&&(i+=e.contents.byteLength),e.children)for(let r of e.children)r&&(i+=this.measureBox(r));return i}}};Vt=new WeakMap,Zt=new WeakMap;var ri,Lt,ye,be,si,Li,$a=class extends ps{constructor(e){super(),D(this,si),D(this,ri,void 0),D(this,Lt,new ArrayBuffer(2**16)),D(this,ye,new Uint8Array(c(this,Lt))),D(this,be,0),Z(this,ri,e)}write(e){z(this,si,Li).call(this,this.pos+e.byteLength),c(this,ye).set(e,this.pos),this.pos+=e.byteLength,Z(this,be,Math.max(c(this,be),this.pos))}finalize(){z(this,si,Li).call(this,this.pos),c(this,ri).buffer=c(this,Lt).slice(0,Math.max(c(this,be),this.pos))}};ri=new WeakMap,Lt=new WeakMap,ye=new WeakMap,be=new WeakMap,si=new WeakSet,Li=function(t){let e=c(this,Lt).byteLength;for(;e<t;)e*=2;if(e===c(this,Lt).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(c(this,ye),0),Z(this,Lt,i),Z(this,ye,r)};var ja=2**24,qa=2,_e,Ot,xe,xt,st,ni,Oi,Gi,ms,Ni,ws,Se,ai,$i=class extends ps{constructor(e){var i,r;super(),D(this,ni),D(this,Gi),D(this,Ni),D(this,Se),D(this,_e,void 0),D(this,Ot,[]),D(this,xe,void 0),D(this,xt,void 0),D(this,st,[]),Z(this,_e,e),Z(this,xe,((i=e.options)==null?void 0:i.chunked)??!1),Z(this,xt,((r=e.options)==null?void 0:r.chunkSize)??ja)}write(e){c(this,Ot).push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}flush(){var r,s;if(c(this,Ot).length===0)return;let e=[],i=[...c(this,Ot)].sort((n,a)=>n.start-a.start);e.push({start:i[0].start,size:i[0].data.byteLength});for(let n=1;n<i.length;n++){let a=e[e.length-1],l=i[n];l.start<=a.start+a.size?a.size=Math.max(a.size,l.start+l.data.byteLength-a.start):e.push({start:l.start,size:l.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let a of c(this,Ot))n.start<=a.start&&a.start<n.start+n.size&&n.data.set(a.data,a.start-n.start);c(this,xe)?(z(this,ni,Oi).call(this,n.data,n.start),z(this,Se,ai).call(this)):(s=(r=c(this,_e).options).onData)==null||s.call(r,n.data,n.start)}c(this,Ot).length=0}finalize(){c(this,xe)&&z(this,Se,ai).call(this,!0)}};_e=new WeakMap,Ot=new WeakMap,xe=new WeakMap,xt=new WeakMap,st=new WeakMap,ni=new WeakSet,Oi=function(t,e){let i=c(this,st).findIndex(l=>l.start<=e&&e<l.start+c(this,xt));i===-1&&(i=z(this,Ni,ws).call(this,e));let r=c(this,st)[i],s=e-r.start,n=t.subarray(0,Math.min(c(this,xt)-s,t.byteLength));r.data.set(n,s);let a={start:s,end:s+n.byteLength};if(z(this,Gi,ms).call(this,r,a),r.written[0].start===0&&r.written[0].end===c(this,xt)&&(r.shouldFlush=!0),c(this,st).length>qa){for(let l=0;l<c(this,st).length-1;l++)c(this,st)[l].shouldFlush=!0;z(this,Se,ai).call(this)}n.byteLength<t.byteLength&&z(this,ni,Oi).call(this,t.subarray(n.byteLength),e+n.byteLength)},Gi=new WeakSet,ms=function(t,e){let i=0,r=t.written.length-1,s=-1;for(;i<=r;){let n=Math.floor(i+(r-i+1)/2);t.written[n].start<=e.start?(i=n+1,s=n):r=n-1}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;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)},Ni=new WeakSet,ws=function(t){let i={start:Math.floor(t/c(this,xt))*c(this,xt),data:new Uint8Array(c(this,xt)),written:[],shouldFlush:!1};return c(this,st).push(i),c(this,st).sort((r,s)=>r.start-s.start),c(this,st).indexOf(i)},Se=new WeakSet,ai=function(t=!1){var e,i;for(let r=0;r<c(this,st).length;r++){let s=c(this,st)[r];if(!(!s.shouldFlush&&!t)){for(let n of s.written)(i=(e=c(this,_e).options).onData)==null||i.call(e,s.data.subarray(n.start,n.end),s.start+n.start);c(this,st).splice(r--,1)}}};var Ha=class extends $i{constructor(e){var i;super(new us({onData:(r,s)=>e.stream.write({type:"write",data:r,position:s}),chunked:!0,chunkSize:(i=e.options)==null?void 0:i.chunkSize}))}},ji=1e3,Xa=["avc","hevc","vp9","av1"],Ya=["aac","opus"],Ja=2082844800,Ka=["strict","offset","cross-track-offset"],I,R,oi,nt,it,Q,Qt,te,qi,Gt,Nt,Ce,Hi,gs,Xi,vs,Yi,ys,Ji,bs,Ki,_s,hi,Zi,ut,St,Qi,xs,Ee,li,di,tr,ee,Te,ci,er,Za=class{constructor(e){if(D(this,Hi),D(this,Xi),D(this,Yi),D(this,Ji),D(this,Ki),D(this,hi),D(this,ut),D(this,Qi),D(this,Ee),D(this,di),D(this,ee),D(this,ci),D(this,I,void 0),D(this,R,void 0),D(this,oi,void 0),D(this,nt,void 0),D(this,it,null),D(this,Q,null),D(this,Qt,Math.floor(Date.now()/1e3)+Ja),D(this,te,[]),D(this,qi,1),D(this,Gt,[]),D(this,Nt,[]),D(this,Ce,!1),z(this,Hi,gs).call(this,e),e.video=ve(e.video),e.audio=ve(e.audio),e.fastStart=ve(e.fastStart),this.target=e.target,Z(this,I,{firstTimestampBehavior:"strict",...e}),e.target instanceof fs)Z(this,R,new $a(e.target));else if(e.target instanceof us)Z(this,R,new $i(e.target));else if(e.target instanceof Na)Z(this,R,new Ha(e.target));else throw new Error(`Invalid target: ${e.target}`);z(this,Ji,bs).call(this),z(this,Xi,vs).call(this)}addVideoChunk(e,i,r,s){if(!(e instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(i&&typeof i!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(s!==void 0&&!Number.isFinite(s))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let n=new Uint8Array(e.byteLength);e.copyTo(n),this.addVideoChunkRaw(n,e.type,r??e.timestamp,e.duration,i,s)}addVideoChunkRaw(e,i,r,s,n,a){if(!(e instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(r)||r<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(n&&typeof n!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(a!==void 0&&!Number.isFinite(a))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(z(this,ci,er).call(this),!c(this,I).video)throw new Error("No video track declared.");if(typeof c(this,I).fastStart=="object"&&c(this,it).samples.length===c(this,I).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${c(this,I).fastStart.expectedVideoChunks}).`);let l=z(this,hi,Zi).call(this,c(this,it),e,i,r,s,n,a);if(c(this,I).fastStart==="fragmented"&&c(this,Q)){for(;c(this,Nt).length>0&&c(this,Nt)[0].decodeTimestamp<=l.decodeTimestamp;){let u=c(this,Nt).shift();z(this,ut,St).call(this,c(this,Q),u)}l.decodeTimestamp<=c(this,Q).lastDecodeTimestamp?z(this,ut,St).call(this,c(this,it),l):c(this,Gt).push(l)}else z(this,ut,St).call(this,c(this,it),l)}addAudioChunk(e,i,r){if(!(e instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(i&&typeof i!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let s=new Uint8Array(e.byteLength);e.copyTo(s),this.addAudioChunkRaw(s,e.type,r??e.timestamp,e.duration,i)}addAudioChunkRaw(e,i,r,s,n){if(!(e instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(r)||r<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(n&&typeof n!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(z(this,ci,er).call(this),!c(this,I).audio)throw new Error("No audio track declared.");if(typeof c(this,I).fastStart=="object"&&c(this,Q).samples.length===c(this,I).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${c(this,I).fastStart.expectedAudioChunks}).`);let a=z(this,hi,Zi).call(this,c(this,Q),e,i,r,s,n);if(c(this,I).fastStart==="fragmented"&&c(this,it)){for(;c(this,Gt).length>0&&c(this,Gt)[0].decodeTimestamp<=a.decodeTimestamp;){let l=c(this,Gt).shift();z(this,ut,St).call(this,c(this,it),l)}a.decodeTimestamp<=c(this,it).lastDecodeTimestamp?z(this,ut,St).call(this,c(this,Q),a):c(this,Nt).push(a)}else z(this,ut,St).call(this,c(this,Q),a)}finalize(){if(c(this,Ce))throw new Error("Cannot finalize a muxer more than once.");if(c(this,I).fastStart==="fragmented"){for(let i of c(this,Gt))z(this,ut,St).call(this,c(this,it),i);for(let i of c(this,Nt))z(this,ut,St).call(this,c(this,Q),i);z(this,di,tr).call(this,!1)}else c(this,it)&&z(this,Ee,li).call(this,c(this,it)),c(this,Q)&&z(this,Ee,li).call(this,c(this,Q));let e=[c(this,it),c(this,Q)].filter(Boolean);if(c(this,I).fastStart==="in-memory"){let i;for(let s=0;s<2;s++){let n=ei(e,c(this,Qt)),a=c(this,R).measureBox(n);i=c(this,R).measureBox(c(this,nt));let l=c(this,R).pos+a+i;for(let u of c(this,te)){u.offset=l;for(let{data:g}of u.samples)l+=g.byteLength,i+=g.byteLength}if(l<2**32)break;i>=2**32&&(c(this,nt).largeSize=!0)}let r=ei(e,c(this,Qt));c(this,R).writeBox(r),c(this,nt).size=i,c(this,R).writeBox(c(this,nt));for(let s of c(this,te))for(let n of s.samples)c(this,R).write(n.data),n.data=null}else if(c(this,I).fastStart==="fragmented"){let i=c(this,R).pos,r=Da(e);c(this,R).writeBox(r);let s=c(this,R).pos-i;c(this,R).seek(c(this,R).pos-4),c(this,R).writeU32(s)}else{let i=c(this,R).offsets.get(c(this,nt)),r=c(this,R).pos-i;c(this,nt).size=r,c(this,nt).largeSize=r>=2**32,c(this,R).patchBox(c(this,nt));let s=ei(e,c(this,Qt));if(typeof c(this,I).fastStart=="object"){c(this,R).seek(c(this,oi)),c(this,R).writeBox(s);let n=i-c(this,R).pos;c(this,R).writeBox(Jn(n))}else c(this,R).writeBox(s)}z(this,ee,Te).call(this),c(this,R).finalize(),Z(this,Ce,!0)}};I=new WeakMap,R=new WeakMap,oi=new WeakMap,nt=new WeakMap,it=new WeakMap,Q=new WeakMap,Qt=new WeakMap,te=new WeakMap,qi=new WeakMap,Gt=new WeakMap,Nt=new WeakMap,Ce=new WeakMap,Hi=new WeakSet,gs=function(t){if(typeof t!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(t.target instanceof ii))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(!Xa.includes(t.video.codec))throw new TypeError(`Unsupported video codec: ${t.video.codec}`);if(!Number.isInteger(t.video.width)||t.video.width<=0)throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);if(!Number.isInteger(t.video.height)||t.video.height<=0)throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);const e=t.video.rotation;if(typeof e=="number"&&![0,90,180,270].includes(e))throw new TypeError(`Invalid video rotation: ${e}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(e)&&(e.length!==9||e.some(i=>typeof i!="number")))throw new TypeError(`Invalid video transformation matrix: ${e.join()}`);if(t.video.frameRate!==void 0&&(!Number.isInteger(t.video.frameRate)||t.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.video.frameRate}. Must be a positive integer.`)}if(t.audio){if(!Ya.includes(t.audio.codec))throw new TypeError(`Unsupported audio codec: ${t.audio.codec}`);if(!Number.isInteger(t.audio.numberOfChannels)||t.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(t.audio.sampleRate)||t.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`)}if(t.firstTimestampBehavior&&!Ka.includes(t.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if(typeof t.fastStart=="object"){if(t.video){if(t.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(t.fastStart.expectedVideoChunks)||t.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(t.audio){if(t.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(t.fastStart.expectedAudioChunks)||t.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(t.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(t.minFragmentDuration!==void 0&&(!Number.isFinite(t.minFragmentDuration)||t.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")},Xi=new WeakSet,vs=function(){var t;if(c(this,R).writeBox(Yn({holdsAvc:((t=c(this,I).video)==null?void 0:t.codec)==="avc",fragmented:c(this,I).fastStart==="fragmented"})),Z(this,oi,c(this,R).pos),c(this,I).fastStart==="in-memory")Z(this,nt,Vi(!1));else if(c(this,I).fastStart!=="fragmented"){if(typeof c(this,I).fastStart=="object"){let e=z(this,Yi,ys).call(this);c(this,R).seek(c(this,R).pos+e)}Z(this,nt,Vi(!0)),c(this,R).writeBox(c(this,nt))}z(this,ee,Te).call(this)},Yi=new WeakSet,ys=function(){if(typeof c(this,I).fastStart!="object")return;let t=0,e=[c(this,I).fastStart.expectedVideoChunks,c(this,I).fastStart.expectedAudioChunks];for(let i of e)i&&(t+=8*Math.ceil(2/3*i),t+=4*i,t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i);return t+=4096,t},Ji=new WeakSet,bs=function(){if(c(this,I).video&&Z(this,it,{id:1,info:{type:"video",codec:c(this,I).video.codec,width:c(this,I).video.width,height:c(this,I).video.height,rotation:c(this,I).video.rotation??0,decoderConfig:null},timescale:c(this,I).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),c(this,I).audio&&(Z(this,Q,{id:c(this,I).video?2:1,info:{type:"audio",codec:c(this,I).audio.codec,numberOfChannels:c(this,I).audio.numberOfChannels,sampleRate:c(this,I).audio.sampleRate,decoderConfig:null},timescale:c(this,I).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),c(this,I).audio.codec==="aac")){let t=z(this,Ki,_s).call(this,2,c(this,I).audio.sampleRate,c(this,I).audio.numberOfChannels);c(this,Q).info.decoderConfig={codec:c(this,I).audio.codec,description:t,numberOfChannels:c(this,I).audio.numberOfChannels,sampleRate:c(this,I).audio.sampleRate}}},Ki=new WeakSet,_s=function(t,e,i){let s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(e),n=i,a="";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");let l=Math.ceil(a.length/8)*8;a=a.padEnd(l,"0");let u=new Uint8Array(a.length/8);for(let g=0;g<a.length;g+=8)u[g/8]=parseInt(a.slice(g,g+8),2);return u},hi=new WeakSet,Zi=function(t,e,i,r,s,n,a){let l=r/1e6,u=(r-(a??0))/1e6,g=s/1e6,v=z(this,Qi,xs).call(this,l,u,t);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)),{presentationTimestamp:l,decodeTimestamp:u,duration:g,data:e,size:e.byteLength,type:i,timescaleUnitsToNextSample:ft(g,t.timescale)}},ut=new WeakSet,St=function(t,e){c(this,I).fastStart!=="fragmented"&&t.samples.push(e);const i=ft(e.presentationTimestamp-e.decodeTimestamp,t.timescale);if(t.lastTimescaleUnits!==null){let s=ft(e.decodeTimestamp,t.timescale,!1),n=Math.round(s-t.lastTimescaleUnits);if(t.lastTimescaleUnits+=n,t.lastSample.timescaleUnitsToNextSample=n,c(this,I).fastStart!=="fragmented"){let a=ti(t.timeToSampleTable);a.sampleCount===1?(a.sampleDelta=n,a.sampleCount++):a.sampleDelta===n?a.sampleCount++:(a.sampleCount--,t.timeToSampleTable.push({sampleCount:2,sampleDelta:n}));const l=ti(t.compositionTimeOffsetTable);l.sampleCompositionTimeOffset===i?l.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else t.lastTimescaleUnits=0,c(this,I).fastStart!=="fragmented"&&(t.timeToSampleTable.push({sampleCount:1,sampleDelta:ft(e.duration,t.timescale)}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));t.lastSample=e;let r=!1;if(!t.currentChunk)r=!0;else{let s=e.presentationTimestamp-t.currentChunk.startTimestamp;if(c(this,I).fastStart==="fragmented"){let n=c(this,it)??c(this,Q);const a=c(this,I).minFragmentDuration??1;t===n&&e.type==="key"&&s>=a&&(r=!0,z(this,di,tr).call(this))}else r=s>=.5}r&&(t.currentChunk&&z(this,Ee,li).call(this,t),t.currentChunk={startTimestamp:e.presentationTimestamp,samples:[]}),t.currentChunk.samples.push(e)},Qi=new WeakSet,xs=function(t,e,i){var a,l;const r=c(this,I).firstTimestampBehavior==="strict",s=i.lastDecodeTimestamp===-1;if(r&&s&&e!==0)throw new Error(`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.
23
+ • saveSVG('out', { silent: true }) — never prompt; matches old behavior.`))return console.info("[p5.export] saveSVG cancelled by user"),null}if(a.raster||!u||p){const c=xt(this);if(!c)throw new Error("[p5.export] saveSVG: no canvas found");p?console.warn(`[p5.export] saveSVG: ${v.toLocaleString()} vector ops — falling back to raster.`):!u&&!a.raster&&console.info("[p5.export] saveSVG: WebGL renderer detected — embedding canvas as raster <image> in SVG."),l=Ds(c)}else l=tn(this,{outlineText:Qr(this,a)});const d=new Blob([l],{type:"image/svg+xml"});return rt(d,s?_t(s,"svg"):bt("svg")),d},e.getSVG=function(s={}){return this._p5ExportSVGRecorder?tn(this,{outlineText:Qr(this,s)}):""},e.setSVGTextMode=function(s){this._p5ExportSVGRecorder&&(this._p5ExportSVGRecorder.textOutline=s==="outline")},e.clearSVGRecording=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.clear()},e.beginRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"beginRaster"])},e.endRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"endRaster"])},e.rasterize=function(s){this.beginRasterRegion();try{return s.call(this)}finally{this.endRasterRegion()}},e.setSVGRecordingFrames=function(s){this._p5ExportSVGRecorder&&(s===1/0||s<0?this._p5ExportSVGRecorder.maxFrames=1/0:this._p5ExportSVGRecorder.maxFrames=Math.max(1,Math.floor(s)))};const r=e.createCanvas;typeof r=="function"&&(e.createCanvas=function(...s){const a=r.apply(this,s);this._p5ExportSVGRecorder=null,Kr(this);try{jr(t,this)}catch{}return a});const n=e.text;if(typeof n=="function"&&(e.text=function(s,a,l,u,m){const v=this._p5ExportSVGRecorder,p=this._renderer;if(!v||!p||!p.states)return n.apply(this,arguments);const h=p.states,d=h.textFont&&h.textFont.font,c={str:s,x:a,y:l,w:u,h:m,font:d,textSize:h.textSize,textAlign:h.textAlign,textBaseline:h.textBaseline,textLeading:h.textLeading,rectMode:h.rectMode,strokeWeight:h.strokeWeight,hasStroke:!!(h.strokeColor&&h.strokeSet),fill:null,stroke:null};v.ops.push([5,"textStart",c]);let w;try{w=n.apply(this,arguments),c.fill=this.drawingContext.fillStyle,c.hasStroke&&(c.stroke=this.drawingContext.strokeStyle)}finally{v.ops.push([5,"textEnd"])}return w}),i&&typeof i=="object"){const s=i.presetup;i.presetup=function(){typeof s=="function"&&s.call(this);try{jr(t,this)}catch{}};const a=i.postsetup;i.postsetup=function(){typeof a=="function"&&a.call(this),Kr(this)};const l=i.predraw;i.predraw=function(){typeof l=="function"&&l.call(this),this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.markFrameBoundary()}}}function Ws(t){return new Promise((e,i)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=i,r.readAsDataURL(t)})}let ii=null;function zs(){return ii||(ii=(async()=>{if(typeof window<"u"){if(window.jspdf&&window.jspdf.jsPDF)return window.jspdf.jsPDF;if(window.jsPDF)return window.jsPDF}try{const t=await import("jspdf");if(t&&t.jsPDF)return t.jsPDF}catch{}throw new Error('[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.')})(),ii)}function Os(t,e){e.savePDF=async function(i,r={}){const n=xt(this);if(!n)throw new Error("[p5.export] savePDF: no canvas found");const s=await zs(),a=(r.imageFormat||"png").toUpperCase(),l=a==="JPEG"?"image/jpeg":a==="WEBP"?"image/webp":"image/png",u=n.width,m=n.height,v=a==="JPEG"?"jpg":a==="WEBP"?"webp":"png",p=r.scale;let h;if(!p||p<=1||p<=(this.pixelDensity?this.pixelDensity():1))h=n.toDataURL(l,r.quality);else{const j=await Lr(this,p,v,r.quality);j?h=await Ws(j):h=await Gr(this,p,()=>xt(this).toDataURL(l,r.quality))}const d=r.unit||"pt",c=r.orientation||(u>=m?"l":"p"),w=r.format||[u,m],g=new s({orientation:c,unit:d,format:w}),y=g.internal.pageSize.getWidth(),M=g.internal.pageSize.getHeight(),C=Math.min(y/u,M/m),x=u*C,E=m*C,W=(y-x)/2,I=(M-E)/2;return g.addImage(h,a,W,I,x,E),g.save(i?_t(i,"pdf"):bt("pdf")),g}}var Vs={trailer:59};function en(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView(){return i.subarray(0,e)},bytes(){return i.slice(0,e)},writeByte(n){r(e+1),i[e]=n,e++},writeBytes(n,s=0,a=n.length){r(e+a);for(let l=0;l<a;l++)i[e++]=n[l+s]},writeBytesView(n,s=0,a=n.byteLength){r(e+a),i.set(n.subarray(s,s+a),e),e+=a}};function r(n){var s=i.length;if(s>=n)return;var a=1024*1024;n=Math.max(n,s*(s<a?2:1.125)>>>0),s!=0&&(n=Math.max(n,256));let l=i;i=new Uint8Array(n),e>0&&i.set(l.subarray(0,e),0)}}var Wi=12,rn=5003,Ls=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function Gs(t,e,i,r,n=en(512),s=new Uint8Array(256),a=new Int32Array(rn),l=new Int32Array(rn)){let u=a.length,m=Math.max(2,r);s.fill(0),l.fill(0),a.fill(-1);let v=0,p=0,h=m+1,d=h,c=!1,w=d,g=(1<<w)-1,y=1<<h-1,M=y+1,C=y+2,x=0,E=i[0],W=0;for(let N=u;N<65536;N*=2)++W;W=8-W,n.writeByte(m),j(y);let I=i.length;for(let N=1;N<I;N++)t:{let Y=i[N],X=(Y<<Wi)+E,q=Y<<W^E;if(a[q]===X){E=l[q];break t}let ht=q===0?1:u-q;for(;a[q]>=0;)if(q-=ht,q<0&&(q+=u),a[q]===X){E=l[q];break t}j(E),E=Y,C<1<<Wi?(l[q]=C++,a[q]=X):(a.fill(-1),C=y+2,c=!0,j(y))}return j(E),j(M),n.writeByte(0),n.bytesView();function j(N){for(v&=Ls[p],p>0?v|=N<<p:v=N,p+=w;p>=8;)s[x++]=v&255,x>=254&&(n.writeByte(x),n.writeBytesView(s,0,x),x=0),v>>=8,p-=8;if((C>g||c)&&(c?(w=d,g=(1<<w)-1,c=!1):(++w,g=w===Wi?1<<w:(1<<w)-1)),N==M){for(;p>0;)s[x++]=v&255,x>=254&&(n.writeByte(x),n.writeBytesView(s,0,x),x=0),v>>=8,p-=8;x>0&&(n.writeByte(x),n.writeBytesView(s,0,x),x=0)}}}var Ns=Gs;function nn(t,e,i){return t<<8&63488|e<<2&992|i>>3}function sn(t,e,i,r){return t>>4|e&240|(i&240)<<4|(r&240)<<8}function an(t,e,i){return t>>4<<8|e&240|i>>4}function ri(t,e,i){return t<e?e:t>i?i:t}function ni(t){return t*t}function on(t,e,i){var r=0,n=1e100;let s=t[e],a=s.cnt;s.ac;let l=s.rc,u=s.gc,m=s.bc;for(var v=s.fw;v!=0;v=t[v].fw){let h=t[v],d=h.cnt,c=a*d/(a+d);if(!(c>=n)){var p=0;p+=c*ni(h.rc-l),!(p>=n)&&(p+=c*ni(h.gc-u),!(p>=n)&&(p+=c*ni(h.bc-m),!(p>=n)&&(n=p,r=v)))}}s.err=n,s.nn=r}function zi(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function $s(t,e){let i=e==="rgb444"?4096:65536,r=new Array(i),n=t.length;if(e==="rgba4444")for(let s=0;s<n;++s){let a=t[s],l=a>>24&255,u=a>>16&255,m=a>>8&255,v=a&255,p=sn(v,m,u,l),h=p in r?r[p]:r[p]=zi();h.rc+=v,h.gc+=m,h.bc+=u,h.ac+=l,h.cnt++}else if(e==="rgb444")for(let s=0;s<n;++s){let a=t[s],l=a>>16&255,u=a>>8&255,m=a&255,v=an(m,u,l),p=v in r?r[v]:r[v]=zi();p.rc+=m,p.gc+=u,p.bc+=l,p.cnt++}else for(let s=0;s<n;++s){let a=t[s],l=a>>16&255,u=a>>8&255,m=a&255,v=nn(m,u,l),p=v in r?r[v]:r[v]=zi();p.rc+=m,p.gc+=u,p.bc+=l,p.cnt++}return r}function ln(t,e,i={}){let{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:a=0,oneBitAlpha:l=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let u=new Uint32Array(t.buffer),m=i.useSqrt!==!1,v=r==="rgba4444",p=$s(u,r),h=p.length,d=h-1,c=new Uint32Array(h+1);for(var w=0,g=0;g<h;++g){let K=p[g];if(K!=null){var y=1/K.cnt;v&&(K.ac*=y),K.rc*=y,K.gc*=y,K.bc*=y,p[w++]=K}}ni(e)/w<.022&&(m=!1);for(var g=0;g<w-1;++g)p[g].fw=g+1,p[g+1].bk=g,m&&(p[g].cnt=Math.sqrt(p[g].cnt));m&&(p[g].cnt=Math.sqrt(p[g].cnt));var M,C,x;for(g=0;g<w;++g){on(p,g);var E=p[g].err;for(C=++c[0];C>1&&(x=C>>1,!(p[M=c[x]].err<=E));C=x)c[C]=M;c[C]=g}var W=w-e;for(g=0;g<W;){for(var I;;){var j=c[1];if(I=p[j],I.tm>=I.mtm&&p[I.nn].mtm<=I.tm)break;I.mtm==d?j=c[1]=c[c[0]--]:(on(p,j),I.tm=g);var E=p[j].err;for(C=1;(x=C+C)<=c[0]&&(x<c[0]&&p[c[x]].err>p[c[x+1]].err&&x++,!(E<=p[M=c[x]].err));C=x)c[C]=M;c[C]=j}var N=p[I.nn],Y=I.cnt,X=N.cnt,y=1/(Y+X);v&&(I.ac=y*(Y*I.ac+X*N.ac)),I.rc=y*(Y*I.rc+X*N.rc),I.gc=y*(Y*I.gc+X*N.gc),I.bc=y*(Y*I.bc+X*N.bc),I.cnt+=N.cnt,I.mtm=++g,p[N.bk].fw=N.fw,p[N.fw].bk=N.bk,N.mtm=d}let q=[];var ht=0;for(g=0;;++ht){let K=ri(Math.round(p[g].rc),0,255),Qt=ri(Math.round(p[g].gc),0,255),dt=ri(Math.round(p[g].bc),0,255),ot=255;v&&(ot=ri(Math.round(p[g].ac),0,255),l&&(ot=ot<=(typeof l=="number"?l:127)?0:255),n&&ot<=a&&(K=Qt=dt=s,ot=0));let L=v?[K,Qt,dt,ot]:[K,Qt,dt];if(js(q,L)||q.push(L),(g=p[g].fw)==0)break}return q}function js(t,e){for(let i=0;i<t.length;i++){let r=t[i],n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],s=r.length>=4&&e.length>=4?r[3]===e[3]:!0;if(n&&s)return!0}return!1}function hn(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");let r=new Uint32Array(t.buffer),n=r.length,s=i==="rgb444"?4096:65536,a=new Uint8Array(n),l=new Array(s);if(i==="rgba4444")for(let u=0;u<n;u++){let m=r[u],v=m>>24&255,p=m>>16&255,h=m>>8&255,d=m&255,c=sn(d,h,p,v),w=c in l?l[c]:l[c]=qs(d,h,p,v,e);a[u]=w}else{let u=i==="rgb444"?an:nn;for(let m=0;m<n;m++){let v=r[m],p=v>>16&255,h=v>>8&255,d=v&255,c=u(d,h,p),w=c in l?l[c]:l[c]=Hs(d,h,p,e);a[m]=w}}return a}function qs(t,e,i,r,n){let s=0,a=1e100;for(let l=0;l<n.length;l++){let u=n[l],m=u[3],v=Ot(m-r);if(v>a)continue;let p=u[0];if(v+=Ot(p-t),v>a)continue;let h=u[1];if(v+=Ot(h-e),v>a)continue;let d=u[2];v+=Ot(d-i),!(v>a)&&(a=v,s=l)}return s}function Hs(t,e,i,r){let n=0,s=1e100;for(let a=0;a<r.length;a++){let l=r[a],u=l[0],m=Ot(u-t);if(m>s)continue;let v=l[1];if(m+=Ot(v-e),m>s)continue;let p=l[2];m+=Ot(p-i),!(m>s)&&(s=m,n=a)}return n}function Ot(t){return t*t}function dn(t={}){let{initialCapacity:e=4096,auto:i=!0}=t,r=en(e),n=5003,s=new Uint8Array(256),a=new Int32Array(n),l=new Int32Array(n),u=!1;return{reset(){r.reset(),u=!1},finish(){r.writeByte(Vs.trailer)},bytes(){return r.bytes()},bytesView(){return r.bytesView()},get buffer(){return r.buffer},get stream(){return r},writeHeader:m,writeFrame(v,p,h,d={}){let{transparent:c=!1,transparentIndex:w=0,delay:g=0,palette:y=null,repeat:M=0,colorDepth:C=8,dispose:x=-1}=d,E=!1;if(i?u||(E=!0,m(),u=!0):E=!!d.first,p=Math.max(0,Math.floor(p)),h=Math.max(0,Math.floor(h)),E){if(!y)throw new Error("First frame must include a { palette } option");Ys(r,p,h,y,C),cn(r,y),M>=0&&Js(r,M)}let W=Math.round(g/10);Xs(r,x,W,c,w);let I=!!y&&!E;Ks(r,p,h,I?y:null),I&&cn(r,y),Zs(r,v,p,h,C,s,a,l)}};function m(){fn(r,"GIF89a")}}function Xs(t,e,i,r,n){t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1);var s,a;r?(s=1,a=2):(s=0,a=0),e>=0&&(a=e&7),a<<=2,t.writeByte(0|a|0|s),Pt(t,i),t.writeByte(n||0),t.writeByte(0)}function Ys(t,e,i,r,n=8){let s=1,a=0,l=Oi(r.length)-1,u=s<<7|n-1<<4|a<<3|l;Pt(t,e),Pt(t,i),t.writeBytes([u,0,0])}function Js(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),fn(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),Pt(t,e),t.writeByte(0)}function cn(t,e){let i=1<<Oi(e.length);for(let r=0;r<i;r++){let n=[0,0,0];r<e.length&&(n=e[r]),t.writeByte(n[0]),t.writeByte(n[1]),t.writeByte(n[2])}}function Ks(t,e,i,r){if(t.writeByte(44),Pt(t,0),Pt(t,0),Pt(t,e),Pt(t,i),r){let n=0,s=0,a=Oi(r.length)-1;t.writeByte(128|n|s|0|a)}else t.writeByte(0)}function Zs(t,e,i,r,n=8,s,a,l){Ns(i,r,e,n,t,s,a,l)}function Pt(t,e){t.writeByte(e&255),t.writeByte(e>>8&255)}function fn(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function Oi(t){return Math.max(Math.ceil(Math.log2(t)),1)}class Qs{constructor(e){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||(()=>{}),this.frames=[],this.startTime=0,this.active=!1,this.framesRecorded=0}start(){this.active||(this.frames=[],this.framesRecorded=0,this.startTime=performance.now(),this.active=!0,this._nextFrameAt=this.startTime)}tick(){if(!this.active)return;const e=performance.now();if(e<this._nextFrameAt)return;const i=this.canvas.getContext("2d",{willReadFrequently:!0})||this.canvas.getContext("webgl2")||this.canvas.getContext("webgl");let r;if(i&&i.getImageData)r=i.getImageData(0,0,this.canvas.width,this.canvas.height).data;else{const n=document.createElement("canvas");n.width=this.canvas.width,n.height=this.canvas.height,n.getContext("2d").drawImage(this.canvas,0,0),r=n.getContext("2d").getImageData(0,0,n.width,n.height).data}this.frames.push({data:new Uint8ClampedArray(r),width:this.canvas.width,height:this.canvas.height}),this.framesRecorded++,this._nextFrameAt+=1e3/this.fps,this.duration&&e-this.startTime>=this.duration*1e3&&this.stop()}async stop(){if(!this.active)return null;this.active=!1;const e=await this._encode(),i=this.filename?_t(this.filename,"gif"):bt("gif");return rt(e,i),e}async encode(){return this.active=!1,this._encode()}async _encode(){const e=dn(),i=Math.round(1e3/this.fps),r=this.frames.length;for(let n=0;n<r;n++){const s=this.frames[n],a=ln(s.data,this.maxColors),l=hn(s.data,a);e.writeFrame(l,s.width,s.height,{palette:a,delay:i}),this.onProgress((n+1)/r),n%4===3&&await new Promise(u=>setTimeout(u,0))}return e.finish(),new Blob([e.bytes()],{type:"image/gif"})}}function ta(t,e,i){if(e.recordGIF=function(r={}){const n=xt(this);if(!n)throw new Error("[p5.export] recordGIF: no canvas found");if(this._p5ExportGIF&&this._p5ExportGIF.active)throw new Error("[p5.export] a GIF recording is already in progress");const s=new Qs({canvas:n,...r});return s.start(),this._p5ExportGIF=s,s},e.stopGIF=function(){const r=this._p5ExportGIF;return r?(this._p5ExportGIF=null,r.stop()):null},i&&typeof i=="object"){const r=i.postdraw;i.postdraw=function(){typeof r=="function"&&r.call(this),this._p5ExportGIF&&this._p5ExportGIF.active&&this._p5ExportGIF.tick()}}}class ea{constructor({canvas:e,fps:i=30,duration:r,maxFrames:n=900}){this.canvas=e,this.fps=i,this.duration=r,this.maxFrames=n,this.width=e.width,this.height=e.height,this.frames=[],this.recording=!1,this.startTime=0,this._nextFrameAt=0}start(){this.frames=[],this.recording=!0,this.startTime=performance.now(),this._nextFrameAt=this.startTime}tick(){if(!this.recording)return;const e=performance.now();if(e<this._nextFrameAt)return;if(this.frames.length>=this.maxFrames){this.stop();return}let i;const r=this.canvas.getContext("2d",{willReadFrequently:!0});if(r&&typeof r.getImageData=="function")i=r.getImageData(0,0,this.width,this.height).data;else{const n=document.createElement("canvas");n.width=this.width,n.height=this.height;const s=n.getContext("2d");s.drawImage(this.canvas,0,0),i=s.getImageData(0,0,this.width,this.height).data}this.frames.push(new Uint8ClampedArray(i)),this._nextFrameAt+=1e3/this.fps,this.duration&&e-this.startTime>=this.duration*1e3&&this.stop()}stop(){this.recording=!1}clear(){this.frames=[]}get framesRecorded(){return this.frames.length}get capturedSeconds(){return this.frames.length/this.fps}}var Vi=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},f=(t,e,i)=>(Vi(t,e,"read from private field"),i?i.call(t):e.get(t)),D=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},Q=(t,e,i,r)=>(Vi(t,e,"write to private field"),e.set(t,i),i),ia=(t,e,i,r)=>({set _(n){Q(t,e,n)},get _(){return f(t,e,r)}}),z=(t,e,i)=>(Vi(t,e,"access private method"),i),V=new Uint8Array(8),ft=new DataView(V.buffer),Z=t=>[(t%256+256)%256],$=t=>(ft.setUint16(0,t,!1),[V[0],V[1]]),ra=t=>(ft.setInt16(0,t,!1),[V[0],V[1]]),un=t=>(ft.setUint32(0,t,!1),[V[1],V[2],V[3]]),S=t=>(ft.setUint32(0,t,!1),[V[0],V[1],V[2],V[3]]),na=t=>(ft.setInt32(0,t,!1),[V[0],V[1],V[2],V[3]]),Vt=t=>(ft.setUint32(0,Math.floor(t/2**32),!1),ft.setUint32(4,t,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Li=t=>(ft.setInt16(0,2**8*t,!1),[V[0],V[1]]),ut=t=>(ft.setInt32(0,2**16*t,!1),[V[0],V[1],V[2],V[3]]),Gi=t=>(ft.setInt32(0,2**30*t,!1),[V[0],V[1],V[2],V[3]]),lt=(t,e=!1)=>{let i=Array(t.length).fill(null).map((r,n)=>t.charCodeAt(n));return e&&i.push(0),i},si=t=>t&&t[t.length-1],Ni=t=>{let e;for(let i of t)(!e||i.presentationTimestamp>e.presentationTimestamp)&&(e=i);return e},pt=(t,e,i=!0)=>{let r=t*e;return i?Math.round(r):r},pn=t=>{let e=t*(Math.PI/180),i=Math.cos(e),r=Math.sin(e);return[i,r,0,-r,i,0,0,0,1]},mn=pn(0),wn=t=>[ut(t[0]),ut(t[1]),Gi(t[2]),ut(t[3]),ut(t[4]),Gi(t[5]),ut(t[6]),ut(t[7]),Gi(t[8])],xe=t=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(xe):Object.fromEntries(Object.entries(t).map(([e,i])=>[e,xe(i)])),ee=t=>t>=0&&t<2**32,J=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),H=(t,e,i,r,n)=>J(t,[Z(e),un(i),r??[]],n),sa=t=>{let e=512;return t.fragmented?J("ftyp",[lt("iso5"),S(e),lt("iso5"),lt("iso6"),lt("mp41")]):J("ftyp",[lt("isom"),S(e),lt("isom"),t.holdsAvc?lt("avc1"):[],lt("mp41")])},$i=t=>({type:"mdat",largeSize:t}),aa=t=>({type:"free",size:t}),ai=(t,e,i=!1)=>J("moov",null,[oa(e,t),...t.map(r=>la(r,e)),i?Oa(t):null]),oa=(t,e)=>{let i=pt(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const l=Ni(a.samples);return l.presentationTimestamp+l.duration})),Ji),r=Math.max(...e.map(a=>a.id))+1,n=!ee(t)||!ee(i),s=n?Vt:S;return H("mvhd",+n,0,[s(t),s(t),S(Ji),s(i),ut(1),Li(1),Array(10).fill(0),wn(mn),Array(24).fill(0),S(r)])},la=(t,e)=>J("trak",null,[ha(t,e),da(t,e)]),ha=(t,e)=>{let i=Ni(t.samples),r=pt(i?i.presentationTimestamp+i.duration:0,Ji),n=!ee(e)||!ee(r),s=n?Vt:S,a;return t.info.type==="video"?a=typeof t.info.rotation=="number"?pn(t.info.rotation):t.info.rotation:a=mn,H("tkhd",+n,3,[s(e),s(e),S(t.id),S(0),s(r),Array(8).fill(0),$(0),$(0),Li(t.info.type==="audio"?1:0),$(0),wn(a),ut(t.info.type==="video"?t.info.width:0),ut(t.info.type==="video"?t.info.height:0)])},da=(t,e)=>J("mdia",null,[ca(t,e),fa(t.info.type==="video"?"vide":"soun"),ua(t)]),ca=(t,e)=>{let i=Ni(t.samples),r=pt(i?i.presentationTimestamp+i.duration:0,t.timescale),n=!ee(e)||!ee(r),s=n?Vt:S;return H("mdhd",+n,0,[s(e),s(e),S(t.timescale),s(r),$(21956),$(0)])},fa=t=>H("hdlr",0,0,[lt("mhlr"),lt(t),S(0),S(0),S(0),lt("mp4-muxer-hdlr",!0)]),ua=t=>J("minf",null,[t.info.type==="video"?pa():ma(),wa(),ya(t)]),pa=()=>H("vmhd",0,1,[$(0),$(0),$(0),$(0)]),ma=()=>H("smhd",0,0,[$(0),$(0)]),wa=()=>J("dinf",null,[ga()]),ga=()=>H("dref",0,0,[S(1)],[va()]),va=()=>H("url ",0,1),ya=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(i=>i.sampleCompositionTimeOffset!==0);return J("stbl",null,[ba(t),Ba(t),Fa(t),Da(t),Ua(t),Wa(t),e?za(t):null])},ba=t=>H("stsd",0,0,[S(1)],[t.info.type==="video"?_a(Ya[t.info.codec],t):Pa(Ka[t.info.codec],t)]),_a=(t,e)=>J(t,[Array(6).fill(0),$(1),$(0),$(0),Array(12).fill(0),$(e.info.width),$(e.info.height),S(4718592),S(4718592),S(0),$(1),Array(32).fill(0),$(24),ra(65535)],[Ja[e.info.codec](e),e.info.decoderConfig.colorSpace?Ea(e):null]),xa={bt709:1,bt470bg:5,smpte170m:6},Sa={bt709:1,smpte170m:6,"iec61966-2-1":13},Ca={rgb:0,bt709:1,bt470bg:5,smpte170m:6},Ea=t=>J("colr",[lt("nclx"),$(xa[t.info.decoderConfig.colorSpace.primaries]),$(Sa[t.info.decoderConfig.colorSpace.transfer]),$(Ca[t.info.decoderConfig.colorSpace.matrix]),Z((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ta=t=>t.info.decoderConfig&&J("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),ka=t=>t.info.decoderConfig&&J("hvcC",[...new Uint8Array(t.info.decoderConfig.description)]),Aa=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig;if(!e.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),l=(Number(i[3])<<4)+(0<<1)+Number(e.colorSpace.fullRange);return H("vpcC",1,0,[Z(r),Z(n),Z(l),Z(2),Z(2),Z(2),$(0)])},Ma=()=>{let i=(1<<7)+1;return J("av1C",[i,0,0,0])},Pa=(t,e)=>J(t,[Array(6).fill(0),$(1),$(0),$(0),S(0),$(e.info.numberOfChannels),$(16),$(0),$(0),ut(e.info.sampleRate)],[Za[e.info.codec](e)]),Ia=t=>{let e=new Uint8Array(t.info.decoderConfig.description);return H("esds",0,0,[S(58753152),Z(32+e.byteLength),$(1),Z(0),S(75530368),Z(18+e.byteLength),Z(64),Z(21),un(0),S(130071),S(130071),S(92307584),Z(e.byteLength),...e,S(109084800),Z(1),Z(2)])},Ra=t=>{var n;let e=3840,i=0;const r=(n=t.info.decoderConfig)==null?void 0:n.description;if(r){if(r.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const s=ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r);e=s.getUint16(10,!0),i=s.getInt16(14,!0)}return J("dOps",[Z(0),Z(t.info.numberOfChannels),$(e),S(t.info.sampleRate),Li(i),Z(0)])},Ba=t=>H("stts",0,0,[S(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[S(e.sampleCount),S(e.sampleDelta)])]),Fa=t=>{if(t.samples.every(i=>i.type==="key"))return null;let e=[...t.samples.entries()].filter(([,i])=>i.type==="key");return H("stss",0,0,[S(e.length),e.map(([i])=>S(i+1))])},Da=t=>H("stsc",0,0,[S(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[S(e.firstChunk),S(e.samplesPerChunk),S(1)])]),Ua=t=>H("stsz",0,0,[S(0),S(t.samples.length),t.samples.map(e=>S(e.size))]),Wa=t=>t.finalizedChunks.length>0&&si(t.finalizedChunks).offset>=2**32?H("co64",0,0,[S(t.finalizedChunks.length),t.finalizedChunks.map(e=>Vt(e.offset))]):H("stco",0,0,[S(t.finalizedChunks.length),t.finalizedChunks.map(e=>S(e.offset))]),za=t=>H("ctts",0,0,[S(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[S(e.sampleCount),S(e.sampleCompositionTimeOffset)])]),Oa=t=>J("mvex",null,t.map(Va)),Va=t=>H("trex",0,0,[S(t.id),S(1),S(0),S(0),S(0)]),gn=(t,e)=>J("moof",null,[La(t),...e.map(Ga)]),La=t=>H("mfhd",0,0,[S(t)]),vn=t=>{let e=0,i=0,r=0,n=0,s=t.type==="delta";return i|=+s,s?e|=1:e|=2,e<<24|i<<16|r<<8|n},Ga=t=>J("traf",null,[Na(t),$a(t),ja(t)]),Na=t=>{let e=0;e|=8,e|=16,e|=32,e|=131072;let i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:vn(i)};return H("tfhd",0,e,[S(t.id),S(r.duration),S(r.size),S(r.flags)])},$a=t=>H("tfdt",1,0,[Vt(pt(t.currentChunk.startTimestamp,t.timescale))]),ja=t=>{let e=t.currentChunk.samples.map(w=>w.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(w=>w.size),r=t.currentChunk.samples.map(vn),n=t.currentChunk.samples.map(w=>pt(w.presentationTimestamp-w.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(i),l=new Set(r),u=new Set(n),m=l.size===2&&r[0]!==r[1],v=s.size>1,p=a.size>1,h=!m&&l.size>1,d=u.size>1||[...u].some(w=>w!==0),c=0;return c|=1,c|=4*+m,c|=256*+v,c|=512*+p,c|=1024*+h,c|=2048*+d,H("trun",1,c,[S(t.currentChunk.samples.length),S(t.currentChunk.offset-t.currentChunk.moofOffset||0),m?S(r[0]):[],t.currentChunk.samples.map((w,g)=>[v?S(e[g]):[],p?S(i[g]):[],h?S(r[g]):[],d?na(n[g]):[]])])},qa=t=>J("mfra",null,[...t.map(Ha),Xa()]),Ha=(t,e)=>H("tfra",1,0,[S(t.id),S(63),S(t.finalizedChunks.length),t.finalizedChunks.map(r=>[Vt(pt(r.startTimestamp,t.timescale)),Vt(r.moofOffset),S(e+1),S(1),S(1)])]),Xa=()=>H("mfro",0,0,[S(0)]),Ya={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},Ja={avc:Ta,hevc:ka,vp9:Aa,av1:Ma},Ka={aac:"mp4a",opus:"Opus"},Za={aac:Ia,opus:Ra},oi=class{},yn=class extends oi{constructor(){super(...arguments),this.buffer=null}},bn=class extends oi{constructor(e){if(super(),this.options=e,typeof e!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(e.onData){if(typeof e.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(e.onData.length<2)throw new TypeError("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.")}if(e.chunked!==void 0&&typeof e.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},Qa=class extends oi{constructor(e,i){if(super(),this.stream=e,this.options=i,!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(i!==void 0&&typeof i!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(i&&i.chunkSize!==void 0&&(!Number.isInteger(i.chunkSize)||i.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},Lt,ie,_n=class{constructor(){this.pos=0,D(this,Lt,new Uint8Array(8)),D(this,ie,new DataView(f(this,Lt).buffer)),this.offsets=new WeakMap}seek(e){this.pos=e}writeU32(e){f(this,ie).setUint32(0,e,!1),this.write(f(this,Lt).subarray(0,4))}writeU64(e){f(this,ie).setUint32(0,Math.floor(e/2**32),!1),f(this,ie).setUint32(4,e,!1),this.write(f(this,Lt).subarray(0,8))}writeAscii(e){for(let i=0;i<e.length;i++)f(this,ie).setUint8(i%8,e.charCodeAt(i)),i%8===7&&this.write(f(this,Lt));e.length%8!==0&&this.write(f(this,Lt).subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.pos),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.write(e.contents);else{let i=this.pos;if(this.writeBoxHeader(e,0),e.contents&&this.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let r=this.pos,n=e.size??r-i;this.seek(i),this.writeBoxHeader(e,n),this.seek(r)}}writeBoxHeader(e,i){this.writeU32(e.largeSize?1:i),this.writeAscii(e.type),e.largeSize&&this.writeU64(i)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let i=this.pos;this.seek(this.offsets.get(e)),this.writeBox(e),this.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let i=this.measureBoxHeader(e);if(e.contents&&(i+=e.contents.byteLength),e.children)for(let r of e.children)r&&(i+=this.measureBox(r));return i}}};Lt=new WeakMap,ie=new WeakMap;var li,Gt,Se,Ce,hi,ji,to=class extends _n{constructor(e){super(),D(this,hi),D(this,li,void 0),D(this,Gt,new ArrayBuffer(2**16)),D(this,Se,new Uint8Array(f(this,Gt))),D(this,Ce,0),Q(this,li,e)}write(e){z(this,hi,ji).call(this,this.pos+e.byteLength),f(this,Se).set(e,this.pos),this.pos+=e.byteLength,Q(this,Ce,Math.max(f(this,Ce),this.pos))}finalize(){z(this,hi,ji).call(this,this.pos),f(this,li).buffer=f(this,Gt).slice(0,Math.max(f(this,Ce),this.pos))}};li=new WeakMap,Gt=new WeakMap,Se=new WeakMap,Ce=new WeakMap,hi=new WeakSet,ji=function(t){let e=f(this,Gt).byteLength;for(;e<t;)e*=2;if(e===f(this,Gt).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(f(this,Se),0),Q(this,Gt,i),Q(this,Se,r)};var eo=2**24,io=2,Ee,Nt,Te,Ct,nt,di,qi,Hi,xn,Xi,Sn,ke,ci,Yi=class extends _n{constructor(e){var i,r;super(),D(this,di),D(this,Hi),D(this,Xi),D(this,ke),D(this,Ee,void 0),D(this,Nt,[]),D(this,Te,void 0),D(this,Ct,void 0),D(this,nt,[]),Q(this,Ee,e),Q(this,Te,((i=e.options)==null?void 0:i.chunked)??!1),Q(this,Ct,((r=e.options)==null?void 0:r.chunkSize)??eo)}write(e){f(this,Nt).push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}flush(){var r,n;if(f(this,Nt).length===0)return;let e=[],i=[...f(this,Nt)].sort((s,a)=>s.start-a.start);e.push({start:i[0].start,size:i[0].data.byteLength});for(let s=1;s<i.length;s++){let a=e[e.length-1],l=i[s];l.start<=a.start+a.size?a.size=Math.max(a.size,l.start+l.data.byteLength-a.start):e.push({start:l.start,size:l.data.byteLength})}for(let s of e){s.data=new Uint8Array(s.size);for(let a of f(this,Nt))s.start<=a.start&&a.start<s.start+s.size&&s.data.set(a.data,a.start-s.start);f(this,Te)?(z(this,di,qi).call(this,s.data,s.start),z(this,ke,ci).call(this)):(n=(r=f(this,Ee).options).onData)==null||n.call(r,s.data,s.start)}f(this,Nt).length=0}finalize(){f(this,Te)&&z(this,ke,ci).call(this,!0)}};Ee=new WeakMap,Nt=new WeakMap,Te=new WeakMap,Ct=new WeakMap,nt=new WeakMap,di=new WeakSet,qi=function(t,e){let i=f(this,nt).findIndex(l=>l.start<=e&&e<l.start+f(this,Ct));i===-1&&(i=z(this,Xi,Sn).call(this,e));let r=f(this,nt)[i],n=e-r.start,s=t.subarray(0,Math.min(f(this,Ct)-n,t.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(z(this,Hi,xn).call(this,r,a),r.written[0].start===0&&r.written[0].end===f(this,Ct)&&(r.shouldFlush=!0),f(this,nt).length>io){for(let l=0;l<f(this,nt).length-1;l++)f(this,nt)[l].shouldFlush=!0;z(this,ke,ci).call(this)}s.byteLength<t.byteLength&&z(this,di,qi).call(this,t.subarray(s.byteLength),e+s.byteLength)},Hi=new WeakSet,xn=function(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){let s=Math.floor(i+(r-i+1)/2);t.written[s].start<=e.start?(i=s+1,n=s):r=s-1}for(t.written.splice(n+1,0,e),(n===-1||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)},Xi=new WeakSet,Sn=function(t){let i={start:Math.floor(t/f(this,Ct))*f(this,Ct),data:new Uint8Array(f(this,Ct)),written:[],shouldFlush:!1};return f(this,nt).push(i),f(this,nt).sort((r,n)=>r.start-n.start),f(this,nt).indexOf(i)},ke=new WeakSet,ci=function(t=!1){var e,i;for(let r=0;r<f(this,nt).length;r++){let n=f(this,nt)[r];if(!(!n.shouldFlush&&!t)){for(let s of n.written)(i=(e=f(this,Ee).options).onData)==null||i.call(e,n.data.subarray(s.start,s.end),n.start+s.start);f(this,nt).splice(r--,1)}}};var ro=class extends Yi{constructor(e){var i;super(new bn({onData:(r,n)=>e.stream.write({type:"write",data:r,position:n}),chunked:!0,chunkSize:(i=e.options)==null?void 0:i.chunkSize}))}},Ji=1e3,no=["avc","hevc","vp9","av1"],so=["aac","opus"],ao=2082844800,oo=["strict","offset","cross-track-offset"],P,B,fi,st,it,tt,re,ne,Ki,$t,jt,Ae,Zi,Cn,Qi,En,tr,Tn,er,kn,ir,An,ui,rr,mt,Et,nr,Mn,Me,pi,mi,sr,se,Pe,wi,ar,lo=class{constructor(e){if(D(this,Zi),D(this,Qi),D(this,tr),D(this,er),D(this,ir),D(this,ui),D(this,mt),D(this,nr),D(this,Me),D(this,mi),D(this,se),D(this,wi),D(this,P,void 0),D(this,B,void 0),D(this,fi,void 0),D(this,st,void 0),D(this,it,null),D(this,tt,null),D(this,re,Math.floor(Date.now()/1e3)+ao),D(this,ne,[]),D(this,Ki,1),D(this,$t,[]),D(this,jt,[]),D(this,Ae,!1),z(this,Zi,Cn).call(this,e),e.video=xe(e.video),e.audio=xe(e.audio),e.fastStart=xe(e.fastStart),this.target=e.target,Q(this,P,{firstTimestampBehavior:"strict",...e}),e.target instanceof yn)Q(this,B,new to(e.target));else if(e.target instanceof bn)Q(this,B,new Yi(e.target));else if(e.target instanceof Qa)Q(this,B,new ro(e.target));else throw new Error(`Invalid target: ${e.target}`);z(this,er,kn).call(this),z(this,Qi,En).call(this)}addVideoChunk(e,i,r,n){if(!(e instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(i&&typeof i!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(n!==void 0&&!Number.isFinite(n))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let s=new Uint8Array(e.byteLength);e.copyTo(s),this.addVideoChunkRaw(s,e.type,r??e.timestamp,e.duration,i,n)}addVideoChunkRaw(e,i,r,n,s,a){if(!(e instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(r)||r<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(n)||n<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(s&&typeof s!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(a!==void 0&&!Number.isFinite(a))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(z(this,wi,ar).call(this),!f(this,P).video)throw new Error("No video track declared.");if(typeof f(this,P).fastStart=="object"&&f(this,it).samples.length===f(this,P).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${f(this,P).fastStart.expectedVideoChunks}).`);let l=z(this,ui,rr).call(this,f(this,it),e,i,r,n,s,a);if(f(this,P).fastStart==="fragmented"&&f(this,tt)){for(;f(this,jt).length>0&&f(this,jt)[0].decodeTimestamp<=l.decodeTimestamp;){let u=f(this,jt).shift();z(this,mt,Et).call(this,f(this,tt),u)}l.decodeTimestamp<=f(this,tt).lastDecodeTimestamp?z(this,mt,Et).call(this,f(this,it),l):f(this,$t).push(l)}else z(this,mt,Et).call(this,f(this,it),l)}addAudioChunk(e,i,r){if(!(e instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(i&&typeof i!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let n=new Uint8Array(e.byteLength);e.copyTo(n),this.addAudioChunkRaw(n,e.type,r??e.timestamp,e.duration,i)}addAudioChunkRaw(e,i,r,n,s){if(!(e instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(r)||r<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(n)||n<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(s&&typeof s!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(z(this,wi,ar).call(this),!f(this,P).audio)throw new Error("No audio track declared.");if(typeof f(this,P).fastStart=="object"&&f(this,tt).samples.length===f(this,P).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${f(this,P).fastStart.expectedAudioChunks}).`);let a=z(this,ui,rr).call(this,f(this,tt),e,i,r,n,s);if(f(this,P).fastStart==="fragmented"&&f(this,it)){for(;f(this,$t).length>0&&f(this,$t)[0].decodeTimestamp<=a.decodeTimestamp;){let l=f(this,$t).shift();z(this,mt,Et).call(this,f(this,it),l)}a.decodeTimestamp<=f(this,it).lastDecodeTimestamp?z(this,mt,Et).call(this,f(this,tt),a):f(this,jt).push(a)}else z(this,mt,Et).call(this,f(this,tt),a)}finalize(){if(f(this,Ae))throw new Error("Cannot finalize a muxer more than once.");if(f(this,P).fastStart==="fragmented"){for(let i of f(this,$t))z(this,mt,Et).call(this,f(this,it),i);for(let i of f(this,jt))z(this,mt,Et).call(this,f(this,tt),i);z(this,mi,sr).call(this,!1)}else f(this,it)&&z(this,Me,pi).call(this,f(this,it)),f(this,tt)&&z(this,Me,pi).call(this,f(this,tt));let e=[f(this,it),f(this,tt)].filter(Boolean);if(f(this,P).fastStart==="in-memory"){let i;for(let n=0;n<2;n++){let s=ai(e,f(this,re)),a=f(this,B).measureBox(s);i=f(this,B).measureBox(f(this,st));let l=f(this,B).pos+a+i;for(let u of f(this,ne)){u.offset=l;for(let{data:m}of u.samples)l+=m.byteLength,i+=m.byteLength}if(l<2**32)break;i>=2**32&&(f(this,st).largeSize=!0)}let r=ai(e,f(this,re));f(this,B).writeBox(r),f(this,st).size=i,f(this,B).writeBox(f(this,st));for(let n of f(this,ne))for(let s of n.samples)f(this,B).write(s.data),s.data=null}else if(f(this,P).fastStart==="fragmented"){let i=f(this,B).pos,r=qa(e);f(this,B).writeBox(r);let n=f(this,B).pos-i;f(this,B).seek(f(this,B).pos-4),f(this,B).writeU32(n)}else{let i=f(this,B).offsets.get(f(this,st)),r=f(this,B).pos-i;f(this,st).size=r,f(this,st).largeSize=r>=2**32,f(this,B).patchBox(f(this,st));let n=ai(e,f(this,re));if(typeof f(this,P).fastStart=="object"){f(this,B).seek(f(this,fi)),f(this,B).writeBox(n);let s=i-f(this,B).pos;f(this,B).writeBox(aa(s))}else f(this,B).writeBox(n)}z(this,se,Pe).call(this),f(this,B).finalize(),Q(this,Ae,!0)}};P=new WeakMap,B=new WeakMap,fi=new WeakMap,st=new WeakMap,it=new WeakMap,tt=new WeakMap,re=new WeakMap,ne=new WeakMap,Ki=new WeakMap,$t=new WeakMap,jt=new WeakMap,Ae=new WeakMap,Zi=new WeakSet,Cn=function(t){if(typeof t!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(t.target instanceof oi))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(!no.includes(t.video.codec))throw new TypeError(`Unsupported video codec: ${t.video.codec}`);if(!Number.isInteger(t.video.width)||t.video.width<=0)throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);if(!Number.isInteger(t.video.height)||t.video.height<=0)throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);const e=t.video.rotation;if(typeof e=="number"&&![0,90,180,270].includes(e))throw new TypeError(`Invalid video rotation: ${e}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(e)&&(e.length!==9||e.some(i=>typeof i!="number")))throw new TypeError(`Invalid video transformation matrix: ${e.join()}`);if(t.video.frameRate!==void 0&&(!Number.isInteger(t.video.frameRate)||t.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.video.frameRate}. Must be a positive integer.`)}if(t.audio){if(!so.includes(t.audio.codec))throw new TypeError(`Unsupported audio codec: ${t.audio.codec}`);if(!Number.isInteger(t.audio.numberOfChannels)||t.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(t.audio.sampleRate)||t.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`)}if(t.firstTimestampBehavior&&!oo.includes(t.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if(typeof t.fastStart=="object"){if(t.video){if(t.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(t.fastStart.expectedVideoChunks)||t.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(t.audio){if(t.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(t.fastStart.expectedAudioChunks)||t.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(t.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(t.minFragmentDuration!==void 0&&(!Number.isFinite(t.minFragmentDuration)||t.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")},Qi=new WeakSet,En=function(){var t;if(f(this,B).writeBox(sa({holdsAvc:((t=f(this,P).video)==null?void 0:t.codec)==="avc",fragmented:f(this,P).fastStart==="fragmented"})),Q(this,fi,f(this,B).pos),f(this,P).fastStart==="in-memory")Q(this,st,$i(!1));else if(f(this,P).fastStart!=="fragmented"){if(typeof f(this,P).fastStart=="object"){let e=z(this,tr,Tn).call(this);f(this,B).seek(f(this,B).pos+e)}Q(this,st,$i(!0)),f(this,B).writeBox(f(this,st))}z(this,se,Pe).call(this)},tr=new WeakSet,Tn=function(){if(typeof f(this,P).fastStart!="object")return;let t=0,e=[f(this,P).fastStart.expectedVideoChunks,f(this,P).fastStart.expectedAudioChunks];for(let i of e)i&&(t+=8*Math.ceil(2/3*i),t+=4*i,t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i);return t+=4096,t},er=new WeakSet,kn=function(){if(f(this,P).video&&Q(this,it,{id:1,info:{type:"video",codec:f(this,P).video.codec,width:f(this,P).video.width,height:f(this,P).video.height,rotation:f(this,P).video.rotation??0,decoderConfig:null},timescale:f(this,P).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),f(this,P).audio&&(Q(this,tt,{id:f(this,P).video?2:1,info:{type:"audio",codec:f(this,P).audio.codec,numberOfChannels:f(this,P).audio.numberOfChannels,sampleRate:f(this,P).audio.sampleRate,decoderConfig:null},timescale:f(this,P).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),f(this,P).audio.codec==="aac")){let t=z(this,ir,An).call(this,2,f(this,P).audio.sampleRate,f(this,P).audio.numberOfChannels);f(this,tt).info.decoderConfig={codec:f(this,P).audio.codec,description:t,numberOfChannels:f(this,P).audio.numberOfChannels,sampleRate:f(this,P).audio.sampleRate}}},ir=new WeakSet,An=function(t,e,i){let n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(e),s=i,a="";a+=t.toString(2).padStart(5,"0"),a+=n.toString(2).padStart(4,"0"),n===15&&(a+=e.toString(2).padStart(24,"0")),a+=s.toString(2).padStart(4,"0");let l=Math.ceil(a.length/8)*8;a=a.padEnd(l,"0");let u=new Uint8Array(a.length/8);for(let m=0;m<a.length;m+=8)u[m/8]=parseInt(a.slice(m,m+8),2);return u},ui=new WeakSet,rr=function(t,e,i,r,n,s,a){let l=r/1e6,u=(r-(a??0))/1e6,m=n/1e6,v=z(this,nr,Mn).call(this,l,u,t);return l=v.presentationTimestamp,u=v.decodeTimestamp,s!=null&&s.decoderConfig&&(t.info.decoderConfig===null?t.info.decoderConfig=s.decoderConfig:Object.assign(t.info.decoderConfig,s.decoderConfig)),{presentationTimestamp:l,decodeTimestamp:u,duration:m,data:e,size:e.byteLength,type:i,timescaleUnitsToNextSample:pt(m,t.timescale)}},mt=new WeakSet,Et=function(t,e){f(this,P).fastStart!=="fragmented"&&t.samples.push(e);const i=pt(e.presentationTimestamp-e.decodeTimestamp,t.timescale);if(t.lastTimescaleUnits!==null){let n=pt(e.decodeTimestamp,t.timescale,!1),s=Math.round(n-t.lastTimescaleUnits);if(t.lastTimescaleUnits+=s,t.lastSample.timescaleUnitsToNextSample=s,f(this,P).fastStart!=="fragmented"){let a=si(t.timeToSampleTable);a.sampleCount===1?(a.sampleDelta=s,a.sampleCount++):a.sampleDelta===s?a.sampleCount++:(a.sampleCount--,t.timeToSampleTable.push({sampleCount:2,sampleDelta:s}));const l=si(t.compositionTimeOffsetTable);l.sampleCompositionTimeOffset===i?l.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else t.lastTimescaleUnits=0,f(this,P).fastStart!=="fragmented"&&(t.timeToSampleTable.push({sampleCount:1,sampleDelta:pt(e.duration,t.timescale)}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));t.lastSample=e;let r=!1;if(!t.currentChunk)r=!0;else{let n=e.presentationTimestamp-t.currentChunk.startTimestamp;if(f(this,P).fastStart==="fragmented"){let s=f(this,it)??f(this,tt);const a=f(this,P).minFragmentDuration??1;t===s&&e.type==="key"&&n>=a&&(r=!0,z(this,mi,sr).call(this))}else r=n>=.5}r&&(t.currentChunk&&z(this,Me,pi).call(this,t),t.currentChunk={startTimestamp:e.presentationTimestamp,samples:[]}),t.currentChunk.samples.push(e)},nr=new WeakSet,Mn=function(t,e,i){var a,l;const r=f(this,P).firstTimestampBehavior==="strict",n=i.lastDecodeTimestamp===-1;if(r&&n&&e!==0)throw new Error(`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.
23
24
 
24
25
  If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
25
- `);if(c(this,I).firstTimestampBehavior==="offset"||c(this,I).firstTimestampBehavior==="cross-track-offset"){i.firstDecodeTimestamp===void 0&&(i.firstDecodeTimestamp=e);let u;c(this,I).firstTimestampBehavior==="offset"?u=i.firstDecodeTimestamp:u=Math.min(((a=c(this,it))==null?void 0:a.firstDecodeTimestamp)??1/0,((l=c(this,Q))==null?void 0:l.firstDecodeTimestamp)??1/0),e-=u,t-=u}if(e<i.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${i.lastDecodeTimestamp*1e6} to ${e*1e6}).`);return i.lastDecodeTimestamp=e,{presentationTimestamp:t,decodeTimestamp:e}},Ee=new WeakSet,li=function(t){if(c(this,I).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(t.currentChunk){if(t.finalizedChunks.push(t.currentChunk),c(this,te).push(t.currentChunk),(t.compactlyCodedChunkTable.length===0||ti(t.compactlyCodedChunkTable).samplesPerChunk!==t.currentChunk.samples.length)&&t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:t.currentChunk.samples.length}),c(this,I).fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=c(this,R).pos;for(let e of t.currentChunk.samples)c(this,R).write(e.data),e.data=null;z(this,ee,Te).call(this)}},di=new WeakSet,tr=function(t=!0){if(c(this,I).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let e=[c(this,it),c(this,Q)].filter(l=>l&&l.currentChunk);if(e.length===0)return;let i=qn(this,qi)._++;if(i===1){let l=ei(e,c(this,Qt),!0);c(this,R).writeBox(l)}let r=c(this,R).pos,s=ds(i,e);c(this,R).writeBox(s);{let l=Vi(!1),u=0;for(let v of e)for(let p of v.currentChunk.samples)u+=p.size;let g=c(this,R).measureBox(l)+u;g>=2**32&&(l.largeSize=!0,g=c(this,R).measureBox(l)+u),l.size=g,c(this,R).writeBox(l)}for(let l of e){l.currentChunk.offset=c(this,R).pos,l.currentChunk.moofOffset=r;for(let u of l.currentChunk.samples)c(this,R).write(u.data),u.data=null}let n=c(this,R).pos;c(this,R).seek(c(this,R).offsets.get(s));let a=ds(i,e);c(this,R).writeBox(a),c(this,R).seek(n);for(let l of e)l.finalizedChunks.push(l.currentChunk),c(this,te).push(l.currentChunk),l.currentChunk=null;t&&z(this,ee,Te).call(this)},ee=new WeakSet,Te=function(){c(this,R)instanceof $i&&c(this,R).flush()},ci=new WeakSet,er=function(){if(c(this,Ce))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};var ir=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},o=(t,e,i)=>(ir(t,e,"read from private field"),i?i.call(t):e.get(t)),x=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},U=(t,e,i,r)=>(ir(t,e,"write to private field"),e.set(t,i),i),T=(t,e,i)=>(ir(t,e,"access private method"),i),Ss=class{constructor(t){this.value=t}},rr=class{constructor(t){this.value=t}},Cs=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,Qa=t=>{if(t<127)return 1;if(t<16383)return 2;if(t<(1<<21)-1)return 3;if(t<(1<<28)-1)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML VINT size not supported "+t)},ie=(t,e,i)=>{let r=0;for(let s=e;s<i;s++){let n=Math.floor(s/8),a=t[n],l=7-(s&7),u=(a&1<<l)>>l;r<<=1,r|=u}return r},to=(t,e,i,r)=>{for(let s=e;s<i;s++){let n=Math.floor(s/8),a=t[n],l=7-(s&7);a&=~(1<<l),a|=(r&1<<i-s-1)>>i-s-1<<l,t[n]=a}},fi=class{},Es=class extends fi{constructor(){super(...arguments),this.buffer=null}},Ts=class extends fi{constructor(t){if(super(),this.options=t,typeof t!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(t.onData){if(typeof t.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(t.onData.length<2)throw new TypeError("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.")}if(t.onHeader&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},eo=class extends fi{constructor(t,e){if(super(),this.stream=t,this.options=e,!(t instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(e!==void 0&&typeof e!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(e&&e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},Mt,N,sr,ks,nr,As,ar,Ms,ui,or,hr,Is,Ps=class{constructor(){x(this,sr),x(this,nr),x(this,ar),x(this,ui),x(this,hr),this.pos=0,x(this,Mt,new Uint8Array(8)),x(this,N,new DataView(o(this,Mt).buffer)),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}seek(t){this.pos=t}writeEBMLVarInt(t,e=Qa(t)){let i=0;switch(e){case 1:o(this,N).setUint8(i++,128|t);break;case 2:o(this,N).setUint8(i++,64|t>>8),o(this,N).setUint8(i++,t);break;case 3:o(this,N).setUint8(i++,32|t>>16),o(this,N).setUint8(i++,t>>8),o(this,N).setUint8(i++,t);break;case 4: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);break;case 5: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);break;case 6: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);break;default:throw new Error("Bad EBML VINT size "+e)}this.write(o(this,Mt).subarray(0,i))}writeEBML(t){if(t!==null)if(t instanceof Uint8Array)this.write(t);else if(Array.isArray(t))for(let e of t)this.writeEBML(e);else if(this.offsets.set(t,this.pos),T(this,ui,or).call(this,t.id),Array.isArray(t.data)){let e=this.pos,i=t.size===-1?1:t.size??4;t.size===-1?T(this,sr,ks).call(this,255):this.seek(this.pos+i);let r=this.pos;if(this.dataOffsets.set(t,r),this.writeEBML(t.data),t.size!==-1){let s=this.pos-r,n=this.pos;this.seek(e),this.writeEBMLVarInt(s,i),this.seek(n)}}else if(typeof t.data=="number"){let e=t.size??Cs(t.data);this.writeEBMLVarInt(e),T(this,ui,or).call(this,t.data,e)}else typeof t.data=="string"?(this.writeEBMLVarInt(t.data.length),T(this,hr,Is).call(this,t.data)):t.data instanceof Uint8Array?(this.writeEBMLVarInt(t.data.byteLength,t.size),this.write(t.data)):t.data instanceof Ss?(this.writeEBMLVarInt(4),T(this,nr,As).call(this,t.data.value)):t.data instanceof rr&&(this.writeEBMLVarInt(8),T(this,ar,Ms).call(this,t.data.value))}};Mt=new WeakMap,N=new WeakMap,sr=new WeakSet,ks=function(t){o(this,N).setUint8(0,t),this.write(o(this,Mt).subarray(0,1))},nr=new WeakSet,As=function(t){o(this,N).setFloat32(0,t,!1),this.write(o(this,Mt).subarray(0,4))},ar=new WeakSet,Ms=function(t){o(this,N).setFloat64(0,t,!1),this.write(o(this,Mt))},ui=new WeakSet,or=function(t,e=Cs(t)){let i=0;switch(e){case 6:o(this,N).setUint8(i++,t/2**40|0);case 5:o(this,N).setUint8(i++,t/2**32|0);case 4:o(this,N).setUint8(i++,t>>24);case 3:o(this,N).setUint8(i++,t>>16);case 2:o(this,N).setUint8(i++,t>>8);case 1:o(this,N).setUint8(i++,t);break;default:throw new Error("Bad UINT size "+e)}this.write(o(this,Mt).subarray(0,i))},hr=new WeakSet,Is=function(t){this.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))};var pi,$t,ke,mi,lr,io=class extends Ps{constructor(t){super(),x(this,mi),x(this,pi,void 0),x(this,$t,new ArrayBuffer(2**16)),x(this,ke,new Uint8Array(o(this,$t))),U(this,pi,t)}write(t){T(this,mi,lr).call(this,this.pos+t.byteLength),o(this,ke).set(t,this.pos),this.pos+=t.byteLength}finalize(){T(this,mi,lr).call(this,this.pos),o(this,pi).buffer=o(this,$t).slice(0,this.pos)}};pi=new WeakMap,$t=new WeakMap,ke=new WeakMap,mi=new WeakSet,lr=function(t){let e=o(this,$t).byteLength;for(;e<t;)e*=2;if(e===o(this,$t).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(o(this,ke),0),U(this,$t,i),U(this,ke,r)};var re,pt,mt,jt,Ae=class extends Ps{constructor(t){super(),this.target=t,x(this,re,!1),x(this,pt,void 0),x(this,mt,void 0),x(this,jt,void 0)}write(t){if(!o(this,re))return;let e=this.pos;if(e<o(this,mt)){if(e+t.byteLength<=o(this,mt))return;t=t.subarray(o(this,mt)-e),e=0}let i=e+t.byteLength-o(this,mt),r=o(this,pt).byteLength;for(;r<i;)r*=2;if(r!==o(this,pt).byteLength){let s=new Uint8Array(r);s.set(o(this,pt),0),U(this,pt,s)}o(this,pt).set(t,e-o(this,mt)),U(this,jt,Math.max(o(this,jt),e+t.byteLength))}startTrackingWrites(){U(this,re,!0),U(this,pt,new Uint8Array(2**10)),U(this,mt,this.pos),U(this,jt,this.pos)}getTrackedWrites(){if(!o(this,re))throw new Error("Can't get tracked writes since nothing was tracked.");let e={data:o(this,pt).subarray(0,o(this,jt)-o(this,mt)),start:o(this,mt),end:o(this,jt)};return U(this,pt,void 0),U(this,re,!1),e}};re=new WeakMap,pt=new WeakMap,mt=new WeakMap,jt=new WeakMap;var ro=2**24,so=2,qt,se,Me,Ie,Ct,at,wi,dr,cr,Rs,fr,Bs,Pe,gi,ur=class extends Ae{constructor(t,e){var i,r;super(t),x(this,wi),x(this,cr),x(this,fr),x(this,Pe),x(this,qt,[]),x(this,se,0),x(this,Me,void 0),x(this,Ie,void 0),x(this,Ct,void 0),x(this,at,[]),U(this,Me,e),U(this,Ie,((i=t.options)==null?void 0:i.chunked)??!1),U(this,Ct,((r=t.options)==null?void 0:r.chunkSize)??ro)}write(t){super.write(t),o(this,qt).push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength}flush(){var i,r;if(o(this,qt).length===0)return;let t=[],e=[...o(this,qt)].sort((s,n)=>s.start-n.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let s=1;s<e.length;s++){let n=t[t.length-1],a=e[s];a.start<=n.start+n.size?n.size=Math.max(n.size,a.start+a.data.byteLength-n.start):t.push({start:a.start,size:a.data.byteLength})}for(let s of t){s.data=new Uint8Array(s.size);for(let n of o(this,qt))s.start<=n.start&&n.start<s.start+s.size&&s.data.set(n.data,n.start-s.start);if(o(this,Ie))T(this,wi,dr).call(this,s.data,s.start),T(this,Pe,gi).call(this);else{if(o(this,Me)&&s.start<o(this,se))throw new Error("Internal error: Monotonicity violation.");(r=(i=this.target.options).onData)==null||r.call(i,s.data,s.start),U(this,se,s.start+s.data.byteLength)}}o(this,qt).length=0}finalize(){o(this,Ie)&&T(this,Pe,gi).call(this,!0)}};qt=new WeakMap,se=new WeakMap,Me=new WeakMap,Ie=new WeakMap,Ct=new WeakMap,at=new WeakMap,wi=new WeakSet,dr=function(t,e){let i=o(this,at).findIndex(l=>l.start<=e&&e<l.start+o(this,Ct));i===-1&&(i=T(this,fr,Bs).call(this,e));let r=o(this,at)[i],s=e-r.start,n=t.subarray(0,Math.min(o(this,Ct)-s,t.byteLength));r.data.set(n,s);let a={start:s,end:s+n.byteLength};if(T(this,cr,Rs).call(this,r,a),r.written[0].start===0&&r.written[0].end===o(this,Ct)&&(r.shouldFlush=!0),o(this,at).length>so){for(let l=0;l<o(this,at).length-1;l++)o(this,at)[l].shouldFlush=!0;T(this,Pe,gi).call(this)}n.byteLength<t.byteLength&&T(this,wi,dr).call(this,t.subarray(n.byteLength),e+n.byteLength)},cr=new WeakSet,Rs=function(t,e){let i=0,r=t.written.length-1,s=-1;for(;i<=r;){let n=Math.floor(i+(r-i+1)/2);t.written[n].start<=e.start?(i=n+1,s=n):r=n-1}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;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)},fr=new WeakSet,Bs=function(t){let i={start:Math.floor(t/o(this,Ct))*o(this,Ct),data:new Uint8Array(o(this,Ct)),written:[],shouldFlush:!1};return o(this,at).push(i),o(this,at).sort((r,s)=>r.start-s.start),o(this,at).indexOf(i)},Pe=new WeakSet,gi=function(t=!1){var e,i;for(let r=0;r<o(this,at).length;r++){let s=o(this,at)[r];if(!(!s.shouldFlush&&!t)){for(let n of s.written){if(o(this,Me)&&s.start+n.start<o(this,se))throw new Error("Internal error: Monotonicity violation.");(i=(e=this.target.options).onData)==null||i.call(e,s.data.subarray(n.start,n.end),s.start+n.start),U(this,se,s.start+n.end)}o(this,at).splice(r--,1)}}};var no=class extends ur{constructor(t,e){var i;super(new Ts({onData:(r,s)=>t.stream.write({type:"write",data:r,position:s}),chunked:!0,chunkSize:(i=t.options)==null?void 0:i.chunkSize}),e)}},ne=1,Re=2,vi=3,ao=1,oo=2,ho=17,lo=2**15,Be=2**13,Fs="https://github.com/Vanilagy/webm-muxer",Us=6,Ds=5,co=["strict","offset","permissive"],P,k,Fe,Ue,Et,ae,oe,Ht,he,It,le,de,wt,De,ce,Pt,Rt,Xt,We,ze,fe,ue,yi,Ve,Le,pr,Ws,mr,zs,wr,Vs,gr,Ls,vr,Os,yr,Gs,br,Ns,bi,_r,_i,xr,Sr,$s,Yt,pe,Jt,me,Cr,js,Er,qs,Oe,xi,Ge,Si,Tr,Hs,gt,Tt,we,Ne,$e,Ci,kr,Xs,Ei,Ar,je,Ti,fo=class{constructor(t){x(this,pr),x(this,mr),x(this,wr),x(this,gr),x(this,vr),x(this,yr),x(this,br),x(this,bi),x(this,_i),x(this,Sr),x(this,Yt),x(this,Jt),x(this,Cr),x(this,Er),x(this,Oe),x(this,Ge),x(this,Tr),x(this,gt),x(this,we),x(this,$e),x(this,kr),x(this,Ei),x(this,je),x(this,P,void 0),x(this,k,void 0),x(this,Fe,void 0),x(this,Ue,void 0),x(this,Et,void 0),x(this,ae,void 0),x(this,oe,void 0),x(this,Ht,void 0),x(this,he,void 0),x(this,It,void 0),x(this,le,void 0),x(this,de,void 0),x(this,wt,void 0),x(this,De,void 0),x(this,ce,0),x(this,Pt,[]),x(this,Rt,[]),x(this,Xt,[]),x(this,We,void 0),x(this,ze,void 0),x(this,fe,-1),x(this,ue,-1),x(this,yi,-1),x(this,Ve,void 0),x(this,Le,!1),T(this,pr,Ws).call(this,t),U(this,P,{type:"webm",firstTimestampBehavior:"strict",...t}),this.target=t.target;let e=!!o(this,P).streaming;if(t.target instanceof Es)U(this,k,new io(t.target));else if(t.target instanceof Ts)U(this,k,new ur(t.target,e));else if(t.target instanceof eo)U(this,k,new no(t.target,e));else throw new Error(`Invalid target: ${t.target}`);T(this,mr,zs).call(this)}addVideoChunk(t,e,i){if(!(t instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (chunk) must be of type EncodedVideoChunk.");if(e&&typeof e!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addVideoChunkRaw(r,t.type,i??t.timestamp,e)}addVideoChunkRaw(t,e,i,r){if(!(t instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addVideoChunkRaw's fourth argument (meta), when provided, must be an object.");if(T(this,je,Ti).call(this),!o(this,P).video)throw new Error("No video track declared.");o(this,We)===void 0&&U(this,We,i),r&&T(this,Cr,js).call(this,r);let s=T(this,Ge,Si).call(this,t,e,i,ne);for(o(this,P).video.codec==="V_VP9"&&T(this,Er,qs).call(this,s),U(this,fe,s.timestamp);o(this,Rt).length>0&&o(this,Rt)[0].timestamp<=s.timestamp;){let n=o(this,Rt).shift();T(this,gt,Tt).call(this,n,!1)}!o(this,P).audio||s.timestamp<=o(this,ue)?T(this,gt,Tt).call(this,s,!0):o(this,Pt).push(s),T(this,Oe,xi).call(this),T(this,Yt,pe).call(this)}addAudioChunk(t,e,i){if(!(t instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (chunk) must be of type EncodedAudioChunk.");if(e&&typeof e!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addAudioChunkRaw(r,t.type,i??t.timestamp,e)}addAudioChunkRaw(t,e,i,r){if(!(t instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addAudioChunkRaw's fourth argument (meta), when provided, must be an object.");if(T(this,je,Ti).call(this),!o(this,P).audio)throw new Error("No audio track declared.");o(this,ze)===void 0&&U(this,ze,i),r!=null&&r.decoderConfig&&(o(this,P).streaming?U(this,It,T(this,we,Ne).call(this,r.decoderConfig.description)):T(this,$e,Ci).call(this,o(this,It),r.decoderConfig.description));let s=T(this,Ge,Si).call(this,t,e,i,Re);for(U(this,ue,s.timestamp);o(this,Pt).length>0&&o(this,Pt)[0].timestamp<=s.timestamp;){let n=o(this,Pt).shift();T(this,gt,Tt).call(this,n,!0)}!o(this,P).video||s.timestamp<=o(this,fe)?T(this,gt,Tt).call(this,s,!o(this,P).video):o(this,Rt).push(s),T(this,Oe,xi).call(this),T(this,Yt,pe).call(this)}addSubtitleChunk(t,e,i){if(typeof t!="object"||!t)throw new TypeError("addSubtitleChunk's first argument (chunk) must be an object.");if(!(t.body instanceof Uint8Array))throw new TypeError("body must be an instance of Uint8Array.");if(!Number.isFinite(t.timestamp)||t.timestamp<0)throw new TypeError("timestamp must be a non-negative real number.");if(!Number.isFinite(t.duration)||t.duration<0)throw new TypeError("duration must be a non-negative real number.");if(t.additions&&!(t.additions instanceof Uint8Array))throw new TypeError("additions, when present, must be an instance of Uint8Array.");if(typeof e!="object")throw new TypeError("addSubtitleChunk's second argument (meta) must be an object.");if(T(this,je,Ti).call(this),!o(this,P).subtitles)throw new Error("No subtitle track declared.");e!=null&&e.decoderConfig&&(o(this,P).streaming?U(this,le,T(this,we,Ne).call(this,e.decoderConfig.description)):T(this,$e,Ci).call(this,o(this,le),e.decoderConfig.description));let r=T(this,Ge,Si).call(this,t.body,"key",i??t.timestamp,vi,t.duration,t.additions);U(this,yi,r.timestamp),o(this,Xt).push(r),T(this,Oe,xi).call(this),T(this,Yt,pe).call(this)}finalize(){if(o(this,Le))throw new Error("Cannot finalize a muxer more than once.");for(;o(this,Pt).length>0;)T(this,gt,Tt).call(this,o(this,Pt).shift(),!0);for(;o(this,Rt).length>0;)T(this,gt,Tt).call(this,o(this,Rt).shift(),!0);for(;o(this,Xt).length>0&&o(this,Xt)[0].timestamp<=o(this,ce);)T(this,gt,Tt).call(this,o(this,Xt).shift(),!1);if(o(this,wt)&&T(this,Ei,Ar).call(this),o(this,k).writeEBML(o(this,de)),!o(this,P).streaming){let t=o(this,k).pos,e=o(this,k).pos-o(this,Jt,me);o(this,k).seek(o(this,k).offsets.get(o(this,Fe))+4),o(this,k).writeEBMLVarInt(e,Us),o(this,oe).data=new rr(o(this,ce)),o(this,k).seek(o(this,k).offsets.get(o(this,oe))),o(this,k).writeEBML(o(this,oe)),o(this,Et).data[0].data[1].data=o(this,k).offsets.get(o(this,de))-o(this,Jt,me),o(this,Et).data[1].data[1].data=o(this,k).offsets.get(o(this,Ue))-o(this,Jt,me),o(this,Et).data[2].data[1].data=o(this,k).offsets.get(o(this,ae))-o(this,Jt,me),o(this,k).seek(o(this,k).offsets.get(o(this,Et))),o(this,k).writeEBML(o(this,Et)),o(this,k).seek(t)}T(this,Yt,pe).call(this),o(this,k).finalize(),U(this,Le,!0)}};P=new WeakMap,k=new WeakMap,Fe=new WeakMap,Ue=new WeakMap,Et=new WeakMap,ae=new WeakMap,oe=new WeakMap,Ht=new WeakMap,he=new WeakMap,It=new WeakMap,le=new WeakMap,de=new WeakMap,wt=new WeakMap,De=new WeakMap,ce=new WeakMap,Pt=new WeakMap,Rt=new WeakMap,Xt=new WeakMap,We=new WeakMap,ze=new WeakMap,fe=new WeakMap,ue=new WeakMap,yi=new WeakMap,Ve=new WeakMap,Le=new WeakMap,pr=new WeakSet,Ws=function(t){if(typeof t!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(t.target instanceof fi))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(typeof t.video.codec!="string")throw new TypeError(`Invalid video codec: ${t.video.codec}. Must be a string.`);if(!Number.isInteger(t.video.width)||t.video.width<=0)throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);if(!Number.isInteger(t.video.height)||t.video.height<=0)throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);if(t.video.frameRate!==void 0&&(!Number.isFinite(t.video.frameRate)||t.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.video.frameRate}. Must be a positive number.`);if(t.video.alpha!==void 0&&typeof t.video.alpha!="boolean")throw new TypeError(`Invalid video alpha: ${t.video.alpha}. Must be a boolean.`)}if(t.audio){if(typeof t.audio.codec!="string")throw new TypeError(`Invalid audio codec: ${t.audio.codec}. Must be a string.`);if(!Number.isInteger(t.audio.numberOfChannels)||t.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(t.audio.sampleRate)||t.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`);if(t.audio.bitDepth!==void 0&&(!Number.isInteger(t.audio.bitDepth)||t.audio.bitDepth<=0))throw new TypeError(`Invalid audio bit depth: ${t.audio.bitDepth}. Must be a positive integer.`)}if(t.subtitles&&typeof t.subtitles.codec!="string")throw new TypeError(`Invalid subtitles codec: ${t.subtitles.codec}. Must be a string.`);if(t.type!==void 0&&!["webm","matroska"].includes(t.type))throw new TypeError(`Invalid type: ${t.type}. Must be 'webm' or 'matroska'.`);if(t.firstTimestampBehavior&&!co.includes(t.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if(t.streaming!==void 0&&typeof t.streaming!="boolean")throw new TypeError(`Invalid streaming option: ${t.streaming}. Must be a boolean.`)},mr=new WeakSet,zs=function(){o(this,k)instanceof Ae&&o(this,k).target.options.onHeader&&o(this,k).startTrackingWrites(),T(this,wr,Vs).call(this),o(this,P).streaming||T(this,yr,Gs).call(this),T(this,br,Ns).call(this),T(this,gr,Ls).call(this),T(this,vr,Os).call(this),o(this,P).streaming||(T(this,bi,_r).call(this),T(this,_i,xr).call(this)),T(this,Sr,$s).call(this),T(this,Yt,pe).call(this)},wr=new WeakSet,Vs=function(){let t={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:o(this,P).type??"webm"},{id:17031,data:2},{id:17029,data:2}]};o(this,k).writeEBML(t)},gr=new WeakSet,Ls=function(){U(this,he,{id:236,size:4,data:new Uint8Array(Be)}),U(this,It,{id:236,size:4,data:new Uint8Array(Be)}),U(this,le,{id:236,size:4,data:new Uint8Array(Be)})},vr=new WeakSet,Os=function(){U(this,Ht,{id:21936,data:[{id:21937,data:2},{id:21946,data:2},{id:21947,data:2},{id:21945,data:0}]})},yr=new WeakSet,Gs=function(){const t=new Uint8Array([28,83,187,107]),e=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]);U(this,Et,{id:290298740,data:[{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:e},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:i},{id:21420,size:5,data:0}]}]})},br=new WeakSet,Ns=function(){let t={id:17545,data:new rr(0)};U(this,oe,t);let e={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Fs},{id:22337,data:Fs},o(this,P).streaming?null:t]};U(this,Ue,e)},bi=new WeakSet,_r=function(){let t={id:374648427,data:[]};U(this,ae,t),o(this,P).video&&t.data.push({id:174,data:[{id:215,data:ne},{id:29637,data:ne},{id:131,data:ao},{id:134,data:o(this,P).video.codec},o(this,he),o(this,P).video.frameRate?{id:2352003,data:1e9/o(this,P).video.frameRate}:null,{id:224,data:[{id:176,data:o(this,P).video.width},{id:186,data:o(this,P).video.height},o(this,P).video.alpha?{id:21440,data:1}:null,o(this,Ht)]}]}),o(this,P).audio&&(U(this,It,o(this,P).streaming?o(this,It)||null:{id:236,size:4,data:new Uint8Array(Be)}),t.data.push({id:174,data:[{id:215,data:Re},{id:29637,data:Re},{id:131,data:oo},{id:134,data:o(this,P).audio.codec},o(this,It),{id:225,data:[{id:181,data:new Ss(o(this,P).audio.sampleRate)},{id:159,data:o(this,P).audio.numberOfChannels},o(this,P).audio.bitDepth?{id:25188,data:o(this,P).audio.bitDepth}:null]}]})),o(this,P).subtitles&&t.data.push({id:174,data:[{id:215,data:vi},{id:29637,data:vi},{id:131,data:ho},{id:134,data:o(this,P).subtitles.codec},o(this,le)]})},_i=new WeakSet,xr=function(){let t={id:408125543,size:o(this,P).streaming?-1:Us,data:[o(this,P).streaming?null:o(this,Et),o(this,Ue),o(this,ae)]};if(U(this,Fe,t),o(this,k).writeEBML(t),o(this,k)instanceof Ae&&o(this,k).target.options.onHeader){let{data:e,start:i}=o(this,k).getTrackedWrites();o(this,k).target.options.onHeader(e,i)}},Sr=new WeakSet,$s=function(){U(this,de,{id:475249515,data:[]})},Yt=new WeakSet,pe=function(){o(this,k)instanceof ur&&o(this,k).flush()},Jt=new WeakSet,me=function(){return o(this,k).dataOffsets.get(o(this,Fe))},Cr=new WeakSet,js=function(t){if(t.decoderConfig){if(t.decoderConfig.colorSpace){let e=t.decoderConfig.colorSpace;if(U(this,Ve,e),o(this,Ht).data=[{id:21937,data:{rgb:1,bt709:1,bt470bg:5,smpte170m:6}[e.matrix]},{id:21946,data:{bt709:1,smpte170m:6,"iec61966-2-1":13}[e.transfer]},{id:21947,data:{bt709:1,bt470bg:5,smpte170m:6}[e.primaries]},{id:21945,data:[1,2][Number(e.fullRange)]}],!o(this,P).streaming){let i=o(this,k).pos;o(this,k).seek(o(this,k).offsets.get(o(this,Ht))),o(this,k).writeEBML(o(this,Ht)),o(this,k).seek(i)}}t.decoderConfig.description&&(o(this,P).streaming?U(this,he,T(this,we,Ne).call(this,t.decoderConfig.description)):T(this,$e,Ci).call(this,o(this,he),t.decoderConfig.description))}},Er=new WeakSet,qs=function(t){if(t.type!=="key"||!o(this,Ve))return;let e=0;if(ie(t.data,0,2)!==2)return;e+=2;let i=(ie(t.data,e+1,e+2)<<1)+ie(t.data,e+0,e+1);e+=2,i===3&&e++;let r=ie(t.data,e+0,e+1);if(e++,r)return;let s=ie(t.data,e+0,e+1);if(e++,s!==0)return;e+=2;let n=ie(t.data,e+0,e+24);if(e+=24,n!==4817730)return;i>=2&&e++;let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[o(this,Ve).matrix];to(t.data,e+0,e+3,a)},Oe=new WeakSet,xi=function(){let t=Math.min(o(this,P).video?o(this,fe):1/0,o(this,P).audio?o(this,ue):1/0),e=o(this,Xt);for(;e.length>0&&e[0].timestamp<=t;)T(this,gt,Tt).call(this,e.shift(),!o(this,P).video&&!o(this,P).audio)},Ge=new WeakSet,Si=function(t,e,i,r,s,n){let a=T(this,Tr,Hs).call(this,i,r);return{data:t,additions:n,type:e,timestamp:a,duration:s,trackNumber:r}},Tr=new WeakSet,Hs=function(t,e){let i=e===ne?o(this,fe):e===Re?o(this,ue):o(this,yi);if(e!==vi){let r=e===ne?o(this,We):o(this,ze);if(o(this,P).firstTimestampBehavior==="strict"&&i===-1&&t!==0)throw new Error(`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.
26
+ `);if(f(this,P).firstTimestampBehavior==="offset"||f(this,P).firstTimestampBehavior==="cross-track-offset"){i.firstDecodeTimestamp===void 0&&(i.firstDecodeTimestamp=e);let u;f(this,P).firstTimestampBehavior==="offset"?u=i.firstDecodeTimestamp:u=Math.min(((a=f(this,it))==null?void 0:a.firstDecodeTimestamp)??1/0,((l=f(this,tt))==null?void 0:l.firstDecodeTimestamp)??1/0),e-=u,t-=u}if(e<i.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${i.lastDecodeTimestamp*1e6} to ${e*1e6}).`);return i.lastDecodeTimestamp=e,{presentationTimestamp:t,decodeTimestamp:e}},Me=new WeakSet,pi=function(t){if(f(this,P).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(t.currentChunk){if(t.finalizedChunks.push(t.currentChunk),f(this,ne).push(t.currentChunk),(t.compactlyCodedChunkTable.length===0||si(t.compactlyCodedChunkTable).samplesPerChunk!==t.currentChunk.samples.length)&&t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:t.currentChunk.samples.length}),f(this,P).fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=f(this,B).pos;for(let e of t.currentChunk.samples)f(this,B).write(e.data),e.data=null;z(this,se,Pe).call(this)}},mi=new WeakSet,sr=function(t=!0){if(f(this,P).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let e=[f(this,it),f(this,tt)].filter(l=>l&&l.currentChunk);if(e.length===0)return;let i=ia(this,Ki)._++;if(i===1){let l=ai(e,f(this,re),!0);f(this,B).writeBox(l)}let r=f(this,B).pos,n=gn(i,e);f(this,B).writeBox(n);{let l=$i(!1),u=0;for(let v of e)for(let p of v.currentChunk.samples)u+=p.size;let m=f(this,B).measureBox(l)+u;m>=2**32&&(l.largeSize=!0,m=f(this,B).measureBox(l)+u),l.size=m,f(this,B).writeBox(l)}for(let l of e){l.currentChunk.offset=f(this,B).pos,l.currentChunk.moofOffset=r;for(let u of l.currentChunk.samples)f(this,B).write(u.data),u.data=null}let s=f(this,B).pos;f(this,B).seek(f(this,B).offsets.get(n));let a=gn(i,e);f(this,B).writeBox(a),f(this,B).seek(s);for(let l of e)l.finalizedChunks.push(l.currentChunk),f(this,ne).push(l.currentChunk),l.currentChunk=null;t&&z(this,se,Pe).call(this)},se=new WeakSet,Pe=function(){f(this,B)instanceof Yi&&f(this,B).flush()},wi=new WeakSet,ar=function(){if(f(this,Ae))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};var or=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},o=(t,e,i)=>(or(t,e,"read from private field"),i?i.call(t):e.get(t)),_=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},F=(t,e,i,r)=>(or(t,e,"write to private field"),e.set(t,i),i),k=(t,e,i)=>(or(t,e,"access private method"),i),Pn=class{constructor(t){this.value=t}},lr=class{constructor(t){this.value=t}},In=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,ho=t=>{if(t<127)return 1;if(t<16383)return 2;if(t<(1<<21)-1)return 3;if(t<(1<<28)-1)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML VINT size not supported "+t)},ae=(t,e,i)=>{let r=0;for(let n=e;n<i;n++){let s=Math.floor(n/8),a=t[s],l=7-(n&7),u=(a&1<<l)>>l;r<<=1,r|=u}return r},co=(t,e,i,r)=>{for(let n=e;n<i;n++){let s=Math.floor(n/8),a=t[s],l=7-(n&7);a&=~(1<<l),a|=(r&1<<i-n-1)>>i-n-1<<l,t[s]=a}},gi=class{},Rn=class extends gi{constructor(){super(...arguments),this.buffer=null}},Bn=class extends gi{constructor(t){if(super(),this.options=t,typeof t!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(t.onData){if(typeof t.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(t.onData.length<2)throw new TypeError("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.")}if(t.onHeader&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},fo=class extends gi{constructor(t,e){if(super(),this.stream=t,this.options=e,!(t instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(e!==void 0&&typeof e!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(e&&e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},It,G,hr,Fn,dr,Dn,cr,Un,vi,fr,ur,Wn,zn=class{constructor(){_(this,hr),_(this,dr),_(this,cr),_(this,vi),_(this,ur),this.pos=0,_(this,It,new Uint8Array(8)),_(this,G,new DataView(o(this,It).buffer)),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}seek(t){this.pos=t}writeEBMLVarInt(t,e=ho(t)){let i=0;switch(e){case 1:o(this,G).setUint8(i++,128|t);break;case 2:o(this,G).setUint8(i++,64|t>>8),o(this,G).setUint8(i++,t);break;case 3:o(this,G).setUint8(i++,32|t>>16),o(this,G).setUint8(i++,t>>8),o(this,G).setUint8(i++,t);break;case 4:o(this,G).setUint8(i++,16|t>>24),o(this,G).setUint8(i++,t>>16),o(this,G).setUint8(i++,t>>8),o(this,G).setUint8(i++,t);break;case 5:o(this,G).setUint8(i++,8|t/2**32&7),o(this,G).setUint8(i++,t>>24),o(this,G).setUint8(i++,t>>16),o(this,G).setUint8(i++,t>>8),o(this,G).setUint8(i++,t);break;case 6:o(this,G).setUint8(i++,4|t/2**40&3),o(this,G).setUint8(i++,t/2**32|0),o(this,G).setUint8(i++,t>>24),o(this,G).setUint8(i++,t>>16),o(this,G).setUint8(i++,t>>8),o(this,G).setUint8(i++,t);break;default:throw new Error("Bad EBML VINT size "+e)}this.write(o(this,It).subarray(0,i))}writeEBML(t){if(t!==null)if(t instanceof Uint8Array)this.write(t);else if(Array.isArray(t))for(let e of t)this.writeEBML(e);else if(this.offsets.set(t,this.pos),k(this,vi,fr).call(this,t.id),Array.isArray(t.data)){let e=this.pos,i=t.size===-1?1:t.size??4;t.size===-1?k(this,hr,Fn).call(this,255):this.seek(this.pos+i);let r=this.pos;if(this.dataOffsets.set(t,r),this.writeEBML(t.data),t.size!==-1){let n=this.pos-r,s=this.pos;this.seek(e),this.writeEBMLVarInt(n,i),this.seek(s)}}else if(typeof t.data=="number"){let e=t.size??In(t.data);this.writeEBMLVarInt(e),k(this,vi,fr).call(this,t.data,e)}else typeof t.data=="string"?(this.writeEBMLVarInt(t.data.length),k(this,ur,Wn).call(this,t.data)):t.data instanceof Uint8Array?(this.writeEBMLVarInt(t.data.byteLength,t.size),this.write(t.data)):t.data instanceof Pn?(this.writeEBMLVarInt(4),k(this,dr,Dn).call(this,t.data.value)):t.data instanceof lr&&(this.writeEBMLVarInt(8),k(this,cr,Un).call(this,t.data.value))}};It=new WeakMap,G=new WeakMap,hr=new WeakSet,Fn=function(t){o(this,G).setUint8(0,t),this.write(o(this,It).subarray(0,1))},dr=new WeakSet,Dn=function(t){o(this,G).setFloat32(0,t,!1),this.write(o(this,It).subarray(0,4))},cr=new WeakSet,Un=function(t){o(this,G).setFloat64(0,t,!1),this.write(o(this,It))},vi=new WeakSet,fr=function(t,e=In(t)){let i=0;switch(e){case 6:o(this,G).setUint8(i++,t/2**40|0);case 5:o(this,G).setUint8(i++,t/2**32|0);case 4:o(this,G).setUint8(i++,t>>24);case 3:o(this,G).setUint8(i++,t>>16);case 2:o(this,G).setUint8(i++,t>>8);case 1:o(this,G).setUint8(i++,t);break;default:throw new Error("Bad UINT size "+e)}this.write(o(this,It).subarray(0,i))},ur=new WeakSet,Wn=function(t){this.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))};var yi,qt,Ie,bi,pr,uo=class extends zn{constructor(t){super(),_(this,bi),_(this,yi,void 0),_(this,qt,new ArrayBuffer(2**16)),_(this,Ie,new Uint8Array(o(this,qt))),F(this,yi,t)}write(t){k(this,bi,pr).call(this,this.pos+t.byteLength),o(this,Ie).set(t,this.pos),this.pos+=t.byteLength}finalize(){k(this,bi,pr).call(this,this.pos),o(this,yi).buffer=o(this,qt).slice(0,this.pos)}};yi=new WeakMap,qt=new WeakMap,Ie=new WeakMap,bi=new WeakSet,pr=function(t){let e=o(this,qt).byteLength;for(;e<t;)e*=2;if(e===o(this,qt).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(o(this,Ie),0),F(this,qt,i),F(this,Ie,r)};var oe,wt,gt,Ht,Re=class extends zn{constructor(t){super(),this.target=t,_(this,oe,!1),_(this,wt,void 0),_(this,gt,void 0),_(this,Ht,void 0)}write(t){if(!o(this,oe))return;let e=this.pos;if(e<o(this,gt)){if(e+t.byteLength<=o(this,gt))return;t=t.subarray(o(this,gt)-e),e=0}let i=e+t.byteLength-o(this,gt),r=o(this,wt).byteLength;for(;r<i;)r*=2;if(r!==o(this,wt).byteLength){let n=new Uint8Array(r);n.set(o(this,wt),0),F(this,wt,n)}o(this,wt).set(t,e-o(this,gt)),F(this,Ht,Math.max(o(this,Ht),e+t.byteLength))}startTrackingWrites(){F(this,oe,!0),F(this,wt,new Uint8Array(2**10)),F(this,gt,this.pos),F(this,Ht,this.pos)}getTrackedWrites(){if(!o(this,oe))throw new Error("Can't get tracked writes since nothing was tracked.");let e={data:o(this,wt).subarray(0,o(this,Ht)-o(this,gt)),start:o(this,gt),end:o(this,Ht)};return F(this,wt,void 0),F(this,oe,!1),e}};oe=new WeakMap,wt=new WeakMap,gt=new WeakMap,Ht=new WeakMap;var po=2**24,mo=2,Xt,le,Be,Fe,Tt,at,_i,mr,wr,On,gr,Vn,De,xi,vr=class extends Re{constructor(t,e){var i,r;super(t),_(this,_i),_(this,wr),_(this,gr),_(this,De),_(this,Xt,[]),_(this,le,0),_(this,Be,void 0),_(this,Fe,void 0),_(this,Tt,void 0),_(this,at,[]),F(this,Be,e),F(this,Fe,((i=t.options)==null?void 0:i.chunked)??!1),F(this,Tt,((r=t.options)==null?void 0:r.chunkSize)??po)}write(t){super.write(t),o(this,Xt).push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength}flush(){var i,r;if(o(this,Xt).length===0)return;let t=[],e=[...o(this,Xt)].sort((n,s)=>n.start-s.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let n=1;n<e.length;n++){let s=t[t.length-1],a=e[n];a.start<=s.start+s.size?s.size=Math.max(s.size,a.start+a.data.byteLength-s.start):t.push({start:a.start,size:a.data.byteLength})}for(let n of t){n.data=new Uint8Array(n.size);for(let s of o(this,Xt))n.start<=s.start&&s.start<n.start+n.size&&n.data.set(s.data,s.start-n.start);if(o(this,Fe))k(this,_i,mr).call(this,n.data,n.start),k(this,De,xi).call(this);else{if(o(this,Be)&&n.start<o(this,le))throw new Error("Internal error: Monotonicity violation.");(r=(i=this.target.options).onData)==null||r.call(i,n.data,n.start),F(this,le,n.start+n.data.byteLength)}}o(this,Xt).length=0}finalize(){o(this,Fe)&&k(this,De,xi).call(this,!0)}};Xt=new WeakMap,le=new WeakMap,Be=new WeakMap,Fe=new WeakMap,Tt=new WeakMap,at=new WeakMap,_i=new WeakSet,mr=function(t,e){let i=o(this,at).findIndex(l=>l.start<=e&&e<l.start+o(this,Tt));i===-1&&(i=k(this,gr,Vn).call(this,e));let r=o(this,at)[i],n=e-r.start,s=t.subarray(0,Math.min(o(this,Tt)-n,t.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(k(this,wr,On).call(this,r,a),r.written[0].start===0&&r.written[0].end===o(this,Tt)&&(r.shouldFlush=!0),o(this,at).length>mo){for(let l=0;l<o(this,at).length-1;l++)o(this,at)[l].shouldFlush=!0;k(this,De,xi).call(this)}s.byteLength<t.byteLength&&k(this,_i,mr).call(this,t.subarray(s.byteLength),e+s.byteLength)},wr=new WeakSet,On=function(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){let s=Math.floor(i+(r-i+1)/2);t.written[s].start<=e.start?(i=s+1,n=s):r=s-1}for(t.written.splice(n+1,0,e),(n===-1||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)},gr=new WeakSet,Vn=function(t){let i={start:Math.floor(t/o(this,Tt))*o(this,Tt),data:new Uint8Array(o(this,Tt)),written:[],shouldFlush:!1};return o(this,at).push(i),o(this,at).sort((r,n)=>r.start-n.start),o(this,at).indexOf(i)},De=new WeakSet,xi=function(t=!1){var e,i;for(let r=0;r<o(this,at).length;r++){let n=o(this,at)[r];if(!(!n.shouldFlush&&!t)){for(let s of n.written){if(o(this,Be)&&n.start+s.start<o(this,le))throw new Error("Internal error: Monotonicity violation.");(i=(e=this.target.options).onData)==null||i.call(e,n.data.subarray(s.start,s.end),n.start+s.start),F(this,le,n.start+s.end)}o(this,at).splice(r--,1)}}};var wo=class extends vr{constructor(t,e){var i;super(new Bn({onData:(r,n)=>t.stream.write({type:"write",data:r,position:n}),chunked:!0,chunkSize:(i=t.options)==null?void 0:i.chunkSize}),e)}},he=1,Ue=2,Si=3,go=1,vo=2,yo=17,bo=2**15,We=2**13,Ln="https://github.com/Vanilagy/webm-muxer",Gn=6,Nn=5,_o=["strict","offset","permissive"],R,A,ze,Oe,kt,de,ce,Yt,fe,Rt,ue,pe,vt,Ve,me,Bt,Ft,Jt,Le,Ge,we,ge,Ci,Ne,$e,yr,$n,br,jn,_r,qn,xr,Hn,Sr,Xn,Cr,Yn,Er,Jn,Ei,Tr,Ti,kr,Ar,Kn,Kt,ve,Zt,ye,Mr,Zn,Pr,Qn,je,ki,qe,Ai,Ir,ts,yt,At,be,He,Xe,Mi,Rr,es,Pi,Br,Ye,Ii,xo=class{constructor(t){_(this,yr),_(this,br),_(this,_r),_(this,xr),_(this,Sr),_(this,Cr),_(this,Er),_(this,Ei),_(this,Ti),_(this,Ar),_(this,Kt),_(this,Zt),_(this,Mr),_(this,Pr),_(this,je),_(this,qe),_(this,Ir),_(this,yt),_(this,be),_(this,Xe),_(this,Rr),_(this,Pi),_(this,Ye),_(this,R,void 0),_(this,A,void 0),_(this,ze,void 0),_(this,Oe,void 0),_(this,kt,void 0),_(this,de,void 0),_(this,ce,void 0),_(this,Yt,void 0),_(this,fe,void 0),_(this,Rt,void 0),_(this,ue,void 0),_(this,pe,void 0),_(this,vt,void 0),_(this,Ve,void 0),_(this,me,0),_(this,Bt,[]),_(this,Ft,[]),_(this,Jt,[]),_(this,Le,void 0),_(this,Ge,void 0),_(this,we,-1),_(this,ge,-1),_(this,Ci,-1),_(this,Ne,void 0),_(this,$e,!1),k(this,yr,$n).call(this,t),F(this,R,{type:"webm",firstTimestampBehavior:"strict",...t}),this.target=t.target;let e=!!o(this,R).streaming;if(t.target instanceof Rn)F(this,A,new uo(t.target));else if(t.target instanceof Bn)F(this,A,new vr(t.target,e));else if(t.target instanceof fo)F(this,A,new wo(t.target,e));else throw new Error(`Invalid target: ${t.target}`);k(this,br,jn).call(this)}addVideoChunk(t,e,i){if(!(t instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (chunk) must be of type EncodedVideoChunk.");if(e&&typeof e!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addVideoChunkRaw(r,t.type,i??t.timestamp,e)}addVideoChunkRaw(t,e,i,r){if(!(t instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addVideoChunkRaw's fourth argument (meta), when provided, must be an object.");if(k(this,Ye,Ii).call(this),!o(this,R).video)throw new Error("No video track declared.");o(this,Le)===void 0&&F(this,Le,i),r&&k(this,Mr,Zn).call(this,r);let n=k(this,qe,Ai).call(this,t,e,i,he);for(o(this,R).video.codec==="V_VP9"&&k(this,Pr,Qn).call(this,n),F(this,we,n.timestamp);o(this,Ft).length>0&&o(this,Ft)[0].timestamp<=n.timestamp;){let s=o(this,Ft).shift();k(this,yt,At).call(this,s,!1)}!o(this,R).audio||n.timestamp<=o(this,ge)?k(this,yt,At).call(this,n,!0):o(this,Bt).push(n),k(this,je,ki).call(this),k(this,Kt,ve).call(this)}addAudioChunk(t,e,i){if(!(t instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (chunk) must be of type EncodedAudioChunk.");if(e&&typeof e!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addAudioChunkRaw(r,t.type,i??t.timestamp,e)}addAudioChunkRaw(t,e,i,r){if(!(t instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addAudioChunkRaw's fourth argument (meta), when provided, must be an object.");if(k(this,Ye,Ii).call(this),!o(this,R).audio)throw new Error("No audio track declared.");o(this,Ge)===void 0&&F(this,Ge,i),r!=null&&r.decoderConfig&&(o(this,R).streaming?F(this,Rt,k(this,be,He).call(this,r.decoderConfig.description)):k(this,Xe,Mi).call(this,o(this,Rt),r.decoderConfig.description));let n=k(this,qe,Ai).call(this,t,e,i,Ue);for(F(this,ge,n.timestamp);o(this,Bt).length>0&&o(this,Bt)[0].timestamp<=n.timestamp;){let s=o(this,Bt).shift();k(this,yt,At).call(this,s,!0)}!o(this,R).video||n.timestamp<=o(this,we)?k(this,yt,At).call(this,n,!o(this,R).video):o(this,Ft).push(n),k(this,je,ki).call(this),k(this,Kt,ve).call(this)}addSubtitleChunk(t,e,i){if(typeof t!="object"||!t)throw new TypeError("addSubtitleChunk's first argument (chunk) must be an object.");if(!(t.body instanceof Uint8Array))throw new TypeError("body must be an instance of Uint8Array.");if(!Number.isFinite(t.timestamp)||t.timestamp<0)throw new TypeError("timestamp must be a non-negative real number.");if(!Number.isFinite(t.duration)||t.duration<0)throw new TypeError("duration must be a non-negative real number.");if(t.additions&&!(t.additions instanceof Uint8Array))throw new TypeError("additions, when present, must be an instance of Uint8Array.");if(typeof e!="object")throw new TypeError("addSubtitleChunk's second argument (meta) must be an object.");if(k(this,Ye,Ii).call(this),!o(this,R).subtitles)throw new Error("No subtitle track declared.");e!=null&&e.decoderConfig&&(o(this,R).streaming?F(this,ue,k(this,be,He).call(this,e.decoderConfig.description)):k(this,Xe,Mi).call(this,o(this,ue),e.decoderConfig.description));let r=k(this,qe,Ai).call(this,t.body,"key",i??t.timestamp,Si,t.duration,t.additions);F(this,Ci,r.timestamp),o(this,Jt).push(r),k(this,je,ki).call(this),k(this,Kt,ve).call(this)}finalize(){if(o(this,$e))throw new Error("Cannot finalize a muxer more than once.");for(;o(this,Bt).length>0;)k(this,yt,At).call(this,o(this,Bt).shift(),!0);for(;o(this,Ft).length>0;)k(this,yt,At).call(this,o(this,Ft).shift(),!0);for(;o(this,Jt).length>0&&o(this,Jt)[0].timestamp<=o(this,me);)k(this,yt,At).call(this,o(this,Jt).shift(),!1);if(o(this,vt)&&k(this,Pi,Br).call(this),o(this,A).writeEBML(o(this,pe)),!o(this,R).streaming){let t=o(this,A).pos,e=o(this,A).pos-o(this,Zt,ye);o(this,A).seek(o(this,A).offsets.get(o(this,ze))+4),o(this,A).writeEBMLVarInt(e,Gn),o(this,ce).data=new lr(o(this,me)),o(this,A).seek(o(this,A).offsets.get(o(this,ce))),o(this,A).writeEBML(o(this,ce)),o(this,kt).data[0].data[1].data=o(this,A).offsets.get(o(this,pe))-o(this,Zt,ye),o(this,kt).data[1].data[1].data=o(this,A).offsets.get(o(this,Oe))-o(this,Zt,ye),o(this,kt).data[2].data[1].data=o(this,A).offsets.get(o(this,de))-o(this,Zt,ye),o(this,A).seek(o(this,A).offsets.get(o(this,kt))),o(this,A).writeEBML(o(this,kt)),o(this,A).seek(t)}k(this,Kt,ve).call(this),o(this,A).finalize(),F(this,$e,!0)}};R=new WeakMap,A=new WeakMap,ze=new WeakMap,Oe=new WeakMap,kt=new WeakMap,de=new WeakMap,ce=new WeakMap,Yt=new WeakMap,fe=new WeakMap,Rt=new WeakMap,ue=new WeakMap,pe=new WeakMap,vt=new WeakMap,Ve=new WeakMap,me=new WeakMap,Bt=new WeakMap,Ft=new WeakMap,Jt=new WeakMap,Le=new WeakMap,Ge=new WeakMap,we=new WeakMap,ge=new WeakMap,Ci=new WeakMap,Ne=new WeakMap,$e=new WeakMap,yr=new WeakSet,$n=function(t){if(typeof t!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(t.target instanceof gi))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(typeof t.video.codec!="string")throw new TypeError(`Invalid video codec: ${t.video.codec}. Must be a string.`);if(!Number.isInteger(t.video.width)||t.video.width<=0)throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);if(!Number.isInteger(t.video.height)||t.video.height<=0)throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);if(t.video.frameRate!==void 0&&(!Number.isFinite(t.video.frameRate)||t.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.video.frameRate}. Must be a positive number.`);if(t.video.alpha!==void 0&&typeof t.video.alpha!="boolean")throw new TypeError(`Invalid video alpha: ${t.video.alpha}. Must be a boolean.`)}if(t.audio){if(typeof t.audio.codec!="string")throw new TypeError(`Invalid audio codec: ${t.audio.codec}. Must be a string.`);if(!Number.isInteger(t.audio.numberOfChannels)||t.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(t.audio.sampleRate)||t.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`);if(t.audio.bitDepth!==void 0&&(!Number.isInteger(t.audio.bitDepth)||t.audio.bitDepth<=0))throw new TypeError(`Invalid audio bit depth: ${t.audio.bitDepth}. Must be a positive integer.`)}if(t.subtitles&&typeof t.subtitles.codec!="string")throw new TypeError(`Invalid subtitles codec: ${t.subtitles.codec}. Must be a string.`);if(t.type!==void 0&&!["webm","matroska"].includes(t.type))throw new TypeError(`Invalid type: ${t.type}. Must be 'webm' or 'matroska'.`);if(t.firstTimestampBehavior&&!_o.includes(t.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if(t.streaming!==void 0&&typeof t.streaming!="boolean")throw new TypeError(`Invalid streaming option: ${t.streaming}. Must be a boolean.`)},br=new WeakSet,jn=function(){o(this,A)instanceof Re&&o(this,A).target.options.onHeader&&o(this,A).startTrackingWrites(),k(this,_r,qn).call(this),o(this,R).streaming||k(this,Cr,Yn).call(this),k(this,Er,Jn).call(this),k(this,xr,Hn).call(this),k(this,Sr,Xn).call(this),o(this,R).streaming||(k(this,Ei,Tr).call(this),k(this,Ti,kr).call(this)),k(this,Ar,Kn).call(this),k(this,Kt,ve).call(this)},_r=new WeakSet,qn=function(){let t={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:o(this,R).type??"webm"},{id:17031,data:2},{id:17029,data:2}]};o(this,A).writeEBML(t)},xr=new WeakSet,Hn=function(){F(this,fe,{id:236,size:4,data:new Uint8Array(We)}),F(this,Rt,{id:236,size:4,data:new Uint8Array(We)}),F(this,ue,{id:236,size:4,data:new Uint8Array(We)})},Sr=new WeakSet,Xn=function(){F(this,Yt,{id:21936,data:[{id:21937,data:2},{id:21946,data:2},{id:21947,data:2},{id:21945,data:0}]})},Cr=new WeakSet,Yn=function(){const t=new Uint8Array([28,83,187,107]),e=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]);F(this,kt,{id:290298740,data:[{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:e},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:i},{id:21420,size:5,data:0}]}]})},Er=new WeakSet,Jn=function(){let t={id:17545,data:new lr(0)};F(this,ce,t);let e={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Ln},{id:22337,data:Ln},o(this,R).streaming?null:t]};F(this,Oe,e)},Ei=new WeakSet,Tr=function(){let t={id:374648427,data:[]};F(this,de,t),o(this,R).video&&t.data.push({id:174,data:[{id:215,data:he},{id:29637,data:he},{id:131,data:go},{id:134,data:o(this,R).video.codec},o(this,fe),o(this,R).video.frameRate?{id:2352003,data:1e9/o(this,R).video.frameRate}:null,{id:224,data:[{id:176,data:o(this,R).video.width},{id:186,data:o(this,R).video.height},o(this,R).video.alpha?{id:21440,data:1}:null,o(this,Yt)]}]}),o(this,R).audio&&(F(this,Rt,o(this,R).streaming?o(this,Rt)||null:{id:236,size:4,data:new Uint8Array(We)}),t.data.push({id:174,data:[{id:215,data:Ue},{id:29637,data:Ue},{id:131,data:vo},{id:134,data:o(this,R).audio.codec},o(this,Rt),{id:225,data:[{id:181,data:new Pn(o(this,R).audio.sampleRate)},{id:159,data:o(this,R).audio.numberOfChannels},o(this,R).audio.bitDepth?{id:25188,data:o(this,R).audio.bitDepth}:null]}]})),o(this,R).subtitles&&t.data.push({id:174,data:[{id:215,data:Si},{id:29637,data:Si},{id:131,data:yo},{id:134,data:o(this,R).subtitles.codec},o(this,ue)]})},Ti=new WeakSet,kr=function(){let t={id:408125543,size:o(this,R).streaming?-1:Gn,data:[o(this,R).streaming?null:o(this,kt),o(this,Oe),o(this,de)]};if(F(this,ze,t),o(this,A).writeEBML(t),o(this,A)instanceof Re&&o(this,A).target.options.onHeader){let{data:e,start:i}=o(this,A).getTrackedWrites();o(this,A).target.options.onHeader(e,i)}},Ar=new WeakSet,Kn=function(){F(this,pe,{id:475249515,data:[]})},Kt=new WeakSet,ve=function(){o(this,A)instanceof vr&&o(this,A).flush()},Zt=new WeakSet,ye=function(){return o(this,A).dataOffsets.get(o(this,ze))},Mr=new WeakSet,Zn=function(t){if(t.decoderConfig){if(t.decoderConfig.colorSpace){let e=t.decoderConfig.colorSpace;if(F(this,Ne,e),o(this,Yt).data=[{id:21937,data:{rgb:1,bt709:1,bt470bg:5,smpte170m:6}[e.matrix]},{id:21946,data:{bt709:1,smpte170m:6,"iec61966-2-1":13}[e.transfer]},{id:21947,data:{bt709:1,bt470bg:5,smpte170m:6}[e.primaries]},{id:21945,data:[1,2][Number(e.fullRange)]}],!o(this,R).streaming){let i=o(this,A).pos;o(this,A).seek(o(this,A).offsets.get(o(this,Yt))),o(this,A).writeEBML(o(this,Yt)),o(this,A).seek(i)}}t.decoderConfig.description&&(o(this,R).streaming?F(this,fe,k(this,be,He).call(this,t.decoderConfig.description)):k(this,Xe,Mi).call(this,o(this,fe),t.decoderConfig.description))}},Pr=new WeakSet,Qn=function(t){if(t.type!=="key"||!o(this,Ne))return;let e=0;if(ae(t.data,0,2)!==2)return;e+=2;let i=(ae(t.data,e+1,e+2)<<1)+ae(t.data,e+0,e+1);e+=2,i===3&&e++;let r=ae(t.data,e+0,e+1);if(e++,r)return;let n=ae(t.data,e+0,e+1);if(e++,n!==0)return;e+=2;let s=ae(t.data,e+0,e+24);if(e+=24,s!==4817730)return;i>=2&&e++;let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[o(this,Ne).matrix];co(t.data,e+0,e+3,a)},je=new WeakSet,ki=function(){let t=Math.min(o(this,R).video?o(this,we):1/0,o(this,R).audio?o(this,ge):1/0),e=o(this,Jt);for(;e.length>0&&e[0].timestamp<=t;)k(this,yt,At).call(this,e.shift(),!o(this,R).video&&!o(this,R).audio)},qe=new WeakSet,Ai=function(t,e,i,r,n,s){let a=k(this,Ir,ts).call(this,i,r);return{data:t,additions:s,type:e,timestamp:a,duration:n,trackNumber:r}},Ir=new WeakSet,ts=function(t,e){let i=e===he?o(this,we):e===Ue?o(this,ge):o(this,Ci);if(e!==Si){let r=e===he?o(this,Le):o(this,Ge);if(o(this,R).firstTimestampBehavior==="strict"&&i===-1&&t!==0)throw new Error(`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.
26
27
 
27
28
  If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
28
29
  If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'permissive'.
29
- `);o(this,P).firstTimestampBehavior==="offset"&&(t-=r)}if(t<i)throw new Error(`Timestamps must be monotonically increasing (went from ${i} to ${t}).`);if(t<0)throw new Error(`Timestamps must be non-negative (received ${t}).`);return t},gt=new WeakSet,Tt=function(t,e){o(this,P).streaming&&!o(this,ae)&&(T(this,bi,_r).call(this),T(this,_i,xr).call(this));let i=Math.floor(t.timestamp/1e3),r=i-o(this,De),s=e&&t.type==="key"&&r>=1e3,n=r>=lo;if((!o(this,wt)||s||n)&&(T(this,kr,Xs).call(this,i),r=0),r<0)return;let a=new Uint8Array(4),l=new DataView(a.buffer);if(l.setUint8(0,128|t.trackNumber),l.setInt16(1,r,!1),t.duration===void 0&&!t.additions){l.setUint8(3,+(t.type==="key")<<7);let u={id:163,data:[a,t.data]};o(this,k).writeEBML(u)}else{let u=Math.floor(t.duration/1e3),g={id:160,data:[{id:161,data:[a,t.data]},t.duration!==void 0?{id:155,data:u}:null,t.additions?{id:30113,data:t.additions}:null]};o(this,k).writeEBML(g)}U(this,ce,Math.max(o(this,ce),i))},we=new WeakSet,Ne=function(t){return{id:25506,size:4,data:new Uint8Array(t)}},$e=new WeakSet,Ci=function(t,e){let i=o(this,k).pos;o(this,k).seek(o(this,k).offsets.get(t));let r=6+e.byteLength,s=Be-r;if(s<0){let n=e.byteLength+s;e instanceof ArrayBuffer?e=e.slice(0,n):e=e.buffer.slice(0,n),s=0}t=[T(this,we,Ne).call(this,e),{id:236,size:4,data:new Uint8Array(s)}],o(this,k).writeEBML(t),o(this,k).seek(i)},kr=new WeakSet,Xs=function(t){o(this,wt)&&T(this,Ei,Ar).call(this),o(this,k)instanceof Ae&&o(this,k).target.options.onCluster&&o(this,k).startTrackingWrites(),U(this,wt,{id:524531317,size:o(this,P).streaming?-1:Ds,data:[{id:231,data:t}]}),o(this,k).writeEBML(o(this,wt)),U(this,De,t);let e=o(this,k).offsets.get(o(this,wt))-o(this,Jt,me);o(this,de).data.push({id:187,data:[{id:179,data:t},o(this,P).video?{id:183,data:[{id:247,data:ne},{id:241,data:e}]}:null,o(this,P).audio?{id:183,data:[{id:247,data:Re},{id:241,data:e}]}:null]})},Ei=new WeakSet,Ar=function(){if(!o(this,P).streaming){let t=o(this,k).pos-o(this,k).dataOffsets.get(o(this,wt)),e=o(this,k).pos;o(this,k).seek(o(this,k).offsets.get(o(this,wt))+4),o(this,k).writeEBMLVarInt(t,Ds),o(this,k).seek(e)}if(o(this,k)instanceof Ae&&o(this,k).target.options.onCluster){let{data:t,start:e}=o(this,k).getTrackedWrites();o(this,k).target.options.onCluster(t,e,o(this,De))}},je=new WeakSet,Ti=function(){if(o(this,Le))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")},new TextEncoder;async function uo(t,e={}){if(!t.frames.length)throw new Error("[p5.export] encodeGIF: no frames to encode");const i=rs(),r=Math.round(1e3/t.fps),s=e.maxColors??256,n=t.frames.length;for(let a=0;a<n;a++){const l=t.frames[a],u=es(l,s),g=is(l,u);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))}return i.finish(),new Blob([i.bytes()],{type:"image/gif"})}function po(){return typeof window<"u"&&typeof window.VideoEncoder=="function"&&typeof window.VideoFrame=="function"}const mo={mp4:["avc1.640028","avc1.4d0028","avc1.42001f","av01.0.04M.08"],webm:["vp09.00.10.08","vp8","av01.0.04M.08"]},wo={avc1:"avc",av01:"av1",hvc1:"hevc",hev1:"hevc"},go={vp09:"V_VP9",vp9:"V_VP9",vp8:"V_VP8",av01:"V_AV1"};function vo(t,e){const i=e.split(".")[0].toLowerCase();return(t==="mp4"?wo:go)[i]||(t==="mp4"?"avc":"V_VP9")}async function yo(t,{width:e,height:i,fps:r,bitrate:s}){for(const n of mo[t]||[])for(const a of[{hardwareAcceleration:"prefer-hardware"},{}])try{const l=await VideoEncoder.isConfigSupported({codec:n,width:e,height:i,bitrate:s,framerate:r,...a});if(l&&l.supported)return n}catch{}return null}async function bo(t,e){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*.2))),l=await yo(i,{width:r,height:s,fps:n,bitrate:a});if(!l)throw new Error(`[p5.export] WebCodecs: no supported ${i.toUpperCase()} codec for ${r}×${s} @ ${n}fps`);const u=i==="mp4"?new fs:new Es,g=vo(i,l),v=i==="mp4"?new Za({target:u,video:{codec:g,width:r,height:s,frameRate:n},fastStart:"in-memory"}):new fo({target:u,video:{codec:g,width:r,height:s,frameRate:n}});let p=null;const h=new VideoEncoder({output:(M,j)=>v.addVideoChunk(M,j),error:M=>{p=p||M}}),d={codec:l,width:r,height:s,bitrate:a,framerate:n};l.startsWith("avc1")&&(d.avc={format:"avc"});const f=[{...d,hardwareAcceleration:"prefer-hardware"},{...d}];let m=null;for(const M of f)try{h.configure(M),m=M;break}catch{}if(!m)throw new Error(`[p5.export] could not configure VideoEncoder for ${l}`);const w=1e6/n,y=t.frames.length,C=Math.max(1,Math.round(n*2)),S=16;for(let M=0;M<y;M++){if(p)throw p;for(;h.encodeQueueSize>S;)if(await new Promise(B=>setTimeout(B,0)),p)throw p;const j=new VideoFrame(t.frames[M],{format:"RGBA",codedWidth:r,codedHeight:s,timestamp:Math.round(M*w),duration:Math.round(w)});h.encode(j,{keyFrame:M%C===0}),j.close(),e.onProgress&&e.onProgress((M+1)/y),(M&31)===31&&await new Promise(B=>setTimeout(B,0))}if(await h.flush(),p)throw p;v.finalize();const _=new Blob([u.buffer],{type:i==="mp4"?"video/mp4":"video/webm"});return _.__ext=i,_}const ki={webm:["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"],mp4:["video/mp4;codecs=avc1","video/mp4;codecs=h264","video/mp4"]};function _o(t){const e=t==="mp4"?[...ki.mp4,...ki.webm]:[...ki.webm,...ki.mp4];for(const i of e)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}function xo(t,e){return new Promise((i,r)=>{const s=e.format||"webm",n=_o(s);if(!n)return r(new Error("[p5.export] MediaRecorder fallback: no supported mime"));s==="mp4"&&n.ext!=="mp4"&&console.warn("[p5.export] MP4 unsupported here — falling back to WebM.");const a=document.createElement("canvas");a.width=t.width,a.height=t.height;const l=a.getContext("2d"),u=a.captureStream(t.fps),g={mimeType:n.mime};e.bitsPerSecond&&(g.videoBitsPerSecond=e.bitsPerSecond);const v=new MediaRecorder(u,g),p=[];v.ondataavailable=m=>{m.data&&m.data.size&&p.push(m.data)},v.onerror=m=>r(m.error||new Error("MediaRecorder error")),v.onstop=()=>{u.getTracks().forEach(w=>w.stop());const m=new Blob(p,{type:n.mime});m.__ext=n.ext,i(m)},l.putImageData(new ImageData(t.frames[0],t.width,t.height),0,0),v.start();const h=1e3/t.fps;let d=1;const f=()=>{if(d>=t.frames.length){setTimeout(()=>v.stop(),100);return}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)};setTimeout(f,h)})}async function So(t,e={}){if(!t.frames.length)throw new Error("[p5.export] encodeVideo: no frames to encode");if(po()){const i=performance.now();try{const r=await bo(t,e),s=performance.now()-i|0;return console.info(`[p5.export] WebCodecs encoded ${t.frames.length} frames in ${s}ms (${t.frames.length/(s/1e3)|0} fps).`),r}catch(r){console.warn("[p5.export] WebCodecs encode failed; falling back to MediaRecorder (real-time, much slower). Cause:",r)}}else console.info("[p5.export] WebCodecs not available in this browser; using MediaRecorder (real-time).");return xo(t,e)}async function Co(t,e={}){if(!t||!t.frames.length)throw new Error("[p5.export] encodeAnimatedWebP: buffer has no frames");const{width:i,height:r,fps:s,frames:n}=t,a=Bo(e.quality??.85),l=Math.max(0,e.loop??0),u=Math.max(1,Math.round(1e3/(s||30)));await Eo(i,r);const g=document.createElement("canvas");g.width=i,g.height=r;const v=g.getContext("2d"),p=v.createImageData(i,r),h=[];for(let m=0;m<n.length;m++){p.data.set(n[m]),v.putImageData(p,0,0);const w=await Ys(g,a),y=new Uint8Array(await w.arrayBuffer());h.push(To(y)),e.onProgress&&e.onProgress((m+1)/n.length)}const d=Io([Mr("VP8X",ko(i,r)),Mr("ANIM",Ao(l)),...h.map(m=>Mr("ANMF",Mo(i,r,u,m)))]),f=new Uint8Array(12+d.length);return Ir(f,0,"RIFF"),Js(f,4,4+d.length),Ir(f,8,"WEBP"),f.set(d,12),new Blob([f],{type:"image/webp"})}async function Eo(t,e){const i=document.createElement("canvas");i.width=Math.min(8,t),i.height=Math.min(8,e);const r=await Ys(i,.9);if(!r||r.type!=="image/webp")throw new Error("[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.")}function Ys(t,e){return new Promise((i,r)=>{t.toBlob(s=>s?i(s):r(new Error("canvas.toBlob returned null")),"image/webp",e)})}function To(t){let e=12;for(;e+8<=t.length;){const i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),r=Ro(t,e+4),s=r+(r&1);if(i==="VP8 "||i==="VP8L")return t.slice(e,e+8+s);e+=8+s}throw new Error("[p5.export] no VP8/VP8L chunk found in encoded WebP frame")}function ko(t,e){const i=new Uint8Array(10);return i[0]=2,qe(i,4,t-1),qe(i,7,e-1),i}function Ao(t){const e=new Uint8Array(6);return Po(e,4,t),e}function Mo(t,e,i,r){const s=new Uint8Array(16);qe(s,6,t-1),qe(s,9,e-1),qe(s,12,i),s[15]=0;const n=new Uint8Array(s.length+r.length);return n.set(s,0),n.set(r,s.length),n}function Mr(t,e){const i=e.length&1,r=new Uint8Array(8+e.length+i);return Ir(r,0,t),Js(r,4,e.length),r.set(e,8),r}function Io(t){let e=0;for(const s of t)e+=s.length;const i=new Uint8Array(e);let r=0;for(const s of t)i.set(s,r),r+=s.length;return i}function Ir(t,e,i){for(let r=0;r<i.length;r++)t[e+r]=i.charCodeAt(r)}function Po(t,e,i){t[e]=i&255,t[e+1]=i>>8&255}function qe(t,e,i){t[e]=i&255,t[e+1]=i>>8&255,t[e+2]=i>>16&255}function Js(t,e,i){t[e]=i&255,t[e+1]=i>>8&255,t[e+2]=i>>16&255,t[e+3]=i>>24&255}function Ro(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24>>>0}function Bo(t){return Math.max(0,Math.min(1,t))}const Ai={webm:["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"],mp4:["video/mp4;codecs=avc1","video/mp4;codecs=h264","video/mp4"]};function Fo(t){const e=t==="mp4"?[...Ai.mp4,...Ai.webm]:[...Ai.webm,...Ai.mp4];for(const i of e)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}class Uo{constructor(e){const i=Fo(e.format||"webm");if(!i)throw new Error("[p5.export] no supported MediaRecorder mime type found");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);const r={mimeType:i.mime};e.bitsPerSecond&&(r.videoBitsPerSecond=e.bitsPerSecond),this.recorder=new MediaRecorder(this.stream,r),this.chunks=[],this.recorder.ondataavailable=s=>{s.data&&s.data.size&&this.chunks.push(s.data)},this.filename=e.filename,this.duration=e.duration,this._mime=i.mime,this._stopPromise=null}start(){this.recorder.start(),this.duration&&setTimeout(()=>this.stop(),this.duration*1e3)}stop(){return this._stopPromise?this._stopPromise:(this._stopPromise=new Promise(e=>{this.recorder.onstop=()=>{const i=new Blob(this.chunks,{type:this._mime}),r=this.filename?yt(this.filename,this.ext):vt(this.ext);rt(i,r),this.stream.getTracks().forEach(s=>s.stop()),e(i)},this.recorder.state!=="inactive"&&this.recorder.stop()}),this._stopPromise)}get state(){return this.recorder.state}}function Do(t,e,i){if(e.recordVideo=function(r={}){const s=bt(this);if(!s)throw new Error("[p5.export] recordVideo: no canvas found");if(this._p5ExportVideo&&this._p5ExportVideo.state==="recording")throw new Error("[p5.export] a video recording is already in progress");const n=new Uo({canvas:s,...r});return n.start(),this._p5ExportVideo=n,n},e.recordWebM=function(r={}){return e.recordVideo.call(this,{...r,format:"webm"})},e.recordMP4=function(r={}){return e.recordVideo.call(this,{...r,format:"mp4"})},e.stopVideo=function(){const r=this._p5ExportVideo;return r?(this._p5ExportVideo=null,r.stop()):null},e.createVideoBuffer=function(r={}){const s=bt(this);if(!s)throw new Error("[p5.export] createVideoBuffer: no canvas found");if(this._p5ExportBuffer&&this._p5ExportBuffer.recording)throw new Error("[p5.export] a video buffer is already recording");const n=this,a=r.scale,l=typeof n.pixelDensity=="function"?n.pixelDensity():1,u=a&&a>0&&a!==l;u&&(n.pixelDensity(a),typeof n.redraw=="function"&&n.redraw());const g=new jn({canvas:s,...r}),v=g.stop.bind(g);let p=!u;return g.stop=function(){v(),p||(p=!0,n.pixelDensity(l),typeof n.redraw=="function"&&n.redraw())},g.start(),this._p5ExportBuffer=g,g},e.stopVideoBuffer=function(){const r=this._p5ExportBuffer;return r&&r.stop(),r||null},e.exportVideoBuffer=async function(r,s={}){if(!r||!r.frames.length)throw new Error("[p5.export] exportVideoBuffer: buffer has no frames");const n=(s.format||"webm").toLowerCase();let a,l;if(n==="gif")a=await uo(r,s),l="gif";else if(n==="webp")a=await Co(r,s),l="webp";else if(n==="webm"||n==="mp4")a=await So(r,{...s,format:n}),l=a.__ext||(n==="mp4"?"mp4":"webm");else throw new Error(`[p5.export] unsupported video format: ${n}`);const u=s.filename?yt(s.filename,l):vt(l);return rt(a,u),a},i&&typeof i=="object"){const r=i.postdraw;i.postdraw=function(){typeof r=="function"&&r.call(this);const s=this._p5ExportBuffer;s&&s.recording&&s.tick()}}}function Ks(t,e){return e&&Array.isArray(e.vertices)&&Array.isArray(e.faces)?e:typeof e=="function"&&typeof t.buildGeometry=="function"?t.buildGeometry(e):null}function Wo(t,e){e.saveSTL=function(i,r,s={}){const n=Ks(this,i);if(!n||typeof n.saveStl!="function"){const l=Mi(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.";throw new Error("[p5.export] saveSTL: no exportable geometry. "+l)}const a=r||"sketch.stl";n.saveStl(a,{binary:!!s.binary})},e.saveOBJ=function(i,r){const s=Ks(this,i);if(!s||typeof s.saveObj!="function"){const a=Mi(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.";throw new Error("[p5.export] saveOBJ: no exportable geometry. "+a)}const n=r||"sketch.obj";s.saveObj(n)}}const zo=".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}";let Zs=!1;function Vo(){if(Zs||typeof document>"u")return;Zs=!0;const t=document.createElement("style");t.setAttribute("data-p5-export",""),t.textContent=zo,document.head.appendChild(t)}const Qs=[{value:"png",label:"PNG (image)"},{value:"jpg",label:"JPG (image)"},{value:"webp",label:"WebP (image)"},{value:"svg",label:"SVG (vector)"},{value:"pdf",label:"PDF (vector)"}],Lo=[{value:"stl",label:"STL (3D)"},{value:"obj",label:"OBJ (3D)"}],Oo=[{value:"webm",label:"WebM (video)"},{value:"mp4",label:"MP4 (video)"},{value:"webp",label:"WebP (animation)"},{value:"gif",label:"GIF (animation)"}],Go=[{value:"1",label:"1×"},{value:"2",label:"2×"},{value:"3",label:"3×"},{value:"4",label:"4×"}],tn=new Set(["png","jpg","webp","pdf"]),Pr='<path d="M2 1.2 L9 5 L2 8.8 Z" fill="currentColor"/>',No='<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"/>',$o=`
30
+ `);o(this,R).firstTimestampBehavior==="offset"&&(t-=r)}if(t<i)throw new Error(`Timestamps must be monotonically increasing (went from ${i} to ${t}).`);if(t<0)throw new Error(`Timestamps must be non-negative (received ${t}).`);return t},yt=new WeakSet,At=function(t,e){o(this,R).streaming&&!o(this,de)&&(k(this,Ei,Tr).call(this),k(this,Ti,kr).call(this));let i=Math.floor(t.timestamp/1e3),r=i-o(this,Ve),n=e&&t.type==="key"&&r>=1e3,s=r>=bo;if((!o(this,vt)||n||s)&&(k(this,Rr,es).call(this,i),r=0),r<0)return;let a=new Uint8Array(4),l=new DataView(a.buffer);if(l.setUint8(0,128|t.trackNumber),l.setInt16(1,r,!1),t.duration===void 0&&!t.additions){l.setUint8(3,+(t.type==="key")<<7);let u={id:163,data:[a,t.data]};o(this,A).writeEBML(u)}else{let u=Math.floor(t.duration/1e3),m={id:160,data:[{id:161,data:[a,t.data]},t.duration!==void 0?{id:155,data:u}:null,t.additions?{id:30113,data:t.additions}:null]};o(this,A).writeEBML(m)}F(this,me,Math.max(o(this,me),i))},be=new WeakSet,He=function(t){return{id:25506,size:4,data:new Uint8Array(t)}},Xe=new WeakSet,Mi=function(t,e){let i=o(this,A).pos;o(this,A).seek(o(this,A).offsets.get(t));let r=6+e.byteLength,n=We-r;if(n<0){let s=e.byteLength+n;e instanceof ArrayBuffer?e=e.slice(0,s):e=e.buffer.slice(0,s),n=0}t=[k(this,be,He).call(this,e),{id:236,size:4,data:new Uint8Array(n)}],o(this,A).writeEBML(t),o(this,A).seek(i)},Rr=new WeakSet,es=function(t){o(this,vt)&&k(this,Pi,Br).call(this),o(this,A)instanceof Re&&o(this,A).target.options.onCluster&&o(this,A).startTrackingWrites(),F(this,vt,{id:524531317,size:o(this,R).streaming?-1:Nn,data:[{id:231,data:t}]}),o(this,A).writeEBML(o(this,vt)),F(this,Ve,t);let e=o(this,A).offsets.get(o(this,vt))-o(this,Zt,ye);o(this,pe).data.push({id:187,data:[{id:179,data:t},o(this,R).video?{id:183,data:[{id:247,data:he},{id:241,data:e}]}:null,o(this,R).audio?{id:183,data:[{id:247,data:Ue},{id:241,data:e}]}:null]})},Pi=new WeakSet,Br=function(){if(!o(this,R).streaming){let t=o(this,A).pos-o(this,A).dataOffsets.get(o(this,vt)),e=o(this,A).pos;o(this,A).seek(o(this,A).offsets.get(o(this,vt))+4),o(this,A).writeEBMLVarInt(t,Nn),o(this,A).seek(e)}if(o(this,A)instanceof Re&&o(this,A).target.options.onCluster){let{data:t,start:e}=o(this,A).getTrackedWrites();o(this,A).target.options.onCluster(t,e,o(this,Ve))}},Ye=new WeakSet,Ii=function(){if(o(this,$e))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")},new TextEncoder;async function So(t,e={}){if(!t.frames.length)throw new Error("[p5.export] encodeGIF: no frames to encode");const i=dn(),r=Math.round(1e3/t.fps),n=e.maxColors??256,s=t.frames.length;for(let a=0;a<s;a++){const l=t.frames[a],u=ln(l,n),m=hn(l,u);i.writeFrame(m,t.width,t.height,{palette:u,delay:r}),e.onProgress&&e.onProgress((a+1)/s),(a&15)===15&&await new Promise(v=>setTimeout(v,0))}return i.finish(),new Blob([i.bytes()],{type:"image/gif"})}function Co(){return typeof window<"u"&&typeof window.VideoEncoder=="function"&&typeof window.VideoFrame=="function"}const Eo={mp4:["avc1.640028","avc1.4d0028","avc1.42001f","av01.0.04M.08"],webm:["vp09.00.10.08","vp8","av01.0.04M.08"]},To={avc1:"avc",av01:"av1",hvc1:"hevc",hev1:"hevc"},ko={vp09:"V_VP9",vp9:"V_VP9",vp8:"V_VP8",av01:"V_AV1"};function Ao(t,e){const i=e.split(".")[0].toLowerCase();return(t==="mp4"?To:ko)[i]||(t==="mp4"?"avc":"V_VP9")}async function Mo(t,{width:e,height:i,fps:r,bitrate:n}){for(const s of Eo[t]||[])for(const a of[{hardwareAcceleration:"prefer-hardware"},{}])try{const l=await VideoEncoder.isConfigSupported({codec:s,width:e,height:i,bitrate:n,framerate:r,...a});if(l&&l.supported)return s}catch{}return null}async function Po(t,e){const i=e.format==="mp4"?"mp4":"webm",r=t.width,n=t.height,s=t.fps,a=e.bitsPerSecond??Math.min(4e7,Math.max(15e5,Math.round(r*n*s*.2))),l=await Mo(i,{width:r,height:n,fps:s,bitrate:a});if(!l)throw new Error(`[p5.export] WebCodecs: no supported ${i.toUpperCase()} codec for ${r}×${n} @ ${s}fps`);const u=i==="mp4"?new yn:new Rn,m=Ao(i,l),v=i==="mp4"?new lo({target:u,video:{codec:m,width:r,height:n,frameRate:s},fastStart:"in-memory"}):new xo({target:u,video:{codec:m,width:r,height:n,frameRate:s}});let p=null;const h=new VideoEncoder({output:(E,W)=>v.addVideoChunk(E,W),error:E=>{p=p||E}}),d={codec:l,width:r,height:n,bitrate:a,framerate:s};l.startsWith("avc1")&&(d.avc={format:"avc"});const c=[{...d,hardwareAcceleration:"prefer-hardware"},{...d}];let w=null;for(const E of c)try{h.configure(E),w=E;break}catch{}if(!w)throw new Error(`[p5.export] could not configure VideoEncoder for ${l}`);const g=1e6/s,y=t.frames.length,M=Math.max(1,Math.round(s*2)),C=16;for(let E=0;E<y;E++){if(p)throw p;for(;h.encodeQueueSize>C;)if(await new Promise(I=>setTimeout(I,0)),p)throw p;const W=new VideoFrame(t.frames[E],{format:"RGBA",codedWidth:r,codedHeight:n,timestamp:Math.round(E*g),duration:Math.round(g)});h.encode(W,{keyFrame:E%M===0}),W.close(),e.onProgress&&e.onProgress((E+1)/y),(E&31)===31&&await new Promise(I=>setTimeout(I,0))}if(await h.flush(),p)throw p;v.finalize();const x=new Blob([u.buffer],{type:i==="mp4"?"video/mp4":"video/webm"});return x.__ext=i,x}const Ri={webm:["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"],mp4:["video/mp4;codecs=avc1","video/mp4;codecs=h264","video/mp4"]};function Io(t){const e=t==="mp4"?[...Ri.mp4,...Ri.webm]:[...Ri.webm,...Ri.mp4];for(const i of e)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}function Ro(t,e){return new Promise((i,r)=>{const n=e.format||"webm",s=Io(n);if(!s)return r(new Error("[p5.export] MediaRecorder fallback: no supported mime"));n==="mp4"&&s.ext!=="mp4"&&console.warn("[p5.export] MP4 unsupported here — falling back to WebM.");const a=document.createElement("canvas");a.width=t.width,a.height=t.height;const l=a.getContext("2d"),u=a.captureStream(t.fps),m={mimeType:s.mime};e.bitsPerSecond&&(m.videoBitsPerSecond=e.bitsPerSecond);const v=new MediaRecorder(u,m),p=[];v.ondataavailable=w=>{w.data&&w.data.size&&p.push(w.data)},v.onerror=w=>r(w.error||new Error("MediaRecorder error")),v.onstop=()=>{u.getTracks().forEach(g=>g.stop());const w=new Blob(p,{type:s.mime});w.__ext=s.ext,i(w)},l.putImageData(new ImageData(t.frames[0],t.width,t.height),0,0),v.start();const h=1e3/t.fps;let d=1;const c=()=>{if(d>=t.frames.length){setTimeout(()=>v.stop(),100);return}l.putImageData(new ImageData(t.frames[d],t.width,t.height),0,0),e.onProgress&&e.onProgress((d+1)/t.frames.length),d++,setTimeout(c,h)};setTimeout(c,h)})}async function Bo(t,e={}){if(!t.frames.length)throw new Error("[p5.export] encodeVideo: no frames to encode");if(Co()){const i=performance.now();try{const r=await Po(t,e),n=performance.now()-i|0;return console.info(`[p5.export] WebCodecs encoded ${t.frames.length} frames in ${n}ms (${t.frames.length/(n/1e3)|0} fps).`),r}catch(r){console.warn("[p5.export] WebCodecs encode failed; falling back to MediaRecorder (real-time, much slower). Cause:",r)}}else console.info("[p5.export] WebCodecs not available in this browser; using MediaRecorder (real-time).");return Ro(t,e)}async function Fo(t,e={}){if(!t||!t.frames.length)throw new Error("[p5.export] encodeAnimatedWebP: buffer has no frames");const{width:i,height:r,fps:n,frames:s}=t,a=No(e.quality??.85),l=Math.max(0,e.loop??0),u=Math.max(1,Math.round(1e3/(n||30)));await Do(i,r);const m=document.createElement("canvas");m.width=i,m.height=r;const v=m.getContext("2d"),p=v.createImageData(i,r),h=[];for(let w=0;w<s.length;w++){p.data.set(s[w]),v.putImageData(p,0,0);const g=await is(m,a),y=new Uint8Array(await g.arrayBuffer());h.push(Uo(y)),e.onProgress&&e.onProgress((w+1)/s.length)}const d=Vo([Fr("VP8X",Wo(i,r)),Fr("ANIM",zo(l)),...h.map(w=>Fr("ANMF",Oo(i,r,u,w)))]),c=new Uint8Array(12+d.length);return Dr(c,0,"RIFF"),rs(c,4,4+d.length),Dr(c,8,"WEBP"),c.set(d,12),new Blob([c],{type:"image/webp"})}async function Do(t,e){const i=document.createElement("canvas");i.width=Math.min(8,t),i.height=Math.min(8,e);const r=await is(i,.9);if(!r||r.type!=="image/webp")throw new Error("[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.")}function is(t,e){return new Promise((i,r)=>{t.toBlob(n=>n?i(n):r(new Error("canvas.toBlob returned null")),"image/webp",e)})}function Uo(t){let e=12;for(;e+8<=t.length;){const i=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),r=Go(t,e+4),n=r+(r&1);if(i==="VP8 "||i==="VP8L")return t.slice(e,e+8+n);e+=8+n}throw new Error("[p5.export] no VP8/VP8L chunk found in encoded WebP frame")}function Wo(t,e){const i=new Uint8Array(10);return i[0]=2,Je(i,4,t-1),Je(i,7,e-1),i}function zo(t){const e=new Uint8Array(6);return Lo(e,4,t),e}function Oo(t,e,i,r){const n=new Uint8Array(16);Je(n,6,t-1),Je(n,9,e-1),Je(n,12,i),n[15]=0;const s=new Uint8Array(n.length+r.length);return s.set(n,0),s.set(r,n.length),s}function Fr(t,e){const i=e.length&1,r=new Uint8Array(8+e.length+i);return Dr(r,0,t),rs(r,4,e.length),r.set(e,8),r}function Vo(t){let e=0;for(const n of t)e+=n.length;const i=new Uint8Array(e);let r=0;for(const n of t)i.set(n,r),r+=n.length;return i}function Dr(t,e,i){for(let r=0;r<i.length;r++)t[e+r]=i.charCodeAt(r)}function Lo(t,e,i){t[e]=i&255,t[e+1]=i>>8&255}function Je(t,e,i){t[e]=i&255,t[e+1]=i>>8&255,t[e+2]=i>>16&255}function rs(t,e,i){t[e]=i&255,t[e+1]=i>>8&255,t[e+2]=i>>16&255,t[e+3]=i>>24&255}function Go(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24>>>0}function No(t){return Math.max(0,Math.min(1,t))}const Bi={webm:["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"],mp4:["video/mp4;codecs=avc1","video/mp4;codecs=h264","video/mp4"]};function $o(t){const e=t==="mp4"?[...Bi.mp4,...Bi.webm]:[...Bi.webm,...Bi.mp4];for(const i of e)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}class jo{constructor(e){const i=$o(e.format||"webm");if(!i)throw new Error("[p5.export] no supported MediaRecorder mime type found");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);const r={mimeType:i.mime};e.bitsPerSecond&&(r.videoBitsPerSecond=e.bitsPerSecond),this.recorder=new MediaRecorder(this.stream,r),this.chunks=[],this.recorder.ondataavailable=n=>{n.data&&n.data.size&&this.chunks.push(n.data)},this.filename=e.filename,this.duration=e.duration,this._mime=i.mime,this._stopPromise=null}start(){this.recorder.start(),this.duration&&setTimeout(()=>this.stop(),this.duration*1e3)}stop(){return this._stopPromise?this._stopPromise:(this._stopPromise=new Promise(e=>{this.recorder.onstop=()=>{const i=new Blob(this.chunks,{type:this._mime}),r=this.filename?_t(this.filename,this.ext):bt(this.ext);rt(i,r),this.stream.getTracks().forEach(n=>n.stop()),e(i)},this.recorder.state!=="inactive"&&this.recorder.stop()}),this._stopPromise)}get state(){return this.recorder.state}}function qo(t,e,i){if(e.recordVideo=function(r={}){const n=xt(this);if(!n)throw new Error("[p5.export] recordVideo: no canvas found");if(this._p5ExportVideo&&this._p5ExportVideo.state==="recording")throw new Error("[p5.export] a video recording is already in progress");const s=new jo({canvas:n,...r});return s.start(),this._p5ExportVideo=s,s},e.recordWebM=function(r={}){return e.recordVideo.call(this,{...r,format:"webm"})},e.recordMP4=function(r={}){return e.recordVideo.call(this,{...r,format:"mp4"})},e.stopVideo=function(){const r=this._p5ExportVideo;return r?(this._p5ExportVideo=null,r.stop()):null},e.createVideoBuffer=function(r={}){const n=xt(this);if(!n)throw new Error("[p5.export] createVideoBuffer: no canvas found");if(this._p5ExportBuffer&&this._p5ExportBuffer.recording)throw new Error("[p5.export] a video buffer is already recording");const s=this,a=r.scale,l=typeof s.pixelDensity=="function"?s.pixelDensity():1,u=a&&a>0&&a!==l;u&&(s.pixelDensity(a),typeof s.redraw=="function"&&s.redraw());const m=new ea({canvas:n,...r}),v=m.stop.bind(m);let p=!u;return m.stop=function(){v(),p||(p=!0,s.pixelDensity(l),typeof s.redraw=="function"&&s.redraw())},m.start(),this._p5ExportBuffer=m,m},e.stopVideoBuffer=function(){const r=this._p5ExportBuffer;return r&&r.stop(),r||null},e.exportVideoBuffer=async function(r,n={}){if(!r||!r.frames.length)throw new Error("[p5.export] exportVideoBuffer: buffer has no frames");const s=(n.format||"webm").toLowerCase();let a,l;if(s==="gif")a=await So(r,n),l="gif";else if(s==="webp")a=await Fo(r,n),l="webp";else if(s==="webm"||s==="mp4")a=await Bo(r,{...n,format:s}),l=a.__ext||(s==="mp4"?"mp4":"webm");else throw new Error(`[p5.export] unsupported video format: ${s}`);const u=n.filename?_t(n.filename,l):bt(l);return rt(a,u),a},i&&typeof i=="object"){const r=i.postdraw;i.postdraw=function(){typeof r=="function"&&r.call(this);const n=this._p5ExportBuffer;n&&n.recording&&n.tick()}}}function ns(t,e){return e&&Array.isArray(e.vertices)&&Array.isArray(e.faces)?e:typeof e=="function"&&typeof t.buildGeometry=="function"?t.buildGeometry(e):null}function Ho(t,e){e.saveSTL=function(i,r,n={}){const s=ns(this,i);if(!s||typeof s.saveStl!="function"){const l=Fi(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.";throw new Error("[p5.export] saveSTL: no exportable geometry. "+l)}const a=r||"sketch.stl";s.saveStl(a,{binary:!!n.binary})},e.saveOBJ=function(i,r){const n=ns(this,i);if(!n||typeof n.saveObj!="function"){const a=Fi(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.";throw new Error("[p5.export] saveOBJ: no exportable geometry. "+a)}const s=r||"sketch.obj";n.saveObj(s)}}const Xo=".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-check{display:flex;align-items:center;gap:6px;cursor:pointer}.p5export-check input{margin:0;cursor:pointer}.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}";let ss=!1;function Yo(){if(ss||typeof document>"u")return;ss=!0;const t=document.createElement("style");t.setAttribute("data-p5-export",""),t.textContent=Xo,document.head.appendChild(t)}const as=[{value:"png",label:"PNG (image)"},{value:"jpg",label:"JPG (image)"},{value:"webp",label:"WebP (image)"},{value:"svg",label:"SVG (vector)"},{value:"pdf",label:"PDF (vector)"}],Jo=[{value:"stl",label:"STL (3D)"},{value:"obj",label:"OBJ (3D)"}],Ko=[{value:"webm",label:"WebM (video)"},{value:"mp4",label:"MP4 (video)"},{value:"webp",label:"WebP (animation)"},{value:"gif",label:"GIF (animation)"}],Zo=[{value:"1",label:"1×"},{value:"2",label:"2×"},{value:"3",label:"3×"},{value:"4",label:"4×"}],os=new Set(["png","jpg","webp","pdf"]),Ur='<path d="M2 1.2 L9 5 L2 8.8 Z" fill="currentColor"/>',Qo='<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"/>',tl=`
30
31
  <div class="p5export-panel">
31
32
  <div class="p5export-header" data-el="header">
32
33
  <span class="p5export-title" data-el="title">p5.export</span>
@@ -49,6 +50,12 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
49
50
  <label>Scale</label>
50
51
  <select class="p5export-select" data-el="imageScale"></select>
51
52
  </div>
53
+ <div class="p5export-row" data-el="svgOutlineRow" hidden>
54
+ <label>Text</label>
55
+ <label class="p5export-check">
56
+ <input type="checkbox" data-el="svgOutline" checked> Outline (vector)
57
+ </label>
58
+ </div>
52
59
  <div class="p5export-row">
53
60
  <label>Name</label>
54
61
  <input class="p5export-input" type="text" placeholder="filename" data-el="imageFilename">
@@ -75,7 +82,7 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
75
82
  <canvas class="p5export-preview-canvas" data-el="previewCanvas"></canvas>
76
83
  <div class="p5export-preview-controls">
77
84
  <button class="p5export-play" data-action="togglePreview" title="Play / pause">
78
- <svg viewBox="0 0 10 10" data-el="playIcon">${Pr}</svg>
85
+ <svg viewBox="0 0 10 10" data-el="playIcon">${Ur}</svg>
79
86
  </button>
80
87
  <input class="p5export-timeline" type="range" min="0" max="0" step="1" value="0" data-el="timeline">
81
88
  <span class="p5export-time" data-el="timeLabel">0:00</span>
@@ -86,5 +93,5 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
86
93
  <div class="p5export-status" data-el="recordedStatus" hidden></div>
87
94
  </div>
88
95
  </div>
89
- </div>`.trim();class jo{constructor(e,i={}){Vo(),this.p=e,this.opts=i,this.tab="image",this.videoState="idle",this.buffer=null,this._statusTimer=null,this.el=document.createRange().createContextualFragment($o).firstElementChild;for(const r of this.el.querySelectorAll("[data-el]"))this[r.dataset.el]=r;for(const r of this.el.querySelectorAll("[data-action]"))r.addEventListener("click",()=>{const s=this[`_${r.dataset.action}`];typeof s=="function"&&s.call(this)});for(const r of this.el.querySelectorAll("[data-tab]"))r.addEventListener("click",()=>this._switchTab(r.dataset.tab));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()}_populateOptions(){const e=Mi(this.p)?[...Qs,...Lo]:Qs;this.imageFormat.innerHTML=Rr(e),this.imageScale.innerHTML=Rr(Go),this.videoFormat.innerHTML=Rr(Oo),this.opts.filename&&(this.imageFilename.value=this.opts.filename,this.videoFilename.value=this.opts.filename)}_wireExtras(){this.imageFormat.addEventListener("change",()=>this._refreshImageScaleEnabled()),this._refreshImageScaleEnabled(),this.timeline.addEventListener("input",()=>{this._pausePreview(),this._previewFrame=Number(this.timeline.value),this._renderPreviewFrame()})}_toggleCollapsed(){this.el.classList.toggle("is-collapsed")}_switchTab(e){this.tab=e;for(const i of this.el.querySelectorAll("[data-tab]"))i.classList.toggle("is-active",i.dataset.tab===e);for(const i of this.el.querySelectorAll("[data-view]"))i.toggleAttribute("hidden",i.dataset.view!==e)}_refreshImageScaleEnabled(){const e=tn.has(this.imageFormat.value);this.imageScale.disabled=!e,this.imageScaleRow.style.opacity=e?"":"0.45"}async _saveImage(){const e=this.imageFormat.value,i=this.imageFilename.value||void 0,r=Number(this.imageScale.value)||1,s=tn.has(e)?{scale:r}:void 0,n=`${e.toUpperCase()}${s&&r>1?` @ ${r}×`:""}`;this._setStatus(this.imageStatus,`Saving ${n}…`);try{if(e==="png")await this.p.savePNG(i,s);else if(e==="jpg")await this.p.saveJPG(i,s);else if(e==="webp")await this.p.saveWebP(i,s);else if(e==="svg")this.p.saveSVG(i);else if(e==="pdf")await this.p.savePDF(i,s);else if(e==="stl"||e==="obj"){this._setStatus(this.imageStatus,`${e.toUpperCase()} needs a p5.Geometry — call saveSTL(myGeometry) from your sketch.`,"error");return}this._setStatus(this.imageStatus,`Saved ${n}.`,"",2e3)}catch(a){console.error(a),this._setStatus(this.imageStatus,`Error: ${a.message}`,"error")}}_videoPrimary(){if(this.videoState==="idle")return this._startRecording();if(this.videoState==="recording")return this._stopRecording();if(this.videoState==="recorded")return this._export(this.videoFormat.value)}_startRecording(){const e=Number(this.videoDuration.value)||void 0;try{this.buffer=this.p.createVideoBuffer({duration:e,fps:30,scale:1})}catch(r){console.error(r),this._setStatus(this.recordedStatus,`Error: ${r.message}`,"error");return}this.videoState="recording",this._updateVideoState();const i=performance.now();this._statusTimer=setInterval(()=>{const r=(performance.now()-i)/1e3,s=e?` / ${e.toFixed(1)}s`:"";this._setStatus(this.recordedStatus,`Recording ${r.toFixed(1)}s${s} · ${this.buffer.framesRecorded} frames`),this.buffer.recording||this._finishRecording()},100)}_stopRecording(){this.buffer&&this.buffer.stop(),this._finishRecording()}_finishRecording(){clearInterval(this._statusTimer),this._statusTimer=null,this.buffer&&(this.videoState="recorded",this._setStatus(this.recordedStatus,""),this._initPreview(),this._updateVideoState())}async _export(e){if(!this.buffer)return;const i=this.videoFilename.value||void 0,r=this.videoState;this.videoState="encoding",this._updateVideoState(),this._setStatus(this.recordedStatus,`Encoding ${e.toUpperCase()}…`);try{await this.p.exportVideoBuffer(this.buffer,{format:e,filename:i,onProgress:s=>this._setStatus(this.recordedStatus,`Encoding ${e.toUpperCase()}… ${Math.round(s*100)}%`)}),this._setStatus(this.recordedStatus,`Saved ${e.toUpperCase()}.`,"",2e3)}catch(s){console.error(s),this._setStatus(this.recordedStatus,`Error: ${s.message}`,"error")}finally{this.videoState=r,this._updateVideoState()}}_resetVideo(){this._pausePreview(),this.buffer&&this.buffer.clear(),this.buffer=null,this._setStatus(this.recordedStatus,""),this.videoState="idle",this._updateVideoState()}_updateVideoState(){const e=this.videoState,i=e==="recorded"||e==="encoding",r=e==="recording";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";const s=e==="encoding";this.videoPrimaryBtn.disabled=s,this.rerecordBtn.disabled=s}_initPreview(){if(!this.buffer||!this.buffer.frames.length)return;const e=320,i=this.buffer.width,r=this.buffer.height,s=Math.min(1,e/Math.max(i,r));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=Pr,this._renderPreviewFrame()}_renderPreviewFrame(){if(!this.buffer||!this._previewCtx)return;const e=Math.max(0,Math.min(this.buffer.frames.length-1,this._previewFrame)),i=this.buffer.frames[e];if(!i)return;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(this._previewSrc,0,0,this._previewSrc.width,this._previewSrc.height,0,0,this.previewCanvas.width,this.previewCanvas.height),this.timeline.value=String(e);const r=this.buffer.fps||30;this.timeLabel.textContent=`${(e/r).toFixed(1)}s`}_togglePreview(){this.buffer&&(this._previewPlaying?this._pausePreview():this._playPreview())}_playPreview(){if(!this.buffer||!this.buffer.frames.length)return;this._previewPlaying=!0,this.playIcon.innerHTML=No;const i=1e3/(this.buffer.fps||30);let r=performance.now();const s=n=>{if(!this._previewPlaying)return;const a=n-r;a>=i&&(r=n-a%i,this._previewFrame++,this._previewFrame>=this.buffer.frames.length&&(this._previewFrame=0),this._renderPreviewFrame()),this._previewRaf=requestAnimationFrame(s)};this._previewRaf=requestAnimationFrame(s)}_pausePreview(){this._previewPlaying&&(this._previewPlaying=!1,this._previewRaf&&cancelAnimationFrame(this._previewRaf),this._previewRaf=null,this.playIcon.innerHTML=Pr)}_setStatus(e,i,r="",s=0){e.textContent=i||"",e.toggleAttribute("hidden",!i),e.classList.toggle("is-error",r==="error"),s&&i&&setTimeout(()=>{e.textContent===i&&this._setStatus(e,"")},s)}_wireDrag(){let e=0,i=0,r=0,s=0,n=!1;const a=u=>{n&&(this.el.style.left=r+u.clientX-e+"px",this.el.style.top=s+u.clientY-i+"px")},l=()=>{n=!1,document.removeEventListener("mousemove",a)};this.header.addEventListener("mousedown",u=>{if(u.target.closest(".p5export-toggle"))return;n=!0,e=u.clientX,i=u.clientY;const g=this.el.getBoundingClientRect();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})})}destroy(){clearInterval(this._statusTimer),this._pausePreview(),this.buffer&&this.buffer.clear(),this.el.remove()}}function Rr(t){return t.map(e=>`<option value="${e.value}">${e.label}</option>`).join("")}function qo(t,e,i){if(e.createExportGUI=function(r={}){if(this._p5ExportPanel)return Object.assign(this._p5ExportPanel.opts,r),this._p5ExportPanel;const s=new jo(this,r);return this._p5ExportPanel=s,s},e.removeExportGUI=function(){this._p5ExportPanel&&(this._p5ExportPanel.destroy(),this._p5ExportPanel=null)},i&&typeof i=="object"){const r=i.postsetup;i.postsetup=function(){typeof r=="function"&&r.call(this),(typeof window<"u"&&window.p5ExportConfig||{}).autoGUI!==!1&&(this._p5ExportPanel||this.createExportGUI())}}}function He(t,e,i){an(t,e),Tn(t,e,i),Mn(t,e),$n(t,e,i),Do(t,e,i),Wo(t,e),qo(t,e,i),Ho(t),e.downloadBlob=function(r,s){return rt(r,s)}}function Ho(t){const e=t&&t.Graphics;if(!e||!e.prototype||e.prototype.__p5ExportGraphicsRandomPatched)return;const i=t.prototype;for(const r of["random","randomSeed","noise","noiseSeed","randomGaussian"])typeof e.prototype[r]!="function"&&typeof i[r]=="function"&&(e.prototype[r]=function(...s){const n=typeof window<"u"&&window.p5&&window.p5.instance||this;return i[r].apply(n,s)});e.prototype.__p5ExportGraphicsRandomPatched=!0}function en(t){if(!t||!t.prototype)return!1;if(t.prototype.__p5ExportInstalled)return!0;t.prototype.__p5ExportInstalled=!0;const e={};He(t,t.prototype,e);const i=(r,s)=>typeof s=="function"&&typeof t.prototype.registerMethod=="function"&&t.prototype.registerMethod(r,s);return i("beforeSetup",e.presetup),i("afterSetup",e.postsetup),i("pre",e.predraw),i("post",e.postdraw),Xo(t),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}function Xo(t){if(typeof window>"u")return;const e=Date.now(),i=setInterval(()=>{if((window.p5ExportConfig||{}).autoGUI===!1){clearInterval(i);return}const s=t&&t.instance;if(s&&s._p5ExportPanel){clearInterval(i);return}if(s&&s._setupDone&&typeof s.createExportGUI=="function"){s.createExportGUI(),clearInterval(i);return}Date.now()-e>3e4&&clearInterval(i)},150)}function rn(t){if(!t)throw new Error("[p5.export] register() called with no p5 constructor");if(typeof t.registerAddon=="function"){t.registerAddon(He);return}if(!en(t))throw new Error("[p5.export] Could not register — no registerAddon and no prototype.registerMethod.")}function Br(){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(He),window.p5.__p5ExportAutoRegistered=!0,!0):en(window.p5)}function Yo(){typeof window>"u"||window.__p5ExportModuleTried||(window.__p5ExportModuleTried=!0,import("p5").then(t=>{const e=t&&(t.default||t.p5)||t;!e||typeof e!="function"&&!e.prototype||e.__p5ExportAutoRegistered||e.prototype&&e.prototype.__p5ExportInstalled||(rn(e),e.__p5ExportAutoRegistered=!0)}).catch(()=>{}))}if(typeof window<"u"&&!Br()){const t=setInterval(()=>{Br()&&clearInterval(t)},10);setTimeout(()=>clearInterval(t),5e3),window.addEventListener("p5Ready",Br,{once:!0}),Yo()}kt.default=He,kt.p5ExportAddon=He,kt.register=rn,Object.defineProperties(kt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
96
+ </div>`.trim();class el{constructor(e,i={}){Yo(),this.p=e,this.opts=i,this.tab="image",this.videoState="idle",this.buffer=null,this._statusTimer=null,this.el=document.createRange().createContextualFragment(tl).firstElementChild;for(const r of this.el.querySelectorAll("[data-el]"))this[r.dataset.el]=r;for(const r of this.el.querySelectorAll("[data-action]"))r.addEventListener("click",()=>{const n=this[`_${r.dataset.action}`];typeof n=="function"&&n.call(this)});for(const r of this.el.querySelectorAll("[data-tab]"))r.addEventListener("click",()=>this._switchTab(r.dataset.tab));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()}_populateOptions(){const e=Fi(this.p)?[...as,...Jo]:as;this.imageFormat.innerHTML=Wr(e),this.imageScale.innerHTML=Wr(Zo),this.videoFormat.innerHTML=Wr(Ko),this.opts.filename&&(this.imageFilename.value=this.opts.filename,this.videoFilename.value=this.opts.filename)}_wireExtras(){this.imageFormat.addEventListener("change",()=>this._refreshImageScaleEnabled()),this._refreshImageScaleEnabled(),this.timeline.addEventListener("input",()=>{this._pausePreview(),this._previewFrame=Number(this.timeline.value),this._renderPreviewFrame()})}_toggleCollapsed(){this.el.classList.toggle("is-collapsed")}_switchTab(e){this.tab=e;for(const i of this.el.querySelectorAll("[data-tab]"))i.classList.toggle("is-active",i.dataset.tab===e);for(const i of this.el.querySelectorAll("[data-view]"))i.toggleAttribute("hidden",i.dataset.view!==e)}_refreshImageScaleEnabled(){const e=this.imageFormat.value,i=os.has(e);this.imageScale.disabled=!i,this.imageScaleRow.style.opacity=i?"":"0.45",this.svgOutlineRow&&this.svgOutlineRow.toggleAttribute("hidden",e!=="svg")}async _saveImage(){const e=this.imageFormat.value,i=this.imageFilename.value||void 0,r=Number(this.imageScale.value)||1,n=os.has(e)?{scale:r}:void 0,s=`${e.toUpperCase()}${n&&r>1?` @ ${r}×`:""}`;this._setStatus(this.imageStatus,`Saving ${s}…`);try{if(e==="png")await this.p.savePNG(i,n);else if(e==="jpg")await this.p.saveJPG(i,n);else if(e==="webp")await this.p.saveWebP(i,n);else if(e==="svg")this.p.saveSVG(i,{outlineText:!!(this.svgOutline&&this.svgOutline.checked)});else if(e==="pdf")await this.p.savePDF(i,n);else if(e==="stl"||e==="obj"){this._setStatus(this.imageStatus,`${e.toUpperCase()} needs a p5.Geometry — call saveSTL(myGeometry) from your sketch.`,"error");return}this._setStatus(this.imageStatus,`Saved ${s}.`,"",2e3)}catch(a){console.error(a),this._setStatus(this.imageStatus,`Error: ${a.message}`,"error")}}_videoPrimary(){if(this.videoState==="idle")return this._startRecording();if(this.videoState==="recording")return this._stopRecording();if(this.videoState==="recorded")return this._export(this.videoFormat.value)}_startRecording(){const e=Number(this.videoDuration.value)||void 0;try{this.buffer=this.p.createVideoBuffer({duration:e,fps:30,scale:1})}catch(r){console.error(r),this._setStatus(this.recordedStatus,`Error: ${r.message}`,"error");return}this.videoState="recording",this._updateVideoState();const i=performance.now();this._statusTimer=setInterval(()=>{const r=(performance.now()-i)/1e3,n=e?` / ${e.toFixed(1)}s`:"";this._setStatus(this.recordedStatus,`Recording ${r.toFixed(1)}s${n} · ${this.buffer.framesRecorded} frames`),this.buffer.recording||this._finishRecording()},100)}_stopRecording(){this.buffer&&this.buffer.stop(),this._finishRecording()}_finishRecording(){clearInterval(this._statusTimer),this._statusTimer=null,this.buffer&&(this.videoState="recorded",this._setStatus(this.recordedStatus,""),this._initPreview(),this._updateVideoState())}async _export(e){if(!this.buffer)return;const i=this.videoFilename.value||void 0,r=this.videoState;this.videoState="encoding",this._updateVideoState(),this._setStatus(this.recordedStatus,`Encoding ${e.toUpperCase()}…`);try{await this.p.exportVideoBuffer(this.buffer,{format:e,filename:i,onProgress:n=>this._setStatus(this.recordedStatus,`Encoding ${e.toUpperCase()}… ${Math.round(n*100)}%`)}),this._setStatus(this.recordedStatus,`Saved ${e.toUpperCase()}.`,"",2e3)}catch(n){console.error(n),this._setStatus(this.recordedStatus,`Error: ${n.message}`,"error")}finally{this.videoState=r,this._updateVideoState()}}_resetVideo(){this._pausePreview(),this.buffer&&this.buffer.clear(),this.buffer=null,this._setStatus(this.recordedStatus,""),this.videoState="idle",this._updateVideoState()}_updateVideoState(){const e=this.videoState,i=e==="recorded"||e==="encoding",r=e==="recording";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";const n=e==="encoding";this.videoPrimaryBtn.disabled=n,this.rerecordBtn.disabled=n}_initPreview(){if(!this.buffer||!this.buffer.frames.length)return;const e=320,i=this.buffer.width,r=this.buffer.height,n=Math.min(1,e/Math.max(i,r));this.previewCanvas.width=Math.max(1,Math.round(i*n)),this.previewCanvas.height=Math.max(1,Math.round(r*n)),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=Ur,this._renderPreviewFrame()}_renderPreviewFrame(){if(!this.buffer||!this._previewCtx)return;const e=Math.max(0,Math.min(this.buffer.frames.length-1,this._previewFrame)),i=this.buffer.frames[e];if(!i)return;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(this._previewSrc,0,0,this._previewSrc.width,this._previewSrc.height,0,0,this.previewCanvas.width,this.previewCanvas.height),this.timeline.value=String(e);const r=this.buffer.fps||30;this.timeLabel.textContent=`${(e/r).toFixed(1)}s`}_togglePreview(){this.buffer&&(this._previewPlaying?this._pausePreview():this._playPreview())}_playPreview(){if(!this.buffer||!this.buffer.frames.length)return;this._previewPlaying=!0,this.playIcon.innerHTML=Qo;const i=1e3/(this.buffer.fps||30);let r=performance.now();const n=s=>{if(!this._previewPlaying)return;const a=s-r;a>=i&&(r=s-a%i,this._previewFrame++,this._previewFrame>=this.buffer.frames.length&&(this._previewFrame=0),this._renderPreviewFrame()),this._previewRaf=requestAnimationFrame(n)};this._previewRaf=requestAnimationFrame(n)}_pausePreview(){this._previewPlaying&&(this._previewPlaying=!1,this._previewRaf&&cancelAnimationFrame(this._previewRaf),this._previewRaf=null,this.playIcon.innerHTML=Ur)}_setStatus(e,i,r="",n=0){e.textContent=i||"",e.toggleAttribute("hidden",!i),e.classList.toggle("is-error",r==="error"),n&&i&&setTimeout(()=>{e.textContent===i&&this._setStatus(e,"")},n)}_wireDrag(){let e=0,i=0,r=0,n=0,s=!1;const a=u=>{s&&(this.el.style.left=r+u.clientX-e+"px",this.el.style.top=n+u.clientY-i+"px")},l=()=>{s=!1,document.removeEventListener("mousemove",a)};this.header.addEventListener("mousedown",u=>{if(u.target.closest(".p5export-toggle"))return;s=!0,e=u.clientX,i=u.clientY;const m=this.el.getBoundingClientRect();r=m.left,n=m.top,this.el.style.left=r+"px",this.el.style.top=n+"px",this.el.style.right="auto",document.addEventListener("mousemove",a),document.addEventListener("mouseup",l,{once:!0})})}destroy(){clearInterval(this._statusTimer),this._pausePreview(),this.buffer&&this.buffer.clear(),this.el.remove()}}function Wr(t){return t.map(e=>`<option value="${e.value}">${e.label}</option>`).join("")}function il(t,e,i){if(e.createExportGUI=function(r={}){if(this._p5ExportPanel)return Object.assign(this._p5ExportPanel.opts,r),this._p5ExportPanel;const n=new el(this,r);return this._p5ExportPanel=n,n},e.removeExportGUI=function(){this._p5ExportPanel&&(this._p5ExportPanel.destroy(),this._p5ExportPanel=null)},i&&typeof i=="object"){const r=i.postsetup;i.postsetup=function(){typeof r=="function"&&r.call(this),(typeof window<"u"&&window.p5ExportConfig||{}).autoGUI!==!1&&(this._p5ExportPanel||this.createExportGUI())}}}function Ke(t,e,i){fs(t,e),Us(t,e,i),Os(t,e),ta(t,e,i),qo(t,e,i),Ho(t,e),il(t,e,i),rl(t),e.downloadBlob=function(r,n){return rt(r,n)}}function rl(t){const e=t&&t.Graphics;if(!e||!e.prototype||e.prototype.__p5ExportGraphicsRandomPatched)return;const i=t.prototype;for(const r of["random","randomSeed","noise","noiseSeed","randomGaussian"])typeof e.prototype[r]!="function"&&typeof i[r]=="function"&&(e.prototype[r]=function(...n){const s=typeof window<"u"&&window.p5&&window.p5.instance||this;return i[r].apply(s,n)});e.prototype.__p5ExportGraphicsRandomPatched=!0}function ls(t){if(!t||!t.prototype)return!1;if(t.prototype.__p5ExportInstalled)return!0;t.prototype.__p5ExportInstalled=!0;const e={};Ke(t,t.prototype,e);const i=(r,n)=>typeof n=="function"&&typeof t.prototype.registerMethod=="function"&&t.prototype.registerMethod(r,n);return i("beforeSetup",e.presetup),i("afterSetup",e.postsetup),i("pre",e.predraw),i("post",e.postdraw),nl(t),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}function nl(t){if(typeof window>"u")return;const e=Date.now(),i=setInterval(()=>{if((window.p5ExportConfig||{}).autoGUI===!1){clearInterval(i);return}const n=t&&t.instance;if(n&&n._p5ExportPanel){clearInterval(i);return}if(n&&n._setupDone&&typeof n.createExportGUI=="function"){n.createExportGUI(),clearInterval(i);return}Date.now()-e>3e4&&clearInterval(i)},150)}function hs(t){if(!t)throw new Error("[p5.export] register() called with no p5 constructor");if(typeof t.registerAddon=="function"){t.registerAddon(Ke);return}if(!ls(t))throw new Error("[p5.export] Could not register — no registerAddon and no prototype.registerMethod.")}function zr(){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(Ke),window.p5.__p5ExportAutoRegistered=!0,!0):ls(window.p5)}function sl(){typeof window>"u"||window.__p5ExportModuleTried||(window.__p5ExportModuleTried=!0,import("p5").then(t=>{const e=t&&(t.default||t.p5)||t;!e||typeof e!="function"&&!e.prototype||e.__p5ExportAutoRegistered||e.prototype&&e.prototype.__p5ExportInstalled||(hs(e),e.__p5ExportAutoRegistered=!0)}).catch(()=>{}))}if(typeof window<"u"&&!zr()){const t=setInterval(()=>{zr()&&clearInterval(t)},10);setTimeout(()=>clearInterval(t),5e3),window.addEventListener("p5Ready",zr,{once:!0}),sl()}Mt.default=Ke,Mt.p5ExportAddon=Ke,Mt.register=hs,Object.defineProperties(Mt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
90
97
  //# sourceMappingURL=p5.export.min.js.map