@munusshih/p5.export 0.1.0-beta.10 → 0.1.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/dist/p5.export.js +1003 -988
- package/dist/p5.export.js.map +1 -1
- package/dist/p5.export.min.js +12 -8
- package/dist/p5.export.min.js.map +1 -1
- package/package.json +2 -1
package/dist/p5.export.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! @munusshih/p5.export v0.1.0-beta.
|
|
2
|
-
(function(
|
|
1
|
+
/*! @munusshih/p5.export v0.1.0-beta.11 | Created by Munus Shih | MIT License | https://github.com/munusshih/p5.export */
|
|
2
|
+
(function(Me,re){typeof exports=="object"&&typeof module<"u"?re(exports):typeof define=="function"&&define.amd?define(["exports"],re):(Me=typeof globalThis<"u"?globalThis:Me||self,re(Me.p5Export={}))})(this,function(Me){"use strict";function re(e,t){const i=URL.createObjectURL(e),r=document.createElement("a");r.href=i,r.download=t,r.style.display="none",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),0)}function be(e,t="sketch"){const i=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");return`${t}-${i}.${e}`}function _e(e,t){return e.toLowerCase().endsWith("."+t.toLowerCase())?e:`${e}.${t}`}function xe(e){return e?e instanceof HTMLCanvasElement?e:e.canvas instanceof HTMLCanvasElement?e.canvas:e.elt instanceof HTMLCanvasElement?e.elt:Vr():Vr()}function Vr(){const e=document.querySelector("canvas.p5Canvas");return e||document.querySelector("canvas")}function Di(e){if(!e)return!1;const t=e._renderer;if(!t)return!1;const i=t.drawingContext;return!!(i&&typeof i.fillRect!="function"||t.GL)}const cs={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};async function Lr(e,t,i,r){const n=e&&e._p5ExportSVGRecorder;if(!n||!n.ops||n.ops.length===0)return null;const s=xe(e);if(!s)return null;const a=typeof e.pixelDensity=="function"?e.pixelDensity():1,o=Math.max(1,Math.round(s.width/a)),p=Math.max(1,Math.round(s.height/a)),w=o*t,v=p*t,m=document.createElement("canvas");m.width=w,m.height=v;const l=m.getContext("2d");if(!l)return null;const d=t/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 S=y[2];l.setTransform(S[0]*d,S[1]*d,S[2]*d,S[3]*d,S[4]*d,S[5]*d)}else l[M](...y[2])}else l[y[1]]=y[2]}catch{}}const u=cs[i]||"image/png";return new Promise((g,y)=>{m.toBlob(M=>M?g(M):y(new Error("[p5.export] toBlob returned null")),u,r)})}async function Gr(e,t,i){if(!t||t<=1)return i();const r=typeof e.pixelDensity=="function"?e.pixelDensity():1;if(t<=r)return i();const n=typeof e.isLooping=="function"?e.isLooping():!0;n&&typeof e.noLoop=="function"&&e.noLoop();try{return e.pixelDensity(t),typeof e.redraw=="function"&&await e.redraw(),await new Promise(s=>requestAnimationFrame(s)),await i()}finally{e.pixelDensity(r),typeof e.redraw=="function"&&await e.redraw(),n&&typeof e.loop=="function"&&e.loop()}}const ps={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"};function Ui(e,t,i){const r=xe(e);if(!r)return Promise.reject(new Error("[p5.export] no canvas found"));const n=ps[t];return n?new Promise((s,a)=>{r.toBlob(o=>o?s(o):a(new Error("[p5.export] toBlob returned null")),n,i)}):Promise.reject(new Error(`[p5.export] unknown image format: ${t}`))}async function ei(e,t,i,r){if(!t||t<=1)return Ui(e,i,r);const n=typeof e.pixelDensity=="function"?e.pixelDensity():1;if(t<=n)return Ui(e,i,r);const s=await Lr(e,t,i,r);return s||Gr(e,t,()=>Ui(e,i,r))}function fs(e,t){t.savePNG=async function(i,r={}){const n=await ei(this,r.scale,"png");return re(n,i?_e(i,"png"):be("png")),n},t.saveJPG=async function(i,r={}){const n=r.quality??.92,s=await ei(this,r.scale,"jpg",n);return re(s,i?_e(i,"jpg"):be("jpg")),s},t.saveJPEG=t.saveJPG,t.saveWebP=async function(i,r={}){const n=r.quality??.92,s=await ei(this,r.scale,"webp",n);return re(s,i?_e(i,"webp"):be("webp")),s},t.saveImage=async function(i,r,n={}){i=(i||"png").toLowerCase(),i==="jpeg"&&(i="jpg");const s=await ei(this,n.scale,i,n.quality);return re(s,r?_e(r,i):be(i)),s}}function us(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Nr={exports:{}};/*!!
|
|
3
3
|
* Canvas 2 Svg v1.0.15
|
|
4
4
|
* A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document.
|
|
5
5
|
*
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* Kerry Liu
|
|
11
11
|
*
|
|
12
12
|
* Copyright (c) 2014 Gliffy Inc.
|
|
13
|
-
*/(function(t){(function(){var e,i,r,n,s;function a(l,d){var c=Object.keys(d),m;for(m=0;m<c.length;m++)l=l.replace(new RegExp("\\{"+c[m]+"\\}","gi"),d[c[m]]);return l}function o(l){var d,c,m;if(!l)throw new Error("cannot create a random attribute name for an undefined object");d="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",c="";do for(c="",m=0;m<12;m++)c+=d[Math.floor(Math.random()*d.length)];while(l[c]);return c}function f(l,d){var c,m,w={},y;for(l=l.split(","),d=d||10,c=0;c<l.length;c+=2)m="&"+l[c+1]+";",y=parseInt(l[c],d),w[m]="&#"+y+";";return w["\\xa0"]=" ",w}function g(l){var d={left:"start",right:"end",center:"middle",start:"start",end:"end"};return d[l]||d.start}function v(l){var d={alphabetic:"alphabetic",hanging:"hanging",top:"text-before-edge",bottom:"text-after-edge",middle:"central"};return d[l]||d.alphabetic}s=f("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(l,d){this.__root=l,this.__ctx=d},r.prototype.addColorStop=function(l,d){var c=this.__ctx.__createElement("stop"),m,w;c.setAttribute("offset",l),d.indexOf("rgba")!==-1?(m=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,w=m.exec(d),c.setAttribute("stop-color",a("rgb({r},{g},{b})",{r:w[1],g:w[2],b:w[3]})),c.setAttribute("stop-opacity",w[4])):c.setAttribute("stop-color",d),this.__root.appendChild(c)},n=function(l,d){this.__root=l,this.__ctx=d},i=function(l){var d={width:500,height:500,enableMirroring:!1},c;if(arguments.length>1?(c=d,c.width=arguments[0],c.height=arguments[1]):l?c=l: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(l,d,c){typeof d>"u"&&(d={});var m=this.__document.createElementNS("http://www.w3.org/2000/svg",l),w=Object.keys(d),y,M;for(c&&(m.setAttribute("fill","none"),m.setAttribute("stroke","none")),y=0;y<w.length;y++)M=w[y],m.setAttribute(M,d[M]);return m},i.prototype.__setDefaultStyles=function(){var l=Object.keys(e),d,c;for(d=0;d<l.length;d++)c=l[d],this[c]=e[c].canvas},i.prototype.__applyStyleState=function(l){var d=Object.keys(l),c,m;for(c=0;c<d.length;c++)m=d[c],this[m]=l[m]},i.prototype.__getStyleState=function(){var l,d={},c=Object.keys(e),m;for(l=0;l<c.length;l++)m=c[l],d[m]=this[m];return d},i.prototype.__applyStyleToCurrentElement=function(l){var d=Object.keys(e),c,m,w,y,M,S;for(c=0;c<d.length;c++)if(m=e[d[c]],w=this[d[c]],m.apply)if(m.apply.indexOf("fill")!==-1&&w instanceof n){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(l)!==-1&&m.svg!==w&&((m.svgAttr==="stroke"||m.svgAttr==="fill")&&w.indexOf("rgba")!==-1?(M=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,S=M.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(l){return l=l||this.__currentElement,l.nodeName==="g"||l.nodeName==="svg"?l:this.__closestGroupOrSvg(l.parentNode)},i.prototype.getSerializedSvg=function(l){var d=new XMLSerializer().serializeToString(this.__root),c,m,w,y,M,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')),l)for(c=Object.keys(s),m=0;m<c.length;m++)w=c[m],y=s[w],M=new RegExp(w,"gi"),M.test(d)&&(d=d.replace(M,y));return d},i.prototype.getSvg=function(){return this.__root},i.prototype.save=function(){var l=this.__createElement("g"),d=this.__closestGroupOrSvg();this.__groupStack.push(d),d.appendChild(l),this.__currentElement=l,this.__stack.push(this.__getStyleState())},i.prototype.restore=function(){this.__currentElement=this.__groupStack.pop();var l=this.__stack.pop();this.__applyStyleState(l)},i.prototype.__addTransform=function(l){var d=this.__closestGroupOrSvg();if(d.childNodes.length>0){var c=this.__createElement("g");d.appendChild(c),this.__currentElement=c}var m=this.__currentElement.getAttribute("transform");m?m+=" ":m="",m+=l,this.__currentElement.setAttribute("transform",m)},i.prototype.scale=function(l,d){d===void 0&&(d=l),this.__addTransform(a("scale({x},{y})",{x:l,y:d}))},i.prototype.rotate=function(l){var d=l*180/Math.PI;this.__addTransform(a("rotate({angle},{cx},{cy})",{angle:d,cx:0,cy:0}))},i.prototype.translate=function(l,d){this.__addTransform(a("translate({x},{y})",{x:l,y:d}))},i.prototype.transform=function(l,d,c,m,w,y){this.__addTransform(a("matrix({a},{b},{c},{d},{e},{f})",{a:l,b:d,c,d:m,e:w,f:y}))},i.prototype.beginPath=function(){var l,d;this.__currentDefaultPath="",this.__currentPosition={},l=this.__createElement("path",{},!0),d=this.__closestGroupOrSvg(),d.appendChild(l),this.__currentElement=l},i.prototype.__applyCurrentDefaultPath=function(){if(this.__currentElement.nodeName==="path"){var l=this.__currentDefaultPath;this.__currentElement.setAttribute("d",l)}else throw new Error("Attempted to apply path command to node "+this.__currentElement.nodeName)},i.prototype.__addPathCommand=function(l){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=l},i.prototype.moveTo=function(l,d){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.__currentPosition={x:l,y:d},this.__addPathCommand(a("M {x} {y}",{x:l,y:d}))},i.prototype.closePath=function(){this.__addPathCommand("Z")},i.prototype.lineTo=function(l,d){this.__currentPosition={x:l,y:d},this.__currentDefaultPath.indexOf("M")>-1?this.__addPathCommand(a("L {x} {y}",{x:l,y:d})):this.__addPathCommand(a("M {x} {y}",{x:l,y:d}))},i.prototype.bezierCurveTo=function(l,d,c,m,w,y){this.__currentPosition={x:w,y},this.__addPathCommand(a("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:l,cp1y:d,cp2x:c,cp2y:m,x:w,y}))},i.prototype.quadraticCurveTo=function(l,d,c,m){this.__currentPosition={x:c,y:m},this.__addPathCommand(a("Q {cpx} {cpy} {x} {y}",{cpx:l,cpy:d,x:c,y:m}))};var u=function(l){var d=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return[l[0]/d,l[1]/d]};i.prototype.arcTo=function(l,d,c,m,w){var y=this.__currentPosition&&this.__currentPosition.x,M=this.__currentPosition&&this.__currentPosition.y;if(!(typeof y>"u"||typeof M>"u")){if(w<0)throw new Error("IndexSizeError: The radius provided ("+w+") is negative.");if(y===l&&M===d||l===c&&d===m||w===0){this.lineTo(l,d);return}var S=u([y-l,M-d]),_=u([c-l,m-d]);if(S[0]*_[1]===S[1]*_[0]){this.lineTo(l,d);return}var E=S[0]*_[0]+S[1]*_[1],D=Math.acos(Math.abs(E)),I=u([S[0]+_[0],S[1]+_[1]]),L=w/Math.sin(D/2),$=l+L*I[0],Y=d+L*I[1],X=[-S[1],S[0]],H=[_[1],-_[0]],ht=function(dt){var ot=dt[0],G=dt[1];return G>=0?Math.acos(ot):-Math.acos(ot)},K=ht(X),Qt=ht(H);this.lineTo($+X[0]*w,Y+X[1]*w),this.arc($,Y,w,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(l,d,c,m){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.moveTo(l,d),this.lineTo(l+c,d),this.lineTo(l+c,d+m),this.lineTo(l,d+m),this.lineTo(l,d),this.closePath()},i.prototype.fillRect=function(l,d,c,m){var w,y;w=this.__createElement("rect",{x:l,y:d,width:c,height:m},!0),y=this.__closestGroupOrSvg(),y.appendChild(w),this.__currentElement=w,this.__applyStyleToCurrentElement("fill")},i.prototype.strokeRect=function(l,d,c,m){var w,y;w=this.__createElement("rect",{x:l,y:d,width:c,height:m},!0),y=this.__closestGroupOrSvg(),y.appendChild(w),this.__currentElement=w,this.__applyStyleToCurrentElement("stroke")},i.prototype.clearRect=function(l,d,c,m){var w,y=this.__closestGroupOrSvg();w=this.__createElement("rect",{x:l,y:d,width:c,height:m,fill:"#FFFFFF"},!0),y.appendChild(w)},i.prototype.createLinearGradient=function(l,d,c,m){var w=this.__createElement("linearGradient",{id:o(this.__ids),x1:l+"px",x2:c+"px",y1:d+"px",y2:m+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(w),new r(w,this)},i.prototype.createRadialGradient=function(l,d,c,m,w,y){var M=this.__createElement("radialGradient",{id:o(this.__ids),cx:m+"px",cy:w+"px",r:y+"px",fx:l+"px",fy:d+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(M),new r(M,this)},i.prototype.__parseFont=function(){var l=/^\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=l.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(l,d){if(l.href){var c=this.__createElement("a");return c.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l.href),c.appendChild(d),c}return d},i.prototype.__applyText=function(l,d,c,m){var w=this.__parseFont(),y=this.__closestGroupOrSvg(),M=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:c,"text-anchor":g(this.textAlign),"dominant-baseline":v(this.textBaseline)},!0);M.appendChild(this.__document.createTextNode(l)),this.__currentElement=M,this.__applyStyleToCurrentElement(m),y.appendChild(this.__wrapTextLink(w,M))},i.prototype.fillText=function(l,d,c){this.__applyText(l,d,c,"fill")},i.prototype.strokeText=function(l,d,c){this.__applyText(l,d,c,"stroke")},i.prototype.measureText=function(l){return this.__ctx.font=this.font,this.__ctx.measureText(l)},i.prototype.arc=function(l,d,c,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 M=l+c*Math.cos(w),S=d+c*Math.sin(w),_=l+c*Math.cos(m),E=d+c*Math.sin(m),D=y?0:1,I=0,L=w-m;L<0&&(L+=2*Math.PI),y?I=L>Math.PI?0:1:I=L>Math.PI?1:0,this.lineTo(_,E),this.__addPathCommand(a("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:c,ry:c,xAxisRotation:0,largeArcFlag:I,sweepFlag:D,endX:M,endY:S})),this.__currentPosition={x:M,y:S}}},i.prototype.clip=function(){var l=this.__closestGroupOrSvg(),d=this.__createElement("clipPath"),c=o(this.__ids),m=this.__createElement("g");l.removeChild(this.__currentElement),d.setAttribute("id",c),d.appendChild(this.__currentElement),this.__defs.appendChild(d),l.setAttribute("clip-path",a("url(#{id})",{id:c})),l.appendChild(m),this.__currentElement=m},i.prototype.drawImage=function(){var l=Array.prototype.slice.call(arguments),d=l[0],c,m,w,y,M=0,S=0,_,E,D,I,L,$,Y,X,H,ht,K;if(l.length===3)c=l[1],m=l[2],_=d.width,E=d.height,w=_,y=E;else if(l.length===5)c=l[1],m=l[2],w=l[3],y=l[4],_=d.width,E=d.height;else if(l.length===9)M=l[1],S=l[2],_=l[3],E=l[4],c=l[5],m=l[6],w=l[7],y=l[8];else throw new Error("Inavlid number of arguments passed to drawImage: "+arguments.length);if(D=this.__closestGroupOrSvg(),Y=this.__currentElement,d instanceof i){for(I=d.getSvg(),L=I.childNodes[0];L.childNodes.length;)K=L.childNodes[0].getAttribute("id"),this.__ids[K]=K,this.__defs.appendChild(L.childNodes[0]);$=I.childNodes[1],D.appendChild($),this.__currentElement=$,this.translate(c,m),this.__currentElement=Y}else(d.nodeName==="CANVAS"||d.nodeName==="IMG")&&(X=this.__createElement("image"),X.setAttribute("width",w),X.setAttribute("height",y),X.setAttribute("preserveAspectRatio","none"),(M||S||_!==d.width||E!==d.height)&&(H=this.__document.createElement("canvas"),H.width=w,H.height=y,ht=H.getContext("2d"),ht.drawImage(d,M,S,_,E,0,0,w,y),d=H),X.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",d.nodeName==="CANVAS"?d.toDataURL():d.getAttribute("src")),D.appendChild(X),this.__currentElement=X,this.translate(c,m),this.__currentElement=Y)},i.prototype.createPattern=function(l,d){var c=this.__document.createElementNS("http://www.w3.org/2000/svg","pattern"),m=o(this.__ids),w;return c.setAttribute("id",m),c.setAttribute("width",l.width),c.setAttribute("height",l.height),l.nodeName==="CANVAS"||l.nodeName==="IMG"?(w=this.__document.createElementNS("http://www.w3.org/2000/svg","image"),w.setAttribute("width",l.width),w.setAttribute("height",l.height),w.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l.nodeName==="CANVAS"?l.toDataURL():l.getAttribute("src")),c.appendChild(w),this.__defs.appendChild(c)):l instanceof i&&(c.appendChild(l.__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 us=Nr.exports;const St=fs(us),ms=Math.PI*2;let gs=0;function ws(){return`p5ExportPattern_${++gs}`}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=ws();const f=vs(this);ys(this,a.kind,{...a,color:f,patternId:s})}}catch{}const o=!!this._p5ExportSVGRecorder&&!!s&&!!a;o&&bs(this,{bbox:a,patternId:s});try{return r.apply(this,n)}finally{o&&_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(o){this.states&&(this.states[a]=o)}})}}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 o=[a[0],a[2],a[4]],f=[a[1],a[3],a[5]],g=Math.min(...o),v=Math.max(...o),u=Math.min(...f),l=Math.max(...f);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]]],x:g,y:u,w:v-g,h:l-u}}),zt(i,"quadPattern",(s,a)=>{const o=[a[0],a[2],a[4],a[6]],f=[a[1],a[3],a[5],a[7]],g=Math.min(...o),v=Math.max(...o),u=Math.min(...f),l=Math.max(...f);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]],[a[6],a[7]]],x:g,y:u,w:v-g,h:l-u}}));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 o=a.bind(n);Object.defineProperty(window,s,{configurable:!0,enumerable:!0,get(){return o},set(f){}})}catch{}}return!0}const Hr="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(#${Hr})`;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,o=i.x+s,f=i.y+a;t.beginPath(),t.ellipse(o,f,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 qr=!1;function Cs(){if(qr)return;qr=!0,St.prototype.setTransform=function(r,n,s,a,o,f){const v=this.__groupStack&&this.__groupStack.length>0?this.__closestGroupOrSvg():this.__root,u=this.__createElement("g");v.appendChild(u),this.__currentElement=u,r===1&&n===0&&s===0&&a===1&&o===0&&f===0||this.__currentElement.setAttribute("transform",`matrix(${r},${n},${s},${a},${o},${f})`)},St.prototype.resetTransform=function(){this.setTransform(1,0,0,1,0,0)},St.prototype.ellipse=function(r,n,s,a,o,f,g,v){if(f===g)return;o=o||0;const u=Math.PI*2,l=Math.abs(g-f)>=u-1e-10;f=f%u,g=g%u;const d=Math.cos(o),c=Math.sin(o),m=D=>{const I=s*Math.cos(D),L=a*Math.sin(D);return{x:r+I*d-L*c,y:n+I*c+L*d}},w=m(f),y=v?0:1,M=o*180/Math.PI;if(this.lineTo(w.x,w.y),l){const D=m(f+(v?-Math.PI:Math.PI));this.__addPathCommand("A "+s+" "+a+" "+M+" 0 "+y+" "+D.x+" "+D.y),this.__addPathCommand("A "+s+" "+a+" "+M+" 0 "+y+" "+w.x+" "+w.y),this.__currentPosition={x:w.x,y:w.y};return}const S=m(g);let _=g-f;_<0&&(_+=u);const E=v?_>Math.PI?0:1:_>Math.PI?1:0;this.__addPathCommand("A "+s+" "+a+" "+M+" "+E+" "+y+" "+S.x+" "+S.y),this.__currentPosition={x:S.x,y:S.y}},typeof St.prototype.roundRect!="function"&&(St.prototype.roundRect=function(r,n,s,a,o){let f,g,v,u;typeof o=="number"?f=g=v=u=o:Array.isArray(o)?o.length===1?f=g=v=u=o[0]:o.length===2?(f=v=o[0],g=u=o[1]):[f,g,v,u]=[o[0],o[1],o[2],o[3]??o[1]]:f=g=v=u=0;const l=Math.min(Math.abs(s),Math.abs(a))/2;f=Math.min(f,l),g=Math.min(g,l),v=Math.min(v,l),u=Math.min(u,l),this.moveTo(r+f,n),this.lineTo(r+s-g,n),this.ellipse(r+s-g,n+g,g,g,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+u,n+a),this.ellipse(r+u,n+a-u,u,u,0,Math.PI/2,Math.PI),this.lineTo(r,n+f),this.ellipse(r+f,n+f,f,f,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 ks(){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 o=te.get(this);return o||(o=[],te.set(this,o)),o.push([r,a.map(f=>Array.isArray(f)?f.slice():f)]),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 o=te.get(this);o||(o=[],te.set(this,o));const f=s?[s.a,s.b,s.c,s.d,s.e,s.f]:null;o.push(["addPath",a.map(([g,v])=>[g,v.slice()]),f])}return i.apply(this,arguments)};r.__p5ExportWrapped=!0;try{t.addPath=r}catch{}}}function Ts(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 o=t[a];typeof o=="function"&&o.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 o={};for(let v=0;v<a;v++){const u=e[v];u[0]===1&&Yr.has(u[1])&&(o[u[1]]=u[2])}e.splice(0,a);const f=[];for(const v in o)f.push([1,v,o[v]]);f.length&&e.unshift(...f);const g=f.length-a;for(let v=1;v<i.length;v++)i[v]+=g}i.shift()}}},n=new Set(["createLinearGradient","createRadialGradient","createConicGradient"]),s=(a,o,f)=>{if(!a)return a;const g=Ps(),v={id:g,kind:o,args:Array.from(f),stops:[]};Jr.set(g,v);try{a.__p5ExportGradId=g}catch{}return new Proxy(a,{get(u,l){if(l==="__p5ExportRealGrad")return u;if(l==="addColorStop"&&typeof u[l]=="function")return function(c,m){return v.stops.push({offset:c,color:m}),u[l].call(u,c,m)};const d=u[l];return typeof d=="function"?d.bind(u):d}})};return r.proxy=new Proxy(t,{get(a,o){const f=a[o];return typeof f=="function"?function(...g){if(!r.paused){const u=g.map(l=>Ts(l)||l);e.push([0,o,u])}const v=f.apply(a,g);return n.has(o)?s(v,o,g):v}:f},set(a,o,f){if((o==="fillStyle"||o==="strokeStyle")&&f&&typeof f=="object"){const g=f.__p5ExportGradId;r.paused||e.push([1,o,g?{__p5ExportGradId:g}:f]),a[o]=f.__p5ExportRealGrad||f}else r.paused||e.push([1,o,f]),a[o]=f;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 o=0;o<t.length;o++){const f=t[o];if(f[0]===2){f[1]==="beginRaster"?a=!0:f[1]==="endRaster"&&(a=!1);continue}if(!a){if(f[0]===1&&f[1]==="fillStyle")n=f[2];else if(f[0]===0&&(f[1]==="fillRect"||f[1]==="clearRect")){const g=f[2],v=g[0],u=g[1],l=g[2],d=g[3];Math.abs(v)<=s&&Math.abs(u)<=s&&Math.abs(l-e)<=s&&Math.abs(d-i)<=s&&(f[1]==="clearRect"||Bs(n))&&(r=o)}}}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 o=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=o}if(!a||!a.length)return!0;t.save(),t.beginPath();for(let f=0;f<a.length;f++){const g=a[f];switch(g[0]){case"M":t.moveTo(g[1],g[2]);break;case"L":t.lineTo(g[1],g[2]);break;case"C":t.bezierCurveTo(g[1],g[2],g[3],g[4],g[5],g[6]);break;case"Q":t.quadraticCurveTo(g[1],g[2],g[3],g[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 o="#000000",f="#000000";const g=new Set,v="http://www.w3.org/2000/svg",u=G=>{if(!G||g.has(G.id))return!0;const k=a.__defs,W=a.__document;let b;if(G.kind==="createLinearGradient"){const[O,et,ct,Dt]=G.args;b=W.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(G.kind==="createRadialGradient"){const[O,et,ct,Dt,Ze,Or]=G.args;b=W.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",G.id);for(const O of G.stops){const et=W.createElementNS(v,"stop");et.setAttribute("offset",String(O.offset)),et.setAttribute("stop-color",String(O.color)),b.appendChild(et)}return k.appendChild(b),g.add(G.id),!0},l=typeof t.pixelDensity=="function"?t.pixelDensity():1,d=1/l,c=r.ops.slice(),m=Zr(c,n,s);let w=0;if(m>0){let G=0,k=-1;for(let b=m-1;b>=0;b--)if(c[b][0]===0){if(c[b][1]==="restore")G++;else if(c[b][1]==="save"){if(G===0){k=b;break}G--}}w=k>=0?k:m;const W={};for(let b=0;b<w;b++){const O=c[b];O[0]===1&&Yr.has(O[1])&&(W[O[1]]=O[2])}for(const b in W){const O=W[b];b==="fillStyle"||b==="strokeStyle"?typeof O=="string"?(b==="fillStyle"?o=O:f=O,a[b]=ei(O)):a[b]=b==="fillStyle"?o:f:a[b]=O}}const y=xt(t),M=y?y.width:n*l,S=y?y.height:s*l;let _=null,E=null,D=null,I=null,L=null,$=!1;const Y="http://www.w3.org/2000/svg",X="http://www.w3.org/1999/xlink",H=()=>{_||(_=document.createElement("canvas"),_.width=M,_.height=S,E=_.getContext("2d")),E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,_.width,_.height),E.setTransform(l,0,0,l,0,0)},ht=()=>{I||(I=document.createElement("canvas"),I.width=M,I.height=S,L=I.getContext("2d"),L.setTransform(l,0,0,l,0,0))},K=G=>{if(!G||!G.hasContent||!_)return;const k=G.bbox;if(!k)return;const W=Math.max(0,Math.floor(k.x*l)),b=Math.max(0,Math.floor(k.y*l)),O=Math.min(_.width,Math.ceil((k.x+k.w)*l)),et=Math.min(_.height,Math.ceil((k.y+k.h)*l)),ct=O-W,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(_,W,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",G.patternId),Ut.setAttribute("patternUnits","userSpaceOnUse"),Ut.setAttribute("x",String(k.x)),Ut.setAttribute("y",String(k.y)),Ut.setAttribute("width",String(k.w)),Ut.setAttribute("height",String(k.h));const Wt=a.__document.createElementNS(Y,"image");Wt.setAttribute("x","0"),Wt.setAttribute("y","0"),Wt.setAttribute("width",String(k.w)),Wt.setAttribute("height",String(k.h)),Wt.setAttributeNS(X,"xlink:href",Ze),Wt.setAttribute("href",Ze),Wt.setAttribute("preserveAspectRatio","none"),Ut.appendChild(Wt),Or.appendChild(Ut)},Qt=()=>{if(!(!I||!$))try{const G=I.toDataURL(),k=a.__defs,W=a.__document.createElementNS(Y,"pattern");W.setAttribute("id",Hr),W.setAttribute("patternUnits","userSpaceOnUse"),W.setAttribute("x","0"),W.setAttribute("y","0"),W.setAttribute("width",String(n)),W.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",G),b.setAttribute("href",G),W.appendChild(b),k.appendChild(W);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",G),O.setAttribute("href",G),a.__root.appendChild(O)}catch{}};let dt=!1,ot=!1;for(let G=w;G<c.length;G++){const k=c[G];if(k[0]===5){k[1]==="textStart"?ot=i?Fs(a,t,k[2],r):!1:k[1]==="textEnd"&&(ot=!1);continue}if(ot)continue;if(k[0]===2){if(k[1]==="beginRaster"){const b=k[2];b&&b.bbox&&b.patternId?(H(),D={bbox:b.bbox,patternId:b.patternId,hasContent:!1}):(ht(),D=null),dt=!0}else k[1]==="endRaster"&&(D&&(K(D),D=null),dt=!1);continue}if(k[0]===3){try{Ss(a,k[1],k[2],!0)}catch{}continue}const W=dt?D?E:L:a;dt&&k[0]===0&&(D?D.hasContent=!0:$=!0);try{if(k[0]===0)if(k[1]==="setTransform"){const b=k[2];W===a?W.setTransform(b[0]*d,b[1]*d,b[2]*d,b[3]*d,b[4]*d,b[5]*d):W.setTransform(b[0],b[1],b[2],b[3],b[4],b[5])}else if((k[1]==="fill"||k[1]==="stroke"||k[1]==="clip")&&k[2]&&k[2][0]&&k[2][0].__p5ExportPath2D){As(W,k[2][0]);const b=W[k[1]];typeof b=="function"&&b.apply(W,k[2].slice(1))}else{const b=W[k[1]];typeof b=="function"&&b.apply(W,k[2])}else if(k[1]==="fillStyle"||k[1]==="strokeStyle"){const b=k[2],O=k[1]==="fillStyle";if(typeof b=="string")O?o=b:f=b,W[k[1]]=W===a?ei(b):b;else if(b&&typeof b=="object"&&b.__p5ExportGradId){const et=Jr.get(b.__p5ExportGradId);W===a&&u(et)?W[k[1]]=`url(#${et.id})`:W===a&&(W[k[1]]=O?o:f)}else if(W===a)W[k[1]]=O?o:f;else try{W[k[1]]=b}catch{}}else if(k[1]==="globalCompositeOperation"){if(W[k[1]]=k[2],W===a){const b=k[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 W[k[1]]=k[2]}catch{}}return D&&K(D),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){ks(),e.saveSVG=function(s,a={}){let o;const f=!!this._p5ExportSVGRecorder,g=2e6;let v=0;if(f){const c=this._p5ExportSVGRecorder.ops.slice(),m=this.width||100,w=this.height||100,y=Zr(c,m,w);let M=0;if(y>0){let _=0;for(let E=y-1;E>=0;E--)if(c[E][0]===0){if(c[E][1]==="restore")_++;else if(c[E][1]==="save"){if(_===0){M=E;break}_--}}}let S=!1;for(let _=M;_<c.length;_++){const E=c[_];if(E[0]===2){E[1]==="beginRaster"?S=!0:E[1]==="endRaster"&&(S=!1);continue}E[0]!==5&&(S||v++)}}const u=f&&!a.forceVector&&v>g;if(!a.raster&&(!f||u)&&!a.silent&&typeof window<"u"&&typeof window.confirm=="function"){const c=u?`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
|
+
*/(function(e){(function(){var t,i,r,n,s;function a(l,d){var c=Object.keys(d),u;for(u=0;u<c.length;u++)l=l.replace(new RegExp("\\{"+c[u]+"\\}","gi"),d[c[u]]);return l}function o(l){var d,c,u;if(!l)throw new Error("cannot create a random attribute name for an undefined object");d="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",c="";do for(c="",u=0;u<12;u++)c+=d[Math.floor(Math.random()*d.length)];while(l[c]);return c}function p(l,d){var c,u,g={},y;for(l=l.split(","),d=d||10,c=0;c<l.length;c+=2)u="&"+l[c+1]+";",y=parseInt(l[c],d),g[u]="&#"+y+";";return g["\\xa0"]=" ",g}function w(l){var d={left:"start",right:"end",center:"middle",start:"start",end:"end"};return d[l]||d.start}function v(l){var d={alphabetic:"alphabetic",hanging:"hanging",top:"text-before-edge",bottom:"text-after-edge",middle:"central"};return d[l]||d.alphabetic}s=p("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),t={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(l,d){this.__root=l,this.__ctx=d},r.prototype.addColorStop=function(l,d){var c=this.__ctx.__createElement("stop"),u,g;c.setAttribute("offset",l),d.indexOf("rgba")!==-1?(u=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,g=u.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(l,d){this.__root=l,this.__ctx=d},i=function(l){var d={width:500,height:500,enableMirroring:!1},c;if(arguments.length>1?(c=d,c.width=arguments[0],c.height=arguments[1]):l?c=l: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(l,d,c){typeof d>"u"&&(d={});var u=this.__document.createElementNS("http://www.w3.org/2000/svg",l),g=Object.keys(d),y,M;for(c&&(u.setAttribute("fill","none"),u.setAttribute("stroke","none")),y=0;y<g.length;y++)M=g[y],u.setAttribute(M,d[M]);return u},i.prototype.__setDefaultStyles=function(){var l=Object.keys(t),d,c;for(d=0;d<l.length;d++)c=l[d],this[c]=t[c].canvas},i.prototype.__applyStyleState=function(l){var d=Object.keys(l),c,u;for(c=0;c<d.length;c++)u=d[c],this[u]=l[u]},i.prototype.__getStyleState=function(){var l,d={},c=Object.keys(t),u;for(l=0;l<c.length;l++)u=c[l],d[u]=this[u];return d},i.prototype.__applyStyleToCurrentElement=function(l){var d=Object.keys(t),c,u,g,y,M,S;for(c=0;c<d.length;c++)if(u=t[d[c]],g=this[d[c]],u.apply)if(u.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 u.apply.indexOf("fill")!==-1&&g instanceof r?this.__currentElement.setAttribute("fill",a("url(#{id})",{id:g.__root.getAttribute("id")})):u.apply.indexOf(l)!==-1&&u.svg!==g&&((u.svgAttr==="stroke"||u.svgAttr==="fill")&&g.indexOf("rgba")!==-1?(M=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi,S=M.exec(g),this.__currentElement.setAttribute(u.svgAttr,a("rgb({r},{g},{b})",{r:S[1],g:S[2],b:S[3]})),this.__currentElement.setAttribute(u.svgAttr+"-opacity",S[4])):this.__currentElement.setAttribute(u.svgAttr,g))},i.prototype.__closestGroupOrSvg=function(l){return l=l||this.__currentElement,l.nodeName==="g"||l.nodeName==="svg"?l:this.__closestGroupOrSvg(l.parentNode)},i.prototype.getSerializedSvg=function(l){var d=new XMLSerializer().serializeToString(this.__root),c,u,g,y,M,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')),l)for(c=Object.keys(s),u=0;u<c.length;u++)g=c[u],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 l=this.__createElement("g"),d=this.__closestGroupOrSvg();this.__groupStack.push(d),d.appendChild(l),this.__currentElement=l,this.__stack.push(this.__getStyleState())},i.prototype.restore=function(){this.__currentElement=this.__groupStack.pop();var l=this.__stack.pop();this.__applyStyleState(l)},i.prototype.__addTransform=function(l){var d=this.__closestGroupOrSvg();if(d.childNodes.length>0){var c=this.__createElement("g");d.appendChild(c),this.__currentElement=c}var u=this.__currentElement.getAttribute("transform");u?u+=" ":u="",u+=l,this.__currentElement.setAttribute("transform",u)},i.prototype.scale=function(l,d){d===void 0&&(d=l),this.__addTransform(a("scale({x},{y})",{x:l,y:d}))},i.prototype.rotate=function(l){var d=l*180/Math.PI;this.__addTransform(a("rotate({angle},{cx},{cy})",{angle:d,cx:0,cy:0}))},i.prototype.translate=function(l,d){this.__addTransform(a("translate({x},{y})",{x:l,y:d}))},i.prototype.transform=function(l,d,c,u,g,y){this.__addTransform(a("matrix({a},{b},{c},{d},{e},{f})",{a:l,b:d,c,d:u,e:g,f:y}))},i.prototype.beginPath=function(){var l,d;this.__currentDefaultPath="",this.__currentPosition={},l=this.__createElement("path",{},!0),d=this.__closestGroupOrSvg(),d.appendChild(l),this.__currentElement=l},i.prototype.__applyCurrentDefaultPath=function(){if(this.__currentElement.nodeName==="path"){var l=this.__currentDefaultPath;this.__currentElement.setAttribute("d",l)}else throw new Error("Attempted to apply path command to node "+this.__currentElement.nodeName)},i.prototype.__addPathCommand=function(l){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=l},i.prototype.moveTo=function(l,d){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.__currentPosition={x:l,y:d},this.__addPathCommand(a("M {x} {y}",{x:l,y:d}))},i.prototype.closePath=function(){this.__addPathCommand("Z")},i.prototype.lineTo=function(l,d){this.__currentPosition={x:l,y:d},this.__currentDefaultPath.indexOf("M")>-1?this.__addPathCommand(a("L {x} {y}",{x:l,y:d})):this.__addPathCommand(a("M {x} {y}",{x:l,y:d}))},i.prototype.bezierCurveTo=function(l,d,c,u,g,y){this.__currentPosition={x:g,y},this.__addPathCommand(a("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:l,cp1y:d,cp2x:c,cp2y:u,x:g,y}))},i.prototype.quadraticCurveTo=function(l,d,c,u){this.__currentPosition={x:c,y:u},this.__addPathCommand(a("Q {cpx} {cpy} {x} {y}",{cpx:l,cpy:d,x:c,y:u}))};var m=function(l){var d=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return[l[0]/d,l[1]/d]};i.prototype.arcTo=function(l,d,c,u,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===l&&M===d||l===c&&d===u||g===0){this.lineTo(l,d);return}var S=m([y-l,M-d]),_=m([c-l,u-d]);if(S[0]*_[1]===S[1]*_[0]){this.lineTo(l,d);return}var E=S[0]*_[0]+S[1]*_[1],D=Math.acos(Math.abs(E)),I=m([S[0]+_[0],S[1]+_[1]]),L=g/Math.sin(D/2),$=l+L*I[0],Y=d+L*I[1],X=[-S[1],S[0]],H=[_[1],-_[0]],he=function(de){var oe=de[0],G=de[1];return G>=0?Math.acos(oe):-Math.acos(oe)},K=he(X),Qe=he(H);this.lineTo($+X[0]*g,Y+X[1]*g),this.arc($,Y,g,K,Qe)}},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(l,d,c,u){this.__currentElement.nodeName!=="path"&&this.beginPath(),this.moveTo(l,d),this.lineTo(l+c,d),this.lineTo(l+c,d+u),this.lineTo(l,d+u),this.lineTo(l,d),this.closePath()},i.prototype.fillRect=function(l,d,c,u){var g,y;g=this.__createElement("rect",{x:l,y:d,width:c,height:u},!0),y=this.__closestGroupOrSvg(),y.appendChild(g),this.__currentElement=g,this.__applyStyleToCurrentElement("fill")},i.prototype.strokeRect=function(l,d,c,u){var g,y;g=this.__createElement("rect",{x:l,y:d,width:c,height:u},!0),y=this.__closestGroupOrSvg(),y.appendChild(g),this.__currentElement=g,this.__applyStyleToCurrentElement("stroke")},i.prototype.clearRect=function(l,d,c,u){var g,y=this.__closestGroupOrSvg();g=this.__createElement("rect",{x:l,y:d,width:c,height:u,fill:"#FFFFFF"},!0),y.appendChild(g)},i.prototype.createLinearGradient=function(l,d,c,u){var g=this.__createElement("linearGradient",{id:o(this.__ids),x1:l+"px",x2:c+"px",y1:d+"px",y2:u+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(g),new r(g,this)},i.prototype.createRadialGradient=function(l,d,c,u,g,y){var M=this.__createElement("radialGradient",{id:o(this.__ids),cx:u+"px",cy:g+"px",r:y+"px",fx:l+"px",fy:d+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(M),new r(M,this)},i.prototype.__parseFont=function(){var l=/^\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=l.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(l,d){if(l.href){var c=this.__createElement("a");return c.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l.href),c.appendChild(d),c}return d},i.prototype.__applyText=function(l,d,c,u){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":w(this.textAlign),"dominant-baseline":v(this.textBaseline)},!0);M.appendChild(this.__document.createTextNode(l)),this.__currentElement=M,this.__applyStyleToCurrentElement(u),y.appendChild(this.__wrapTextLink(g,M))},i.prototype.fillText=function(l,d,c){this.__applyText(l,d,c,"fill")},i.prototype.strokeText=function(l,d,c){this.__applyText(l,d,c,"stroke")},i.prototype.measureText=function(l){return this.__ctx.font=this.font,this.__ctx.measureText(l)},i.prototype.arc=function(l,d,c,u,g,y){if(u!==g){u=u%(2*Math.PI),g=g%(2*Math.PI),u===g&&(g=(g+2*Math.PI-.001*(y?-1:1))%(2*Math.PI));var M=l+c*Math.cos(g),S=d+c*Math.sin(g),_=l+c*Math.cos(u),E=d+c*Math.sin(u),D=y?0:1,I=0,L=g-u;L<0&&(L+=2*Math.PI),y?I=L>Math.PI?0:1:I=L>Math.PI?1:0,this.lineTo(_,E),this.__addPathCommand(a("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:c,ry:c,xAxisRotation:0,largeArcFlag:I,sweepFlag:D,endX:M,endY:S})),this.__currentPosition={x:M,y:S}}},i.prototype.clip=function(){var l=this.__closestGroupOrSvg(),d=this.__createElement("clipPath"),c=o(this.__ids),u=this.__createElement("g");l.removeChild(this.__currentElement),d.setAttribute("id",c),d.appendChild(this.__currentElement),this.__defs.appendChild(d),l.setAttribute("clip-path",a("url(#{id})",{id:c})),l.appendChild(u),this.__currentElement=u},i.prototype.drawImage=function(){var l=Array.prototype.slice.call(arguments),d=l[0],c,u,g,y,M=0,S=0,_,E,D,I,L,$,Y,X,H,he,K;if(l.length===3)c=l[1],u=l[2],_=d.width,E=d.height,g=_,y=E;else if(l.length===5)c=l[1],u=l[2],g=l[3],y=l[4],_=d.width,E=d.height;else if(l.length===9)M=l[1],S=l[2],_=l[3],E=l[4],c=l[5],u=l[6],g=l[7],y=l[8];else throw new Error("Inavlid number of arguments passed to drawImage: "+arguments.length);if(D=this.__closestGroupOrSvg(),Y=this.__currentElement,d instanceof i){for(I=d.getSvg(),L=I.childNodes[0];L.childNodes.length;)K=L.childNodes[0].getAttribute("id"),this.__ids[K]=K,this.__defs.appendChild(L.childNodes[0]);$=I.childNodes[1],D.appendChild($),this.__currentElement=$,this.translate(c,u),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||S||_!==d.width||E!==d.height)&&(H=this.__document.createElement("canvas"),H.width=g,H.height=y,he=H.getContext("2d"),he.drawImage(d,M,S,_,E,0,0,g,y),d=H),X.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",d.nodeName==="CANVAS"?d.toDataURL():d.getAttribute("src")),D.appendChild(X),this.__currentElement=X,this.translate(c,u),this.__currentElement=Y)},i.prototype.createPattern=function(l,d){var c=this.__document.createElementNS("http://www.w3.org/2000/svg","pattern"),u=o(this.__ids),g;return c.setAttribute("id",u),c.setAttribute("width",l.width),c.setAttribute("height",l.height),l.nodeName==="CANVAS"||l.nodeName==="IMG"?(g=this.__document.createElementNS("http://www.w3.org/2000/svg","image"),g.setAttribute("width",l.width),g.setAttribute("height",l.height),g.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l.nodeName==="CANVAS"?l.toDataURL():l.getAttribute("src")),c.appendChild(g),this.__defs.appendChild(c)):l instanceof i&&(c.appendChild(l.__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),e.exports=i})()})(Nr);var ms=Nr.exports;const Se=us(ms),gs=Math.PI*2;let ws=0;function vs(){return`p5ExportPattern_${++ws}`}function ys(e){const t=e._patternControler,i=t&&Array.isArray(t.colors)?t.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 _t(e,t,i,r,n){return n==="corners"?{x:e,y:t,w:i-e,h:r-t}:n==="radius"?{x:e-i,y:t-r,w:2*i,h:2*r}:n==="center"?{x:e-i*.5,y:t-r*.5,w:i,h:r}:{x:e,y:t,w:i,h:r}}function $r(e){return e._renderer&&e._renderer.states&&e._renderer.states.rectMode||"corner"}function Wi(e){return e._renderer&&e._renderer.states&&e._renderer.states.ellipseMode||"center"}function bs(e,t,i){const r=e._p5ExportSVGRecorder;r&&r.ops.push([3,t,i])}function _s(e,t){const i=e._p5ExportSVGRecorder;i&&i.ops.push([2,"beginRaster",t])}function xs(e){const t=e._p5ExportSVGRecorder;t&&t.ops.push([2,"endRaster"])}function ze(e,t,i){const r=e[t];typeof r!="function"||r.__p5ExportWrapped||(e[t]=function(...n){let s,a;try{if(a=i(this,n),a){s=vs();const p=ys(this);bs(this,a.kind,{...a,color:p,patternId:s})}}catch{}const o=!!this._p5ExportSVGRecorder&&!!s&&!!a;o&&_s(this,{bbox:a,patternId:s});try{return r.apply(this,n)}finally{o&&xs(this)}},e[t].__p5ExportWrapped=!0)}const Ss=["rectPattern","squarePattern","ellipsePattern","circlePattern","arcPattern","trianglePattern","quadPattern"];function jr(e,t){if(!e||!e.prototype)return!1;const i=e.prototype;if(typeof i.rectPattern!="function")return!1;const r=!!i.__p5ExportPatternHooksInstalled;if(r||(i.__p5ExportPatternHooksInstalled=!0),t&&t._renderer&&t._renderer.states){const s=e.Renderer||t._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(o){this.states&&(this.states[a]=o)}})}}r||(ze(i,"rectPattern",(s,a)=>({kind:"rect",..._t(a[0],a[1],a[2],a[3],$r(s))})),ze(i,"squarePattern",(s,a)=>({kind:"rect",..._t(a[0],a[1],a[2],a[2],$r(s))})),ze(i,"ellipsePattern",(s,a)=>({kind:"ellipse",..._t(a[0],a[1],a[2],a[3],Wi(s))})),ze(i,"circlePattern",(s,a)=>({kind:"ellipse",..._t(a[0],a[1],a[2],a[2],Wi(s))})),ze(i,"arcPattern",(s,a)=>({kind:"ellipse",..._t(a[0],a[1],a[2],a[3],Wi(s))})),ze(i,"trianglePattern",(s,a)=>{const o=[a[0],a[2],a[4]],p=[a[1],a[3],a[5]],w=Math.min(...o),v=Math.max(...o),m=Math.min(...p),l=Math.max(...p);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]]],x:w,y:m,w:v-w,h:l-m}}),ze(i,"quadPattern",(s,a)=>{const o=[a[0],a[2],a[4],a[6]],p=[a[1],a[3],a[5],a[7]],w=Math.min(...o),v=Math.max(...o),m=Math.min(...p),l=Math.max(...p);return{kind:"polygon",points:[[a[0],a[1]],[a[2],a[3]],[a[4],a[5]],[a[6],a[7]]],x:w,y:m,w:v-w,h:l-m}}));const n=t&&t._isGlobal&&t||typeof window<"u"&&window.p5&&window.p5.instance||null;if(n&&n._isGlobal&&typeof window<"u")for(const s of Ss){const a=i[s];if(typeof a=="function")try{let o=a.bind(n);Object.defineProperty(window,s,{configurable:!0,enumerable:!0,get(){return o},set(p){}})}catch{}}return!0}const Hr="p5ExportSharedRaster";function Cs(e,t,i,r){if(!i||!e)return;const n=e.fillStyle;i.patternId?e.fillStyle=`url(#${i.patternId})`:e.fillStyle=`url(#${Hr})`;try{if(t==="rect")e.beginPath(),e.rect(i.x,i.y,i.w,i.h),e.fill();else if(t==="ellipse"){const s=i.w/2,a=i.h/2,o=i.x+s,p=i.y+a;e.beginPath(),e.ellipse(o,p,s,a,0,0,gs),e.fill()}else if(t==="polygon"){const s=i.points||[];if(s.length>=2){e.beginPath(),e.moveTo(s[0][0],s[0][1]);for(let a=1;a<s.length;a++)e.lineTo(s[a][0],s[a][1]);e.closePath(),e.fill()}}}finally{e.fillStyle=n}}let qr=!1;function Es(){if(qr)return;qr=!0,Se.prototype.setTransform=function(r,n,s,a,o,p){const v=this.__groupStack&&this.__groupStack.length>0?this.__closestGroupOrSvg():this.__root,m=this.__createElement("g");v.appendChild(m),this.__currentElement=m,r===1&&n===0&&s===0&&a===1&&o===0&&p===0||this.__currentElement.setAttribute("transform",`matrix(${r},${n},${s},${a},${o},${p})`)},Se.prototype.resetTransform=function(){this.setTransform(1,0,0,1,0,0)},Se.prototype.ellipse=function(r,n,s,a,o,p,w,v){if(p===w)return;o=o||0;const m=Math.PI*2,l=Math.abs(w-p)>=m-1e-10;p=p%m,w=w%m;const d=Math.cos(o),c=Math.sin(o),u=D=>{const I=s*Math.cos(D),L=a*Math.sin(D);return{x:r+I*d-L*c,y:n+I*c+L*d}},g=u(p),y=v?0:1,M=o*180/Math.PI;if(this.lineTo(g.x,g.y),l){const D=u(p+(v?-Math.PI:Math.PI));this.__addPathCommand("A "+s+" "+a+" "+M+" 0 "+y+" "+D.x+" "+D.y),this.__addPathCommand("A "+s+" "+a+" "+M+" 0 "+y+" "+g.x+" "+g.y),this.__currentPosition={x:g.x,y:g.y};return}const S=u(w);let _=w-p;_<0&&(_+=m);const E=v?_>Math.PI?0:1:_>Math.PI?1:0;this.__addPathCommand("A "+s+" "+a+" "+M+" "+E+" "+y+" "+S.x+" "+S.y),this.__currentPosition={x:S.x,y:S.y}},typeof Se.prototype.roundRect!="function"&&(Se.prototype.roundRect=function(r,n,s,a,o){let p,w,v,m;typeof o=="number"?p=w=v=m=o:Array.isArray(o)?o.length===1?p=w=v=m=o[0]:o.length===2?(p=v=o[0],w=m=o[1]):[p,w,v,m]=[o[0],o[1],o[2],o[3]??o[1]]:p=w=v=m=0;const l=Math.min(Math.abs(s),Math.abs(a))/2;p=Math.min(p,l),w=Math.min(w,l),v=Math.min(v,l),m=Math.min(m,l),this.moveTo(r+p,n),this.lineTo(r+s-w,n),this.ellipse(r+s-w,n+w,w,w,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+m,n+a),this.ellipse(r+m,n+a-m,m,m,0,Math.PI/2,Math.PI),this.lineTo(r,n+p),this.ellipse(r+p,n+p,p,p,0,Math.PI,Math.PI*1.5)}),delete Se.prototype.globalCompositeOperation;const e=Se.prototype.__applyStyleToCurrentElement,t=/^#([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=t.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})`};Se.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 e.call(this,r)}finally{this.fillStyle=n,this.strokeStyle=s}}}const ks=60,et=new WeakMap;let Xr=!1;function Ts(){if(Xr||typeof Path2D>"u")return;Xr=!0;const e=Path2D.prototype,t=["moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath"];for(const r of t){const n=e[r];if(typeof n!="function"||n.__p5ExportWrapped)continue;const s=function(...a){let o=et.get(this);return o||(o=[],et.set(this,o)),o.push([r,a.map(p=>Array.isArray(p)?p.slice():p)]),n.apply(this,a)};s.__p5ExportWrapped=!0;try{e[r]=s}catch{}}const i=e.addPath;if(typeof i=="function"&&!i.__p5ExportWrapped){const r=function(n,s){const a=et.get(n);if(a&&a.length){let o=et.get(this);o||(o=[],et.set(this,o));const p=s?[s.a,s.b,s.c,s.d,s.e,s.f]:null;o.push(["addPath",a.map(([w,v])=>[w,v.slice()]),p])}return i.apply(this,arguments)};r.__p5ExportWrapped=!0;try{e.addPath=r}catch{}}}function As(e){if(!e||typeof e!="object")return null;const t=et.get(e);return t?{__p5ExportPath2D:t.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 Ms(e,t){const i=t&&t.__p5ExportPath2D;if(!i)return!1;e.beginPath();const r=n=>{for(const s of n){const a=s[0];if(a==="addPath"){r(s[1]);continue}const o=e[a];typeof o=="function"&&o.apply(e,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 Ps=0;const Jr=new Map;function Is(){return`p5ExportGrad_${++Ps}`}function Rs(e){const t=[],i=[0],r={proxy:null,ops:t,maxFrames:ks,paused:!1,textOutline:null,clear(){t.length=0,i.length=1,i[0]=0},markFrameBoundary(){if(this.maxFrames===1/0){i.push(t.length);return}for(i.push(t.length);i.length>this.maxFrames+1;){const a=i[1];if(a>0){const o={};for(let v=0;v<a;v++){const m=t[v];m[0]===1&&Yr.has(m[1])&&(o[m[1]]=m[2])}t.splice(0,a);const p=[];for(const v in o)p.push([1,v,o[v]]);p.length&&t.unshift(...p);const w=p.length-a;for(let v=1;v<i.length;v++)i[v]+=w}i.shift()}}},n=new Set(["createLinearGradient","createRadialGradient","createConicGradient"]),s=(a,o,p)=>{if(!a)return a;const w=Is(),v={id:w,kind:o,args:Array.from(p),stops:[]};Jr.set(w,v);try{a.__p5ExportGradId=w}catch{}return new Proxy(a,{get(m,l){if(l==="__p5ExportRealGrad")return m;if(l==="addColorStop"&&typeof m[l]=="function")return function(c,u){return v.stops.push({offset:c,color:u}),m[l].call(m,c,u)};const d=m[l];return typeof d=="function"?d.bind(m):d}})};return r.proxy=new Proxy(e,{get(a,o){const p=a[o];return typeof p=="function"?function(...w){if(!r.paused){const m=w.map(l=>As(l)||l);t.push([0,o,m])}const v=p.apply(a,w);return n.has(o)?s(v,o,w):v}:p},set(a,o,p){if((o==="fillStyle"||o==="strokeStyle")&&p&&typeof p=="object"){const w=p.__p5ExportGradId;r.paused||t.push([1,o,w?{__p5ExportGradId:w}:p]),a[o]=p.__p5ExportRealGrad||p}else r.paused||t.push([1,o,p]),a[o]=p;return!0}}),r}function Bs(e){return!!(e&&typeof e.fillRect=="function")}function Kr(e){if(!e||e._p5ExportSVGRecorder)return;const t=e._renderer;if(!t)return;const i=t.drawingContext;if(!Bs(i))return;const r=Rs(i),n=typeof window<"u"&&window.p5ExportConfig||{};typeof n.svgMaxFrames=="number"&&(r.maxFrames=n.svgMaxFrames>0?n.svgMaxFrames:1/0),e._p5ExportSVGRecorder=r;const s={value:r.proxy,configurable:!0,writable:!0,enumerable:!0};Object.defineProperty(t,"drawingContext",s),Object.defineProperty(e,"drawingContext",s)}function ti(e){if(typeof e!="string")return e;const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return e;const i=parseInt(t[4],16)/255;return`rgba(${parseInt(t[1],16)},${parseInt(t[2],16)},${parseInt(t[3],16)},${i})`}function Fs(e){if(typeof e!="string")return!0;let t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return t?parseInt(t[4],16)===255:(t=/^rgba\(\s*[^,]+,\s*[^,]+,\s*[^,]+,\s*([\d.]+)\s*\)$/i.exec(e),t?parseFloat(t[1])>=1:(t=/^#[0-9a-f]{3}([0-9a-f])$/i.exec(e),t?parseInt(t[1],16)===15:!0))}function Zr(e,t,i){let r=-1,n="#000000";const s=.5;let a=!1;for(let o=0;o<e.length;o++){const p=e[o];if(p[0]===2){p[1]==="beginRaster"?a=!0:p[1]==="endRaster"&&(a=!1);continue}if(!a){if(p[0]===1&&p[1]==="fillStyle")n=p[2];else if(p[0]===0&&(p[1]==="fillRect"||p[1]==="clearRect")){const w=p[2],v=w[0],m=w[1],l=w[2],d=w[3];Math.abs(v)<=s&&Math.abs(m)<=s&&Math.abs(l-t)<=s&&Math.abs(d-i)<=s&&(p[1]==="clearRect"||Fs(n))&&(r=o)}}}return r}function Qr(e,t){if(t&&typeof t.outlineText=="boolean")return t.outlineText;const i=e._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 Ds(e,t,i,r){const n=i&&i.font;if(!n||typeof n.textToPaths!="function"||!n.data)return!1;const s=t._renderer;if(!s)return!1;let a;const o=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=o}if(!a||!a.length)return!0;e.save(),e.beginPath();for(let p=0;p<a.length;p++){const w=a[p];switch(w[0]){case"M":e.moveTo(w[1],w[2]);break;case"L":e.lineTo(w[1],w[2]);break;case"C":e.bezierCurveTo(w[1],w[2],w[3],w[4],w[5],w[6]);break;case"Q":e.quadraticCurveTo(w[1],w[2],w[3],w[4]);break;case"Z":e.closePath();break}}return i.fill&&(e.fillStyle=ti(i.fill),e.fill()),i.hasStroke&&i.stroke&&(e.strokeStyle=ti(i.stroke),i.strokeWeight!=null&&(e.lineWidth=i.strokeWeight),e.stroke()),e.restore(),!0}function en(e,t={}){Es();const i=!!t.outlineText,r=e._p5ExportSVGRecorder,n=e.width||100,s=e.height||100,a=new Se(n,s);if(a.setTransform(1,0,0,1,0,0),!r)return a.getSerializedSvg();let o="#000000",p="#000000";const w=new Set,v="http://www.w3.org/2000/svg",m=G=>{if(!G||w.has(G.id))return!0;const k=a.__defs,W=a.__document;let b;if(G.kind==="createLinearGradient"){const[O,te,ce,De]=G.args;b=W.createElementNS(v,"linearGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("x1",String(O)),b.setAttribute("y1",String(te)),b.setAttribute("x2",String(ce)),b.setAttribute("y2",String(De))}else if(G.kind==="createRadialGradient"){const[O,te,ce,De,Zt,Or]=G.args;b=W.createElementNS(v,"radialGradient"),b.setAttribute("gradientUnits","userSpaceOnUse"),b.setAttribute("fx",String(O)),b.setAttribute("fy",String(te)),b.setAttribute("fr",String(ce)),b.setAttribute("cx",String(De)),b.setAttribute("cy",String(Zt)),b.setAttribute("r",String(Or))}else return!1;b.setAttribute("id",G.id);for(const O of G.stops){const te=W.createElementNS(v,"stop");te.setAttribute("offset",String(O.offset)),te.setAttribute("stop-color",String(O.color)),b.appendChild(te)}return k.appendChild(b),w.add(G.id),!0},l=typeof e.pixelDensity=="function"?e.pixelDensity():1,d=1/l,c=r.ops.slice(),u=Zr(c,n,s);let g=0;if(u>0){let G=0,k=-1;for(let b=u-1;b>=0;b--)if(c[b][0]===0){if(c[b][1]==="restore")G++;else if(c[b][1]==="save"){if(G===0){k=b;break}G--}}g=k>=0?k:u;const W={};for(let b=0;b<g;b++){const O=c[b];O[0]===1&&Yr.has(O[1])&&(W[O[1]]=O[2])}for(const b in W){const O=W[b];b==="fillStyle"||b==="strokeStyle"?typeof O=="string"?(b==="fillStyle"?o=O:p=O,a[b]=ti(O)):a[b]=b==="fillStyle"?o:p:a[b]=O}}const y=xe(e),M=y?y.width:n*l,S=y?y.height:s*l;let _=null,E=null,D=null,I=null,L=null,$=!1;const Y="http://www.w3.org/2000/svg",X="http://www.w3.org/1999/xlink",H=()=>{_||(_=document.createElement("canvas"),_.width=M,_.height=S,E=_.getContext("2d")),E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,_.width,_.height),E.setTransform(l,0,0,l,0,0)},he=()=>{I||(I=document.createElement("canvas"),I.width=M,I.height=S,L=I.getContext("2d"),L.setTransform(l,0,0,l,0,0))},K=G=>{if(!G||!G.hasContent||!_)return;const k=G.bbox;if(!k)return;const W=Math.max(0,Math.floor(k.x*l)),b=Math.max(0,Math.floor(k.y*l)),O=Math.min(_.width,Math.ceil((k.x+k.w)*l)),te=Math.min(_.height,Math.ceil((k.y+k.h)*l)),ce=O-W,De=te-b;if(ce<=0||De<=0)return;let Zt;try{const Qt=document.createElement("canvas");Qt.width=ce,Qt.height=De,Qt.getContext("2d").drawImage(_,W,b,ce,De,0,0,ce,De),Zt=Qt.toDataURL()}catch{return}const Or=a.__defs,Ue=a.__document.createElementNS(Y,"pattern");Ue.setAttribute("id",G.patternId),Ue.setAttribute("patternUnits","userSpaceOnUse"),Ue.setAttribute("x",String(k.x)),Ue.setAttribute("y",String(k.y)),Ue.setAttribute("width",String(k.w)),Ue.setAttribute("height",String(k.h));const We=a.__document.createElementNS(Y,"image");We.setAttribute("x","0"),We.setAttribute("y","0"),We.setAttribute("width",String(k.w)),We.setAttribute("height",String(k.h)),We.setAttributeNS(X,"xlink:href",Zt),We.setAttribute("href",Zt),We.setAttribute("preserveAspectRatio","none"),Ue.appendChild(We),Or.appendChild(Ue)},Qe=()=>{if(!(!I||!$))try{const G=I.toDataURL(),k=a.__defs,W=a.__document.createElementNS(Y,"pattern");W.setAttribute("id",Hr),W.setAttribute("patternUnits","userSpaceOnUse"),W.setAttribute("x","0"),W.setAttribute("y","0"),W.setAttribute("width",String(n)),W.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",G),b.setAttribute("href",G),W.appendChild(b),k.appendChild(W);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",G),O.setAttribute("href",G),a.__root.appendChild(O)}catch{}};let de=!1,oe=!1;for(let G=g;G<c.length;G++){const k=c[G];if(k[0]===5){k[1]==="textStart"?oe=i?Ds(a,e,k[2],r):!1:k[1]==="textEnd"&&(oe=!1);continue}if(oe)continue;if(k[0]===2){if(k[1]==="beginRaster"){const b=k[2];b&&b.bbox&&b.patternId?(H(),D={bbox:b.bbox,patternId:b.patternId,hasContent:!1}):(he(),D=null),de=!0}else k[1]==="endRaster"&&(D&&(K(D),D=null),de=!1);continue}if(k[0]===3){try{Cs(a,k[1],k[2],!0)}catch{}continue}const W=de?D?E:L:a;de&&k[0]===0&&(D?D.hasContent=!0:$=!0);try{if(k[0]===0)if(k[1]==="setTransform"){const b=k[2];W===a?W.setTransform(b[0]*d,b[1]*d,b[2]*d,b[3]*d,b[4]*d,b[5]*d):W.setTransform(b[0],b[1],b[2],b[3],b[4],b[5])}else if((k[1]==="fill"||k[1]==="stroke"||k[1]==="clip")&&k[2]&&k[2][0]&&k[2][0].__p5ExportPath2D){Ms(W,k[2][0]);const b=W[k[1]];typeof b=="function"&&b.apply(W,k[2].slice(1))}else{const b=W[k[1]];typeof b=="function"&&b.apply(W,k[2])}else if(k[1]==="fillStyle"||k[1]==="strokeStyle"){const b=k[2],O=k[1]==="fillStyle";if(typeof b=="string")O?o=b:p=b,W[k[1]]=W===a?ti(b):b;else if(b&&typeof b=="object"&&b.__p5ExportGradId){const te=Jr.get(b.__p5ExportGradId);W===a&&m(te)?W[k[1]]=`url(#${te.id})`:W===a&&(W[k[1]]=O?o:p)}else if(W===a)W[k[1]]=O?o:p;else try{W[k[1]]=b}catch{}}else if(k[1]==="globalCompositeOperation"){if(W[k[1]]=k[2],W===a){const b=k[2],O=a.__currentElement;if(O&&O.setAttribute&&b&&b!=="source-over"){const te=O.getAttribute("style")||"";if(te.indexOf("mix-blend-mode")===-1){const ce=te&&!te.trim().endsWith(";")?";":"";O.setAttribute("style",te+ce+"mix-blend-mode:"+b)}}}}else W[k[1]]=k[2]}catch{}}return D&&K(D),Qe(),a.getSerializedSvg()}function Us(e){const t=e.toDataURL("image/png"),i=e.width,r=e.height;return`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${r}" viewBox="0 0 ${i} ${r}"><image href="${t}" width="${i}" height="${r}"/></svg>`}function Ws(e,t,i){Ts(),t.saveSVG=function(s,a={}){let o;const p=!!this._p5ExportSVGRecorder,w=2e6;let v=0;if(p){const c=this._p5ExportSVGRecorder.ops.slice(),u=this.width||100,g=this.height||100,y=Zr(c,u,g);let M=0;if(y>0){let _=0;for(let E=y-1;E>=0;E--)if(c[E][0]===0){if(c[E][1]==="restore")_++;else if(c[E][1]==="save"){if(_===0){M=E;break}_--}}}let S=!1;for(let _=M;_<c.length;_++){const E=c[_];if(E[0]===2){E[1]==="beginRaster"?S=!0:E[1]==="endRaster"&&(S=!1);continue}E[0]!==5&&(S||v++)}}const m=p&&!a.forceVector&&v>w;if(!a.raster&&(!p||m)&&!a.silent&&typeof window<"u"&&typeof window.confirm=="function"){const c=m?`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
|
|
14
14
|
|
|
15
15
|
${c}
|
|
16
16
|
|
|
@@ -20,14 +20,14 @@ Click Cancel to abort the download.
|
|
|
20
20
|
Tips:
|
|
21
21
|
• Wrap expensive draws in beginRasterRegion()/endRasterRegion() for hybrid output.
|
|
22
22
|
• saveSVG('out', { forceVector: true }) — force vector despite the size.
|
|
23
|
-
• saveSVG('out', { silent: true }) — never prompt; matches old behavior.`))return console.info("[p5.export] saveSVG cancelled by user"),null}if(a.raster||!f||u){const c=xt(this);if(!c)throw new Error("[p5.export] saveSVG: no canvas found");u?console.warn(`[p5.export] saveSVG: ${v.toLocaleString()} vector ops — falling back to raster.`):!f&&!a.raster&&console.info("[p5.export] saveSVG: WebGL renderer detected — embedding canvas as raster <image> in SVG."),o=Ds(c)}else o=tn(this,{outlineText:Qr(this,a)});const d=new Blob([o],{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,o,f,g){const v=this._p5ExportSVGRecorder,u=this._renderer;if(!v||!u||!u.states)return n.apply(this,arguments);const l=u.states,d=l.textFont&&l.textFont.font,c={str:s,x:a,y:o,w:f,h:g,font:d,textSize:l.textSize,textAlign:l.textAlign,textBaseline:l.textBaseline,textLeading:l.textLeading,rectMode:l.rectMode,strokeWeight:l.strokeWeight,hasStroke:!!(l.strokeColor&&l.strokeSet),fill:null,stroke:null};v.ops.push([5,"textStart",c]);let m;try{m=n.apply(this,arguments),c.fill=this.drawingContext.fillStyle,c.hasStroke&&(c.stroke=this.drawingContext.strokeStyle)}finally{v.ops.push([5,"textEnd"])}return m}),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 o=i.predraw;i.predraw=function(){typeof o=="function"&&o.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(),o=a==="JPEG"?"image/jpeg":a==="WEBP"?"image/webp":"image/png",f=n.width,g=n.height,v=a==="JPEG"?"jpg":a==="WEBP"?"webp":"png",u=r.scale;let l;if(!u||u<=1||u<=(this.pixelDensity?this.pixelDensity():1))l=n.toDataURL(o,r.quality);else{const L=await Lr(this,u,v,r.quality);L?l=await Ws(L):l=await Gr(this,u,()=>xt(this).toDataURL(o,r.quality))}const d=r.unit||"pt",c=r.orientation||(f>=g?"l":"p"),m=r.format||[f,g],w=new s({orientation:c,unit:d,format:m}),y=w.internal.pageSize.getWidth(),M=w.internal.pageSize.getHeight(),S=Math.min(y/f,M/g),_=f*S,E=g*S,D=(y-_)/2,I=(M-E)/2;return w.addImage(l,a,D,I,_,E),w.save(i?_t(i,"pdf"):bt("pdf")),w}}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 o=0;o<a;o++)i[e++]=n[o+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 o=i;i=new Uint8Array(n),e>0&&i.set(o.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),o=new Int32Array(rn)){let f=a.length,g=Math.max(2,r);s.fill(0),o.fill(0),a.fill(-1);let v=0,u=0,l=g+1,d=l,c=!1,m=d,w=(1<<m)-1,y=1<<l-1,M=y+1,S=y+2,_=0,E=i[0],D=0;for(let $=f;$<65536;$*=2)++D;D=8-D,n.writeByte(g),L(y);let I=i.length;for(let $=1;$<I;$++)t:{let Y=i[$],X=(Y<<Wi)+E,H=Y<<D^E;if(a[H]===X){E=o[H];break t}let ht=H===0?1:f-H;for(;a[H]>=0;)if(H-=ht,H<0&&(H+=f),a[H]===X){E=o[H];break t}L(E),E=Y,S<1<<Wi?(o[H]=S++,a[H]=X):(a.fill(-1),S=y+2,c=!0,L(y))}return L(E),L(M),n.writeByte(0),n.bytesView();function L($){for(v&=Ls[u],u>0?v|=$<<u:v=$,u+=m;u>=8;)s[_++]=v&255,_>=254&&(n.writeByte(_),n.writeBytesView(s,0,_),_=0),v>>=8,u-=8;if((S>w||c)&&(c?(m=d,w=(1<<m)-1,c=!1):(++m,w=m===Wi?1<<m:(1<<m)-1)),$==M){for(;u>0;)s[_++]=v&255,_>=254&&(n.writeByte(_),n.writeBytesView(s,0,_),_=0),v>>=8,u-=8;_>0&&(n.writeByte(_),n.writeBytesView(s,0,_),_=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 o=s.rc,f=s.gc,g=s.bc;for(var v=s.fw;v!=0;v=t[v].fw){let l=t[v],d=l.cnt,c=a*d/(a+d);if(!(c>=n)){var u=0;u+=c*ni(l.rc-o),!(u>=n)&&(u+=c*ni(l.gc-f),!(u>=n)&&(u+=c*ni(l.bc-g),!(u>=n)&&(n=u,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],o=a>>24&255,f=a>>16&255,g=a>>8&255,v=a&255,u=sn(v,g,f,o),l=u in r?r[u]:r[u]=zi();l.rc+=v,l.gc+=g,l.bc+=f,l.ac+=o,l.cnt++}else if(e==="rgb444")for(let s=0;s<n;++s){let a=t[s],o=a>>16&255,f=a>>8&255,g=a&255,v=an(g,f,o),u=v in r?r[v]:r[v]=zi();u.rc+=g,u.gc+=f,u.bc+=o,u.cnt++}else for(let s=0;s<n;++s){let a=t[s],o=a>>16&255,f=a>>8&255,g=a&255,v=nn(g,f,o),u=v in r?r[v]:r[v]=zi();u.rc+=g,u.gc+=f,u.bc+=o,u.cnt++}return r}function ln(t,e,i={}){let{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:a=0,oneBitAlpha:o=!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 f=new Uint32Array(t.buffer),g=i.useSqrt!==!1,v=r==="rgba4444",u=$s(f,r),l=u.length,d=l-1,c=new Uint32Array(l+1);for(var m=0,w=0;w<l;++w){let K=u[w];if(K!=null){var y=1/K.cnt;v&&(K.ac*=y),K.rc*=y,K.gc*=y,K.bc*=y,u[m++]=K}}ni(e)/m<.022&&(g=!1);for(var w=0;w<m-1;++w)u[w].fw=w+1,u[w+1].bk=w,g&&(u[w].cnt=Math.sqrt(u[w].cnt));g&&(u[w].cnt=Math.sqrt(u[w].cnt));var M,S,_;for(w=0;w<m;++w){on(u,w);var E=u[w].err;for(S=++c[0];S>1&&(_=S>>1,!(u[M=c[_]].err<=E));S=_)c[S]=M;c[S]=w}var D=m-e;for(w=0;w<D;){for(var I;;){var L=c[1];if(I=u[L],I.tm>=I.mtm&&u[I.nn].mtm<=I.tm)break;I.mtm==d?L=c[1]=c[c[0]--]:(on(u,L),I.tm=w);var E=u[L].err;for(S=1;(_=S+S)<=c[0]&&(_<c[0]&&u[c[_]].err>u[c[_+1]].err&&_++,!(E<=u[M=c[_]].err));S=_)c[S]=M;c[S]=L}var $=u[I.nn],Y=I.cnt,X=$.cnt,y=1/(Y+X);v&&(I.ac=y*(Y*I.ac+X*$.ac)),I.rc=y*(Y*I.rc+X*$.rc),I.gc=y*(Y*I.gc+X*$.gc),I.bc=y*(Y*I.bc+X*$.bc),I.cnt+=$.cnt,I.mtm=++w,u[$.bk].fw=$.fw,u[$.fw].bk=$.bk,$.mtm=d}let H=[];var ht=0;for(w=0;;++ht){let K=ri(Math.round(u[w].rc),0,255),Qt=ri(Math.round(u[w].gc),0,255),dt=ri(Math.round(u[w].bc),0,255),ot=255;v&&(ot=ri(Math.round(u[w].ac),0,255),o&&(ot=ot<=(typeof o=="number"?o:127)?0:255),n&&ot<=a&&(K=Qt=dt=s,ot=0));let G=v?[K,Qt,dt,ot]:[K,Qt,dt];if(js(H,G)||H.push(G),(w=u[w].fw)==0)break}return H}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),o=new Array(s);if(i==="rgba4444")for(let f=0;f<n;f++){let g=r[f],v=g>>24&255,u=g>>16&255,l=g>>8&255,d=g&255,c=sn(d,l,u,v),m=c in o?o[c]:o[c]=Hs(d,l,u,v,e);a[f]=m}else{let f=i==="rgb444"?an:nn;for(let g=0;g<n;g++){let v=r[g],u=v>>16&255,l=v>>8&255,d=v&255,c=f(d,l,u),m=c in o?o[c]:o[c]=qs(d,l,u,e);a[g]=m}}return a}function Hs(t,e,i,r,n){let s=0,a=1e100;for(let o=0;o<n.length;o++){let f=n[o],g=f[3],v=Ot(g-r);if(v>a)continue;let u=f[0];if(v+=Ot(u-t),v>a)continue;let l=f[1];if(v+=Ot(l-e),v>a)continue;let d=f[2];v+=Ot(d-i),!(v>a)&&(a=v,s=o)}return s}function qs(t,e,i,r){let n=0,s=1e100;for(let a=0;a<r.length;a++){let o=r[a],f=o[0],g=Ot(f-t);if(g>s)continue;let v=o[1];if(g+=Ot(v-e),g>s)continue;let u=o[2];g+=Ot(u-i),!(g>s)&&(s=g,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),o=new Int32Array(n),f=!1;return{reset(){r.reset(),f=!1},finish(){r.writeByte(Vs.trailer)},bytes(){return r.bytes()},bytesView(){return r.bytesView()},get buffer(){return r.buffer},get stream(){return r},writeHeader:g,writeFrame(v,u,l,d={}){let{transparent:c=!1,transparentIndex:m=0,delay:w=0,palette:y=null,repeat:M=0,colorDepth:S=8,dispose:_=-1}=d,E=!1;if(i?f||(E=!0,g(),f=!0):E=!!d.first,u=Math.max(0,Math.floor(u)),l=Math.max(0,Math.floor(l)),E){if(!y)throw new Error("First frame must include a { palette } option");Ys(r,u,l,y,S),cn(r,y),M>=0&&Js(r,M)}let D=Math.round(w/10);Xs(r,_,D,c,m);let I=!!y&&!E;Ks(r,u,l,I?y:null),I&&cn(r,y),Zs(r,v,u,l,S,s,a,o)}};function g(){pn(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,o=Oi(r.length)-1,f=s<<7|n-1<<4|a<<3|o;Pt(t,e),Pt(t,i),t.writeBytes([f,0,0])}function Js(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),pn(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,o){Ns(i,r,e,n,t,s,a,o)}function Pt(t,e){t.writeByte(e&255),t.writeByte(e>>8&255)}function pn(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),o=hn(s.data,a);e.writeFrame(o,s.width,s.height,{palette:a,delay:i}),this.onProgress((n+1)/r),n%4===3&&await new Promise(f=>setTimeout(f,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)},p=(t,e,i)=>(Vi(t,e,"read from private field"),i?i.call(t):e.get(t)),U=(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 p(t,e,r)}}),z=(t,e,i)=>(Vi(t,e,"access private method"),i),V=new Uint8Array(8),pt=new DataView(V.buffer),Z=t=>[(t%256+256)%256],j=t=>(pt.setUint16(0,t,!1),[V[0],V[1]]),ra=t=>(pt.setInt16(0,t,!1),[V[0],V[1]]),fn=t=>(pt.setUint32(0,t,!1),[V[1],V[2],V[3]]),C=t=>(pt.setUint32(0,t,!1),[V[0],V[1],V[2],V[3]]),na=t=>(pt.setInt32(0,t,!1),[V[0],V[1],V[2],V[3]]),Vt=t=>(pt.setUint32(0,Math.floor(t/2**32),!1),pt.setUint32(4,t,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Li=t=>(pt.setInt16(0,2**8*t,!1),[V[0],V[1]]),ft=t=>(pt.setInt32(0,2**16*t,!1),[V[0],V[1],V[2],V[3]]),Gi=t=>(pt.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},ut=(t,e,i=!0)=>{let r=t*e;return i?Math.round(r):r},un=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=un(0),gn=t=>[ft(t[0]),ft(t[1]),Gi(t[2]),ft(t[3]),ft(t[4]),Gi(t[5]),ft(t[6]),ft(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}),q=(t,e,i,r,n)=>J(t,[Z(e),fn(i),r??[]],n),sa=t=>{let e=512;return t.fragmented?J("ftyp",[lt("iso5"),C(e),lt("iso5"),lt("iso6"),lt("mp41")]):J("ftyp",[lt("isom"),C(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=ut(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=Ni(a.samples);return o.presentationTimestamp+o.duration})),Ji),r=Math.max(...e.map(a=>a.id))+1,n=!ee(t)||!ee(i),s=n?Vt:C;return q("mvhd",+n,0,[s(t),s(t),C(Ji),s(i),ft(1),Li(1),Array(10).fill(0),gn(mn),Array(24).fill(0),C(r)])},la=(t,e)=>J("trak",null,[ha(t,e),da(t,e)]),ha=(t,e)=>{let i=Ni(t.samples),r=ut(i?i.presentationTimestamp+i.duration:0,Ji),n=!ee(e)||!ee(r),s=n?Vt:C,a;return t.info.type==="video"?a=typeof t.info.rotation=="number"?un(t.info.rotation):t.info.rotation:a=mn,q("tkhd",+n,3,[s(e),s(e),C(t.id),C(0),s(r),Array(8).fill(0),j(0),j(0),Li(t.info.type==="audio"?1:0),j(0),gn(a),ft(t.info.type==="video"?t.info.width:0),ft(t.info.type==="video"?t.info.height:0)])},da=(t,e)=>J("mdia",null,[ca(t,e),pa(t.info.type==="video"?"vide":"soun"),fa(t)]),ca=(t,e)=>{let i=Ni(t.samples),r=ut(i?i.presentationTimestamp+i.duration:0,t.timescale),n=!ee(e)||!ee(r),s=n?Vt:C;return q("mdhd",+n,0,[s(e),s(e),C(t.timescale),s(r),j(21956),j(0)])},pa=t=>q("hdlr",0,0,[lt("mhlr"),lt(t),C(0),C(0),C(0),lt("mp4-muxer-hdlr",!0)]),fa=t=>J("minf",null,[t.info.type==="video"?ua():ma(),ga(),ya(t)]),ua=()=>q("vmhd",0,1,[j(0),j(0),j(0),j(0)]),ma=()=>q("smhd",0,0,[j(0),j(0)]),ga=()=>J("dinf",null,[wa()]),wa=()=>q("dref",0,0,[C(1)],[va()]),va=()=>q("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=>q("stsd",0,0,[C(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),j(1),j(0),j(0),Array(12).fill(0),j(e.info.width),j(e.info.height),C(4718592),C(4718592),C(0),j(1),Array(32).fill(0),j(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"),j(xa[t.info.decoderConfig.colorSpace.primaries]),j(Sa[t.info.decoderConfig.colorSpace.transfer]),j(Ca[t.info.decoderConfig.colorSpace.matrix]),Z((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),ka=t=>t.info.decoderConfig&&J("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),Ta=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]),o=(Number(i[3])<<4)+(0<<1)+Number(e.colorSpace.fullRange);return q("vpcC",1,0,[Z(r),Z(n),Z(o),Z(2),Z(2),Z(2),j(0)])},Ma=()=>{let i=(1<<7)+1;return J("av1C",[i,0,0,0])},Pa=(t,e)=>J(t,[Array(6).fill(0),j(1),j(0),j(0),C(0),j(e.info.numberOfChannels),j(16),j(0),j(0),ft(e.info.sampleRate)],[Za[e.info.codec](e)]),Ia=t=>{let e=new Uint8Array(t.info.decoderConfig.description);return q("esds",0,0,[C(58753152),Z(32+e.byteLength),j(1),Z(0),C(75530368),Z(18+e.byteLength),Z(64),Z(21),fn(0),C(130071),C(130071),C(92307584),Z(e.byteLength),...e,C(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),j(e),C(t.info.sampleRate),Li(i),Z(0)])},Ba=t=>q("stts",0,0,[C(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[C(e.sampleCount),C(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 q("stss",0,0,[C(e.length),e.map(([i])=>C(i+1))])},Da=t=>q("stsc",0,0,[C(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[C(e.firstChunk),C(e.samplesPerChunk),C(1)])]),Ua=t=>q("stsz",0,0,[C(0),C(t.samples.length),t.samples.map(e=>C(e.size))]),Wa=t=>t.finalizedChunks.length>0&&si(t.finalizedChunks).offset>=2**32?q("co64",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>Vt(e.offset))]):q("stco",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>C(e.offset))]),za=t=>q("ctts",0,0,[C(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[C(e.sampleCount),C(e.sampleCompositionTimeOffset)])]),Oa=t=>J("mvex",null,t.map(Va)),Va=t=>q("trex",0,0,[C(t.id),C(1),C(0),C(0),C(0)]),wn=(t,e)=>J("moof",null,[La(t),...e.map(Ga)]),La=t=>q("mfhd",0,0,[C(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 q("tfhd",0,e,[C(t.id),C(r.duration),C(r.size),C(r.flags)])},$a=t=>q("tfdt",1,0,[Vt(ut(t.currentChunk.startTimestamp,t.timescale))]),ja=t=>{let e=t.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(m=>m.size),r=t.currentChunk.samples.map(vn),n=t.currentChunk.samples.map(m=>ut(m.presentationTimestamp-m.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(i),o=new Set(r),f=new Set(n),g=o.size===2&&r[0]!==r[1],v=s.size>1,u=a.size>1,l=!g&&o.size>1,d=f.size>1||[...f].some(m=>m!==0),c=0;return c|=1,c|=4*+g,c|=256*+v,c|=512*+u,c|=1024*+l,c|=2048*+d,q("trun",1,c,[C(t.currentChunk.samples.length),C(t.currentChunk.offset-t.currentChunk.moofOffset||0),g?C(r[0]):[],t.currentChunk.samples.map((m,w)=>[v?C(e[w]):[],u?C(i[w]):[],l?C(r[w]):[],d?na(n[w]):[]])])},Ha=t=>J("mfra",null,[...t.map(qa),Xa()]),qa=(t,e)=>q("tfra",1,0,[C(t.id),C(63),C(t.finalizedChunks.length),t.finalizedChunks.map(r=>[Vt(ut(r.startTimestamp,t.timescale)),Vt(r.moofOffset),C(e+1),C(1),C(1)])]),Xa=()=>q("mfro",0,0,[C(0)]),Ya={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},Ja={avc:ka,hevc:Ta,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,U(this,Lt,new Uint8Array(8)),U(this,ie,new DataView(p(this,Lt).buffer)),this.offsets=new WeakMap}seek(e){this.pos=e}writeU32(e){p(this,ie).setUint32(0,e,!1),this.write(p(this,Lt).subarray(0,4))}writeU64(e){p(this,ie).setUint32(0,Math.floor(e/2**32),!1),p(this,ie).setUint32(4,e,!1),this.write(p(this,Lt).subarray(0,8))}writeAscii(e){for(let i=0;i<e.length;i++)p(this,ie).setUint8(i%8,e.charCodeAt(i)),i%8===7&&this.write(p(this,Lt));e.length%8!==0&&this.write(p(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(),U(this,hi),U(this,li,void 0),U(this,Gt,new ArrayBuffer(2**16)),U(this,Se,new Uint8Array(p(this,Gt))),U(this,Ce,0),Q(this,li,e)}write(e){z(this,hi,ji).call(this,this.pos+e.byteLength),p(this,Se).set(e,this.pos),this.pos+=e.byteLength,Q(this,Ce,Math.max(p(this,Ce),this.pos))}finalize(){z(this,hi,ji).call(this,this.pos),p(this,li).buffer=p(this,Gt).slice(0,Math.max(p(this,Ce),this.pos))}};li=new WeakMap,Gt=new WeakMap,Se=new WeakMap,Ce=new WeakMap,hi=new WeakSet,ji=function(t){let e=p(this,Gt).byteLength;for(;e<t;)e*=2;if(e===p(this,Gt).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(p(this,Se),0),Q(this,Gt,i),Q(this,Se,r)};var eo=2**24,io=2,Ee,Nt,ke,Ct,nt,di,Hi,qi,xn,Xi,Sn,Te,ci,Yi=class extends _n{constructor(e){var i,r;super(),U(this,di),U(this,qi),U(this,Xi),U(this,Te),U(this,Ee,void 0),U(this,Nt,[]),U(this,ke,void 0),U(this,Ct,void 0),U(this,nt,[]),Q(this,Ee,e),Q(this,ke,((i=e.options)==null?void 0:i.chunked)??!1),Q(this,Ct,((r=e.options)==null?void 0:r.chunkSize)??eo)}write(e){p(this,Nt).push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}flush(){var r,n;if(p(this,Nt).length===0)return;let e=[],i=[...p(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],o=i[s];o.start<=a.start+a.size?a.size=Math.max(a.size,o.start+o.data.byteLength-a.start):e.push({start:o.start,size:o.data.byteLength})}for(let s of e){s.data=new Uint8Array(s.size);for(let a of p(this,Nt))s.start<=a.start&&a.start<s.start+s.size&&s.data.set(a.data,a.start-s.start);p(this,ke)?(z(this,di,Hi).call(this,s.data,s.start),z(this,Te,ci).call(this)):(n=(r=p(this,Ee).options).onData)==null||n.call(r,s.data,s.start)}p(this,Nt).length=0}finalize(){p(this,ke)&&z(this,Te,ci).call(this,!0)}};Ee=new WeakMap,Nt=new WeakMap,ke=new WeakMap,Ct=new WeakMap,nt=new WeakMap,di=new WeakSet,Hi=function(t,e){let i=p(this,nt).findIndex(o=>o.start<=e&&e<o.start+p(this,Ct));i===-1&&(i=z(this,Xi,Sn).call(this,e));let r=p(this,nt)[i],n=e-r.start,s=t.subarray(0,Math.min(p(this,Ct)-n,t.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(z(this,qi,xn).call(this,r,a),r.written[0].start===0&&r.written[0].end===p(this,Ct)&&(r.shouldFlush=!0),p(this,nt).length>io){for(let o=0;o<p(this,nt).length-1;o++)p(this,nt)[o].shouldFlush=!0;z(this,Te,ci).call(this)}s.byteLength<t.byteLength&&z(this,di,Hi).call(this,t.subarray(s.byteLength),e+s.byteLength)},qi=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/p(this,Ct))*p(this,Ct),data:new Uint8Array(p(this,Ct)),written:[],shouldFlush:!1};return p(this,nt).push(i),p(this,nt).sort((r,n)=>r.start-n.start),p(this,nt).indexOf(i)},Te=new WeakSet,ci=function(t=!1){var e,i;for(let r=0;r<p(this,nt).length;r++){let n=p(this,nt)[r];if(!(!n.shouldFlush&&!t)){for(let s of n.written)(i=(e=p(this,Ee).options).onData)==null||i.call(e,n.data.subarray(s.start,s.end),n.start+s.start);p(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,pi,st,it,tt,re,ne,Ki,$t,jt,Ae,Zi,Cn,Qi,En,tr,kn,er,Tn,ir,An,fi,rr,mt,Et,nr,Mn,Me,ui,mi,sr,se,Pe,gi,ar,lo=class{constructor(e){if(U(this,Zi),U(this,Qi),U(this,tr),U(this,er),U(this,ir),U(this,fi),U(this,mt),U(this,nr),U(this,Me),U(this,mi),U(this,se),U(this,gi),U(this,P,void 0),U(this,B,void 0),U(this,pi,void 0),U(this,st,void 0),U(this,it,null),U(this,tt,null),U(this,re,Math.floor(Date.now()/1e3)+ao),U(this,ne,[]),U(this,Ki,1),U(this,$t,[]),U(this,jt,[]),U(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,Tn).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,gi,ar).call(this),!p(this,P).video)throw new Error("No video track declared.");if(typeof p(this,P).fastStart=="object"&&p(this,it).samples.length===p(this,P).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${p(this,P).fastStart.expectedVideoChunks}).`);let o=z(this,fi,rr).call(this,p(this,it),e,i,r,n,s,a);if(p(this,P).fastStart==="fragmented"&&p(this,tt)){for(;p(this,jt).length>0&&p(this,jt)[0].decodeTimestamp<=o.decodeTimestamp;){let f=p(this,jt).shift();z(this,mt,Et).call(this,p(this,tt),f)}o.decodeTimestamp<=p(this,tt).lastDecodeTimestamp?z(this,mt,Et).call(this,p(this,it),o):p(this,$t).push(o)}else z(this,mt,Et).call(this,p(this,it),o)}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,gi,ar).call(this),!p(this,P).audio)throw new Error("No audio track declared.");if(typeof p(this,P).fastStart=="object"&&p(this,tt).samples.length===p(this,P).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${p(this,P).fastStart.expectedAudioChunks}).`);let a=z(this,fi,rr).call(this,p(this,tt),e,i,r,n,s);if(p(this,P).fastStart==="fragmented"&&p(this,it)){for(;p(this,$t).length>0&&p(this,$t)[0].decodeTimestamp<=a.decodeTimestamp;){let o=p(this,$t).shift();z(this,mt,Et).call(this,p(this,it),o)}a.decodeTimestamp<=p(this,it).lastDecodeTimestamp?z(this,mt,Et).call(this,p(this,tt),a):p(this,jt).push(a)}else z(this,mt,Et).call(this,p(this,tt),a)}finalize(){if(p(this,Ae))throw new Error("Cannot finalize a muxer more than once.");if(p(this,P).fastStart==="fragmented"){for(let i of p(this,$t))z(this,mt,Et).call(this,p(this,it),i);for(let i of p(this,jt))z(this,mt,Et).call(this,p(this,tt),i);z(this,mi,sr).call(this,!1)}else p(this,it)&&z(this,Me,ui).call(this,p(this,it)),p(this,tt)&&z(this,Me,ui).call(this,p(this,tt));let e=[p(this,it),p(this,tt)].filter(Boolean);if(p(this,P).fastStart==="in-memory"){let i;for(let n=0;n<2;n++){let s=ai(e,p(this,re)),a=p(this,B).measureBox(s);i=p(this,B).measureBox(p(this,st));let o=p(this,B).pos+a+i;for(let f of p(this,ne)){f.offset=o;for(let{data:g}of f.samples)o+=g.byteLength,i+=g.byteLength}if(o<2**32)break;i>=2**32&&(p(this,st).largeSize=!0)}let r=ai(e,p(this,re));p(this,B).writeBox(r),p(this,st).size=i,p(this,B).writeBox(p(this,st));for(let n of p(this,ne))for(let s of n.samples)p(this,B).write(s.data),s.data=null}else if(p(this,P).fastStart==="fragmented"){let i=p(this,B).pos,r=Ha(e);p(this,B).writeBox(r);let n=p(this,B).pos-i;p(this,B).seek(p(this,B).pos-4),p(this,B).writeU32(n)}else{let i=p(this,B).offsets.get(p(this,st)),r=p(this,B).pos-i;p(this,st).size=r,p(this,st).largeSize=r>=2**32,p(this,B).patchBox(p(this,st));let n=ai(e,p(this,re));if(typeof p(this,P).fastStart=="object"){p(this,B).seek(p(this,pi)),p(this,B).writeBox(n);let s=i-p(this,B).pos;p(this,B).writeBox(aa(s))}else p(this,B).writeBox(n)}z(this,se,Pe).call(this),p(this,B).finalize(),Q(this,Ae,!0)}};P=new WeakMap,B=new WeakMap,pi=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(p(this,B).writeBox(sa({holdsAvc:((t=p(this,P).video)==null?void 0:t.codec)==="avc",fragmented:p(this,P).fastStart==="fragmented"})),Q(this,pi,p(this,B).pos),p(this,P).fastStart==="in-memory")Q(this,st,$i(!1));else if(p(this,P).fastStart!=="fragmented"){if(typeof p(this,P).fastStart=="object"){let e=z(this,tr,kn).call(this);p(this,B).seek(p(this,B).pos+e)}Q(this,st,$i(!0)),p(this,B).writeBox(p(this,st))}z(this,se,Pe).call(this)},tr=new WeakSet,kn=function(){if(typeof p(this,P).fastStart!="object")return;let t=0,e=[p(this,P).fastStart.expectedVideoChunks,p(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,Tn=function(){if(p(this,P).video&&Q(this,it,{id:1,info:{type:"video",codec:p(this,P).video.codec,width:p(this,P).video.width,height:p(this,P).video.height,rotation:p(this,P).video.rotation??0,decoderConfig:null},timescale:p(this,P).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),p(this,P).audio&&(Q(this,tt,{id:p(this,P).video?2:1,info:{type:"audio",codec:p(this,P).audio.codec,numberOfChannels:p(this,P).audio.numberOfChannels,sampleRate:p(this,P).audio.sampleRate,decoderConfig:null},timescale:p(this,P).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),p(this,P).audio.codec==="aac")){let t=z(this,ir,An).call(this,2,p(this,P).audio.sampleRate,p(this,P).audio.numberOfChannels);p(this,tt).info.decoderConfig={codec:p(this,P).audio.codec,description:t,numberOfChannels:p(this,P).audio.numberOfChannels,sampleRate:p(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 o=Math.ceil(a.length/8)*8;a=a.padEnd(o,"0");let f=new Uint8Array(a.length/8);for(let g=0;g<a.length;g+=8)f[g/8]=parseInt(a.slice(g,g+8),2);return f},fi=new WeakSet,rr=function(t,e,i,r,n,s,a){let o=r/1e6,f=(r-(a??0))/1e6,g=n/1e6,v=z(this,nr,Mn).call(this,o,f,t);return o=v.presentationTimestamp,f=v.decodeTimestamp,s!=null&&s.decoderConfig&&(t.info.decoderConfig===null?t.info.decoderConfig=s.decoderConfig:Object.assign(t.info.decoderConfig,s.decoderConfig)),{presentationTimestamp:o,decodeTimestamp:f,duration:g,data:e,size:e.byteLength,type:i,timescaleUnitsToNextSample:ut(g,t.timescale)}},mt=new WeakSet,Et=function(t,e){p(this,P).fastStart!=="fragmented"&&t.samples.push(e);const i=ut(e.presentationTimestamp-e.decodeTimestamp,t.timescale);if(t.lastTimescaleUnits!==null){let n=ut(e.decodeTimestamp,t.timescale,!1),s=Math.round(n-t.lastTimescaleUnits);if(t.lastTimescaleUnits+=s,t.lastSample.timescaleUnitsToNextSample=s,p(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 o=si(t.compositionTimeOffsetTable);o.sampleCompositionTimeOffset===i?o.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else t.lastTimescaleUnits=0,p(this,P).fastStart!=="fragmented"&&(t.timeToSampleTable.push({sampleCount:1,sampleDelta:ut(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(p(this,P).fastStart==="fragmented"){let s=p(this,it)??p(this,tt);const a=p(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,ui).call(this,t),t.currentChunk={startTimestamp:e.presentationTimestamp,samples:[]}),t.currentChunk.samples.push(e)},nr=new WeakSet,Mn=function(t,e,i){var a,o;const r=p(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
|
+
• saveSVG('out', { silent: true }) — never prompt; matches old behavior.`))return console.info("[p5.export] saveSVG cancelled by user"),null}if(a.raster||!p||m){const c=xe(this);if(!c)throw new Error("[p5.export] saveSVG: no canvas found");m?console.warn(`[p5.export] saveSVG: ${v.toLocaleString()} vector ops — falling back to raster.`):!p&&!a.raster&&console.info("[p5.export] saveSVG: WebGL renderer detected — embedding canvas as raster <image> in SVG."),o=Us(c)}else o=en(this,{outlineText:Qr(this,a)});const d=new Blob([o],{type:"image/svg+xml"});return re(d,s?_e(s,"svg"):be("svg")),d},t.getSVG=function(s={}){return this._p5ExportSVGRecorder?en(this,{outlineText:Qr(this,s)}):""},t.setSVGTextMode=function(s){this._p5ExportSVGRecorder&&(this._p5ExportSVGRecorder.textOutline=s==="outline")},t.clearSVGRecording=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.clear()},t.beginRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"beginRaster"])},t.endRasterRegion=function(){this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.ops.push([2,"endRaster"])},t.rasterize=function(s){this.beginRasterRegion();try{return s.call(this)}finally{this.endRasterRegion()}},t.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=t.createCanvas;typeof r=="function"&&(t.createCanvas=function(...s){const a=r.apply(this,s);this._p5ExportSVGRecorder=null,Kr(this);try{jr(e,this)}catch{}return a});const n=t.text;if(typeof n=="function"&&(t.text=function(s,a,o,p,w){const v=this._p5ExportSVGRecorder,m=this._renderer;if(!v||!m||!m.states)return n.apply(this,arguments);const l=m.states,d=l.textFont&&l.textFont.font,c={str:s,x:a,y:o,w:p,h:w,font:d,textSize:l.textSize,textAlign:l.textAlign,textBaseline:l.textBaseline,textLeading:l.textLeading,rectMode:l.rectMode,strokeWeight:l.strokeWeight,hasStroke:!!(l.strokeColor&&l.strokeSet),fill:null,stroke:null};v.ops.push([5,"textStart",c]);let u;try{u=n.apply(this,arguments),c.fill=this.drawingContext.fillStyle,c.hasStroke&&(c.stroke=this.drawingContext.strokeStyle)}finally{v.ops.push([5,"textEnd"])}return u}),i&&typeof i=="object"){const s=i.presetup;i.presetup=function(){typeof s=="function"&&s.call(this);try{jr(e,this)}catch{}};const a=i.postsetup;i.postsetup=function(){typeof a=="function"&&a.call(this),Kr(this)};const o=i.predraw;i.predraw=function(){typeof o=="function"&&o.call(this),this._p5ExportSVGRecorder&&this._p5ExportSVGRecorder.markFrameBoundary()}}}function zs(e){return new Promise((t,i)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=i,r.readAsDataURL(e)})}let ii=null;function Os(){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 e=await import("jspdf");if(e&&e.jsPDF)return e.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 Vs(e,t){t.savePDF=async function(i,r={}){const n=xe(this);if(!n)throw new Error("[p5.export] savePDF: no canvas found");const s=await Os(),a=(r.imageFormat||"png").toUpperCase(),o=a==="JPEG"?"image/jpeg":a==="WEBP"?"image/webp":"image/png",p=n.width,w=n.height,v=a==="JPEG"?"jpg":a==="WEBP"?"webp":"png",m=r.scale;let l;if(!m||m<=1||m<=(this.pixelDensity?this.pixelDensity():1))l=n.toDataURL(o,r.quality);else{const L=await Lr(this,m,v,r.quality);L?l=await zs(L):l=await Gr(this,m,()=>xe(this).toDataURL(o,r.quality))}const d=r.unit||"pt",c=r.orientation||(p>=w?"l":"p"),u=r.format||[p,w],g=new s({orientation:c,unit:d,format:u}),y=g.internal.pageSize.getWidth(),M=g.internal.pageSize.getHeight(),S=Math.min(y/p,M/w),_=p*S,E=w*S,D=(y-_)/2,I=(M-E)/2;return g.addImage(l,a,D,I,_,E),g.save(i?_e(i,"pdf"):be("pdf")),g}}var Ls={trailer:59};function tn(e=256){let t=0,i=new Uint8Array(e);return{get buffer(){return i.buffer},reset(){t=0},bytesView(){return i.subarray(0,t)},bytes(){return i.slice(0,t)},writeByte(n){r(t+1),i[t]=n,t++},writeBytes(n,s=0,a=n.length){r(t+a);for(let o=0;o<a;o++)i[t++]=n[o+s]},writeBytesView(n,s=0,a=n.byteLength){r(t+a),i.set(n.subarray(s,s+a),t),t+=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 o=i;i=new Uint8Array(n),t>0&&i.set(o.subarray(0,t),0)}}var zi=12,rn=5003,Gs=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function Ns(e,t,i,r,n=tn(512),s=new Uint8Array(256),a=new Int32Array(rn),o=new Int32Array(rn)){let p=a.length,w=Math.max(2,r);s.fill(0),o.fill(0),a.fill(-1);let v=0,m=0,l=w+1,d=l,c=!1,u=d,g=(1<<u)-1,y=1<<l-1,M=y+1,S=y+2,_=0,E=i[0],D=0;for(let $=p;$<65536;$*=2)++D;D=8-D,n.writeByte(w),L(y);let I=i.length;for(let $=1;$<I;$++)e:{let Y=i[$],X=(Y<<zi)+E,H=Y<<D^E;if(a[H]===X){E=o[H];break e}let he=H===0?1:p-H;for(;a[H]>=0;)if(H-=he,H<0&&(H+=p),a[H]===X){E=o[H];break e}L(E),E=Y,S<1<<zi?(o[H]=S++,a[H]=X):(a.fill(-1),S=y+2,c=!0,L(y))}return L(E),L(M),n.writeByte(0),n.bytesView();function L($){for(v&=Gs[m],m>0?v|=$<<m:v=$,m+=u;m>=8;)s[_++]=v&255,_>=254&&(n.writeByte(_),n.writeBytesView(s,0,_),_=0),v>>=8,m-=8;if((S>g||c)&&(c?(u=d,g=(1<<u)-1,c=!1):(++u,g=u===zi?1<<u:(1<<u)-1)),$==M){for(;m>0;)s[_++]=v&255,_>=254&&(n.writeByte(_),n.writeBytesView(s,0,_),_=0),v>>=8,m-=8;_>0&&(n.writeByte(_),n.writeBytesView(s,0,_),_=0)}}}var $s=Ns;function nn(e,t,i){return e<<8&63488|t<<2&992|i>>3}function sn(e,t,i,r){return e>>4|t&240|(i&240)<<4|(r&240)<<8}function an(e,t,i){return e>>4<<8|t&240|i>>4}function ri(e,t,i){return e<t?t:e>i?i:e}function ni(e){return e*e}function on(e,t,i){var r=0,n=1e100;let s=e[t],a=s.cnt;s.ac;let o=s.rc,p=s.gc,w=s.bc;for(var v=s.fw;v!=0;v=e[v].fw){let l=e[v],d=l.cnt,c=a*d/(a+d);if(!(c>=n)){var m=0;m+=c*ni(l.rc-o),!(m>=n)&&(m+=c*ni(l.gc-p),!(m>=n)&&(m+=c*ni(l.bc-w),!(m>=n)&&(n=m,r=v)))}}s.err=n,s.nn=r}function Oi(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function js(e,t){let i=t==="rgb444"?4096:65536,r=new Array(i),n=e.length;if(t==="rgba4444")for(let s=0;s<n;++s){let a=e[s],o=a>>24&255,p=a>>16&255,w=a>>8&255,v=a&255,m=sn(v,w,p,o),l=m in r?r[m]:r[m]=Oi();l.rc+=v,l.gc+=w,l.bc+=p,l.ac+=o,l.cnt++}else if(t==="rgb444")for(let s=0;s<n;++s){let a=e[s],o=a>>16&255,p=a>>8&255,w=a&255,v=an(w,p,o),m=v in r?r[v]:r[v]=Oi();m.rc+=w,m.gc+=p,m.bc+=o,m.cnt++}else for(let s=0;s<n;++s){let a=e[s],o=a>>16&255,p=a>>8&255,w=a&255,v=nn(w,p,o),m=v in r?r[v]:r[v]=Oi();m.rc+=w,m.gc+=p,m.bc+=o,m.cnt++}return r}function ln(e,t,i={}){let{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:a=0,oneBitAlpha:o=!1}=i;if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let p=new Uint32Array(e.buffer),w=i.useSqrt!==!1,v=r==="rgba4444",m=js(p,r),l=m.length,d=l-1,c=new Uint32Array(l+1);for(var u=0,g=0;g<l;++g){let K=m[g];if(K!=null){var y=1/K.cnt;v&&(K.ac*=y),K.rc*=y,K.gc*=y,K.bc*=y,m[u++]=K}}ni(t)/u<.022&&(w=!1);for(var g=0;g<u-1;++g)m[g].fw=g+1,m[g+1].bk=g,w&&(m[g].cnt=Math.sqrt(m[g].cnt));w&&(m[g].cnt=Math.sqrt(m[g].cnt));var M,S,_;for(g=0;g<u;++g){on(m,g);var E=m[g].err;for(S=++c[0];S>1&&(_=S>>1,!(m[M=c[_]].err<=E));S=_)c[S]=M;c[S]=g}var D=u-t;for(g=0;g<D;){for(var I;;){var L=c[1];if(I=m[L],I.tm>=I.mtm&&m[I.nn].mtm<=I.tm)break;I.mtm==d?L=c[1]=c[c[0]--]:(on(m,L),I.tm=g);var E=m[L].err;for(S=1;(_=S+S)<=c[0]&&(_<c[0]&&m[c[_]].err>m[c[_+1]].err&&_++,!(E<=m[M=c[_]].err));S=_)c[S]=M;c[S]=L}var $=m[I.nn],Y=I.cnt,X=$.cnt,y=1/(Y+X);v&&(I.ac=y*(Y*I.ac+X*$.ac)),I.rc=y*(Y*I.rc+X*$.rc),I.gc=y*(Y*I.gc+X*$.gc),I.bc=y*(Y*I.bc+X*$.bc),I.cnt+=$.cnt,I.mtm=++g,m[$.bk].fw=$.fw,m[$.fw].bk=$.bk,$.mtm=d}let H=[];var he=0;for(g=0;;++he){let K=ri(Math.round(m[g].rc),0,255),Qe=ri(Math.round(m[g].gc),0,255),de=ri(Math.round(m[g].bc),0,255),oe=255;v&&(oe=ri(Math.round(m[g].ac),0,255),o&&(oe=oe<=(typeof o=="number"?o:127)?0:255),n&&oe<=a&&(K=Qe=de=s,oe=0));let G=v?[K,Qe,de,oe]:[K,Qe,de];if(Hs(H,G)||H.push(G),(g=m[g].fw)==0)break}return H}function Hs(e,t){for(let i=0;i<e.length;i++){let r=e[i],n=r[0]===t[0]&&r[1]===t[1]&&r[2]===t[2],s=r.length>=4&&t.length>=4?r[3]===t[3]:!0;if(n&&s)return!0}return!1}function hn(e,t,i="rgb565"){if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(t.length>256)throw new Error("applyPalette() only works with 256 colors or less");let r=new Uint32Array(e.buffer),n=r.length,s=i==="rgb444"?4096:65536,a=new Uint8Array(n),o=new Array(s);if(i==="rgba4444")for(let p=0;p<n;p++){let w=r[p],v=w>>24&255,m=w>>16&255,l=w>>8&255,d=w&255,c=sn(d,l,m,v),u=c in o?o[c]:o[c]=qs(d,l,m,v,t);a[p]=u}else{let p=i==="rgb444"?an:nn;for(let w=0;w<n;w++){let v=r[w],m=v>>16&255,l=v>>8&255,d=v&255,c=p(d,l,m),u=c in o?o[c]:o[c]=Xs(d,l,m,t);a[w]=u}}return a}function qs(e,t,i,r,n){let s=0,a=1e100;for(let o=0;o<n.length;o++){let p=n[o],w=p[3],v=Oe(w-r);if(v>a)continue;let m=p[0];if(v+=Oe(m-e),v>a)continue;let l=p[1];if(v+=Oe(l-t),v>a)continue;let d=p[2];v+=Oe(d-i),!(v>a)&&(a=v,s=o)}return s}function Xs(e,t,i,r){let n=0,s=1e100;for(let a=0;a<r.length;a++){let o=r[a],p=o[0],w=Oe(p-e);if(w>s)continue;let v=o[1];if(w+=Oe(v-t),w>s)continue;let m=o[2];w+=Oe(m-i),!(w>s)&&(s=w,n=a)}return n}function Oe(e){return e*e}function dn(e={}){let{initialCapacity:t=4096,auto:i=!0}=e,r=tn(t),n=5003,s=new Uint8Array(256),a=new Int32Array(n),o=new Int32Array(n),p=!1;return{reset(){r.reset(),p=!1},finish(){r.writeByte(Ls.trailer)},bytes(){return r.bytes()},bytesView(){return r.bytesView()},get buffer(){return r.buffer},get stream(){return r},writeHeader:w,writeFrame(v,m,l,d={}){let{transparent:c=!1,transparentIndex:u=0,delay:g=0,palette:y=null,repeat:M=0,colorDepth:S=8,dispose:_=-1}=d,E=!1;if(i?p||(E=!0,w(),p=!0):E=!!d.first,m=Math.max(0,Math.floor(m)),l=Math.max(0,Math.floor(l)),E){if(!y)throw new Error("First frame must include a { palette } option");Js(r,m,l,y,S),cn(r,y),M>=0&&Ks(r,M)}let D=Math.round(g/10);Ys(r,_,D,c,u);let I=!!y&&!E;Zs(r,m,l,I?y:null),I&&cn(r,y),Qs(r,v,m,l,S,s,a,o)}};function w(){pn(r,"GIF89a")}}function Ys(e,t,i,r,n){e.writeByte(33),e.writeByte(249),e.writeByte(4),n<0&&(n=0,r=!1);var s,a;r?(s=1,a=2):(s=0,a=0),t>=0&&(a=t&7),a<<=2,e.writeByte(0|a|0|s),Pe(e,i),e.writeByte(n||0),e.writeByte(0)}function Js(e,t,i,r,n=8){let s=1,a=0,o=Vi(r.length)-1,p=s<<7|n-1<<4|a<<3|o;Pe(e,t),Pe(e,i),e.writeBytes([p,0,0])}function Ks(e,t){e.writeByte(33),e.writeByte(255),e.writeByte(11),pn(e,"NETSCAPE2.0"),e.writeByte(3),e.writeByte(1),Pe(e,t),e.writeByte(0)}function cn(e,t){let i=1<<Vi(t.length);for(let r=0;r<i;r++){let n=[0,0,0];r<t.length&&(n=t[r]),e.writeByte(n[0]),e.writeByte(n[1]),e.writeByte(n[2])}}function Zs(e,t,i,r){if(e.writeByte(44),Pe(e,0),Pe(e,0),Pe(e,t),Pe(e,i),r){let n=0,s=0,a=Vi(r.length)-1;e.writeByte(128|n|s|0|a)}else e.writeByte(0)}function Qs(e,t,i,r,n=8,s,a,o){$s(i,r,t,n,e,s,a,o)}function Pe(e,t){e.writeByte(t&255),e.writeByte(t>>8&255)}function pn(e,t){for(var i=0;i<t.length;i++)e.writeByte(t.charCodeAt(i))}function Vi(e){return Math.max(Math.ceil(Math.log2(e)),1)}class ea{constructor(t){this.canvas=t.canvas,this.fps=t.fps??30,this.duration=t.duration,this.maxColors=t.maxColors??256,this.filename=t.filename,this.onProgress=t.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 t=performance.now();if(t<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&&t-this.startTime>=this.duration*1e3&&this.stop()}async stop(){if(!this.active)return null;this.active=!1;const t=await this._encode(),i=this.filename?_e(this.filename,"gif"):be("gif");return re(t,i),t}async encode(){return this.active=!1,this._encode()}async _encode(){const t=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),o=hn(s.data,a);t.writeFrame(o,s.width,s.height,{palette:a,delay:i}),this.onProgress((n+1)/r),n%4===3&&await new Promise(p=>setTimeout(p,0))}return t.finish(),new Blob([t.bytes()],{type:"image/gif"})}}function ta(e,t,i){if(t.recordGIF=function(r={}){const n=xe(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 ea({canvas:n,...r});return s.start(),this._p5ExportGIF=s,s},t.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 ia{constructor({canvas:t,fps:i=30,duration:r,maxFrames:n=900}){this.canvas=t,this.fps=i,this.duration=r,this.maxFrames=n,this.width=t.width,this.height=t.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 t=performance.now();if(t<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&&t-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 Li=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},f=(e,t,i)=>(Li(e,t,"read from private field"),i?i.call(e):t.get(e)),U=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Q=(e,t,i,r)=>(Li(e,t,"write to private field"),t.set(e,i),i),ra=(e,t,i,r)=>({set _(n){Q(e,t,n)},get _(){return f(e,t,r)}}),z=(e,t,i)=>(Li(e,t,"access private method"),i),V=new Uint8Array(8),pe=new DataView(V.buffer),Z=e=>[(e%256+256)%256],j=e=>(pe.setUint16(0,e,!1),[V[0],V[1]]),na=e=>(pe.setInt16(0,e,!1),[V[0],V[1]]),fn=e=>(pe.setUint32(0,e,!1),[V[1],V[2],V[3]]),C=e=>(pe.setUint32(0,e,!1),[V[0],V[1],V[2],V[3]]),sa=e=>(pe.setInt32(0,e,!1),[V[0],V[1],V[2],V[3]]),Ve=e=>(pe.setUint32(0,Math.floor(e/2**32),!1),pe.setUint32(4,e,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Gi=e=>(pe.setInt16(0,2**8*e,!1),[V[0],V[1]]),fe=e=>(pe.setInt32(0,2**16*e,!1),[V[0],V[1],V[2],V[3]]),Ni=e=>(pe.setInt32(0,2**30*e,!1),[V[0],V[1],V[2],V[3]]),le=(e,t=!1)=>{let i=Array(e.length).fill(null).map((r,n)=>e.charCodeAt(n));return t&&i.push(0),i},si=e=>e&&e[e.length-1],$i=e=>{let t;for(let i of e)(!t||i.presentationTimestamp>t.presentationTimestamp)&&(t=i);return t},ue=(e,t,i=!0)=>{let r=e*t;return i?Math.round(r):r},un=e=>{let t=e*(Math.PI/180),i=Math.cos(t),r=Math.sin(t);return[i,r,0,-r,i,0,0,0,1]},mn=un(0),gn=e=>[fe(e[0]),fe(e[1]),Ni(e[2]),fe(e[3]),fe(e[4]),Ni(e[5]),fe(e[6]),fe(e[7]),Ni(e[8])],xt=e=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(xt):Object.fromEntries(Object.entries(e).map(([t,i])=>[t,xt(i)])),tt=e=>e>=0&&e<2**32,J=(e,t,i)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:i}),q=(e,t,i,r,n)=>J(e,[Z(t),fn(i),r??[]],n),aa=e=>{let t=512;return e.fragmented?J("ftyp",[le("iso5"),C(t),le("iso5"),le("iso6"),le("mp41")]):J("ftyp",[le("isom"),C(t),le("isom"),e.holdsAvc?le("avc1"):[],le("mp41")])},ji=e=>({type:"mdat",largeSize:e}),oa=e=>({type:"free",size:e}),ai=(e,t,i=!1)=>J("moov",null,[la(t,e),...e.map(r=>ha(r,t)),i?Va(e):null]),la=(e,t)=>{let i=ue(Math.max(0,...t.filter(a=>a.samples.length>0).map(a=>{const o=$i(a.samples);return o.presentationTimestamp+o.duration})),Ki),r=Math.max(...t.map(a=>a.id))+1,n=!tt(e)||!tt(i),s=n?Ve:C;return q("mvhd",+n,0,[s(e),s(e),C(Ki),s(i),fe(1),Gi(1),Array(10).fill(0),gn(mn),Array(24).fill(0),C(r)])},ha=(e,t)=>J("trak",null,[da(e,t),ca(e,t)]),da=(e,t)=>{let i=$i(e.samples),r=ue(i?i.presentationTimestamp+i.duration:0,Ki),n=!tt(t)||!tt(r),s=n?Ve:C,a;return e.info.type==="video"?a=typeof e.info.rotation=="number"?un(e.info.rotation):e.info.rotation:a=mn,q("tkhd",+n,3,[s(t),s(t),C(e.id),C(0),s(r),Array(8).fill(0),j(0),j(0),Gi(e.info.type==="audio"?1:0),j(0),gn(a),fe(e.info.type==="video"?e.info.width:0),fe(e.info.type==="video"?e.info.height:0)])},ca=(e,t)=>J("mdia",null,[pa(e,t),fa(e.info.type==="video"?"vide":"soun"),ua(e)]),pa=(e,t)=>{let i=$i(e.samples),r=ue(i?i.presentationTimestamp+i.duration:0,e.timescale),n=!tt(t)||!tt(r),s=n?Ve:C;return q("mdhd",+n,0,[s(t),s(t),C(e.timescale),s(r),j(21956),j(0)])},fa=e=>q("hdlr",0,0,[le("mhlr"),le(e),C(0),C(0),C(0),le("mp4-muxer-hdlr",!0)]),ua=e=>J("minf",null,[e.info.type==="video"?ma():ga(),wa(),ba(e)]),ma=()=>q("vmhd",0,1,[j(0),j(0),j(0),j(0)]),ga=()=>q("smhd",0,0,[j(0),j(0)]),wa=()=>J("dinf",null,[va()]),va=()=>q("dref",0,0,[C(1)],[ya()]),ya=()=>q("url ",0,1),ba=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(i=>i.sampleCompositionTimeOffset!==0);return J("stbl",null,[_a(e),Fa(e),Da(e),Ua(e),Wa(e),za(e),t?Oa(e):null])},_a=e=>q("stsd",0,0,[C(1)],[e.info.type==="video"?xa(Ja[e.info.codec],e):Ia(Za[e.info.codec],e)]),xa=(e,t)=>J(e,[Array(6).fill(0),j(1),j(0),j(0),Array(12).fill(0),j(t.info.width),j(t.info.height),C(4718592),C(4718592),C(0),j(1),Array(32).fill(0),j(24),na(65535)],[Ka[t.info.codec](t),t.info.decoderConfig.colorSpace?ka(t):null]),Sa={bt709:1,bt470bg:5,smpte170m:6},Ca={bt709:1,smpte170m:6,"iec61966-2-1":13},Ea={rgb:0,bt709:1,bt470bg:5,smpte170m:6},ka=e=>J("colr",[le("nclx"),j(Sa[e.info.decoderConfig.colorSpace.primaries]),j(Ca[e.info.decoderConfig.colorSpace.transfer]),j(Ea[e.info.decoderConfig.colorSpace.matrix]),Z((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ta=e=>e.info.decoderConfig&&J("avcC",[...new Uint8Array(e.info.decoderConfig.description)]),Aa=e=>e.info.decoderConfig&&J("hvcC",[...new Uint8Array(e.info.decoderConfig.description)]),Ma=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig;if(!t.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let i=t.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+(0<<1)+Number(t.colorSpace.fullRange);return q("vpcC",1,0,[Z(r),Z(n),Z(o),Z(2),Z(2),Z(2),j(0)])},Pa=()=>{let i=(1<<7)+1;return J("av1C",[i,0,0,0])},Ia=(e,t)=>J(e,[Array(6).fill(0),j(1),j(0),j(0),C(0),j(t.info.numberOfChannels),j(16),j(0),j(0),fe(t.info.sampleRate)],[Qa[t.info.codec](t)]),Ra=e=>{let t=new Uint8Array(e.info.decoderConfig.description);return q("esds",0,0,[C(58753152),Z(32+t.byteLength),j(1),Z(0),C(75530368),Z(18+t.byteLength),Z(64),Z(21),fn(0),C(130071),C(130071),C(92307584),Z(t.byteLength),...t,C(109084800),Z(1),Z(2)])},Ba=e=>{var n;let t=3840,i=0;const r=(n=e.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);t=s.getUint16(10,!0),i=s.getInt16(14,!0)}return J("dOps",[Z(0),Z(e.info.numberOfChannels),j(t),C(e.info.sampleRate),Gi(i),Z(0)])},Fa=e=>q("stts",0,0,[C(e.timeToSampleTable.length),e.timeToSampleTable.map(t=>[C(t.sampleCount),C(t.sampleDelta)])]),Da=e=>{if(e.samples.every(i=>i.type==="key"))return null;let t=[...e.samples.entries()].filter(([,i])=>i.type==="key");return q("stss",0,0,[C(t.length),t.map(([i])=>C(i+1))])},Ua=e=>q("stsc",0,0,[C(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(t=>[C(t.firstChunk),C(t.samplesPerChunk),C(1)])]),Wa=e=>q("stsz",0,0,[C(0),C(e.samples.length),e.samples.map(t=>C(t.size))]),za=e=>e.finalizedChunks.length>0&&si(e.finalizedChunks).offset>=2**32?q("co64",0,0,[C(e.finalizedChunks.length),e.finalizedChunks.map(t=>Ve(t.offset))]):q("stco",0,0,[C(e.finalizedChunks.length),e.finalizedChunks.map(t=>C(t.offset))]),Oa=e=>q("ctts",0,0,[C(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(t=>[C(t.sampleCount),C(t.sampleCompositionTimeOffset)])]),Va=e=>J("mvex",null,e.map(La)),La=e=>q("trex",0,0,[C(e.id),C(1),C(0),C(0),C(0)]),wn=(e,t)=>J("moof",null,[Ga(e),...t.map(Na)]),Ga=e=>q("mfhd",0,0,[C(e)]),vn=e=>{let t=0,i=0,r=0,n=0,s=e.type==="delta";return i|=+s,s?t|=1:t|=2,t<<24|i<<16|r<<8|n},Na=e=>J("traf",null,[$a(e),ja(e),Ha(e)]),$a=e=>{let t=0;t|=8,t|=16,t|=32,t|=131072;let i=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:vn(i)};return q("tfhd",0,t,[C(e.id),C(r.duration),C(r.size),C(r.flags)])},ja=e=>q("tfdt",1,0,[Ve(ue(e.currentChunk.startTimestamp,e.timescale))]),Ha=e=>{let t=e.currentChunk.samples.map(u=>u.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(u=>u.size),r=e.currentChunk.samples.map(vn),n=e.currentChunk.samples.map(u=>ue(u.presentationTimestamp-u.decodeTimestamp,e.timescale)),s=new Set(t),a=new Set(i),o=new Set(r),p=new Set(n),w=o.size===2&&r[0]!==r[1],v=s.size>1,m=a.size>1,l=!w&&o.size>1,d=p.size>1||[...p].some(u=>u!==0),c=0;return c|=1,c|=4*+w,c|=256*+v,c|=512*+m,c|=1024*+l,c|=2048*+d,q("trun",1,c,[C(e.currentChunk.samples.length),C(e.currentChunk.offset-e.currentChunk.moofOffset||0),w?C(r[0]):[],e.currentChunk.samples.map((u,g)=>[v?C(t[g]):[],m?C(i[g]):[],l?C(r[g]):[],d?sa(n[g]):[]])])},qa=e=>J("mfra",null,[...e.map(Xa),Ya()]),Xa=(e,t)=>q("tfra",1,0,[C(e.id),C(63),C(e.finalizedChunks.length),e.finalizedChunks.map(r=>[Ve(ue(r.startTimestamp,e.timescale)),Ve(r.moofOffset),C(t+1),C(1),C(1)])]),Ya=()=>q("mfro",0,0,[C(0)]),Ja={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},Ka={avc:Ta,hevc:Aa,vp9:Ma,av1:Pa},Za={aac:"mp4a",opus:"Opus"},Qa={aac:Ra,opus:Ba},oi=class{},yn=class extends oi{constructor(){super(...arguments),this.buffer=null}},bn=class extends oi{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.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 oi{constructor(t,i){if(super(),this.stream=t,this.options=i,!(t 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")}},Le,it,_n=class{constructor(){this.pos=0,U(this,Le,new Uint8Array(8)),U(this,it,new DataView(f(this,Le).buffer)),this.offsets=new WeakMap}seek(t){this.pos=t}writeU32(t){f(this,it).setUint32(0,t,!1),this.write(f(this,Le).subarray(0,4))}writeU64(t){f(this,it).setUint32(0,Math.floor(t/2**32),!1),f(this,it).setUint32(4,t,!1),this.write(f(this,Le).subarray(0,8))}writeAscii(t){for(let i=0;i<t.length;i++)f(this,it).setUint8(i%8,t.charCodeAt(i)),i%8===7&&this.write(f(this,Le));t.length%8!==0&&this.write(f(this,Le).subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.pos),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.write(t.contents);else{let i=this.pos;if(this.writeBoxHeader(t,0),t.contents&&this.write(t.contents),t.children)for(let s of t.children)s&&this.writeBox(s);let r=this.pos,n=t.size??r-i;this.seek(i),this.writeBoxHeader(t,n),this.seek(r)}}writeBoxHeader(t,i){this.writeU32(t.largeSize?1:i),this.writeAscii(t.type),t.largeSize&&this.writeU64(i)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){let i=this.pos;this.seek(this.offsets.get(t)),this.writeBox(t),this.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let i=this.measureBoxHeader(t);if(t.contents&&(i+=t.contents.byteLength),t.children)for(let r of t.children)r&&(i+=this.measureBox(r));return i}}};Le=new WeakMap,it=new WeakMap;var li,Ge,St,Ct,hi,Hi,to=class extends _n{constructor(t){super(),U(this,hi),U(this,li,void 0),U(this,Ge,new ArrayBuffer(2**16)),U(this,St,new Uint8Array(f(this,Ge))),U(this,Ct,0),Q(this,li,t)}write(t){z(this,hi,Hi).call(this,this.pos+t.byteLength),f(this,St).set(t,this.pos),this.pos+=t.byteLength,Q(this,Ct,Math.max(f(this,Ct),this.pos))}finalize(){z(this,hi,Hi).call(this,this.pos),f(this,li).buffer=f(this,Ge).slice(0,Math.max(f(this,Ct),this.pos))}};li=new WeakMap,Ge=new WeakMap,St=new WeakMap,Ct=new WeakMap,hi=new WeakSet,Hi=function(e){let t=f(this,Ge).byteLength;for(;t<e;)t*=2;if(t===f(this,Ge).byteLength)return;let i=new ArrayBuffer(t),r=new Uint8Array(i);r.set(f(this,St),0),Q(this,Ge,i),Q(this,St,r)};var io=2**24,ro=2,Et,Ne,kt,Ce,ne,di,qi,Xi,xn,Yi,Sn,Tt,ci,Ji=class extends _n{constructor(t){var i,r;super(),U(this,di),U(this,Xi),U(this,Yi),U(this,Tt),U(this,Et,void 0),U(this,Ne,[]),U(this,kt,void 0),U(this,Ce,void 0),U(this,ne,[]),Q(this,Et,t),Q(this,kt,((i=t.options)==null?void 0:i.chunked)??!1),Q(this,Ce,((r=t.options)==null?void 0:r.chunkSize)??io)}write(t){f(this,Ne).push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength}flush(){var r,n;if(f(this,Ne).length===0)return;let t=[],i=[...f(this,Ne)].sort((s,a)=>s.start-a.start);t.push({start:i[0].start,size:i[0].data.byteLength});for(let s=1;s<i.length;s++){let a=t[t.length-1],o=i[s];o.start<=a.start+a.size?a.size=Math.max(a.size,o.start+o.data.byteLength-a.start):t.push({start:o.start,size:o.data.byteLength})}for(let s of t){s.data=new Uint8Array(s.size);for(let a of f(this,Ne))s.start<=a.start&&a.start<s.start+s.size&&s.data.set(a.data,a.start-s.start);f(this,kt)?(z(this,di,qi).call(this,s.data,s.start),z(this,Tt,ci).call(this)):(n=(r=f(this,Et).options).onData)==null||n.call(r,s.data,s.start)}f(this,Ne).length=0}finalize(){f(this,kt)&&z(this,Tt,ci).call(this,!0)}};Et=new WeakMap,Ne=new WeakMap,kt=new WeakMap,Ce=new WeakMap,ne=new WeakMap,di=new WeakSet,qi=function(e,t){let i=f(this,ne).findIndex(o=>o.start<=t&&t<o.start+f(this,Ce));i===-1&&(i=z(this,Yi,Sn).call(this,t));let r=f(this,ne)[i],n=t-r.start,s=e.subarray(0,Math.min(f(this,Ce)-n,e.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(z(this,Xi,xn).call(this,r,a),r.written[0].start===0&&r.written[0].end===f(this,Ce)&&(r.shouldFlush=!0),f(this,ne).length>ro){for(let o=0;o<f(this,ne).length-1;o++)f(this,ne)[o].shouldFlush=!0;z(this,Tt,ci).call(this)}s.byteLength<e.byteLength&&z(this,di,qi).call(this,e.subarray(s.byteLength),t+s.byteLength)},Xi=new WeakSet,xn=function(e,t){let i=0,r=e.written.length-1,n=-1;for(;i<=r;){let s=Math.floor(i+(r-i+1)/2);e.written[s].start<=t.start?(i=s+1,n=s):r=s-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)},Yi=new WeakSet,Sn=function(e){let i={start:Math.floor(e/f(this,Ce))*f(this,Ce),data:new Uint8Array(f(this,Ce)),written:[],shouldFlush:!1};return f(this,ne).push(i),f(this,ne).sort((r,n)=>r.start-n.start),f(this,ne).indexOf(i)},Tt=new WeakSet,ci=function(e=!1){var t,i;for(let r=0;r<f(this,ne).length;r++){let n=f(this,ne)[r];if(!(!n.shouldFlush&&!e)){for(let s of n.written)(i=(t=f(this,Et).options).onData)==null||i.call(t,n.data.subarray(s.start,s.end),n.start+s.start);f(this,ne).splice(r--,1)}}};var no=class extends Ji{constructor(t){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}))}},Ki=1e3,so=["avc","hevc","vp9","av1"],ao=["aac","opus"],oo=2082844800,lo=["strict","offset","cross-track-offset"],P,B,pi,se,ie,ee,rt,nt,Zi,$e,je,At,Qi,Cn,er,En,tr,kn,ir,Tn,rr,An,fi,nr,me,Ee,sr,Mn,Mt,ui,mi,ar,st,Pt,gi,or,ho=class{constructor(t){if(U(this,Qi),U(this,er),U(this,tr),U(this,ir),U(this,rr),U(this,fi),U(this,me),U(this,sr),U(this,Mt),U(this,mi),U(this,st),U(this,gi),U(this,P,void 0),U(this,B,void 0),U(this,pi,void 0),U(this,se,void 0),U(this,ie,null),U(this,ee,null),U(this,rt,Math.floor(Date.now()/1e3)+oo),U(this,nt,[]),U(this,Zi,1),U(this,$e,[]),U(this,je,[]),U(this,At,!1),z(this,Qi,Cn).call(this,t),t.video=xt(t.video),t.audio=xt(t.audio),t.fastStart=xt(t.fastStart),this.target=t.target,Q(this,P,{firstTimestampBehavior:"strict",...t}),t.target instanceof yn)Q(this,B,new to(t.target));else if(t.target instanceof bn)Q(this,B,new Ji(t.target));else if(t.target instanceof eo)Q(this,B,new no(t.target));else throw new Error(`Invalid target: ${t.target}`);z(this,ir,Tn).call(this),z(this,er,En).call(this)}addVideoChunk(t,i,r,n){if(!(t 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(t.byteLength);t.copyTo(s),this.addVideoChunkRaw(s,t.type,r??t.timestamp,t.duration,i,n)}addVideoChunkRaw(t,i,r,n,s,a){if(!(t 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,gi,or).call(this),!f(this,P).video)throw new Error("No video track declared.");if(typeof f(this,P).fastStart=="object"&&f(this,ie).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 o=z(this,fi,nr).call(this,f(this,ie),t,i,r,n,s,a);if(f(this,P).fastStart==="fragmented"&&f(this,ee)){for(;f(this,je).length>0&&f(this,je)[0].decodeTimestamp<=o.decodeTimestamp;){let p=f(this,je).shift();z(this,me,Ee).call(this,f(this,ee),p)}o.decodeTimestamp<=f(this,ee).lastDecodeTimestamp?z(this,me,Ee).call(this,f(this,ie),o):f(this,$e).push(o)}else z(this,me,Ee).call(this,f(this,ie),o)}addAudioChunk(t,i,r){if(!(t 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(t.byteLength);t.copyTo(n),this.addAudioChunkRaw(n,t.type,r??t.timestamp,t.duration,i)}addAudioChunkRaw(t,i,r,n,s){if(!(t 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,gi,or).call(this),!f(this,P).audio)throw new Error("No audio track declared.");if(typeof f(this,P).fastStart=="object"&&f(this,ee).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,fi,nr).call(this,f(this,ee),t,i,r,n,s);if(f(this,P).fastStart==="fragmented"&&f(this,ie)){for(;f(this,$e).length>0&&f(this,$e)[0].decodeTimestamp<=a.decodeTimestamp;){let o=f(this,$e).shift();z(this,me,Ee).call(this,f(this,ie),o)}a.decodeTimestamp<=f(this,ie).lastDecodeTimestamp?z(this,me,Ee).call(this,f(this,ee),a):f(this,je).push(a)}else z(this,me,Ee).call(this,f(this,ee),a)}finalize(){if(f(this,At))throw new Error("Cannot finalize a muxer more than once.");if(f(this,P).fastStart==="fragmented"){for(let i of f(this,$e))z(this,me,Ee).call(this,f(this,ie),i);for(let i of f(this,je))z(this,me,Ee).call(this,f(this,ee),i);z(this,mi,ar).call(this,!1)}else f(this,ie)&&z(this,Mt,ui).call(this,f(this,ie)),f(this,ee)&&z(this,Mt,ui).call(this,f(this,ee));let t=[f(this,ie),f(this,ee)].filter(Boolean);if(f(this,P).fastStart==="in-memory"){let i;for(let n=0;n<2;n++){let s=ai(t,f(this,rt)),a=f(this,B).measureBox(s);i=f(this,B).measureBox(f(this,se));let o=f(this,B).pos+a+i;for(let p of f(this,nt)){p.offset=o;for(let{data:w}of p.samples)o+=w.byteLength,i+=w.byteLength}if(o<2**32)break;i>=2**32&&(f(this,se).largeSize=!0)}let r=ai(t,f(this,rt));f(this,B).writeBox(r),f(this,se).size=i,f(this,B).writeBox(f(this,se));for(let n of f(this,nt))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(t);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,se)),r=f(this,B).pos-i;f(this,se).size=r,f(this,se).largeSize=r>=2**32,f(this,B).patchBox(f(this,se));let n=ai(t,f(this,rt));if(typeof f(this,P).fastStart=="object"){f(this,B).seek(f(this,pi)),f(this,B).writeBox(n);let s=i-f(this,B).pos;f(this,B).writeBox(oa(s))}else f(this,B).writeBox(n)}z(this,st,Pt).call(this),f(this,B).finalize(),Q(this,At,!0)}};P=new WeakMap,B=new WeakMap,pi=new WeakMap,se=new WeakMap,ie=new WeakMap,ee=new WeakMap,rt=new WeakMap,nt=new WeakMap,Zi=new WeakMap,$e=new WeakMap,je=new WeakMap,At=new WeakMap,Qi=new WeakSet,Cn=function(e){if(typeof e!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(e.target instanceof oi))throw new TypeError("The target must be provided and an instance of Target.");if(e.video){if(!so.includes(e.video.codec))throw new TypeError(`Unsupported video codec: ${e.video.codec}`);if(!Number.isInteger(e.video.width)||e.video.width<=0)throw new TypeError(`Invalid video width: ${e.video.width}. Must be a positive integer.`);if(!Number.isInteger(e.video.height)||e.video.height<=0)throw new TypeError(`Invalid video height: ${e.video.height}. Must be a positive integer.`);const t=e.video.rotation;if(typeof t=="number"&&![0,90,180,270].includes(t))throw new TypeError(`Invalid video rotation: ${t}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(t)&&(t.length!==9||t.some(i=>typeof i!="number")))throw new TypeError(`Invalid video transformation matrix: ${t.join()}`);if(e.video.frameRate!==void 0&&(!Number.isInteger(e.video.frameRate)||e.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.video.frameRate}. Must be a positive integer.`)}if(e.audio){if(!ao.includes(e.audio.codec))throw new TypeError(`Unsupported audio codec: ${e.audio.codec}`);if(!Number.isInteger(e.audio.numberOfChannels)||e.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${e.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(e.audio.sampleRate)||e.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${e.audio.sampleRate}. Must be a positive integer.`)}if(e.firstTimestampBehavior&&!lo.includes(e.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${e.firstTimestampBehavior}`);if(typeof e.fastStart=="object"){if(e.video){if(e.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(e.fastStart.expectedVideoChunks)||e.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(e.audio){if(e.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(e.fastStart.expectedAudioChunks)||e.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(e.minFragmentDuration!==void 0&&(!Number.isFinite(e.minFragmentDuration)||e.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")},er=new WeakSet,En=function(){var e;if(f(this,B).writeBox(aa({holdsAvc:((e=f(this,P).video)==null?void 0:e.codec)==="avc",fragmented:f(this,P).fastStart==="fragmented"})),Q(this,pi,f(this,B).pos),f(this,P).fastStart==="in-memory")Q(this,se,ji(!1));else if(f(this,P).fastStart!=="fragmented"){if(typeof f(this,P).fastStart=="object"){let t=z(this,tr,kn).call(this);f(this,B).seek(f(this,B).pos+t)}Q(this,se,ji(!0)),f(this,B).writeBox(f(this,se))}z(this,st,Pt).call(this)},tr=new WeakSet,kn=function(){if(typeof f(this,P).fastStart!="object")return;let e=0,t=[f(this,P).fastStart.expectedVideoChunks,f(this,P).fastStart.expectedAudioChunks];for(let i of t)i&&(e+=8*Math.ceil(2/3*i),e+=4*i,e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i);return e+=4096,e},ir=new WeakSet,Tn=function(){if(f(this,P).video&&Q(this,ie,{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,ee,{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 e=z(this,rr,An).call(this,2,f(this,P).audio.sampleRate,f(this,P).audio.numberOfChannels);f(this,ee).info.decoderConfig={codec:f(this,P).audio.codec,description:e,numberOfChannels:f(this,P).audio.numberOfChannels,sampleRate:f(this,P).audio.sampleRate}}},rr=new WeakSet,An=function(e,t,i){let n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(t),s=i,a="";a+=e.toString(2).padStart(5,"0"),a+=n.toString(2).padStart(4,"0"),n===15&&(a+=t.toString(2).padStart(24,"0")),a+=s.toString(2).padStart(4,"0");let o=Math.ceil(a.length/8)*8;a=a.padEnd(o,"0");let p=new Uint8Array(a.length/8);for(let w=0;w<a.length;w+=8)p[w/8]=parseInt(a.slice(w,w+8),2);return p},fi=new WeakSet,nr=function(e,t,i,r,n,s,a){let o=r/1e6,p=(r-(a??0))/1e6,w=n/1e6,v=z(this,sr,Mn).call(this,o,p,e);return o=v.presentationTimestamp,p=v.decodeTimestamp,s!=null&&s.decoderConfig&&(e.info.decoderConfig===null?e.info.decoderConfig=s.decoderConfig:Object.assign(e.info.decoderConfig,s.decoderConfig)),{presentationTimestamp:o,decodeTimestamp:p,duration:w,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:ue(w,e.timescale)}},me=new WeakSet,Ee=function(e,t){f(this,P).fastStart!=="fragmented"&&e.samples.push(t);const i=ue(t.presentationTimestamp-t.decodeTimestamp,e.timescale);if(e.lastTimescaleUnits!==null){let n=ue(t.decodeTimestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=s,e.lastSample.timescaleUnitsToNextSample=s,f(this,P).fastStart!=="fragmented"){let a=si(e.timeToSampleTable);a.sampleCount===1?(a.sampleDelta=s,a.sampleCount++):a.sampleDelta===s?a.sampleCount++:(a.sampleCount--,e.timeToSampleTable.push({sampleCount:2,sampleDelta:s}));const o=si(e.compositionTimeOffsetTable);o.sampleCompositionTimeOffset===i?o.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=0,f(this,P).fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:ue(t.duration,e.timescale)}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=t;let r=!1;if(!e.currentChunk)r=!0;else{let n=t.presentationTimestamp-e.currentChunk.startTimestamp;if(f(this,P).fastStart==="fragmented"){let s=f(this,ie)??f(this,ee);const a=f(this,P).minFragmentDuration??1;e===s&&t.type==="key"&&n>=a&&(r=!0,z(this,mi,ar).call(this))}else r=n>=.5}r&&(e.currentChunk&&z(this,Mt,ui).call(this,e),e.currentChunk={startTimestamp:t.presentationTimestamp,samples:[]}),e.currentChunk.samples.push(t)},sr=new WeakSet,Mn=function(e,t,i){var a,o;const r=f(this,P).firstTimestampBehavior==="strict",n=i.lastDecodeTimestamp===-1;if(r&&n&&t!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received DTS=${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 thedocument, which is probably what you want.
|
|
24
24
|
|
|
25
25
|
If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
|
|
26
|
-
`);if(p(this,P).firstTimestampBehavior==="offset"||p(this,P).firstTimestampBehavior==="cross-track-offset"){i.firstDecodeTimestamp===void 0&&(i.firstDecodeTimestamp=e);let f;p(this,P).firstTimestampBehavior==="offset"?f=i.firstDecodeTimestamp:f=Math.min(((a=p(this,it))==null?void 0:a.firstDecodeTimestamp)??1/0,((o=p(this,tt))==null?void 0:o.firstDecodeTimestamp)??1/0),e-=f,t-=f}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,ui=function(t){if(p(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),p(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}),p(this,P).fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=p(this,B).pos;for(let e of t.currentChunk.samples)p(this,B).write(e.data),e.data=null;z(this,se,Pe).call(this)}},mi=new WeakSet,sr=function(t=!0){if(p(this,P).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let e=[p(this,it),p(this,tt)].filter(o=>o&&o.currentChunk);if(e.length===0)return;let i=ia(this,Ki)._++;if(i===1){let o=ai(e,p(this,re),!0);p(this,B).writeBox(o)}let r=p(this,B).pos,n=wn(i,e);p(this,B).writeBox(n);{let o=$i(!1),f=0;for(let v of e)for(let u of v.currentChunk.samples)f+=u.size;let g=p(this,B).measureBox(o)+f;g>=2**32&&(o.largeSize=!0,g=p(this,B).measureBox(o)+f),o.size=g,p(this,B).writeBox(o)}for(let o of e){o.currentChunk.offset=p(this,B).pos,o.currentChunk.moofOffset=r;for(let f of o.currentChunk.samples)p(this,B).write(f.data),f.data=null}let s=p(this,B).pos;p(this,B).seek(p(this,B).offsets.get(n));let a=wn(i,e);p(this,B).writeBox(a),p(this,B).seek(s);for(let o of e)o.finalizedChunks.push(o.currentChunk),p(this,ne).push(o.currentChunk),o.currentChunk=null;t&&z(this,se,Pe).call(this)},se=new WeakSet,Pe=function(){p(this,B)instanceof Yi&&p(this,B).flush()},gi=new WeakSet,ar=function(){if(p(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)},h=(t,e,i)=>(or(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)},F=(t,e,i,r)=>(or(t,e,"write to private field"),e.set(t,i),i),T=(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],o=7-(n&7),f=(a&1<<o)>>o;r<<=1,r|=f}return r},co=(t,e,i,r)=>{for(let n=e;n<i;n++){let s=Math.floor(n/8),a=t[s],o=7-(n&7);a&=~(1<<o),a|=(r&1<<i-n-1)>>i-n-1<<o,t[s]=a}},wi=class{},Rn=class extends wi{constructor(){super(...arguments),this.buffer=null}},Bn=class extends wi{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.")}},po=class extends wi{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,N,hr,Fn,dr,Dn,cr,Un,vi,pr,fr,Wn,zn=class{constructor(){x(this,hr),x(this,dr),x(this,cr),x(this,vi),x(this,fr),this.pos=0,x(this,It,new Uint8Array(8)),x(this,N,new DataView(h(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:h(this,N).setUint8(i++,128|t);break;case 2:h(this,N).setUint8(i++,64|t>>8),h(this,N).setUint8(i++,t);break;case 3:h(this,N).setUint8(i++,32|t>>16),h(this,N).setUint8(i++,t>>8),h(this,N).setUint8(i++,t);break;case 4:h(this,N).setUint8(i++,16|t>>24),h(this,N).setUint8(i++,t>>16),h(this,N).setUint8(i++,t>>8),h(this,N).setUint8(i++,t);break;case 5:h(this,N).setUint8(i++,8|t/2**32&7),h(this,N).setUint8(i++,t>>24),h(this,N).setUint8(i++,t>>16),h(this,N).setUint8(i++,t>>8),h(this,N).setUint8(i++,t);break;case 6:h(this,N).setUint8(i++,4|t/2**40&3),h(this,N).setUint8(i++,t/2**32|0),h(this,N).setUint8(i++,t>>24),h(this,N).setUint8(i++,t>>16),h(this,N).setUint8(i++,t>>8),h(this,N).setUint8(i++,t);break;default:throw new Error("Bad EBML VINT size "+e)}this.write(h(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),T(this,vi,pr).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,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),T(this,vi,pr).call(this,t.data,e)}else typeof t.data=="string"?(this.writeEBMLVarInt(t.data.length),T(this,fr,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),T(this,dr,Dn).call(this,t.data.value)):t.data instanceof lr&&(this.writeEBMLVarInt(8),T(this,cr,Un).call(this,t.data.value))}};It=new WeakMap,N=new WeakMap,hr=new WeakSet,Fn=function(t){h(this,N).setUint8(0,t),this.write(h(this,It).subarray(0,1))},dr=new WeakSet,Dn=function(t){h(this,N).setFloat32(0,t,!1),this.write(h(this,It).subarray(0,4))},cr=new WeakSet,Un=function(t){h(this,N).setFloat64(0,t,!1),this.write(h(this,It))},vi=new WeakSet,pr=function(t,e=In(t)){let i=0;switch(e){case 6:h(this,N).setUint8(i++,t/2**40|0);case 5:h(this,N).setUint8(i++,t/2**32|0);case 4:h(this,N).setUint8(i++,t>>24);case 3:h(this,N).setUint8(i++,t>>16);case 2:h(this,N).setUint8(i++,t>>8);case 1:h(this,N).setUint8(i++,t);break;default:throw new Error("Bad UINT size "+e)}this.write(h(this,It).subarray(0,i))},fr=new WeakSet,Wn=function(t){this.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))};var yi,Ht,Ie,bi,ur,fo=class extends zn{constructor(t){super(),x(this,bi),x(this,yi,void 0),x(this,Ht,new ArrayBuffer(2**16)),x(this,Ie,new Uint8Array(h(this,Ht))),F(this,yi,t)}write(t){T(this,bi,ur).call(this,this.pos+t.byteLength),h(this,Ie).set(t,this.pos),this.pos+=t.byteLength}finalize(){T(this,bi,ur).call(this,this.pos),h(this,yi).buffer=h(this,Ht).slice(0,this.pos)}};yi=new WeakMap,Ht=new WeakMap,Ie=new WeakMap,bi=new WeakSet,ur=function(t){let e=h(this,Ht).byteLength;for(;e<t;)e*=2;if(e===h(this,Ht).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(h(this,Ie),0),F(this,Ht,i),F(this,Ie,r)};var oe,gt,wt,qt,Re=class extends zn{constructor(t){super(),this.target=t,x(this,oe,!1),x(this,gt,void 0),x(this,wt,void 0),x(this,qt,void 0)}write(t){if(!h(this,oe))return;let e=this.pos;if(e<h(this,wt)){if(e+t.byteLength<=h(this,wt))return;t=t.subarray(h(this,wt)-e),e=0}let i=e+t.byteLength-h(this,wt),r=h(this,gt).byteLength;for(;r<i;)r*=2;if(r!==h(this,gt).byteLength){let n=new Uint8Array(r);n.set(h(this,gt),0),F(this,gt,n)}h(this,gt).set(t,e-h(this,wt)),F(this,qt,Math.max(h(this,qt),e+t.byteLength))}startTrackingWrites(){F(this,oe,!0),F(this,gt,new Uint8Array(2**10)),F(this,wt,this.pos),F(this,qt,this.pos)}getTrackedWrites(){if(!h(this,oe))throw new Error("Can't get tracked writes since nothing was tracked.");let e={data:h(this,gt).subarray(0,h(this,qt)-h(this,wt)),start:h(this,wt),end:h(this,qt)};return F(this,gt,void 0),F(this,oe,!1),e}};oe=new WeakMap,gt=new WeakMap,wt=new WeakMap,qt=new WeakMap;var uo=2**24,mo=2,Xt,le,Be,Fe,kt,at,_i,mr,gr,On,wr,Vn,De,xi,vr=class extends Re{constructor(t,e){var i,r;super(t),x(this,_i),x(this,gr),x(this,wr),x(this,De),x(this,Xt,[]),x(this,le,0),x(this,Be,void 0),x(this,Fe,void 0),x(this,kt,void 0),x(this,at,[]),F(this,Be,e),F(this,Fe,((i=t.options)==null?void 0:i.chunked)??!1),F(this,kt,((r=t.options)==null?void 0:r.chunkSize)??uo)}write(t){super.write(t),h(this,Xt).push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength}flush(){var i,r;if(h(this,Xt).length===0)return;let t=[],e=[...h(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 h(this,Xt))n.start<=s.start&&s.start<n.start+n.size&&n.data.set(s.data,s.start-n.start);if(h(this,Fe))T(this,_i,mr).call(this,n.data,n.start),T(this,De,xi).call(this);else{if(h(this,Be)&&n.start<h(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)}}h(this,Xt).length=0}finalize(){h(this,Fe)&&T(this,De,xi).call(this,!0)}};Xt=new WeakMap,le=new WeakMap,Be=new WeakMap,Fe=new WeakMap,kt=new WeakMap,at=new WeakMap,_i=new WeakSet,mr=function(t,e){let i=h(this,at).findIndex(o=>o.start<=e&&e<o.start+h(this,kt));i===-1&&(i=T(this,wr,Vn).call(this,e));let r=h(this,at)[i],n=e-r.start,s=t.subarray(0,Math.min(h(this,kt)-n,t.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(T(this,gr,On).call(this,r,a),r.written[0].start===0&&r.written[0].end===h(this,kt)&&(r.shouldFlush=!0),h(this,at).length>mo){for(let o=0;o<h(this,at).length-1;o++)h(this,at)[o].shouldFlush=!0;T(this,De,xi).call(this)}s.byteLength<t.byteLength&&T(this,_i,mr).call(this,t.subarray(s.byteLength),e+s.byteLength)},gr=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)},wr=new WeakSet,Vn=function(t){let i={start:Math.floor(t/h(this,kt))*h(this,kt),data:new Uint8Array(h(this,kt)),written:[],shouldFlush:!1};return h(this,at).push(i),h(this,at).sort((r,n)=>r.start-n.start),h(this,at).indexOf(i)},De=new WeakSet,xi=function(t=!1){var e,i;for(let r=0;r<h(this,at).length;r++){let n=h(this,at)[r];if(!(!n.shouldFlush&&!t)){for(let s of n.written){if(h(this,Be)&&n.start+s.start<h(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)}h(this,at).splice(r--,1)}}};var go=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,wo=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,Tt,de,ce,Yt,pe,Rt,fe,ue,vt,Ve,me,Bt,Ft,Jt,Le,Ge,ge,we,Ci,Ne,$e,yr,$n,br,jn,_r,Hn,xr,qn,Sr,Xn,Cr,Yn,Er,Jn,Ei,kr,ki,Tr,Ar,Kn,Kt,ve,Zt,ye,Mr,Zn,Pr,Qn,je,Ti,He,Ai,Ir,ts,yt,At,be,qe,Xe,Mi,Rr,es,Pi,Br,Ye,Ii,xo=class{constructor(t){x(this,yr),x(this,br),x(this,_r),x(this,xr),x(this,Sr),x(this,Cr),x(this,Er),x(this,Ei),x(this,ki),x(this,Ar),x(this,Kt),x(this,Zt),x(this,Mr),x(this,Pr),x(this,je),x(this,He),x(this,Ir),x(this,yt),x(this,be),x(this,Xe),x(this,Rr),x(this,Pi),x(this,Ye),x(this,R,void 0),x(this,A,void 0),x(this,ze,void 0),x(this,Oe,void 0),x(this,Tt,void 0),x(this,de,void 0),x(this,ce,void 0),x(this,Yt,void 0),x(this,pe,void 0),x(this,Rt,void 0),x(this,fe,void 0),x(this,ue,void 0),x(this,vt,void 0),x(this,Ve,void 0),x(this,me,0),x(this,Bt,[]),x(this,Ft,[]),x(this,Jt,[]),x(this,Le,void 0),x(this,Ge,void 0),x(this,ge,-1),x(this,we,-1),x(this,Ci,-1),x(this,Ne,void 0),x(this,$e,!1),T(this,yr,$n).call(this,t),F(this,R,{type:"webm",firstTimestampBehavior:"strict",...t}),this.target=t.target;let e=!!h(this,R).streaming;if(t.target instanceof Rn)F(this,A,new fo(t.target));else if(t.target instanceof Bn)F(this,A,new vr(t.target,e));else if(t.target instanceof po)F(this,A,new go(t.target,e));else throw new Error(`Invalid target: ${t.target}`);T(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(T(this,Ye,Ii).call(this),!h(this,R).video)throw new Error("No video track declared.");h(this,Le)===void 0&&F(this,Le,i),r&&T(this,Mr,Zn).call(this,r);let n=T(this,He,Ai).call(this,t,e,i,he);for(h(this,R).video.codec==="V_VP9"&&T(this,Pr,Qn).call(this,n),F(this,ge,n.timestamp);h(this,Ft).length>0&&h(this,Ft)[0].timestamp<=n.timestamp;){let s=h(this,Ft).shift();T(this,yt,At).call(this,s,!1)}!h(this,R).audio||n.timestamp<=h(this,we)?T(this,yt,At).call(this,n,!0):h(this,Bt).push(n),T(this,je,Ti).call(this),T(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(T(this,Ye,Ii).call(this),!h(this,R).audio)throw new Error("No audio track declared.");h(this,Ge)===void 0&&F(this,Ge,i),r!=null&&r.decoderConfig&&(h(this,R).streaming?F(this,Rt,T(this,be,qe).call(this,r.decoderConfig.description)):T(this,Xe,Mi).call(this,h(this,Rt),r.decoderConfig.description));let n=T(this,He,Ai).call(this,t,e,i,Ue);for(F(this,we,n.timestamp);h(this,Bt).length>0&&h(this,Bt)[0].timestamp<=n.timestamp;){let s=h(this,Bt).shift();T(this,yt,At).call(this,s,!0)}!h(this,R).video||n.timestamp<=h(this,ge)?T(this,yt,At).call(this,n,!h(this,R).video):h(this,Ft).push(n),T(this,je,Ti).call(this),T(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(T(this,Ye,Ii).call(this),!h(this,R).subtitles)throw new Error("No subtitle track declared.");e!=null&&e.decoderConfig&&(h(this,R).streaming?F(this,fe,T(this,be,qe).call(this,e.decoderConfig.description)):T(this,Xe,Mi).call(this,h(this,fe),e.decoderConfig.description));let r=T(this,He,Ai).call(this,t.body,"key",i??t.timestamp,Si,t.duration,t.additions);F(this,Ci,r.timestamp),h(this,Jt).push(r),T(this,je,Ti).call(this),T(this,Kt,ve).call(this)}finalize(){if(h(this,$e))throw new Error("Cannot finalize a muxer more than once.");for(;h(this,Bt).length>0;)T(this,yt,At).call(this,h(this,Bt).shift(),!0);for(;h(this,Ft).length>0;)T(this,yt,At).call(this,h(this,Ft).shift(),!0);for(;h(this,Jt).length>0&&h(this,Jt)[0].timestamp<=h(this,me);)T(this,yt,At).call(this,h(this,Jt).shift(),!1);if(h(this,vt)&&T(this,Pi,Br).call(this),h(this,A).writeEBML(h(this,ue)),!h(this,R).streaming){let t=h(this,A).pos,e=h(this,A).pos-h(this,Zt,ye);h(this,A).seek(h(this,A).offsets.get(h(this,ze))+4),h(this,A).writeEBMLVarInt(e,Gn),h(this,ce).data=new lr(h(this,me)),h(this,A).seek(h(this,A).offsets.get(h(this,ce))),h(this,A).writeEBML(h(this,ce)),h(this,Tt).data[0].data[1].data=h(this,A).offsets.get(h(this,ue))-h(this,Zt,ye),h(this,Tt).data[1].data[1].data=h(this,A).offsets.get(h(this,Oe))-h(this,Zt,ye),h(this,Tt).data[2].data[1].data=h(this,A).offsets.get(h(this,de))-h(this,Zt,ye),h(this,A).seek(h(this,A).offsets.get(h(this,Tt))),h(this,A).writeEBML(h(this,Tt)),h(this,A).seek(t)}T(this,Kt,ve).call(this),h(this,A).finalize(),F(this,$e,!0)}};R=new WeakMap,A=new WeakMap,ze=new WeakMap,Oe=new WeakMap,Tt=new WeakMap,de=new WeakMap,ce=new WeakMap,Yt=new WeakMap,pe=new WeakMap,Rt=new WeakMap,fe=new WeakMap,ue=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,ge=new WeakMap,we=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 wi))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(){h(this,A)instanceof Re&&h(this,A).target.options.onHeader&&h(this,A).startTrackingWrites(),T(this,_r,Hn).call(this),h(this,R).streaming||T(this,Cr,Yn).call(this),T(this,Er,Jn).call(this),T(this,xr,qn).call(this),T(this,Sr,Xn).call(this),h(this,R).streaming||(T(this,Ei,kr).call(this),T(this,ki,Tr).call(this)),T(this,Ar,Kn).call(this),T(this,Kt,ve).call(this)},_r=new WeakSet,Hn=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:h(this,R).type??"webm"},{id:17031,data:2},{id:17029,data:2}]};h(this,A).writeEBML(t)},xr=new WeakSet,qn=function(){F(this,pe,{id:236,size:4,data:new Uint8Array(We)}),F(this,Rt,{id:236,size:4,data:new Uint8Array(We)}),F(this,fe,{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,Tt,{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},h(this,R).streaming?null:t]};F(this,Oe,e)},Ei=new WeakSet,kr=function(){let t={id:374648427,data:[]};F(this,de,t),h(this,R).video&&t.data.push({id:174,data:[{id:215,data:he},{id:29637,data:he},{id:131,data:wo},{id:134,data:h(this,R).video.codec},h(this,pe),h(this,R).video.frameRate?{id:2352003,data:1e9/h(this,R).video.frameRate}:null,{id:224,data:[{id:176,data:h(this,R).video.width},{id:186,data:h(this,R).video.height},h(this,R).video.alpha?{id:21440,data:1}:null,h(this,Yt)]}]}),h(this,R).audio&&(F(this,Rt,h(this,R).streaming?h(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:h(this,R).audio.codec},h(this,Rt),{id:225,data:[{id:181,data:new Pn(h(this,R).audio.sampleRate)},{id:159,data:h(this,R).audio.numberOfChannels},h(this,R).audio.bitDepth?{id:25188,data:h(this,R).audio.bitDepth}:null]}]})),h(this,R).subtitles&&t.data.push({id:174,data:[{id:215,data:Si},{id:29637,data:Si},{id:131,data:yo},{id:134,data:h(this,R).subtitles.codec},h(this,fe)]})},ki=new WeakSet,Tr=function(){let t={id:408125543,size:h(this,R).streaming?-1:Gn,data:[h(this,R).streaming?null:h(this,Tt),h(this,Oe),h(this,de)]};if(F(this,ze,t),h(this,A).writeEBML(t),h(this,A)instanceof Re&&h(this,A).target.options.onHeader){let{data:e,start:i}=h(this,A).getTrackedWrites();h(this,A).target.options.onHeader(e,i)}},Ar=new WeakSet,Kn=function(){F(this,ue,{id:475249515,data:[]})},Kt=new WeakSet,ve=function(){h(this,A)instanceof vr&&h(this,A).flush()},Zt=new WeakSet,ye=function(){return h(this,A).dataOffsets.get(h(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),h(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)]}],!h(this,R).streaming){let i=h(this,A).pos;h(this,A).seek(h(this,A).offsets.get(h(this,Yt))),h(this,A).writeEBML(h(this,Yt)),h(this,A).seek(i)}}t.decoderConfig.description&&(h(this,R).streaming?F(this,pe,T(this,be,qe).call(this,t.decoderConfig.description)):T(this,Xe,Mi).call(this,h(this,pe),t.decoderConfig.description))}},Pr=new WeakSet,Qn=function(t){if(t.type!=="key"||!h(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}[h(this,Ne).matrix];co(t.data,e+0,e+3,a)},je=new WeakSet,Ti=function(){let t=Math.min(h(this,R).video?h(this,ge):1/0,h(this,R).audio?h(this,we):1/0),e=h(this,Jt);for(;e.length>0&&e[0].timestamp<=t;)T(this,yt,At).call(this,e.shift(),!h(this,R).video&&!h(this,R).audio)},He=new WeakSet,Ai=function(t,e,i,r,n,s){let a=T(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?h(this,ge):e===Ue?h(this,we):h(this,Ci);if(e!==Si){let r=e===he?h(this,Le):h(this,Ge);if(h(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
|
+
`);if(f(this,P).firstTimestampBehavior==="offset"||f(this,P).firstTimestampBehavior==="cross-track-offset"){i.firstDecodeTimestamp===void 0&&(i.firstDecodeTimestamp=t);let p;f(this,P).firstTimestampBehavior==="offset"?p=i.firstDecodeTimestamp:p=Math.min(((a=f(this,ie))==null?void 0:a.firstDecodeTimestamp)??1/0,((o=f(this,ee))==null?void 0:o.firstDecodeTimestamp)??1/0),t-=p,e-=p}if(t<i.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${i.lastDecodeTimestamp*1e6} to ${t*1e6}).`);return i.lastDecodeTimestamp=t,{presentationTimestamp:e,decodeTimestamp:t}},Mt=new WeakSet,ui=function(e){if(f(this,P).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),f(this,nt).push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||si(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),f(this,P).fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=f(this,B).pos;for(let t of e.currentChunk.samples)f(this,B).write(t.data),t.data=null;z(this,st,Pt).call(this)}},mi=new WeakSet,ar=function(e=!0){if(f(this,P).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let t=[f(this,ie),f(this,ee)].filter(o=>o&&o.currentChunk);if(t.length===0)return;let i=ra(this,Zi)._++;if(i===1){let o=ai(t,f(this,rt),!0);f(this,B).writeBox(o)}let r=f(this,B).pos,n=wn(i,t);f(this,B).writeBox(n);{let o=ji(!1),p=0;for(let v of t)for(let m of v.currentChunk.samples)p+=m.size;let w=f(this,B).measureBox(o)+p;w>=2**32&&(o.largeSize=!0,w=f(this,B).measureBox(o)+p),o.size=w,f(this,B).writeBox(o)}for(let o of t){o.currentChunk.offset=f(this,B).pos,o.currentChunk.moofOffset=r;for(let p of o.currentChunk.samples)f(this,B).write(p.data),p.data=null}let s=f(this,B).pos;f(this,B).seek(f(this,B).offsets.get(n));let a=wn(i,t);f(this,B).writeBox(a),f(this,B).seek(s);for(let o of t)o.finalizedChunks.push(o.currentChunk),f(this,nt).push(o.currentChunk),o.currentChunk=null;e&&z(this,st,Pt).call(this)},st=new WeakSet,Pt=function(){f(this,B)instanceof Ji&&f(this,B).flush()},gi=new WeakSet,or=function(){if(f(this,At))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};var lr=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},h=(e,t,i)=>(lr(e,t,"read from private field"),i?i.call(e):t.get(e)),x=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},F=(e,t,i,r)=>(lr(e,t,"write to private field"),t.set(e,i),i),T=(e,t,i)=>(lr(e,t,"access private method"),i),Pn=class{constructor(e){this.value=e}},hr=class{constructor(e){this.value=e}},In=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,co=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<(1<<21)-1)return 3;if(e<(1<<28)-1)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML VINT size not supported "+e)},at=(e,t,i)=>{let r=0;for(let n=t;n<i;n++){let s=Math.floor(n/8),a=e[s],o=7-(n&7),p=(a&1<<o)>>o;r<<=1,r|=p}return r},po=(e,t,i,r)=>{for(let n=t;n<i;n++){let s=Math.floor(n/8),a=e[s],o=7-(n&7);a&=~(1<<o),a|=(r&1<<i-n-1)>>i-n-1<<o,e[s]=a}},wi=class{},Rn=class extends wi{constructor(){super(...arguments),this.buffer=null}},Bn=class extends wi{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.onHeader&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");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.")}},fo=class extends wi{constructor(e,t){if(super(),this.stream=e,this.options=t,!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(t!==void 0&&typeof t!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(t&&t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},Ie,N,dr,Fn,cr,Dn,pr,Un,vi,fr,ur,Wn,zn=class{constructor(){x(this,dr),x(this,cr),x(this,pr),x(this,vi),x(this,ur),this.pos=0,x(this,Ie,new Uint8Array(8)),x(this,N,new DataView(h(this,Ie).buffer)),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}seek(e){this.pos=e}writeEBMLVarInt(e,t=co(e)){let i=0;switch(t){case 1:h(this,N).setUint8(i++,128|e);break;case 2:h(this,N).setUint8(i++,64|e>>8),h(this,N).setUint8(i++,e);break;case 3:h(this,N).setUint8(i++,32|e>>16),h(this,N).setUint8(i++,e>>8),h(this,N).setUint8(i++,e);break;case 4:h(this,N).setUint8(i++,16|e>>24),h(this,N).setUint8(i++,e>>16),h(this,N).setUint8(i++,e>>8),h(this,N).setUint8(i++,e);break;case 5:h(this,N).setUint8(i++,8|e/2**32&7),h(this,N).setUint8(i++,e>>24),h(this,N).setUint8(i++,e>>16),h(this,N).setUint8(i++,e>>8),h(this,N).setUint8(i++,e);break;case 6:h(this,N).setUint8(i++,4|e/2**40&3),h(this,N).setUint8(i++,e/2**32|0),h(this,N).setUint8(i++,e>>24),h(this,N).setUint8(i++,e>>16),h(this,N).setUint8(i++,e>>8),h(this,N).setUint8(i++,e);break;default:throw new Error("Bad EBML VINT size "+t)}this.write(h(this,Ie).subarray(0,i))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.pos),T(this,vi,fr).call(this,e.id),Array.isArray(e.data)){let t=this.pos,i=e.size===-1?1:e.size??4;e.size===-1?T(this,dr,Fn).call(this,255):this.seek(this.pos+i);let r=this.pos;if(this.dataOffsets.set(e,r),this.writeEBML(e.data),e.size!==-1){let n=this.pos-r,s=this.pos;this.seek(t),this.writeEBMLVarInt(n,i),this.seek(s)}}else if(typeof e.data=="number"){let t=e.size??In(e.data);this.writeEBMLVarInt(t),T(this,vi,fr).call(this,e.data,t)}else typeof e.data=="string"?(this.writeEBMLVarInt(e.data.length),T(this,ur,Wn).call(this,e.data)):e.data instanceof Uint8Array?(this.writeEBMLVarInt(e.data.byteLength,e.size),this.write(e.data)):e.data instanceof Pn?(this.writeEBMLVarInt(4),T(this,cr,Dn).call(this,e.data.value)):e.data instanceof hr&&(this.writeEBMLVarInt(8),T(this,pr,Un).call(this,e.data.value))}};Ie=new WeakMap,N=new WeakMap,dr=new WeakSet,Fn=function(e){h(this,N).setUint8(0,e),this.write(h(this,Ie).subarray(0,1))},cr=new WeakSet,Dn=function(e){h(this,N).setFloat32(0,e,!1),this.write(h(this,Ie).subarray(0,4))},pr=new WeakSet,Un=function(e){h(this,N).setFloat64(0,e,!1),this.write(h(this,Ie))},vi=new WeakSet,fr=function(e,t=In(e)){let i=0;switch(t){case 6:h(this,N).setUint8(i++,e/2**40|0);case 5:h(this,N).setUint8(i++,e/2**32|0);case 4:h(this,N).setUint8(i++,e>>24);case 3:h(this,N).setUint8(i++,e>>16);case 2:h(this,N).setUint8(i++,e>>8);case 1:h(this,N).setUint8(i++,e);break;default:throw new Error("Bad UINT size "+t)}this.write(h(this,Ie).subarray(0,i))},ur=new WeakSet,Wn=function(e){this.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))};var yi,He,It,bi,mr,uo=class extends zn{constructor(e){super(),x(this,bi),x(this,yi,void 0),x(this,He,new ArrayBuffer(2**16)),x(this,It,new Uint8Array(h(this,He))),F(this,yi,e)}write(e){T(this,bi,mr).call(this,this.pos+e.byteLength),h(this,It).set(e,this.pos),this.pos+=e.byteLength}finalize(){T(this,bi,mr).call(this,this.pos),h(this,yi).buffer=h(this,He).slice(0,this.pos)}};yi=new WeakMap,He=new WeakMap,It=new WeakMap,bi=new WeakSet,mr=function(e){let t=h(this,He).byteLength;for(;t<e;)t*=2;if(t===h(this,He).byteLength)return;let i=new ArrayBuffer(t),r=new Uint8Array(i);r.set(h(this,It),0),F(this,He,i),F(this,It,r)};var ot,ge,we,qe,Rt=class extends zn{constructor(e){super(),this.target=e,x(this,ot,!1),x(this,ge,void 0),x(this,we,void 0),x(this,qe,void 0)}write(e){if(!h(this,ot))return;let t=this.pos;if(t<h(this,we)){if(t+e.byteLength<=h(this,we))return;e=e.subarray(h(this,we)-t),t=0}let i=t+e.byteLength-h(this,we),r=h(this,ge).byteLength;for(;r<i;)r*=2;if(r!==h(this,ge).byteLength){let n=new Uint8Array(r);n.set(h(this,ge),0),F(this,ge,n)}h(this,ge).set(e,t-h(this,we)),F(this,qe,Math.max(h(this,qe),t+e.byteLength))}startTrackingWrites(){F(this,ot,!0),F(this,ge,new Uint8Array(2**10)),F(this,we,this.pos),F(this,qe,this.pos)}getTrackedWrites(){if(!h(this,ot))throw new Error("Can't get tracked writes since nothing was tracked.");let t={data:h(this,ge).subarray(0,h(this,qe)-h(this,we)),start:h(this,we),end:h(this,qe)};return F(this,ge,void 0),F(this,ot,!1),t}};ot=new WeakMap,ge=new WeakMap,we=new WeakMap,qe=new WeakMap;var mo=2**24,go=2,Xe,lt,Bt,Ft,ke,ae,_i,gr,wr,On,vr,Vn,Dt,xi,yr=class extends Rt{constructor(e,t){var i,r;super(e),x(this,_i),x(this,wr),x(this,vr),x(this,Dt),x(this,Xe,[]),x(this,lt,0),x(this,Bt,void 0),x(this,Ft,void 0),x(this,ke,void 0),x(this,ae,[]),F(this,Bt,t),F(this,Ft,((i=e.options)==null?void 0:i.chunked)??!1),F(this,ke,((r=e.options)==null?void 0:r.chunkSize)??mo)}write(e){super.write(e),h(this,Xe).push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}flush(){var i,r;if(h(this,Xe).length===0)return;let e=[],t=[...h(this,Xe)].sort((n,s)=>n.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let s=e[e.length-1],a=t[n];a.start<=s.start+s.size?s.size=Math.max(s.size,a.start+a.data.byteLength-s.start):e.push({start:a.start,size:a.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let s of h(this,Xe))n.start<=s.start&&s.start<n.start+n.size&&n.data.set(s.data,s.start-n.start);if(h(this,Ft))T(this,_i,gr).call(this,n.data,n.start),T(this,Dt,xi).call(this);else{if(h(this,Bt)&&n.start<h(this,lt))throw new Error("Internal error: Monotonicity violation.");(r=(i=this.target.options).onData)==null||r.call(i,n.data,n.start),F(this,lt,n.start+n.data.byteLength)}}h(this,Xe).length=0}finalize(){h(this,Ft)&&T(this,Dt,xi).call(this,!0)}};Xe=new WeakMap,lt=new WeakMap,Bt=new WeakMap,Ft=new WeakMap,ke=new WeakMap,ae=new WeakMap,_i=new WeakSet,gr=function(e,t){let i=h(this,ae).findIndex(o=>o.start<=t&&t<o.start+h(this,ke));i===-1&&(i=T(this,vr,Vn).call(this,t));let r=h(this,ae)[i],n=t-r.start,s=e.subarray(0,Math.min(h(this,ke)-n,e.byteLength));r.data.set(s,n);let a={start:n,end:n+s.byteLength};if(T(this,wr,On).call(this,r,a),r.written[0].start===0&&r.written[0].end===h(this,ke)&&(r.shouldFlush=!0),h(this,ae).length>go){for(let o=0;o<h(this,ae).length-1;o++)h(this,ae)[o].shouldFlush=!0;T(this,Dt,xi).call(this)}s.byteLength<e.byteLength&&T(this,_i,gr).call(this,e.subarray(s.byteLength),t+s.byteLength)},wr=new WeakSet,On=function(e,t){let i=0,r=e.written.length-1,n=-1;for(;i<=r;){let s=Math.floor(i+(r-i+1)/2);e.written[s].start<=t.start?(i=s+1,n=s):r=s-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)},vr=new WeakSet,Vn=function(e){let i={start:Math.floor(e/h(this,ke))*h(this,ke),data:new Uint8Array(h(this,ke)),written:[],shouldFlush:!1};return h(this,ae).push(i),h(this,ae).sort((r,n)=>r.start-n.start),h(this,ae).indexOf(i)},Dt=new WeakSet,xi=function(e=!1){var t,i;for(let r=0;r<h(this,ae).length;r++){let n=h(this,ae)[r];if(!(!n.shouldFlush&&!e)){for(let s of n.written){if(h(this,Bt)&&n.start+s.start<h(this,lt))throw new Error("Internal error: Monotonicity violation.");(i=(t=this.target.options).onData)==null||i.call(t,n.data.subarray(s.start,s.end),n.start+s.start),F(this,lt,n.start+s.end)}h(this,ae).splice(r--,1)}}};var wo=class extends yr{constructor(e,t){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}),t)}},ht=1,Ut=2,Si=3,vo=1,yo=2,bo=17,_o=2**15,Wt=2**13,Ln="https://github.com/Vanilagy/webm-muxer",Gn=6,Nn=5,xo=["strict","offset","permissive"],R,A,zt,Ot,Te,dt,ct,Ye,pt,Re,ft,ut,ve,Vt,mt,Be,Fe,Je,Lt,Gt,gt,wt,Ci,Nt,$t,br,$n,_r,jn,xr,Hn,Sr,qn,Cr,Xn,Er,Yn,kr,Jn,Ei,Tr,ki,Ar,Mr,Kn,Ke,vt,Ze,yt,Pr,Zn,Ir,Qn,jt,Ti,Ht,Ai,Rr,es,ye,Ae,bt,qt,Xt,Mi,Br,ts,Pi,Fr,Yt,Ii,So=class{constructor(e){x(this,br),x(this,_r),x(this,xr),x(this,Sr),x(this,Cr),x(this,Er),x(this,kr),x(this,Ei),x(this,ki),x(this,Mr),x(this,Ke),x(this,Ze),x(this,Pr),x(this,Ir),x(this,jt),x(this,Ht),x(this,Rr),x(this,ye),x(this,bt),x(this,Xt),x(this,Br),x(this,Pi),x(this,Yt),x(this,R,void 0),x(this,A,void 0),x(this,zt,void 0),x(this,Ot,void 0),x(this,Te,void 0),x(this,dt,void 0),x(this,ct,void 0),x(this,Ye,void 0),x(this,pt,void 0),x(this,Re,void 0),x(this,ft,void 0),x(this,ut,void 0),x(this,ve,void 0),x(this,Vt,void 0),x(this,mt,0),x(this,Be,[]),x(this,Fe,[]),x(this,Je,[]),x(this,Lt,void 0),x(this,Gt,void 0),x(this,gt,-1),x(this,wt,-1),x(this,Ci,-1),x(this,Nt,void 0),x(this,$t,!1),T(this,br,$n).call(this,e),F(this,R,{type:"webm",firstTimestampBehavior:"strict",...e}),this.target=e.target;let t=!!h(this,R).streaming;if(e.target instanceof Rn)F(this,A,new uo(e.target));else if(e.target instanceof Bn)F(this,A,new yr(e.target,t));else if(e.target instanceof fo)F(this,A,new wo(e.target,t));else throw new Error(`Invalid target: ${e.target}`);T(this,_r,jn).call(this)}addVideoChunk(e,t,i){if(!(e instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (chunk) must be of type EncodedVideoChunk.");if(t&&typeof t!="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(e.byteLength);e.copyTo(r),this.addVideoChunkRaw(r,e.type,i??e.timestamp,t)}addVideoChunkRaw(e,t,i,r){if(!(e instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(t!=="key"&&t!=="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,Yt,Ii).call(this),!h(this,R).video)throw new Error("No video track declared.");h(this,Lt)===void 0&&F(this,Lt,i),r&&T(this,Pr,Zn).call(this,r);let n=T(this,Ht,Ai).call(this,e,t,i,ht);for(h(this,R).video.codec==="V_VP9"&&T(this,Ir,Qn).call(this,n),F(this,gt,n.timestamp);h(this,Fe).length>0&&h(this,Fe)[0].timestamp<=n.timestamp;){let s=h(this,Fe).shift();T(this,ye,Ae).call(this,s,!1)}!h(this,R).audio||n.timestamp<=h(this,wt)?T(this,ye,Ae).call(this,n,!0):h(this,Be).push(n),T(this,jt,Ti).call(this),T(this,Ke,vt).call(this)}addAudioChunk(e,t,i){if(!(e instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (chunk) must be of type EncodedAudioChunk.");if(t&&typeof t!="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(e.byteLength);e.copyTo(r),this.addAudioChunkRaw(r,e.type,i??e.timestamp,t)}addAudioChunkRaw(e,t,i,r){if(!(e instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(t!=="key"&&t!=="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,Yt,Ii).call(this),!h(this,R).audio)throw new Error("No audio track declared.");h(this,Gt)===void 0&&F(this,Gt,i),r!=null&&r.decoderConfig&&(h(this,R).streaming?F(this,Re,T(this,bt,qt).call(this,r.decoderConfig.description)):T(this,Xt,Mi).call(this,h(this,Re),r.decoderConfig.description));let n=T(this,Ht,Ai).call(this,e,t,i,Ut);for(F(this,wt,n.timestamp);h(this,Be).length>0&&h(this,Be)[0].timestamp<=n.timestamp;){let s=h(this,Be).shift();T(this,ye,Ae).call(this,s,!0)}!h(this,R).video||n.timestamp<=h(this,gt)?T(this,ye,Ae).call(this,n,!h(this,R).video):h(this,Fe).push(n),T(this,jt,Ti).call(this),T(this,Ke,vt).call(this)}addSubtitleChunk(e,t,i){if(typeof e!="object"||!e)throw new TypeError("addSubtitleChunk's first argument (chunk) must be an object.");if(!(e.body instanceof Uint8Array))throw new TypeError("body must be an instance of Uint8Array.");if(!Number.isFinite(e.timestamp)||e.timestamp<0)throw new TypeError("timestamp must be a non-negative real number.");if(!Number.isFinite(e.duration)||e.duration<0)throw new TypeError("duration must be a non-negative real number.");if(e.additions&&!(e.additions instanceof Uint8Array))throw new TypeError("additions, when present, must be an instance of Uint8Array.");if(typeof t!="object")throw new TypeError("addSubtitleChunk's second argument (meta) must be an object.");if(T(this,Yt,Ii).call(this),!h(this,R).subtitles)throw new Error("No subtitle track declared.");t!=null&&t.decoderConfig&&(h(this,R).streaming?F(this,ft,T(this,bt,qt).call(this,t.decoderConfig.description)):T(this,Xt,Mi).call(this,h(this,ft),t.decoderConfig.description));let r=T(this,Ht,Ai).call(this,e.body,"key",i??e.timestamp,Si,e.duration,e.additions);F(this,Ci,r.timestamp),h(this,Je).push(r),T(this,jt,Ti).call(this),T(this,Ke,vt).call(this)}finalize(){if(h(this,$t))throw new Error("Cannot finalize a muxer more than once.");for(;h(this,Be).length>0;)T(this,ye,Ae).call(this,h(this,Be).shift(),!0);for(;h(this,Fe).length>0;)T(this,ye,Ae).call(this,h(this,Fe).shift(),!0);for(;h(this,Je).length>0&&h(this,Je)[0].timestamp<=h(this,mt);)T(this,ye,Ae).call(this,h(this,Je).shift(),!1);if(h(this,ve)&&T(this,Pi,Fr).call(this),h(this,A).writeEBML(h(this,ut)),!h(this,R).streaming){let e=h(this,A).pos,t=h(this,A).pos-h(this,Ze,yt);h(this,A).seek(h(this,A).offsets.get(h(this,zt))+4),h(this,A).writeEBMLVarInt(t,Gn),h(this,ct).data=new hr(h(this,mt)),h(this,A).seek(h(this,A).offsets.get(h(this,ct))),h(this,A).writeEBML(h(this,ct)),h(this,Te).data[0].data[1].data=h(this,A).offsets.get(h(this,ut))-h(this,Ze,yt),h(this,Te).data[1].data[1].data=h(this,A).offsets.get(h(this,Ot))-h(this,Ze,yt),h(this,Te).data[2].data[1].data=h(this,A).offsets.get(h(this,dt))-h(this,Ze,yt),h(this,A).seek(h(this,A).offsets.get(h(this,Te))),h(this,A).writeEBML(h(this,Te)),h(this,A).seek(e)}T(this,Ke,vt).call(this),h(this,A).finalize(),F(this,$t,!0)}};R=new WeakMap,A=new WeakMap,zt=new WeakMap,Ot=new WeakMap,Te=new WeakMap,dt=new WeakMap,ct=new WeakMap,Ye=new WeakMap,pt=new WeakMap,Re=new WeakMap,ft=new WeakMap,ut=new WeakMap,ve=new WeakMap,Vt=new WeakMap,mt=new WeakMap,Be=new WeakMap,Fe=new WeakMap,Je=new WeakMap,Lt=new WeakMap,Gt=new WeakMap,gt=new WeakMap,wt=new WeakMap,Ci=new WeakMap,Nt=new WeakMap,$t=new WeakMap,br=new WeakSet,$n=function(e){if(typeof e!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(e.target instanceof wi))throw new TypeError("The target must be provided and an instance of Target.");if(e.video){if(typeof e.video.codec!="string")throw new TypeError(`Invalid video codec: ${e.video.codec}. Must be a string.`);if(!Number.isInteger(e.video.width)||e.video.width<=0)throw new TypeError(`Invalid video width: ${e.video.width}. Must be a positive integer.`);if(!Number.isInteger(e.video.height)||e.video.height<=0)throw new TypeError(`Invalid video height: ${e.video.height}. Must be a positive integer.`);if(e.video.frameRate!==void 0&&(!Number.isFinite(e.video.frameRate)||e.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.video.frameRate}. Must be a positive number.`);if(e.video.alpha!==void 0&&typeof e.video.alpha!="boolean")throw new TypeError(`Invalid video alpha: ${e.video.alpha}. Must be a boolean.`)}if(e.audio){if(typeof e.audio.codec!="string")throw new TypeError(`Invalid audio codec: ${e.audio.codec}. Must be a string.`);if(!Number.isInteger(e.audio.numberOfChannels)||e.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${e.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(e.audio.sampleRate)||e.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${e.audio.sampleRate}. Must be a positive integer.`);if(e.audio.bitDepth!==void 0&&(!Number.isInteger(e.audio.bitDepth)||e.audio.bitDepth<=0))throw new TypeError(`Invalid audio bit depth: ${e.audio.bitDepth}. Must be a positive integer.`)}if(e.subtitles&&typeof e.subtitles.codec!="string")throw new TypeError(`Invalid subtitles codec: ${e.subtitles.codec}. Must be a string.`);if(e.type!==void 0&&!["webm","matroska"].includes(e.type))throw new TypeError(`Invalid type: ${e.type}. Must be 'webm' or 'matroska'.`);if(e.firstTimestampBehavior&&!xo.includes(e.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${e.firstTimestampBehavior}`);if(e.streaming!==void 0&&typeof e.streaming!="boolean")throw new TypeError(`Invalid streaming option: ${e.streaming}. Must be a boolean.`)},_r=new WeakSet,jn=function(){h(this,A)instanceof Rt&&h(this,A).target.options.onHeader&&h(this,A).startTrackingWrites(),T(this,xr,Hn).call(this),h(this,R).streaming||T(this,Er,Yn).call(this),T(this,kr,Jn).call(this),T(this,Sr,qn).call(this),T(this,Cr,Xn).call(this),h(this,R).streaming||(T(this,Ei,Tr).call(this),T(this,ki,Ar).call(this)),T(this,Mr,Kn).call(this),T(this,Ke,vt).call(this)},xr=new WeakSet,Hn=function(){let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:h(this,R).type??"webm"},{id:17031,data:2},{id:17029,data:2}]};h(this,A).writeEBML(e)},Sr=new WeakSet,qn=function(){F(this,pt,{id:236,size:4,data:new Uint8Array(Wt)}),F(this,Re,{id:236,size:4,data:new Uint8Array(Wt)}),F(this,ft,{id:236,size:4,data:new Uint8Array(Wt)})},Cr=new WeakSet,Xn=function(){F(this,Ye,{id:21936,data:[{id:21937,data:2},{id:21946,data:2},{id:21947,data:2},{id:21945,data:0}]})},Er=new WeakSet,Yn=function(){const e=new Uint8Array([28,83,187,107]),t=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]);F(this,Te,{id:290298740,data:[{id:19899,data:[{id:21419,data:e},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:i},{id:21420,size:5,data:0}]}]})},kr=new WeakSet,Jn=function(){let e={id:17545,data:new hr(0)};F(this,ct,e);let t={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Ln},{id:22337,data:Ln},h(this,R).streaming?null:e]};F(this,Ot,t)},Ei=new WeakSet,Tr=function(){let e={id:374648427,data:[]};F(this,dt,e),h(this,R).video&&e.data.push({id:174,data:[{id:215,data:ht},{id:29637,data:ht},{id:131,data:vo},{id:134,data:h(this,R).video.codec},h(this,pt),h(this,R).video.frameRate?{id:2352003,data:1e9/h(this,R).video.frameRate}:null,{id:224,data:[{id:176,data:h(this,R).video.width},{id:186,data:h(this,R).video.height},h(this,R).video.alpha?{id:21440,data:1}:null,h(this,Ye)]}]}),h(this,R).audio&&(F(this,Re,h(this,R).streaming?h(this,Re)||null:{id:236,size:4,data:new Uint8Array(Wt)}),e.data.push({id:174,data:[{id:215,data:Ut},{id:29637,data:Ut},{id:131,data:yo},{id:134,data:h(this,R).audio.codec},h(this,Re),{id:225,data:[{id:181,data:new Pn(h(this,R).audio.sampleRate)},{id:159,data:h(this,R).audio.numberOfChannels},h(this,R).audio.bitDepth?{id:25188,data:h(this,R).audio.bitDepth}:null]}]})),h(this,R).subtitles&&e.data.push({id:174,data:[{id:215,data:Si},{id:29637,data:Si},{id:131,data:bo},{id:134,data:h(this,R).subtitles.codec},h(this,ft)]})},ki=new WeakSet,Ar=function(){let e={id:408125543,size:h(this,R).streaming?-1:Gn,data:[h(this,R).streaming?null:h(this,Te),h(this,Ot),h(this,dt)]};if(F(this,zt,e),h(this,A).writeEBML(e),h(this,A)instanceof Rt&&h(this,A).target.options.onHeader){let{data:t,start:i}=h(this,A).getTrackedWrites();h(this,A).target.options.onHeader(t,i)}},Mr=new WeakSet,Kn=function(){F(this,ut,{id:475249515,data:[]})},Ke=new WeakSet,vt=function(){h(this,A)instanceof yr&&h(this,A).flush()},Ze=new WeakSet,yt=function(){return h(this,A).dataOffsets.get(h(this,zt))},Pr=new WeakSet,Zn=function(e){if(e.decoderConfig){if(e.decoderConfig.colorSpace){let t=e.decoderConfig.colorSpace;if(F(this,Nt,t),h(this,Ye).data=[{id:21937,data:{rgb:1,bt709:1,bt470bg:5,smpte170m:6}[t.matrix]},{id:21946,data:{bt709:1,smpte170m:6,"iec61966-2-1":13}[t.transfer]},{id:21947,data:{bt709:1,bt470bg:5,smpte170m:6}[t.primaries]},{id:21945,data:[1,2][Number(t.fullRange)]}],!h(this,R).streaming){let i=h(this,A).pos;h(this,A).seek(h(this,A).offsets.get(h(this,Ye))),h(this,A).writeEBML(h(this,Ye)),h(this,A).seek(i)}}e.decoderConfig.description&&(h(this,R).streaming?F(this,pt,T(this,bt,qt).call(this,e.decoderConfig.description)):T(this,Xt,Mi).call(this,h(this,pt),e.decoderConfig.description))}},Ir=new WeakSet,Qn=function(e){if(e.type!=="key"||!h(this,Nt))return;let t=0;if(at(e.data,0,2)!==2)return;t+=2;let i=(at(e.data,t+1,t+2)<<1)+at(e.data,t+0,t+1);t+=2,i===3&&t++;let r=at(e.data,t+0,t+1);if(t++,r)return;let n=at(e.data,t+0,t+1);if(t++,n!==0)return;t+=2;let s=at(e.data,t+0,t+24);if(t+=24,s!==4817730)return;i>=2&&t++;let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[h(this,Nt).matrix];po(e.data,t+0,t+3,a)},jt=new WeakSet,Ti=function(){let e=Math.min(h(this,R).video?h(this,gt):1/0,h(this,R).audio?h(this,wt):1/0),t=h(this,Je);for(;t.length>0&&t[0].timestamp<=e;)T(this,ye,Ae).call(this,t.shift(),!h(this,R).video&&!h(this,R).audio)},Ht=new WeakSet,Ai=function(e,t,i,r,n,s){let a=T(this,Rr,es).call(this,i,r);return{data:e,additions:s,type:t,timestamp:a,duration:n,trackNumber:r}},Rr=new WeakSet,es=function(e,t){let i=t===ht?h(this,gt):t===Ut?h(this,wt):h(this,Ci);if(t!==Si){let r=t===ht?h(this,Lt):h(this,Gt);if(h(this,R).firstTimestampBehavior==="strict"&&i===-1&&e!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received ${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 the document, which is probably what you want.
|
|
27
27
|
|
|
28
28
|
If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
|
|
29
29
|
If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'permissive'.
|
|
30
|
-
`);h(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){h(this,R).streaming&&!h(this,de)&&(T(this,Ei,kr).call(this),T(this,ki,Tr).call(this));let i=Math.floor(t.timestamp/1e3),r=i-h(this,Ve),n=e&&t.type==="key"&&r>=1e3,s=r>=bo;if((!h(this,vt)||n||s)&&(T(this,Rr,es).call(this,i),r=0),r<0)return;let a=new Uint8Array(4),o=new DataView(a.buffer);if(o.setUint8(0,128|t.trackNumber),o.setInt16(1,r,!1),t.duration===void 0&&!t.additions){o.setUint8(3,+(t.type==="key")<<7);let f={id:163,data:[a,t.data]};h(this,A).writeEBML(f)}else{let f=Math.floor(t.duration/1e3),g={id:160,data:[{id:161,data:[a,t.data]},t.duration!==void 0?{id:155,data:f}:null,t.additions?{id:30113,data:t.additions}:null]};h(this,A).writeEBML(g)}F(this,me,Math.max(h(this,me),i))},be=new WeakSet,qe=function(t){return{id:25506,size:4,data:new Uint8Array(t)}},Xe=new WeakSet,Mi=function(t,e){let i=h(this,A).pos;h(this,A).seek(h(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=[T(this,be,qe).call(this,e),{id:236,size:4,data:new Uint8Array(n)}],h(this,A).writeEBML(t),h(this,A).seek(i)},Rr=new WeakSet,es=function(t){h(this,vt)&&T(this,Pi,Br).call(this),h(this,A)instanceof Re&&h(this,A).target.options.onCluster&&h(this,A).startTrackingWrites(),F(this,vt,{id:524531317,size:h(this,R).streaming?-1:Nn,data:[{id:231,data:t}]}),h(this,A).writeEBML(h(this,vt)),F(this,Ve,t);let e=h(this,A).offsets.get(h(this,vt))-h(this,Zt,ye);h(this,ue).data.push({id:187,data:[{id:179,data:t},h(this,R).video?{id:183,data:[{id:247,data:he},{id:241,data:e}]}:null,h(this,R).audio?{id:183,data:[{id:247,data:Ue},{id:241,data:e}]}:null]})},Pi=new WeakSet,Br=function(){if(!h(this,R).streaming){let t=h(this,A).pos-h(this,A).dataOffsets.get(h(this,vt)),e=h(this,A).pos;h(this,A).seek(h(this,A).offsets.get(h(this,vt))+4),h(this,A).writeEBMLVarInt(t,Nn),h(this,A).seek(e)}if(h(this,A)instanceof Re&&h(this,A).target.options.onCluster){let{data:t,start:e}=h(this,A).getTrackedWrites();h(this,A).target.options.onCluster(t,e,h(this,Ve))}},Ye=new WeakSet,Ii=function(){if(h(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 o=t.frames[a],f=ln(o,n),g=hn(o,f);i.writeFrame(g,t.width,t.height,{palette:f,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"]},ko={avc1:"avc",av01:"av1",hvc1:"hevc",hev1:"hevc"},To={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"?ko:To)[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 o=await VideoEncoder.isConfigSupported({codec:s,width:e,height:i,bitrate:n,framerate:r,...a});if(o&&o.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))),o=await Mo(i,{width:r,height:n,fps:s,bitrate:a});if(!o)throw new Error(`[p5.export] WebCodecs: no supported ${i.toUpperCase()} codec for ${r}×${n} @ ${s}fps`);const f=i==="mp4"?new yn:new Rn,g=Ao(i,o),v=i==="mp4"?new lo({target:f,video:{codec:g,width:r,height:n,frameRate:s},fastStart:"in-memory"}):new xo({target:f,video:{codec:g,width:r,height:n,frameRate:s}});let u=null;const l=new VideoEncoder({output:(E,D)=>v.addVideoChunk(E,D),error:E=>{u=u||E}}),d={codec:o,width:r,height:n,bitrate:a,framerate:s};o.startsWith("avc1")&&(d.avc={format:"avc"});const c=[{...d,hardwareAcceleration:"prefer-hardware"},{...d}];let m=null;for(const E of c)try{l.configure(E),m=E;break}catch{}if(!m)throw new Error(`[p5.export] could not configure VideoEncoder for ${o}`);const w=1e6/s,y=t.frames.length,M=Math.max(1,Math.round(s*2)),S=16;for(let E=0;E<y;E++){if(u)throw u;for(;l.encodeQueueSize>S;)if(await new Promise(I=>setTimeout(I,0)),u)throw u;const D=new VideoFrame(t.frames[E],{format:"RGBA",codedWidth:r,codedHeight:n,timestamp:Math.round(E*w),duration:Math.round(w)});l.encode(D,{keyFrame:E%M===0}),D.close(),e.onProgress&&e.onProgress((E+1)/y),(E&31)===31&&await new Promise(I=>setTimeout(I,0))}if(await l.flush(),u)throw u;v.finalize();const _=new Blob([f.buffer],{type:i==="mp4"?"video/mp4":"video/webm"});return _.__ext=i,_}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 o=a.getContext("2d"),f=a.captureStream(t.fps),g={mimeType:s.mime};e.bitsPerSecond&&(g.videoBitsPerSecond=e.bitsPerSecond);const v=new MediaRecorder(f,g),u=[];v.ondataavailable=m=>{m.data&&m.data.size&&u.push(m.data)},v.onerror=m=>r(m.error||new Error("MediaRecorder error")),v.onstop=()=>{f.getTracks().forEach(w=>w.stop());const m=new Blob(u,{type:s.mime});m.__ext=s.ext,i(m)},o.putImageData(new ImageData(t.frames[0],t.width,t.height),0,0),v.start();const l=1e3/t.fps;let d=1;const c=()=>{if(d>=t.frames.length){setTimeout(()=>v.stop(),100);return}o.putImageData(new ImageData(t.frames[d],t.width,t.height),0,0),e.onProgress&&e.onProgress((d+1)/t.frames.length),d++,setTimeout(c,l)};setTimeout(c,l)})}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),o=Math.max(0,e.loop??0),f=Math.max(1,Math.round(1e3/(n||30)));await Do(i,r);const g=document.createElement("canvas");g.width=i,g.height=r;const v=g.getContext("2d"),u=v.createImageData(i,r),l=[];for(let m=0;m<s.length;m++){u.data.set(s[m]),v.putImageData(u,0,0);const w=await is(g,a),y=new Uint8Array(await w.arrayBuffer());l.push(Uo(y)),e.onProgress&&e.onProgress((m+1)/s.length)}const d=Vo([Fr("VP8X",Wo(i,r)),Fr("ANIM",zo(o)),...l.map(m=>Fr("ANMF",Oo(i,r,f,m)))]),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 Ho(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,o=typeof s.pixelDensity=="function"?s.pixelDensity():1,f=a&&a>0&&a!==o;f&&(s.pixelDensity(a),typeof s.redraw=="function"&&s.redraw());const g=new ea({canvas:n,...r}),v=g.stop.bind(g);let u=!f;return g.stop=function(){v(),u||(u=!0,s.pixelDensity(o),typeof s.redraw=="function"&&s.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,n={}){if(!r||!r.frames.length)throw new Error("[p5.export] exportVideoBuffer: buffer has no frames");const s=(n.format||"webm").toLowerCase();let a,o;if(s==="gif")a=await So(r,n),o="gif";else if(s==="webp")a=await Fo(r,n),o="webp";else if(s==="webm"||s==="mp4")a=await Bo(r,{...n,format:s}),o=a.__ext||(s==="mp4"?"mp4":"webm");else throw new Error(`[p5.export] unsupported video format: ${s}`);const f=n.filename?_t(n.filename,o):bt(o);return rt(a,f),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 qo(t,e){e.saveSTL=function(i,r,n={}){const s=ns(this,i);if(!s||typeof s.saveStl!="function"){const o=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. "+o)}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{--p5export-pink: #ed225d;--p5export-pink-dark: #d4144f;--p5export-ink: #333;--p5export-muted: #6b6b6b;--p5export-line: #b5b5b5;--p5export-line-soft: #d6d6d6;--p5export-toolbar: #f4f4f4;--p5export-canvas: #fff;position:fixed;top:16px;right:16px;z-index:99999;width:276px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow:hidden;color:var(--p5export-ink);background:var(--p5export-canvas);border:1px solid var(--p5export-line);border-radius:0;box-shadow:3px 3px #0000001f;font-family:Montserrat,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:normal;letter-spacing:normal;word-spacing:0;-webkit-user-select:none;user-select:none}.p5export-panel *,.p5export-panel *:before,.p5export-panel *:after{box-sizing:border-box}.p5export-header{display:flex;min-height:42px;align-items:center;justify-content:space-between;padding:0 8px 0 0;background:var(--p5export-toolbar);border-bottom:1px dashed var(--p5export-line);cursor:grab;touch-action:none}.p5export-header:active{cursor:grabbing}.p5export-title{display:inline-flex;align-items:center;gap:9px;min-width:0;font-size:12px;font-weight:400}.p5export-brand-mark{display:inline-flex;width:48px;min-height:41px;align-items:center;justify-content:center;color:#fff;background:var(--p5export-pink);font-size:17px;font-weight:700;letter-spacing:-.8px}.p5export-toggle{width:26px;height:26px;padding:0;color:var(--p5export-ink);background:transparent;border:1px solid transparent;border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font-family:inherit;font-size:18px;line-height:22px}.p5export-toggle:hover{background:#e1e1e1;border-color:var(--p5export-line)}.p5export-tabs{display:grid;grid-template-columns:1fr 1fr;padding:0;background:var(--p5export-toolbar);border-bottom:1px solid var(--p5export-line)}.p5export-tab{min-height:35px;margin:0;padding:0 12px;color:var(--p5export-muted);background:transparent;border:0;border-right:1px solid var(--p5export-line-soft);border-bottom:3px solid transparent;border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font:inherit;text-align:left}.p5export-tab:last-child{border-right:0}.p5export-tab:hover{color:var(--p5export-ink);background:#e9e9e9}.p5export-tab.is-active{color:var(--p5export-pink);background:var(--p5export-canvas);border-bottom-color:var(--p5export-pink);font-weight:400}.p5export-body{max-height:calc(100vh - 94px);padding:14px 12px 12px;overflow-y:auto}.p5export-panel.is-collapsed .p5export-body,.p5export-panel.is-collapsed .p5export-tabs{display:none}.p5export-view:not([hidden]){display:flex;flex-direction:column;gap:10px}.p5export-row{display:grid;grid-template-columns:68px minmax(0,1fr);align-items:center;gap:8px}.p5export-row>label:first-child{color:var(--p5export-muted);font-size:12px;font-weight:400}.p5export-check{display:flex;min-height:30px;align-items:center;gap:7px;color:var(--p5export-ink);cursor:pointer}.p5export-check input{width:14px;height:14px;margin:0;accent-color:var(--p5export-pink);cursor:pointer}.p5export-input,.p5export-select{width:100%;min-height:32px;padding:6px 8px;color:var(--p5export-ink);background:#fff;border:1px solid var(--p5export-line);border-radius:0;outline:0;font:inherit}.p5export-input:hover,.p5export-select:hover{border-color:#777}.p5export-input:focus,.p5export-select:focus{border-color:var(--p5export-pink);box-shadow:0 0 0 1px var(--p5export-pink)}.p5export-input::placeholder{color:#929292}.p5export-select{cursor:pointer}.p5export-input:disabled,.p5export-select:disabled{color:#8d8d8d;background:#ececec;cursor:not-allowed}.p5export-btn{min-height:34px;padding:7px 12px;color:#fff;background:var(--p5export-pink);border:1px solid var(--p5export-pink);border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font:inherit;font-weight:700;line-height:12px}.p5export-btn:hover{background:var(--p5export-pink-dark);border-color:var(--p5export-pink-dark)}.p5export-btn:active{transform:translate(1px,1px)}.p5export-btn.is-ghost{color:var(--p5export-ink);background:var(--p5export-toolbar);border-color:var(--p5export-line)}.p5export-btn.is-ghost:hover{background:#e5e5e5}.p5export-btn.is-danger{color:#fff;background:#b52b46;border-color:#b52b46}.p5export-btn:disabled{opacity:.45;cursor:not-allowed;transform:none}.p5export-status{padding:7px 8px;color:var(--p5export-muted);background:var(--p5export-toolbar);border-left:3px solid var(--p5export-line)}.p5export-status.is-error{color:#8d1732;background:#fff0f4;border-left-color:var(--p5export-pink)}.p5export-status[hidden]{display:none}.p5export-preview:not([hidden]){display:flex;flex-direction:column;gap:6px}.p5export-preview-canvas{display:block;width:100%;background:#eee;border:1px solid var(--p5export-line);border-radius:0;image-rendering:pixelated}.p5export-preview-controls{display:flex;align-items:center;gap:8px;padding:6px 0}.p5export-play{width:24px;height:24px;padding:6px;color:#fff;background:var(--p5export-pink);border:0;border-radius:50%;cursor:pointer}.p5export-play:hover{background:var(--p5export-pink-dark)}.p5export-play svg{display:block;width:100%;height:100%}.p5export-timeline{flex:1;height:3px;margin:0;background:var(--p5export-line);border-radius:0;outline:0;-moz-appearance:none;appearance:none;-webkit-appearance:none;cursor:pointer}.p5export-timeline::-webkit-slider-thumb{width:10px;height:16px;background:var(--p5export-pink);border:0;border-radius:0;-moz-appearance:none;appearance:none;-webkit-appearance:none;cursor:grab}.p5export-timeline::-moz-range-thumb{width:10px;height:16px;background:var(--p5export-pink);border:0;border-radius:0;cursor:grab}.p5export-time{min-width:29px;color:var(--p5export-muted);font-variant-numeric:tabular-nums;text-align:right}.p5export-tab:focus-visible,.p5export-toggle:focus-visible,.p5export-btn:focus-visible,.p5export-play:focus-visible{outline:2px solid var(--p5export-pink);outline-offset:-2px}@media (prefers-reduced-motion: reduce){.p5export-btn:active{transform:none}}";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
|
+
`);h(this,R).firstTimestampBehavior==="offset"&&(e-=r)}if(e<i)throw new Error(`Timestamps must be monotonically increasing (went from ${i} to ${e}).`);if(e<0)throw new Error(`Timestamps must be non-negative (received ${e}).`);return e},ye=new WeakSet,Ae=function(e,t){h(this,R).streaming&&!h(this,dt)&&(T(this,Ei,Tr).call(this),T(this,ki,Ar).call(this));let i=Math.floor(e.timestamp/1e3),r=i-h(this,Vt),n=t&&e.type==="key"&&r>=1e3,s=r>=_o;if((!h(this,ve)||n||s)&&(T(this,Br,ts).call(this,i),r=0),r<0)return;let a=new Uint8Array(4),o=new DataView(a.buffer);if(o.setUint8(0,128|e.trackNumber),o.setInt16(1,r,!1),e.duration===void 0&&!e.additions){o.setUint8(3,+(e.type==="key")<<7);let p={id:163,data:[a,e.data]};h(this,A).writeEBML(p)}else{let p=Math.floor(e.duration/1e3),w={id:160,data:[{id:161,data:[a,e.data]},e.duration!==void 0?{id:155,data:p}:null,e.additions?{id:30113,data:e.additions}:null]};h(this,A).writeEBML(w)}F(this,mt,Math.max(h(this,mt),i))},bt=new WeakSet,qt=function(e){return{id:25506,size:4,data:new Uint8Array(e)}},Xt=new WeakSet,Mi=function(e,t){let i=h(this,A).pos;h(this,A).seek(h(this,A).offsets.get(e));let r=6+t.byteLength,n=Wt-r;if(n<0){let s=t.byteLength+n;t instanceof ArrayBuffer?t=t.slice(0,s):t=t.buffer.slice(0,s),n=0}e=[T(this,bt,qt).call(this,t),{id:236,size:4,data:new Uint8Array(n)}],h(this,A).writeEBML(e),h(this,A).seek(i)},Br=new WeakSet,ts=function(e){h(this,ve)&&T(this,Pi,Fr).call(this),h(this,A)instanceof Rt&&h(this,A).target.options.onCluster&&h(this,A).startTrackingWrites(),F(this,ve,{id:524531317,size:h(this,R).streaming?-1:Nn,data:[{id:231,data:e}]}),h(this,A).writeEBML(h(this,ve)),F(this,Vt,e);let t=h(this,A).offsets.get(h(this,ve))-h(this,Ze,yt);h(this,ut).data.push({id:187,data:[{id:179,data:e},h(this,R).video?{id:183,data:[{id:247,data:ht},{id:241,data:t}]}:null,h(this,R).audio?{id:183,data:[{id:247,data:Ut},{id:241,data:t}]}:null]})},Pi=new WeakSet,Fr=function(){if(!h(this,R).streaming){let e=h(this,A).pos-h(this,A).dataOffsets.get(h(this,ve)),t=h(this,A).pos;h(this,A).seek(h(this,A).offsets.get(h(this,ve))+4),h(this,A).writeEBMLVarInt(e,Nn),h(this,A).seek(t)}if(h(this,A)instanceof Rt&&h(this,A).target.options.onCluster){let{data:e,start:t}=h(this,A).getTrackedWrites();h(this,A).target.options.onCluster(e,t,h(this,Vt))}},Yt=new WeakSet,Ii=function(){if(h(this,$t))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")},new TextEncoder;async function Co(e,t={}){if(!e.frames.length)throw new Error("[p5.export] encodeGIF: no frames to encode");const i=dn(),r=Math.round(1e3/e.fps),n=t.maxColors??256,s=e.frames.length;for(let a=0;a<s;a++){const o=e.frames[a],p=ln(o,n),w=hn(o,p);i.writeFrame(w,e.width,e.height,{palette:p,delay:r}),t.onProgress&&t.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 Eo(){return typeof window<"u"&&typeof window.VideoEncoder=="function"&&typeof window.VideoFrame=="function"}const ko={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"},Ao={vp09:"V_VP9",vp9:"V_VP9",vp8:"V_VP8",av01:"V_AV1"};function Mo(e,t){const i=t.split(".")[0].toLowerCase();return(e==="mp4"?To:Ao)[i]||(e==="mp4"?"avc":"V_VP9")}async function Po(e,{width:t,height:i,fps:r,bitrate:n}){for(const s of ko[e]||[])for(const a of[{hardwareAcceleration:"prefer-hardware"},{}])try{const o=await VideoEncoder.isConfigSupported({codec:s,width:t,height:i,bitrate:n,framerate:r,...a});if(o&&o.supported)return s}catch{}return null}async function Io(e,t){const i=t.format==="mp4"?"mp4":"webm",r=e.width,n=e.height,s=e.fps,a=t.bitsPerSecond??Math.min(4e7,Math.max(15e5,Math.round(r*n*s*.2))),o=await Po(i,{width:r,height:n,fps:s,bitrate:a});if(!o)throw new Error(`[p5.export] WebCodecs: no supported ${i.toUpperCase()} codec for ${r}×${n} @ ${s}fps`);const p=i==="mp4"?new yn:new Rn,w=Mo(i,o),v=i==="mp4"?new ho({target:p,video:{codec:w,width:r,height:n,frameRate:s},fastStart:"in-memory"}):new So({target:p,video:{codec:w,width:r,height:n,frameRate:s}});let m=null;const l=new VideoEncoder({output:(E,D)=>v.addVideoChunk(E,D),error:E=>{m=m||E}}),d={codec:o,width:r,height:n,bitrate:a,framerate:s};o.startsWith("avc1")&&(d.avc={format:"avc"});const c=[{...d,hardwareAcceleration:"prefer-hardware"},{...d}];let u=null;for(const E of c)try{l.configure(E),u=E;break}catch{}if(!u)throw new Error(`[p5.export] could not configure VideoEncoder for ${o}`);const g=1e6/s,y=e.frames.length,M=Math.max(1,Math.round(s*2)),S=16;for(let E=0;E<y;E++){if(m)throw m;for(;l.encodeQueueSize>S;)if(await new Promise(I=>setTimeout(I,0)),m)throw m;const D=new VideoFrame(e.frames[E],{format:"RGBA",codedWidth:r,codedHeight:n,timestamp:Math.round(E*g),duration:Math.round(g)});l.encode(D,{keyFrame:E%M===0}),D.close(),t.onProgress&&t.onProgress((E+1)/y),(E&31)===31&&await new Promise(I=>setTimeout(I,0))}if(await l.flush(),m)throw m;v.finalize();const _=new Blob([p.buffer],{type:i==="mp4"?"video/mp4":"video/webm"});return _.__ext=i,_}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 Ro(e){const t=e==="mp4"?[...Ri.mp4,...Ri.webm]:[...Ri.webm,...Ri.mp4];for(const i of t)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}function Bo(e,t){return new Promise((i,r)=>{const n=t.format||"webm",s=Ro(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=e.width,a.height=e.height;const o=a.getContext("2d"),p=a.captureStream(e.fps),w={mimeType:s.mime};t.bitsPerSecond&&(w.videoBitsPerSecond=t.bitsPerSecond);const v=new MediaRecorder(p,w),m=[];v.ondataavailable=u=>{u.data&&u.data.size&&m.push(u.data)},v.onerror=u=>r(u.error||new Error("MediaRecorder error")),v.onstop=()=>{p.getTracks().forEach(g=>g.stop());const u=new Blob(m,{type:s.mime});u.__ext=s.ext,i(u)},o.putImageData(new ImageData(e.frames[0],e.width,e.height),0,0),v.start();const l=1e3/e.fps;let d=1;const c=()=>{if(d>=e.frames.length){setTimeout(()=>v.stop(),100);return}o.putImageData(new ImageData(e.frames[d],e.width,e.height),0,0),t.onProgress&&t.onProgress((d+1)/e.frames.length),d++,setTimeout(c,l)};setTimeout(c,l)})}async function Fo(e,t={}){if(!e.frames.length)throw new Error("[p5.export] encodeVideo: no frames to encode");if(Eo()){const i=performance.now();try{const r=await Io(e,t),n=performance.now()-i|0;return console.info(`[p5.export] WebCodecs encoded ${e.frames.length} frames in ${n}ms (${e.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 Bo(e,t)}async function Do(e,t={}){if(!e||!e.frames.length)throw new Error("[p5.export] encodeAnimatedWebP: buffer has no frames");const{width:i,height:r,fps:n,frames:s}=e,a=$o(t.quality??.85),o=Math.max(0,t.loop??0),p=Math.max(1,Math.round(1e3/(n||30)));await Uo(i,r);const w=document.createElement("canvas");w.width=i,w.height=r;const v=w.getContext("2d"),m=v.createImageData(i,r),l=[];for(let u=0;u<s.length;u++){m.data.set(s[u]),v.putImageData(m,0,0);const g=await is(w,a),y=new Uint8Array(await g.arrayBuffer());l.push(Wo(y)),t.onProgress&&t.onProgress((u+1)/s.length)}const d=Lo([Dr("VP8X",zo(i,r)),Dr("ANIM",Oo(o)),...l.map(u=>Dr("ANMF",Vo(i,r,p,u)))]),c=new Uint8Array(12+d.length);return Ur(c,0,"RIFF"),rs(c,4,4+d.length),Ur(c,8,"WEBP"),c.set(d,12),new Blob([c],{type:"image/webp"})}async function Uo(e,t){const i=document.createElement("canvas");i.width=Math.min(8,e),i.height=Math.min(8,t);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(e,t){return new Promise((i,r)=>{e.toBlob(n=>n?i(n):r(new Error("canvas.toBlob returned null")),"image/webp",t)})}function Wo(e){let t=12;for(;t+8<=e.length;){const i=String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]),r=No(e,t+4),n=r+(r&1);if(i==="VP8 "||i==="VP8L")return e.slice(t,t+8+n);t+=8+n}throw new Error("[p5.export] no VP8/VP8L chunk found in encoded WebP frame")}function zo(e,t){const i=new Uint8Array(10);return i[0]=2,Jt(i,4,e-1),Jt(i,7,t-1),i}function Oo(e){const t=new Uint8Array(6);return Go(t,4,e),t}function Vo(e,t,i,r){const n=new Uint8Array(16);Jt(n,6,e-1),Jt(n,9,t-1),Jt(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 Dr(e,t){const i=t.length&1,r=new Uint8Array(8+t.length+i);return Ur(r,0,e),rs(r,4,t.length),r.set(t,8),r}function Lo(e){let t=0;for(const n of e)t+=n.length;const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return i}function Ur(e,t,i){for(let r=0;r<i.length;r++)e[t+r]=i.charCodeAt(r)}function Go(e,t,i){e[t]=i&255,e[t+1]=i>>8&255}function Jt(e,t,i){e[t]=i&255,e[t+1]=i>>8&255,e[t+2]=i>>16&255}function rs(e,t,i){e[t]=i&255,e[t+1]=i>>8&255,e[t+2]=i>>16&255,e[t+3]=i>>24&255}function No(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24>>>0}function $o(e){return Math.max(0,Math.min(1,e))}function jo(e,t){let i=t;return i==null&&typeof e.getTargetFrameRate=="function"&&(i=e.getTargetFrameRate()),i==null&&(i=e._targetFrameRate),i=Number(i),Number.isFinite(i)&&i>0?i:30}function Ho(e,t){const i=typeof e.pixelDensity=="function"?e.pixelDensity():1,r=Number(t);if(!(Number.isFinite(r)&&r>0&&r!==i))return()=>{};e.pixelDensity(r),typeof e.redraw=="function"&&e.redraw();let s=!1;return()=>{s||(s=!0,e.pixelDensity(i),typeof e.redraw=="function"&&e.redraw())}}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 qo(e){const t=e==="mp4"?[...Bi.mp4,...Bi.webm]:[...Bi.webm,...Bi.mp4];for(const i of t)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i))return{mime:i,ext:i.startsWith("video/mp4")?"mp4":"webm"};return null}class Xo{constructor(t){const i=qo(t.format||"webm");if(!i)throw new Error("[p5.export] no supported MediaRecorder mime type found");this.ext=i.ext,t.format==="mp4"&&this.ext!=="mp4"&&console.warn("[p5.export] MP4 not supported by this browser — falling back to WebM"),this.stream=t.canvas.captureStream(t.fps||60);const r={mimeType:i.mime};t.bitsPerSecond&&(r.videoBitsPerSecond=t.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=t.filename,this.duration=t.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(t=>{this.recorder.onstop=()=>{const i=new Blob(this.chunks,{type:this._mime}),r=this.filename?_e(this.filename,this.ext):be(this.ext);re(i,r),this.stream.getTracks().forEach(n=>n.stop()),t(i)},this.recorder.state!=="inactive"&&this.recorder.stop()}),this._stopPromise)}get state(){return this.recorder.state}}function Yo(e,t,i){if(t.recordVideo=function(r={}){const n=xe(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 Xo({canvas:n,...r});return s.start(),this._p5ExportVideo=s,s},t.recordWebM=function(r={}){return t.recordVideo.call(this,{...r,format:"webm"})},t.recordMP4=function(r={}){return t.recordVideo.call(this,{...r,format:"mp4"})},t.stopVideo=function(){const r=this._p5ExportVideo;return r?(this._p5ExportVideo=null,r.stop()):null},t.createVideoBuffer=function(r={}){const n=xe(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=jo(s,r.fps),o=Ho(s,r.scale),p=new ia({canvas:n,...r,fps:a}),w=p.stop.bind(p);return p.stop=function(){w(),o()},p.start(),this._p5ExportBuffer=p,p},t.stopVideoBuffer=function(){const r=this._p5ExportBuffer;return r&&r.stop(),r||null},t.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,o;if(s==="gif")a=await Co(r,n),o="gif";else if(s==="webp")a=await Do(r,n),o="webp";else if(s==="webm"||s==="mp4")a=await Fo(r,{...n,format:s}),o=a.__ext||(s==="mp4"?"mp4":"webm");else throw new Error(`[p5.export] unsupported video format: ${s}`);const p=n.filename?_e(n.filename,o):be(o);return re(a,p),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(e,t){return t&&Array.isArray(t.vertices)&&Array.isArray(t.faces)?t:typeof t=="function"&&typeof e.buildGeometry=="function"?e.buildGeometry(t):null}function Jo(e,t){t.saveSTL=function(i,r,n={}){const s=ns(this,i);if(!s||typeof s.saveStl!="function"){const o=Di(this)?"Pass a p5.Geometry (from buildGeometry / loadModel) or a buildGeometry-style callback.":"STL is a 3D format; this sketch is P2D. Use a WEBGL renderer (createCanvas(w, h, WEBGL)) and pass a p5.Geometry.";throw new Error("[p5.export] saveSTL: no exportable geometry. "+o)}const a=r||"sketch.stl";s.saveStl(a,{binary:!!n.binary})},t.saveOBJ=function(i,r){const n=ns(this,i);if(!n||typeof n.saveObj!="function"){const a=Di(this)?"Pass a p5.Geometry (from buildGeometry / loadModel) or a buildGeometry-style callback.":"OBJ is a 3D format; this sketch is P2D. Use a WEBGL renderer and pass a p5.Geometry.";throw new Error("[p5.export] saveOBJ: no exportable geometry. "+a)}const s=r||"sketch.obj";n.saveObj(s)}}const Ko=".p5export-panel{--p5export-pink: #ed225d;--p5export-pink-dark: #d4144f;--p5export-ink: #333;--p5export-muted: #6b6b6b;--p5export-line: #b5b5b5;--p5export-line-soft: #d6d6d6;--p5export-toolbar: #f4f4f4;--p5export-canvas: #fff;position:fixed;top:16px;right:16px;z-index:99999;width:276px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow:hidden;color:var(--p5export-ink);background:var(--p5export-canvas);border:1px solid var(--p5export-line);border-radius:0;box-shadow:3px 3px #0000001f;font-family:Montserrat,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:normal;letter-spacing:normal;word-spacing:0;-webkit-user-select:none;user-select:none}.p5export-panel *,.p5export-panel *:before,.p5export-panel *:after{box-sizing:border-box}.p5export-header{display:flex;min-height:42px;align-items:center;justify-content:space-between;padding:0 8px 0 0;background:var(--p5export-toolbar);border-bottom:1px dashed var(--p5export-line);cursor:grab;touch-action:none}.p5export-header:active{cursor:grabbing}.p5export-title{display:inline-flex;align-items:center;gap:9px;min-width:0;font-size:12px;font-weight:400}.p5export-brand-mark{display:inline-flex;width:48px;min-height:41px;align-items:center;justify-content:center;color:#fff;background:var(--p5export-pink);font-size:17px;font-weight:700;letter-spacing:-.8px}.p5export-toggle{width:26px;height:26px;padding:0;color:var(--p5export-ink);background:transparent;border:1px solid transparent;border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font-family:inherit;font-size:18px;line-height:22px}.p5export-toggle:hover{background:#e1e1e1;border-color:var(--p5export-line)}.p5export-tabs{display:grid;grid-template-columns:1fr 1fr;padding:0;background:var(--p5export-toolbar);border-bottom:1px solid var(--p5export-line)}.p5export-tab{min-height:35px;margin:0;padding:0 12px;color:var(--p5export-muted);background:transparent;border:0;border-right:1px solid var(--p5export-line-soft);border-bottom:3px solid transparent;border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font:inherit;text-align:left}.p5export-tab:last-child{border-right:0}.p5export-tab:hover{color:var(--p5export-ink);background:#e9e9e9}.p5export-tab.is-active{color:var(--p5export-pink);background:var(--p5export-canvas);border-bottom-color:var(--p5export-pink);font-weight:400}.p5export-body{max-height:calc(100vh - 94px);padding:14px 12px 12px;overflow-y:auto}.p5export-panel.is-collapsed .p5export-body,.p5export-panel.is-collapsed .p5export-tabs{display:none}.p5export-view:not([hidden]){display:flex;flex-direction:column;gap:10px}.p5export-row{display:grid;grid-template-columns:68px minmax(0,1fr);align-items:center;gap:8px}.p5export-row>label:first-child{color:var(--p5export-muted);font-size:12px;font-weight:400}.p5export-check{display:flex;min-height:30px;align-items:center;gap:7px;color:var(--p5export-ink);cursor:pointer}.p5export-check input{width:14px;height:14px;margin:0;accent-color:var(--p5export-pink);cursor:pointer}.p5export-input,.p5export-select{width:100%;min-height:32px;padding:6px 8px;color:var(--p5export-ink);background:#fff;border:1px solid var(--p5export-line);border-radius:0;outline:0;font:inherit}.p5export-input:hover,.p5export-select:hover{border-color:#777}.p5export-input:focus,.p5export-select:focus{border-color:var(--p5export-pink);box-shadow:0 0 0 1px var(--p5export-pink)}.p5export-input::placeholder{color:#929292}.p5export-select{cursor:pointer}.p5export-input:disabled,.p5export-select:disabled{color:#8d8d8d;background:#ececec;cursor:not-allowed}.p5export-btn{min-height:34px;padding:7px 12px;color:#fff;background:var(--p5export-pink);border:1px solid var(--p5export-pink);border-radius:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;font:inherit;font-weight:700;line-height:12px}.p5export-btn:hover{background:var(--p5export-pink-dark);border-color:var(--p5export-pink-dark)}.p5export-btn:active{transform:translate(1px,1px)}.p5export-btn.is-ghost{color:var(--p5export-ink);background:var(--p5export-toolbar);border-color:var(--p5export-line)}.p5export-btn.is-ghost:hover{background:#e5e5e5}.p5export-btn.is-danger{color:#fff;background:#b52b46;border-color:#b52b46}.p5export-btn:disabled{opacity:.45;cursor:not-allowed;transform:none}.p5export-status{padding:7px 8px;color:var(--p5export-muted);background:var(--p5export-toolbar);border-left:3px solid var(--p5export-line)}.p5export-status.is-error{color:#8d1732;background:#fff0f4;border-left-color:var(--p5export-pink)}.p5export-status[hidden]{display:none}.p5export-preview:not([hidden]){display:flex;flex-direction:column;gap:6px}.p5export-preview-canvas{display:block;width:100%;background:#eee;border:1px solid var(--p5export-line);border-radius:0;image-rendering:pixelated}.p5export-preview-controls{display:flex;align-items:center;gap:8px;padding:6px 0}.p5export-play{width:24px;height:24px;padding:6px;color:#fff;background:var(--p5export-pink);border:0;border-radius:50%;cursor:pointer}.p5export-play:hover{background:var(--p5export-pink-dark)}.p5export-play svg{display:block;width:100%;height:100%}.p5export-timeline{flex:1;height:3px;margin:0;background:var(--p5export-line);border-radius:0;outline:0;-moz-appearance:none;appearance:none;-webkit-appearance:none;cursor:pointer}.p5export-timeline::-webkit-slider-thumb{width:10px;height:16px;background:var(--p5export-pink);border:0;border-radius:0;-moz-appearance:none;appearance:none;-webkit-appearance:none;cursor:grab}.p5export-timeline::-moz-range-thumb{width:10px;height:16px;background:var(--p5export-pink);border:0;border-radius:0;cursor:grab}.p5export-time{min-width:29px;color:var(--p5export-muted);font-variant-numeric:tabular-nums;text-align:right}.p5export-tab:focus-visible,.p5export-toggle:focus-visible,.p5export-btn:focus-visible,.p5export-play:focus-visible{outline:2px solid var(--p5export-pink);outline-offset:-2px}@media (prefers-reduced-motion: reduce){.p5export-btn:active{transform:none}}";let ss=!1;function Zo(){if(ss||typeof document>"u")return;ss=!0;const e=document.createElement("style");e.setAttribute("data-p5-export",""),e.textContent=Ko,document.head.appendChild(e)}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)"}],Qo=[{value:"stl",label:"STL (3D)"},{value:"obj",label:"OBJ (3D)"}],el=[{value:"webm",label:"WebM (video)"},{value:"mp4",label:"MP4 (video)"},{value:"webp",label:"WebP (animation)"},{value:"gif",label:"GIF (animation)"}],os=[{value:"1",label:"1×"},{value:"2",label:"2×"},{value:"3",label:"3×"},{value:"4",label:"4×"}],ls=new Set(["png","jpg","webp","pdf"]),Wr='<path d="M2 1.2 L9 5 L2 8.8 Z" fill="currentColor"/>',tl='<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"/>',il=`
|
|
31
31
|
<div class="p5export-panel">
|
|
32
32
|
<div class="p5export-header" data-el="header">
|
|
33
33
|
<span class="p5export-title" data-el="title">
|
|
@@ -77,6 +77,10 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
|
|
|
77
77
|
<label>Duration</label>
|
|
78
78
|
<input class="p5export-input" type="number" min="0.5" step="0.5" value="3" data-el="videoDuration">
|
|
79
79
|
</div>
|
|
80
|
+
<div class="p5export-row">
|
|
81
|
+
<label>Scale</label>
|
|
82
|
+
<select class="p5export-select" data-el="videoScale"></select>
|
|
83
|
+
</div>
|
|
80
84
|
<div class="p5export-row">
|
|
81
85
|
<label>Name</label>
|
|
82
86
|
<input class="p5export-input" type="text" placeholder="filename" data-el="videoFilename">
|
|
@@ -85,7 +89,7 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
|
|
|
85
89
|
<canvas class="p5export-preview-canvas" data-el="previewCanvas"></canvas>
|
|
86
90
|
<div class="p5export-preview-controls">
|
|
87
91
|
<button class="p5export-play" data-action="togglePreview" title="Play / pause">
|
|
88
|
-
<svg viewBox="0 0 10 10" data-el="playIcon">${
|
|
92
|
+
<svg viewBox="0 0 10 10" data-el="playIcon">${Wr}</svg>
|
|
89
93
|
</button>
|
|
90
94
|
<input class="p5export-timeline" type="range" min="0" max="0" step="1" value="0" data-el="timeline">
|
|
91
95
|
<span class="p5export-time" data-el="timeLabel">0:00</span>
|
|
@@ -96,5 +100,5 @@ If you want to allow non-zero first timestamps, set firstTimestampBehavior: 'per
|
|
|
96
100
|
<div class="p5export-status" data-el="recordedStatus" hidden></div>
|
|
97
101
|
</div>
|
|
98
102
|
</div>
|
|
99
|
-
</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"),this._syncCollapsedState(),(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"),this._syncCollapsedState()}_syncCollapsedState(){const e=this.el.classList.contains("is-collapsed");this.collapseToggle.textContent=e?"+":"−",this.collapseToggle.title=e?"Expand":"Collapse",this.collapseToggle.setAttribute("aria-label",`${e?"Expand":"Collapse"} export panel`),this.collapseToggle.setAttribute("aria-expanded",String(!e))}_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 i=0,r=0,n=0,s=0,a=!1,o=null;const f=(d,c,m)=>Math.min(Math.max(d,c),Math.max(c,m)),g=(d,c)=>{const m=this.el.getBoundingClientRect(),w=window.innerWidth-m.width-8,y=window.innerHeight-m.height-8;this.el.style.left=f(d,8,w)+"px",this.el.style.top=f(c,8,y)+"px",this.el.style.right="auto"};this._clampToViewport=()=>{const d=this.el.getBoundingClientRect();g(d.left,d.top)};const v=d=>{!a||d.pointerId!==o||g(n+d.clientX-i,s+d.clientY-r)},u=d=>{!a||d.pointerId!==o||(a=!1,this.header.hasPointerCapture(o)&&this.header.releasePointerCapture(o),o=null)},l=d=>{if(d.button!==0||d.target.closest(".p5export-toggle"))return;d.preventDefault(),a=!0,o=d.pointerId,i=d.clientX,r=d.clientY;const c=this.el.getBoundingClientRect();n=c.left,s=c.top,g(n,s),this.header.setPointerCapture(o)};this.header.addEventListener("pointerdown",l),this.header.addEventListener("pointermove",v),this.header.addEventListener("pointerup",u),this.header.addEventListener("pointercancel",u),window.addEventListener("resize",this._clampToViewport),typeof ResizeObserver<"u"&&(this._dragResizeObserver=new ResizeObserver(this._clampToViewport),this._dragResizeObserver.observe(this.el)),this._dragHandlers={onDown:l,onMove:v,onUp:u},this._clampToViewport()}destroy(){clearInterval(this._statusTimer),this._pausePreview(),this.buffer&&this.buffer.clear(),this._dragHandlers&&(this.header.removeEventListener("pointerdown",this._dragHandlers.onDown),this.header.removeEventListener("pointermove",this._dragHandlers.onMove),this.header.removeEventListener("pointerup",this._dragHandlers.onUp),this.header.removeEventListener("pointercancel",this._dragHandlers.onUp)),this._clampToViewport&&window.removeEventListener("resize",this._clampToViewport),this._dragResizeObserver&&this._dragResizeObserver.disconnect(),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){ps(t,e),Us(t,e,i),Os(t,e),ta(t,e,i),Ho(t,e,i),qo(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"}})});
|
|
103
|
+
</div>`.trim();class rl{constructor(t,i={}){Zo(),this.p=t,this.opts=i,this.tab="image",this.videoState="idle",this.buffer=null,this._statusTimer=null,this.el=document.createRange().createContextualFragment(il).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"),this._syncCollapsedState(),(i.parent||document.body).appendChild(this.el),this._wireDrag()}_populateOptions(){const t=Di(this.p)?[...as,...Qo]:as;this.imageFormat.innerHTML=Fi(t),this.imageScale.innerHTML=Fi(os),this.videoFormat.innerHTML=Fi(el),this.videoScale.innerHTML=Fi(os),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"),this._syncCollapsedState()}_syncCollapsedState(){const t=this.el.classList.contains("is-collapsed");this.collapseToggle.textContent=t?"+":"−",this.collapseToggle.title=t?"Expand":"Collapse",this.collapseToggle.setAttribute("aria-label",`${t?"Expand":"Collapse"} export panel`),this.collapseToggle.setAttribute("aria-expanded",String(!t))}_switchTab(t){this.tab=t;for(const i of this.el.querySelectorAll("[data-tab]"))i.classList.toggle("is-active",i.dataset.tab===t);for(const i of this.el.querySelectorAll("[data-view]"))i.toggleAttribute("hidden",i.dataset.view!==t)}_refreshImageScaleEnabled(){const t=this.imageFormat.value,i=ls.has(t);this.imageScale.disabled=!i,this.imageScaleRow.style.opacity=i?"":"0.45",this.svgOutlineRow&&this.svgOutlineRow.toggleAttribute("hidden",t!=="svg")}async _saveImage(){const t=this.imageFormat.value,i=this.imageFilename.value||void 0,r=Number(this.imageScale.value)||1,n=ls.has(t)?{scale:r}:void 0,s=`${t.toUpperCase()}${n&&r>1?` @ ${r}×`:""}`;this._setStatus(this.imageStatus,`Saving ${s}…`);try{if(t==="png")await this.p.savePNG(i,n);else if(t==="jpg")await this.p.saveJPG(i,n);else if(t==="webp")await this.p.saveWebP(i,n);else if(t==="svg")this.p.saveSVG(i,{outlineText:!!(this.svgOutline&&this.svgOutline.checked)});else if(t==="pdf")await this.p.savePDF(i,n);else if(t==="stl"||t==="obj"){this._setStatus(this.imageStatus,`${t.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 t=Number(this.videoDuration.value)||void 0,i=Number(this.videoScale.value)||1;try{this.buffer=this.p.createVideoBuffer({duration:t,scale:i})}catch(n){console.error(n),this._setStatus(this.recordedStatus,`Error: ${n.message}`,"error");return}this.videoState="recording",this._updateVideoState();const r=performance.now();this._statusTimer=setInterval(()=>{const n=(performance.now()-r)/1e3,s=t?` / ${t.toFixed(1)}s`:"";this._setStatus(this.recordedStatus,`Recording ${n.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(t){if(!this.buffer)return;const i=this.videoFilename.value||void 0,r=this.videoState;this.videoState="encoding",this._updateVideoState(),this._setStatus(this.recordedStatus,`Encoding ${t.toUpperCase()}…`);try{await this.p.exportVideoBuffer(this.buffer,{format:t,filename:i,onProgress:n=>this._setStatus(this.recordedStatus,`Encoding ${t.toUpperCase()}… ${Math.round(n*100)}%`)}),this._setStatus(this.recordedStatus,`Saved ${t.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 t=this.videoState,i=t==="recorded"||t==="encoding",r=t==="recording";this.videoFormat.disabled=r,this.videoDuration.disabled=r,this.videoScale.disabled=r,this.videoFilename.disabled=r,this.previewWrap.toggleAttribute("hidden",!i),this.rerecordBtn.toggleAttribute("hidden",!i),this.videoPrimaryBtn.className="p5export-btn"+(t==="recording"?" is-danger":""),this.videoPrimaryBtn.textContent=t==="recording"?"Stop":i?"Export":"Record";const n=t==="encoding";this.videoPrimaryBtn.disabled=n,this.rerecordBtn.disabled=n}_initPreview(){if(!this.buffer||!this.buffer.frames.length)return;const t=320,i=this.buffer.width,r=this.buffer.height,n=Math.min(1,t/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=Wr,this._renderPreviewFrame()}_renderPreviewFrame(){if(!this.buffer||!this._previewCtx)return;const t=Math.max(0,Math.min(this.buffer.frames.length-1,this._previewFrame)),i=this.buffer.frames[t];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(t);const r=this.buffer.fps||30;this.timeLabel.textContent=`${(t/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=tl;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=Wr)}_setStatus(t,i,r="",n=0){t.textContent=i||"",t.toggleAttribute("hidden",!i),t.classList.toggle("is-error",r==="error"),n&&i&&setTimeout(()=>{t.textContent===i&&this._setStatus(t,"")},n)}_wireDrag(){let i=0,r=0,n=0,s=0,a=!1,o=null;const p=(d,c,u)=>Math.min(Math.max(d,c),Math.max(c,u)),w=(d,c)=>{const u=this.el.getBoundingClientRect(),g=window.innerWidth-u.width-8,y=window.innerHeight-u.height-8;this.el.style.left=p(d,8,g)+"px",this.el.style.top=p(c,8,y)+"px",this.el.style.right="auto"};this._clampToViewport=()=>{const d=this.el.getBoundingClientRect();w(d.left,d.top)};const v=d=>{!a||d.pointerId!==o||w(n+d.clientX-i,s+d.clientY-r)},m=d=>{!a||d.pointerId!==o||(a=!1,this.header.hasPointerCapture(o)&&this.header.releasePointerCapture(o),o=null)},l=d=>{if(d.button!==0||d.target.closest(".p5export-toggle"))return;d.preventDefault(),a=!0,o=d.pointerId,i=d.clientX,r=d.clientY;const c=this.el.getBoundingClientRect();n=c.left,s=c.top,w(n,s),this.header.setPointerCapture(o)};this.header.addEventListener("pointerdown",l),this.header.addEventListener("pointermove",v),this.header.addEventListener("pointerup",m),this.header.addEventListener("pointercancel",m),window.addEventListener("resize",this._clampToViewport),typeof ResizeObserver<"u"&&(this._dragResizeObserver=new ResizeObserver(this._clampToViewport),this._dragResizeObserver.observe(this.el)),this._dragHandlers={onDown:l,onMove:v,onUp:m},this._clampToViewport()}destroy(){clearInterval(this._statusTimer),this._pausePreview(),this.buffer&&this.buffer.clear(),this._dragHandlers&&(this.header.removeEventListener("pointerdown",this._dragHandlers.onDown),this.header.removeEventListener("pointermove",this._dragHandlers.onMove),this.header.removeEventListener("pointerup",this._dragHandlers.onUp),this.header.removeEventListener("pointercancel",this._dragHandlers.onUp)),this._clampToViewport&&window.removeEventListener("resize",this._clampToViewport),this._dragResizeObserver&&this._dragResizeObserver.disconnect(),this.el.remove()}}function Fi(e){return e.map(t=>`<option value="${t.value}">${t.label}</option>`).join("")}function nl(e,t,i){if(t.createExportGUI=function(r={}){if(this._p5ExportPanel)return Object.assign(this._p5ExportPanel.opts,r),this._p5ExportPanel;const n=new rl(this,r);return this._p5ExportPanel=n,n},t.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 Kt(e,t,i){fs(e,t),Ws(e,t,i),Vs(e,t),ta(e,t,i),Yo(e,t,i),Jo(e,t),nl(e,t,i),sl(e),t.downloadBlob=function(r,n){return re(r,n)}}function sl(e){const t=e&&e.Graphics;if(!t||!t.prototype||t.prototype.__p5ExportGraphicsRandomPatched)return;const i=e.prototype;for(const r of["random","randomSeed","noise","noiseSeed","randomGaussian"])typeof t.prototype[r]!="function"&&typeof i[r]=="function"&&(t.prototype[r]=function(...n){const s=typeof window<"u"&&window.p5&&window.p5.instance||this;return i[r].apply(s,n)});t.prototype.__p5ExportGraphicsRandomPatched=!0}function hs(e){if(!e||!e.prototype)return!1;if(e.prototype.__p5ExportInstalled)return!0;e.prototype.__p5ExportInstalled=!0;const t={};Kt(e,e.prototype,t);const i=(r,n)=>typeof n=="function"&&typeof e.prototype.registerMethod=="function"&&e.prototype.registerMethod(r,n);return i("beforeSetup",t.presetup),i("afterSetup",t.postsetup),i("pre",t.predraw),i("post",t.postdraw),al(e),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 al(e){if(typeof window>"u")return;const t=Date.now(),i=setInterval(()=>{if((window.p5ExportConfig||{}).autoGUI===!1){clearInterval(i);return}const n=e&&e.instance;if(n&&n._p5ExportPanel){clearInterval(i);return}if(n&&n._setupDone&&typeof n.createExportGUI=="function"){n.createExportGUI(),clearInterval(i);return}Date.now()-t>3e4&&clearInterval(i)},150)}function ds(e){if(!e)throw new Error("[p5.export] register() called with no p5 constructor");if(typeof e.registerAddon=="function"){e.registerAddon(Kt);return}if(!hs(e))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(Kt),window.p5.__p5ExportAutoRegistered=!0,!0):hs(window.p5)}function ol(){typeof window>"u"||window.__p5ExportModuleTried||(window.__p5ExportModuleTried=!0,import("p5").then(e=>{const t=e&&(e.default||e.p5)||e;!t||typeof t!="function"&&!t.prototype||t.__p5ExportAutoRegistered||t.prototype&&t.prototype.__p5ExportInstalled||(ds(t),t.__p5ExportAutoRegistered=!0)}).catch(()=>{}))}if(typeof window<"u"&&!zr()){const e=setInterval(()=>{zr()&&clearInterval(e)},10);setTimeout(()=>clearInterval(e),5e3),window.addEventListener("p5Ready",zr,{once:!0}),ol()}Me.default=Kt,Me.p5ExportAddon=Kt,Me.register=ds,Object.defineProperties(Me,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
100
104
|
//# sourceMappingURL=p5.export.min.js.map
|