webwallgl 1.3.16 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/webwallgl.min.mjs CHANGED
@@ -1,32 +1,32 @@
1
- function Kr(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function wn(t,e){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++){let s=0;for(let a=0;a<4;a++)s+=t[a*4+i]*e[r*4+a];n[r*4+i]=s}return n}function Zr(t,e,n,r,i,s){const a=Kr();return a[0]=2/(e-t),a[5]=2/(r-n),a[10]=-2/(s-i),a[12]=-(e+t)/(e-t),a[13]=-(r+n)/(r-n),a[14]=-0/(s-i),a}function Jr(t,e,n,r){return wn(t,new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,e,n,r,1]))}function $c(t){const e=new Float32Array(16);for(let n=0;n<4;n++)for(let r=0;r<4;r++)e[r*4+n]=t[n*4+r];return e}function Li(t,e,n,r){return wn(t,new Float32Array([e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1]))}function Qc(t,e){const n=Math.cos(e),r=Math.sin(e);return wn(t,new Float32Array([n,r,0,0,-r,n,0,0,0,0,1,0,0,0,0,1]))}function bh(t,e){const n=Math.cos(e),r=Math.sin(e);return wn(t,new Float32Array([1,0,0,0,0,n,r,0,0,-r,n,0,0,0,0,1]))}function wh(t,e){const n=Math.cos(e),r=Math.sin(e);return wn(t,new Float32Array([n,0,-r,0,0,1,0,0,r,0,n,0,0,0,0,1]))}function vh(t,e,n,r){const i=1/Math.tan(t*Math.PI/180/2),s=new Float32Array(16);return s[0]=i/(e||1),s[5]=i,s[10]=(r+n)/(n-r),s[11]=-1,s[14]=2*r*n/(n-r),s}function Ds(t,e){const n=t&&typeof t=="object"?t.value:t;return typeof n=="number"&&Number.isFinite(n)?n:e}function kh(t){const e=t&&t.general;return!e||e.orthogonalprojection?!1:Ds(e.fov,0)>0}function Ah(t,e){return e&&e.perspective&&t&&t.isSkybox&&e.eye?e.eye:t.origin}function xh(t,e,n){const r=Kc([t[0]-e[0],t[1]-e[1],t[2]-e[2]]),i=Kc(Zc(n,r)),s=Zc(r,i),a=new Float32Array([i[0],s[0],r[0],0,i[1],s[1],r[1],0,i[2],s[2],r[2],0,0,0,0,1]);return a[12]=-(i[0]*t[0]+i[1]*t[1]+i[2]*t[2]),a[13]=-(s[0]*t[0]+s[1]*t[1]+s[2]*t[2]),a[14]=-(r[0]*t[0]+r[1]*t[1]+r[2]*t[2]),a}function Th(t,e,n,r){const i=t[3]*e+t[7]*n+t[11]*r+t[15];return[(t[0]*e+t[4]*n+t[8]*r+t[12])/i,(t[1]*e+t[5]*n+t[9]*r+t[13])/i,(t[2]*e+t[6]*n+t[10]*r+t[14])/i]}const Sh=[[16,9],[16,10],[21,9],[32,9]];function Ph(t,e,n,r,i){const s=t/e;if(!Number.isFinite(s)||s<=0||!(n>0)||!(r>0))return null;const a=.02,o=n/r;if(Math.abs(s-o)<=a*o)return{viewW:n,viewH:r};for(const[c,u]of Sh){const l=c/u;if(Math.abs(s-l)>a*l)continue;const f=r,d=r*l;return d>n+1e-6?{viewW:n,viewH:n/l}:{viewW:d,viewH:f}}return null}function _h(t){let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const s of t||[]){if(!s||s.visible===!1||s.destroyed)continue;const a=Math.abs((s.size?.[0]??0)*(s.scale?.[0]??1)),o=Math.abs((s.size?.[1]??0)*(s.scale?.[1]??1));if(!(a>0)&&!(o>0))continue;const c=Number(s.angles?.[2]??0)||0,u=Math.abs(Math.cos(c)),l=Math.abs(Math.sin(c)),f=a*u+o*l,d=a*l+o*u,h=Number(s.origin?.[0]??0)||0,p=Number(s.origin?.[1]??0)||0;e=Math.min(e,h-f/2),r=Math.max(r,h+f/2),n=Math.min(n,p-d/2),i=Math.max(i,p+d/2)}return{minX:e,minY:n,maxX:r,maxY:i}}function za(t,e,n,r,i,s,a){const o=Yc(s),c=Yc(a);if(t==="cover"){const u=Ph(r,i,e,n);if(u)return{offX:(e-u.viewW)*o,offY:(n-u.viewH)*c,viewW:u.viewW,viewH:u.viewH};const l=Math.max(r/e,i/n),f=r/l,d=i/l;return{offX:(e-f)*o,offY:(n-d)*c,viewW:f,viewH:d}}if(t==="contain"){const u=r/i;if(e/n>u){const h=e,p=e/u;return{offX:0,offY:(n-p)/2,viewW:h,viewH:p}}const f=n,d=n*u;return{offY:0,offX:(e-d)/2,viewW:d,viewH:f}}return{offX:0,offY:0,viewW:e,viewH:n}}function Eh(t,e,n,r,i,s){const a=t.general,o=t.camera,c=o&&o.eye?Ha(o.eye):[0,0,0],u=o&&o.center?Ha(o.center):[0,0,-1],l=o&&o.up?Ha(o.up):[0,1,0];if(kh(t)){const b=n>0?e/n:1.7777777777777777,v=Ds(a.fov,50),k=Math.max(Ds(a.nearz,.01),1e-4),A=Math.max(Ds(a.farz,1e4),k+1),T=xh(c,u,l),S=vh(v,b,k,A);return{view:T,projection:S,eye:c,center:u,projW:b,projH:1,offX:0,offY:0,viewW:b,viewH:1,perspective:!0}}const f=Kr(),d=a&&a.orthogonalprojection&&a.orthogonalprojection.width||e,h=a&&a.orthogonalprojection&&a.orthogonalprojection.height||n,p=za(r,d,h,e,n,i,s),m=t&&t.cameraTransforms?t.cameraTransforms.zoom:a&&a.zoom,g=m&&typeof m=="object"?m.value:m,w=Number(g);if(Number.isFinite(w)&&w>0&&Math.abs(w-1)>1e-6){const b=p.offX+p.viewW/2,v=p.offY+p.viewH/2,k=p.viewW/w,A=p.viewH/w;p.offX=b-k/2,p.offY=v-A/2,p.viewW=k,p.viewH=A}const y=Zr(p.offX,p.offX+p.viewW,p.offY+p.viewH,p.offY,-1e4,1e4);return{view:f,projection:y,eye:c,projW:d,projH:h,offX:p.offX,offY:p.offY,viewW:p.viewW,viewH:p.viewH,perspective:!1}}function Yc(t){const e=Number(t);return Number.isFinite(e)?e<0?0:e>1?1:e:.5}function Ha(t){return String(t).trim().split(/\s+/).map(Number)}function Kc(t){const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]}function Zc(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function ei(t){const e=Number(t);return Number.isFinite(e)?e*.5:0}function Ns(t,e){const n=e?.renderDpr??t.cfg?.renderDpr??1;return Math.min(window.devicePixelRatio||1,n)}function Mr(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function Va(t){const e=Mr(t);return e==="contain"?{objectFit:"contain",background:"rgba(10,12,16,0.85)"}:e==="stretch"?{objectFit:"fill",background:"transparent"}:{objectFit:"cover",background:"transparent"}}function Ch(t){return{cfg:{type:"canvas"},coverAlign:{x:.5,y:.5,tx:.5,ty:.5},frameMeter:{stamps:[],last:0,fps:0},disposers:[]}}(()=>{const t=e=>e.preventDefault();window.addEventListener("contextmenu",t,!0),document.addEventListener("contextmenu",t,!0),window.__blockContextMenu=e=>e.addEventListener("contextmenu",t,!0)})();function rr(t){if(t.iframe)try{t.iframe.contentWindow?.location.replace("about:blank")}catch{}if(t.wrap)t.wrap.innerHTML="";else if(t.iframe?.isConnected)try{t.iframe.remove()}catch{}t.raf!==void 0&&cancelAnimationFrame(t.raf),t.raf=void 0;for(const n of t.videoPairs??[])n.destroy();if(t.videoPairs=void 0,t.webcodecsPreferred=void 0,t.sceneCleanup)try{t.sceneCleanup()}catch{}t.sceneCleanup=void 0,t.sceneCtl=void 0,t.pointerCtl=void 0,t.mediaCtl=void 0;const e=t.wallpaperDisposers??[];t.wallpaperDisposers=[];for(const n of e)try{n()}catch{}t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0);for(const n of t.videoTextures??[])n.pause(),n.removeAttribute("src"),n.load(),n.remove();t.videoTextures=void 0;for(const n of t.objectUrls??[])try{URL.revokeObjectURL(n)}catch{}if(t.objectUrls=void 0,t.sceneAudio){for(const n of t.sceneAudio.audios)n.pause(),n.removeAttribute("src"),n.load();t.sceneAudio=void 0}if(t.video){t.video.pause(),t.video.removeAttribute("src");try{t.video.load()}catch{}t.video.remove()}t.video=void 0,t.img=void 0,t.iframe=void 0,t.canvas=void 0,t.ctx=void 0,t.info=void 0,Dh(),el(t)}function Ih(t){try{rr(t)}catch{}t.peekRaf!==void 0&&(cancelAnimationFrame(t.peekRaf),t.peekRaf=void 0);for(const e of t.disposers.splice(0))try{e()}catch{}t.wrap?.remove(),t.wrap=void 0}const Mh=new TextDecoder,zt=t=>Mh.decode(t).replace(/^\uFEFF/,""),Jc=500;function ir(t,e){const n=t.frameMeter.stamps;n.push(e),t.frameMeter.last=e;const r=e-Jc;for(;n.length&&n[0]<r;)n.shift();const i=n.length>=2?n[n.length-1]-n[0]:0;t.frameMeter.fps=i>0?(n.length-1)*1e3/i:0}function el(t){t.frameMeter.stamps.length=0,t.frameMeter.last=0,t.frameMeter.fps=0}function Bh(t){return!t.frameMeter.last||t.paused?{fps:0,running:!1}:performance.now()-t.frameMeter.last>Math.max(Jc,400)?{fps:0,running:!1}:{fps:t.frameMeter.fps,running:!0}}function ce(t,e,n){try{t.onDiagnostic?.(n,/fail|error|失败|ERROR/.test(n)?"error":"info")}catch{}try{const r=e.mediaBase?new URL(e.mediaBase,window.location.href).origin:"";if(r){const i=new Image;i.src=`${r}/diag?msg=${encodeURIComponent(`scene ${e.src??"?"}: ${n.slice(0,500)}`)}`}}catch{}}function Wa(t){t.coverAlign.x=t.coverAlign.y=t.coverAlign.tx=t.coverAlign.ty=.5,Rh(t)}function Rh(t){const e=`${(t.coverAlign.x*100).toFixed(2)}% ${(t.coverAlign.y*100).toFixed(2)}%`,n=t.video??t.img;n&&n.isConnected&&(n.style.objectPosition=e)}const Fh=["__scene","__sceneLayers","__textures","__objScripts","__textWidgets","__mediaHooks","__mediaControl","__mediaStats","__mediaSet","__system","__liveSystem","__audioStats","__audioMute","__particleStats","__particleToggle","__pointerStats","__compositeStats","__compositeEnable"];function Dh(){const t=window;for(const e of Fh)e in t&&delete t[e]}function tl(t,e,n){const r=Ns(t,n),i=Math.max(1,Math.round((e.clientWidth||window.innerWidth||1)*r)),s=Math.max(1,Math.round((e.clientHeight||window.innerHeight||1)*r));return e.width===i&&e.height===s?!1:(e.width=i,e.height=s,!0)}const Nh=.5,nl=.12,Lh=.125,Uh=.0625,rl=64;function il(t,e){const n=H=>{const G=document.createElement("video");H&&(G.src=t),G.muted=e.muted,G.playsInline=!0,G.preload="metadata";const Y=Math.min(window.devicePixelRatio||1,e.renderDpr||1),J=Math.max(1,Math.round((e.maxW||innerWidth)*Y)),ne=Math.max(1,Math.round((e.maxH||innerHeight)*Y));return G.width=J,G.height=ne,G.loop=!0,G};let r=n(!0),i=n(!1),s=!1,a=1,o=e.muted;i.muted=!0;const c=()=>{s||(i.src=t,s=!0)};let u=!1,l=!1,f,d=-1,h=0,p=0,m=nl,g=!1,w=0,y=0,b=0,v=0,k,A=-1,T=0,S=!1;const P=H=>{if(S||H!==r)return;if(!u||!g){M(),H.loop=!0,H.play().catch(()=>{}),q.onFallback?.();return}i.playbackRate=1;const G=r;l=!0,G.style.transition=`opacity ${rl}ms linear`,G.style.opacity="0";let Y=!1;const J=()=>{Y||S||(Y=!0,l=!1,G.style.transition="",B(),G.style.opacity="1")};G.addEventListener("transitionend",J,{once:!0}),f=window.setTimeout(J,rl+80)},M=()=>{u=!1,p=0,g=!1,l&&(l=!1,f&&(clearTimeout(f),f=void 0),r.style.transition="",r.style.opacity="1"),k&&(k.loop=!0,k=void 0),i.paused||i.pause(),i.playbackRate=1;try{i.currentTime=0}catch{}},B=()=>{const H=r;r=i,i=H,u=!1,p=0,g=!1,h=0,d=-1,b=0,v=0,y=performance.now()+Math.max(800,m*1e3+300),r.paused&&r.play().catch(()=>{}),r.playbackRate!==1&&(r.playbackRate=1),r.muted=o,r.volume=a,H.pause(),H.playbackRate=1;try{H.currentTime=0}catch{}H.muted=!0,H.loop=!0,A=-1,s=!0,q.onSwap?.(r)},N=(H,G)=>{const Y=performance.now();if(!(Y-v<1e3)){if(v=Y,b++,h=0,d=-1,b>=3){b=0;const J=G,ne=r;e.onRecover?.(`${H}\uFF1A\u91CD\u8F7D\u5A92\u4F53\u7BA1\u7EBF @${J.toFixed(2)}s`),A=-1,ne.addEventListener("loadedmetadata",()=>{if(!(S||ne!==r)){try{ne.currentTime=Math.max(0,Math.min(J,(ne.duration||J)-.05))}catch{}ne.play().catch(()=>{})}},{once:!0}),ne.src=t,ne.play().catch(()=>{});return}if(b===2){e.onRecover?.(`${H}\uFF1Aseek \u91CD\u542F\u89E3\u7801 @${G.toFixed(2)}s`);try{r.currentTime=Math.max(0,G-.001)}catch{}r.play().catch(()=>{});return}e.onRecover?.(`${H}\uFF1A\u8E22 play`),r.pause(),r.play().catch(()=>{})}},O=()=>{if(S)return;T=requestAnimationFrame(O);const H=r.duration;if(!isFinite(H)||H<=0)return;const G=r.currentTime;if(!document.hidden&&!l&&performance.now()>=y?r.paused&&!r.ended&&r.readyState>=1?(h++,h>30&&N("\u9759\u9ED8\u6682\u505C",G)):!r.paused&&r.readyState>=2?(d===G?(h++,h>30&&N("\u5047\u64AD\u653E",G)):(h=0,b=0),d=G):(h=0,d=-1):(h=0,d=-1),A>=0&&G<A-.05){const ne=u,fe=g;M(),A=G,ne&&!fe&&(m=Math.min(1,m*2)),ne||q.onFallback?.();return}A=G;const Y=H-G,J=Math.max(Nh,m+.5);if(Y>J+.5){u&&M();return}if(u){if(!g&&i.currentTime>.004){g=!0;const ne=performance.now()-w;m=Math.min(1,Math.max(nl,ne/1e3*1.5+.15)),k!==r&&(r.loop=!1,k=r)}!l&&g&&(r.ended||p>0&&performance.now()-p>1500)&&P(r);return}if(Y<=J&&(c(),i.readyState>=2)){if(Y<=m){try{i.currentTime=0}catch{}i.playbackRate=m>.3?Uh:Lh,w=performance.now(),g=!1,i.play().catch(()=>{}),u=!0,p=performance.now()}else if(i.paused)try{i.currentTime=0}catch{}}};T=requestAnimationFrame(O),r.addEventListener("ended",()=>P(r)),i.addEventListener("ended",()=>P(i));const q={get active(){return r},get standby(){return i},onSwap:void 0,onFallback:void 0,setVolume(H){a=Math.max(0,Math.min(1,H)),o=H<=0,r.muted=o,r.volume=a,i.muted=!0,i.volume=a},pause(){M(),r.pause(),T&&cancelAnimationFrame(T),T=0},resume(){S||(r.play().catch(H=>{H&&H.name}),T||(T=requestAnimationFrame(O)))},destroy(){S=!0,T&&cancelAnimationFrame(T),T=0;for(const H of[r,i]){H.pause(),H.removeAttribute("src");try{H.load()}catch{}H.remove()}}};return q}function R(t){if(!t)throw new Error("Assertion failed.")}const ja=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},Rt=t=>t&&t[t.length-1],le=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Rn=t=>{const e=le(t);return(e&1)===0?-(e>>1):e+1>>1},Fn=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Me=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Ft=new TextDecoder,qa=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),Xa={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Dn=qa(Xa),Ga={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Nn=qa(Ga),$a={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Ln=qa($a),Qa=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,sl={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Oh=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Ls{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const n=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),r=this.currentPromise;return this.currentPromise=n,this.pending++,await r,e}}const zh=/^[0-9a-fA-F]+$/,Ui=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Hh=t=>{R(t.length%2===0);const e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.slice(n,n+2),16);return e},al=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),Oi=(t,e,n)=>{let r=0,i=t.length-1,s=-1;for(;r<=i;){const a=r+i>>1,o=n(t[a]);o===e?(s=a,i=a-1):o<e?r=a+1:i=a-1}return s},_e=(t,e,n)=>{let r=0,i=t.length-1,s=-1;for(;r<=i;){const a=r+(i-r+1)/2|0;n(t[a])<=e?(s=a,r=a+1):i=a-1}return s},ol=(t,e,n)=>{const r=_e(t,n(e),n);t.splice(r+1,0,e)},gt=()=>{let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}},Ya=(t,e)=>{const n=t.indexOf(e);n!==-1&&t.splice(n,1)},cl=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return t[n]},Ka=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1},Vh=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},Wh=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},Us=t=>{throw new Error(`Unexpected value: ${t}`)},ll=(t,e,n)=>{const r=t.getUint8(e),i=t.getUint8(e+1),s=t.getUint8(e+2);return r<<16|i<<8|s},jh=(t,e,n,r)=>{n=n>>>0,n=n&16777215,t.setUint8(e,n>>>16&255),t.setUint8(e+1,n>>>8&255),t.setUint8(e+2,n&255)},zi=(t,e,n)=>Math.max(e,Math.min(n,t)),Et="und",Hi=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},Za=(t,e)=>Math.round(t/e)*e,ul=(t,e)=>Math.round(t*e)/e,Ja=(t,e)=>Math.floor(t/e)*e,qh=t=>{let e=0;for(;t;)e++,t>>=1;return e},eo=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},Xh=/^[a-z]{3}$/,fl=t=>Xh.test(t),ti=1e6*(1+Number.EPSILON),dl=(t,e)=>{const n={...t,...e};if(t.headers||e.headers){const r=t.headers?to(t.headers):{},i=e.headers?to(e.headers):{},s={...r};Object.entries(i).forEach(([a,o])=>{const c=Object.keys(s).find(u=>u.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),n.headers=s}return n},to=t=>{if(t instanceof Headers){const e={};return t.forEach((n,r)=>{e[r]=n}),e}if(Array.isArray(t)){const e={};return t.forEach(([n,r])=>{e[n]=r}),e}return t},hl=async(t,e,n,r,i)=>{let s=0;for(;;)try{return await t(e,n)}catch(a){if(i())throw a;s++;const o=r(s,a,e);if(o===null)throw a;if(pe._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Hs(1e3*o),i())throw a}};class Gh{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let no=null;const ro=()=>no!==null?no:no=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let io=null;const $h=()=>io!==null?io:io=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let so=null;const ao=()=>so!==null?so:so=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Qh=t=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${t} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${t} is not available in this environment.`,Yh=(async()=>{})().constructor,ie=t=>t instanceof Yh||t instanceof Promise?!0:typeof t?.then=="function",ni=(t,e)=>t!==-1?t:e,oo=(t,e,n,r)=>t<=r&&n<=e,ml=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n},Kh=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0},co=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Os=t=>typeof t=="number"&&!Number.isNaN(t),sr=(t,e)=>{if(e.includes("://"))return e;if(t.includes("://")){const o=t.indexOf("?");o!==-1&&(t=t.slice(0,o))}let n;if(e.startsWith("/")){const o=t.indexOf("://");if(o===-1)n=e;else{const c=t.indexOf("/",o+3);c===-1?n=t+e:n=t.slice(0,c)+e}}else{const o=t.lastIndexOf("/");o===-1?n=e:n=t.slice(0,o+1)+e}let r="";const i=n.indexOf("://");if(i!==-1){const o=n.indexOf("/",i+3);o!==-1&&(r=n.slice(0,o),n=n.slice(o))}const s=n.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return r+a.join("/")},Vi=(t,e)=>{let n=0;for(let r=0;r<t.length;r++)e(t[r])&&n++;return n},lo=(t,e)=>{let n=-1,r=1/0;for(let i=0;i<t.length;i++){const s=e(t[i]);s<r&&(r=s,n=i)}return n},zs=t=>{R(Number.isInteger(t.num)),R(Number.isInteger(t.den)),R(t.den!==0);let e=Math.abs(t.num),n=Math.abs(t.den);for(;n!==0;){const i=e%n;e=n,n=i}const r=e||1;return{num:t.num/r,den:t.den/r}},uo=(t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},Hs=t=>new Promise(e=>setTimeout(e,t));class fo{constructor(){this._listeners=new Map}on(e,n,r){this._listeners.has(e)||this._listeners.set(e,new Set);const i={fn:n,once:r?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){const[n,r]=e,i=this._listeners.get(n);if(i)for(const s of i){try{s.fn(r)}catch(a){console.error(a)}s.once&&i.delete(s)}}}var vn;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(vn||(vn={}));class pe{constructor(){}static get level(){return pe._level}static set level(e){if(e!==vn.Silent&&e!==vn.Errors&&e!==vn.Warnings&&e!==vn.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");pe._level=e}static get _emitter(){return pe._emitterInstance??=new fo}static on(e,n,r){return pe._emitter.on(e,n,r)}static _error(...e){pe._emitter._emit("error",e),pe._level>=vn.Errors&&console.error(...e)}static _warn(...e){pe._emitter._emit("warn",e),pe._level>=vn.Warnings&&console.warn(...e)}static _info(...e){pe._emitter._emit("info",e),pe._level>=vn.Info&&console.info(...e)}}pe._level=vn.Info,pe._emitterInstance=null;class Vs{constructor(e,n){if(this.data=e,this.mimeType=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof n!="string")throw new TypeError("mimeType must be a string.")}}class Zh{constructor(e,n,r,i){if(this.data=e,this.mimeType=n,this.name=r,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(n!==void 0&&typeof n!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}}const Un={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ee{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),n=this.bytes[e]??0,r=7-(this.pos&7),i=(n&1<<r)>>r;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let n=0;for(let r=0;r<e;r++)n<<=1,n|=this.readBit();return n}writeBits(e,n){const r=this.pos+e;for(let i=this.pos;i<r;i++){const s=Math.floor(i/8);let a=this.bytes[s];const o=7-(i&7);a&=~(1<<o),a|=(n&1<<r-i-1)>>r-i-1<<o,this.bytes[s]=a}this.pos=r}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,n=this.bytes[e]??0;return this.pos+=8,n}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new Ee(this.bytes);return e.pos=this.pos,e}}const Wi=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ho=[-1,1,2,3,4,5,6,8],pl=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Ee(t),n=mo(e),{frequencyIndex:r,sampleRate:i}=po(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=ho[s]);let o=n,c=!1,u=i;if(n===5||n===29)c=n===29,u=po(e).sampleRate,o=mo(e),o===22&&e.skipBits(4);else for(;e.getBitsLeft()>15;){const l=e.pos;if(e.readBits(11)!==695){e.pos=l+1;continue}mo(e)===5&&e.readBits(1)&&(u=po(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(c=!!e.readBits(1)));break}return a!==null&&a>1&&(c=!1),{objectType:n,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:u,outputNumberOfChannels:c&&a===1?2:a}},mo=t=>{const e=t.readBits(5);return e===31?32+t.readBits(6):e},po=t=>{const e=t.readBits(4);return e===15?{frequencyIndex:e,sampleRate:t.readBits(24)}:{frequencyIndex:e,sampleRate:e<Wi.length?Wi[e]:null}};const Ws=[48e3,44100,32e3],gl=[24e3,22050,16e3];var ut;(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(ut||(ut={}));var Ge;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Ge||(Ge={}));const js=function*(t){let e=0,n=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(r===-1||r>=t.length-2)break;e=r;let i=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?i=4:t[e+1]===0&&t[e+2]===1&&(i=3),i===0){e++;continue}n!==-1&&e>n&&(yield{offset:n,length:e-n}),n=e+i,e=n}n!==-1&&n<t.length&&(yield{offset:n,length:t.length-n})},yl=function*(t,e){let n=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;n+e<=t.length;){let i;e===1?i=r.getUint8(n):e===2?i=r.getUint16(n,!1):e===3?i=ll(r,n):(R(e===4),i=r.getUint32(n,!1)),n+=e,yield{offset:n,length:i},n+=i}},bl=(t,e)=>{if(e.description){const i=(Fn(e.description)[4]&3)+1;return yl(t,i)}else return js(t)},qs=t=>t&31,Xs=t=>{const e=[],n=t.length;for(let r=0;r<n;r++)r+2<n&&t[r]===0&&t[r+1]===0&&t[r+2]===3?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},go=new Uint8Array([0,0,0,1]),wl=t=>{const e=t.reduce((i,s)=>i+go.byteLength+s.byteLength,0),n=new Uint8Array(e);let r=0;for(const i of t)n.set(go,r),r+=go.byteLength,n.set(i,r),r+=i.byteLength;return n},vl=(t,e)=>{const n=t.reduce((s,a)=>s+e+a.byteLength,0),r=new Uint8Array(n);let i=0;for(const s of t){const a=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:jh(a,i,s.byteLength);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,r.set(s,i),i+=s.byteLength}return r},Jh=(t,e)=>{if(e.description){const i=(Fn(e.description)[4]&3)+1;return vl(t,i)}else return wl(t)},yo=t=>{try{const e=[],n=[],r=[];for(const o of js(t)){const c=t.subarray(o.offset,o.offset+o.length),u=qs(c[0]);u===ut.SPS?e.push(c):u===ut.PPS?n.push(c):u===ut.SPS_EXT&&r.push(c)}if(e.length===0||n.length===0)return null;const i=e[0],s=Gs(i);R(s!==null);const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(e){return pe._error("Error building AVC Decoder Configuration Record:",e),null}},kl=t=>{try{const e=Me(t);let n=0;const r=e.getUint8(n++),i=e.getUint8(n++),s=e.getUint8(n++),a=e.getUint8(n++),o=e.getUint8(n++)&3,c=e.getUint8(n++)&31,u=[];for(let h=0;h<c;h++){const p=e.getUint16(n,!1);n+=2,u.push(t.subarray(n,n+p)),n+=p}const l=e.getUint8(n++),f=[];for(let h=0;h<l;h++){const p=e.getUint16(n,!1);n+=2,f.push(t.subarray(n,n+p)),n+=p}const d={configurationVersion:r,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:u,pictureParameterSets:f,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=t.length){const h=e.getUint8(n++)&3,p=e.getUint8(n++)&7,m=e.getUint8(n++)&7,g=e.getUint8(n++);d.chromaFormat=h,d.bitDepthLumaMinus8=p,d.bitDepthChromaMinus8=m;const w=[];for(let y=0;y<g;y++){const b=e.getUint16(n,!1);n+=2,w.push(t.subarray(n,n+b)),n+=b}d.sequenceParameterSetExt=w}return d}catch(e){return pe._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Al={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Gs=t=>{try{const e=new Ee(Xs(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const r=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();le(e);let a=1,o=0,c=0,u=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(a=le(e),a===3&&(u=e.readBits(1)),o=le(e),c=le(e),e.skipBits(1),e.readBits(1))){for(let N=0;N<(a!==3?8:12);N++)if(e.readBits(1)){const q=N<6?16:64;let H=8,G=8;for(let Y=0;Y<q;Y++){if(G!==0){const J=Rn(e);G=(H+J+256)%256}H=G===0?H:G}}}le(e);const l=le(e);if(l===0)le(e);else if(l===1){e.skipBits(1),Rn(e),Rn(e);const B=le(e);for(let N=0;N<B;N++)Rn(e)}le(e),e.skipBits(1);const f=le(e),d=le(e),h=16*(f+1),p=16*(d+1);let m=h,g=p;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const B=le(e),N=le(e),O=le(e),q=le(e);let H,G;if((u===0?a:0)===0)H=1,G=2-w;else{const J=a===3?1:2,ne=a===1?2:1;H=J,G=ne*(2-w)}m-=H*(B+N),g-=G*(O+q)}let b=2,v=2,k=2,A=0,T={num:1,den:1},S=null,P=null;if(e.readBits(1)){if(e.readBits(1)){const ne=e.readBits(8);if(ne===255)T={num:e.readBits(16),den:e.readBits(16)};else{const fe=Al[ne];fe&&(T=fe)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),A=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),v=e.readBits(8),k=e.readBits(8))),e.readBits(1)&&(le(e),le(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const G=e.readBits(1);G&&xl(e);const Y=e.readBits(1);Y&&xl(e),(G||Y)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),le(e),le(e),le(e),le(e),S=le(e),P=le(e))}if(S===null){R(P===null);const B=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&B)S=0,P=0;else{const N=f+1,O=d+1,q=(2-w)*O,H=Ul.find(Y=>Y.level>=s)??Rt(Ul),G=Math.min(Math.floor(H.maxDpbMbs/(N*q)),16);S=G,P=G}}return R(P!==null),{profileIdc:r,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:w,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:p,displayWidth:m,displayHeight:g,pixelAspectRatio:T,colourPrimaries:b,matrixCoefficients:k,transferCharacteristics:v,fullRangeFlag:A,numReorderFrames:S,maxDecFrameBuffering:P}}catch(e){return pe._error("Error parsing AVC SPS:",e),null}},xl=t=>{const e=le(t);t.skipBits(4),t.skipBits(4);for(let n=0;n<=e;n++)le(t),le(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},em=(t,e)=>{if(e.description){const i=(Fn(e.description)[21]&3)+1;return vl(t,i)}else return wl(t)},$s=(t,e)=>{if(e.description){const i=(Fn(e.description)[21]&3)+1;return yl(t,i)}else return js(t)},ri=t=>t>>1&63,bo=t=>{try{const e=new Ee(Xs(t));e.skipBits(16),e.readBits(4);const n=e.readBits(3),r=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=tm(e,n);le(e);const l=le(e);let f=0;l===3&&(f=e.readBits(1));const d=le(e),h=le(e);let p=d,m=h;if(e.readBits(1)){const N=le(e),O=le(e),q=le(e),H=le(e);let G=1,Y=1;const J=f===0?l:0;J===1?(G=2,Y=2):J===2&&(G=2,Y=1),p-=(N+O)*G,m-=(q+H)*Y}const g=le(e),w=le(e);le(e);const b=e.readBits(1)?0:n;let v=0;for(let N=b;N<=n;N++)le(e),v=le(e),le(e);le(e),le(e),le(e),le(e),le(e),le(e),e.readBits(1)&&e.readBits(1)&&nm(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),le(e),le(e),e.skipBits(1));const k=le(e);if(rm(e,k),e.readBits(1)){const N=le(e);for(let O=0;O<N;O++)le(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let A=2,T=2,S=2,P=0,M=0,B={num:1,den:1};if(e.readBits(1)){const N=sm(e,n);B=N.pixelAspectRatio,A=N.colourPrimaries,T=N.transferCharacteristics,S=N.matrixCoefficients,P=N.fullRangeFlag,M=N.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:B,colourPrimaries:A,transferCharacteristics:T,matrixCoefficients:S,fullRangeFlag:P,maxDecFrameBuffering:v+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:g,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:M}}catch(e){return pe._error("Error parsing HEVC SPS:",e),null}},wo=t=>{try{const e=[],n=[],r=[],i=[];for(const u of js(t)){const l=t.subarray(u.offset,u.offset+u.length),f=ri(l[0]);f===Ge.VPS_NUT?e.push(l):f===Ge.SPS_NUT?n.push(l):f===Ge.PPS_NUT?r.push(l):(f===Ge.PREFIX_SEI_NUT||f===Ge.SUFFIX_SEI_NUT)&&i.push(l)}if(n.length===0||r.length===0)return null;const s=bo(n[0]);if(!s)return null;let a=0;if(r.length>0){const u=r[0],l=new Ee(Xs(u));l.skipBits(16),le(l),le(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),le(l),le(l),Rn(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&le(l),Rn(l),Rn(l),l.skipBits(1),l.skipBits(1),l.skipBits(1),l.skipBits(1);const f=l.readBits(1),d=l.readBits(1);!f&&!d?a=0:f&&!d?a=2:!f&&d?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:Ge.VPS_NUT,nalUnits:e}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Ge.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ge.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ri(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return pe._error("Error building HEVC Decoder Configuration Record:",e),null}},tm=(t,e)=>{const n=t.readBits(2),r=t.readBits(1),i=t.readBits(5);let s=0;for(let l=0;l<32;l++)s=s<<1|t.readBits(1);const a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=t.readBits(8);const o=t.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(t.readBits(1)),u.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)c[l]&&t.skipBits(88),u[l]&&t.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},nm=t=>{for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBits(1))le(t);else{const i=Math.min(64,1<<4+(e<<1));e>1&&Rn(t);for(let s=0;s<i;s++)Rn(t)}},rm=(t,e)=>{const n=[];for(let r=0;r<e;r++)n[r]=im(t,r,e,n)},im=(t,e,n,r)=>{let i=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===n){const c=le(t);a=e-(c+1)}else a=e-1;t.readBits(1),le(t);const o=r[a]??0;for(let c=0;c<=o;c++)t.readBits(1)||t.readBits(1);i=r[a]}else{const o=le(t),c=le(t);for(let u=0;u<o;u++)le(t),t.readBits(1);for(let u=0;u<c;u++)le(t),t.readBits(1);i=o+c}return i},sm=(t,e)=>{let n=2,r=2,i=2,s=0,a=0,o={num:1,den:1};if(t.readBits(1)){const c=t.readBits(8);if(c===255)o={num:t.readBits(16),den:t.readBits(16)};else{const u=Al[c];u&&(o=u)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(n=t.readBits(8),r=t.readBits(8),i=t.readBits(8))),t.readBits(1)&&(le(t),le(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(le(t),le(t),le(t),le(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&le(t),t.readBits(1)&&am(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=le(t),le(t),le(t),le(t),le(t)),{pixelAspectRatio:o,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},am=(t,e,n)=>{let r=!1,i=!1,s=!1;r=t.readBits(1)===1,i=t.readBits(1)===1,(r||i)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){const o=t.readBits(1)===1;let c=!0;o||(c=t.readBits(1)===1);let u=!1;c?le(t):u=t.readBits(1)===1;let l=1;u||(l=le(t)+1),r&&Tl(t,l,s),i&&Tl(t,l,s)}},Tl=(t,e,n)=>{for(let r=0;r<e;r++)le(t),le(t),n&&(le(t),le(t)),t.readBits(1)},om=t=>{try{const e=Me(t);let n=0;const r=e.getUint8(n++),i=e.getUint8(n++),s=i>>6&3,a=i>>5&1,o=i&31,c=e.getUint32(n,!1);n+=4;const u=t.subarray(n,n+6);n+=6;const l=e.getUint8(n++),f=(e.getUint8(n++)&15)<<8|e.getUint8(n++),d=e.getUint8(n++)&3,h=e.getUint8(n++)&3,p=e.getUint8(n++)&7,m=e.getUint8(n++)&7,g=e.getUint16(n,!1);n+=2;const w=e.getUint8(n++),y=w>>6&3,b=w>>3&7,v=w>>2&1,k=w&3,A=e.getUint8(n++),T=[];for(let S=0;S<A;S++){const P=e.getUint8(n++),M=P>>7&1,B=P&63,N=e.getUint16(n,!1);n+=2;const O=[];for(let q=0;q<N;q++){const H=e.getUint16(n,!1);n+=2,O.push(t.subarray(n,n+H)),n+=H}T.push({arrayCompleteness:M,nalUnitType:B,nalUnits:O})}return{configurationVersion:r,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:f,parallelismType:d,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:g,constantFrameRate:y,numTemporalLayers:b,temporalIdNested:v,lengthSizeMinusOne:k,arrays:T}}catch(e){return pe._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var yt;(function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"})(yt||(yt={}));const cm=(t,e)=>{const n=new Set;let r=yt.audAllowed;for(const s of $s(t,e)){if(r===yt.noMoreDataAllowed){n.add(s.offset);continue}const a=ri(t[s.offset]);if(r===yt.eoBitstreamAllowed&&a!==37){n.add(s.offset);continue}let o=!1;a===35?r>yt.audAllowed?o=!0:r=yt.beforeFirstVcl:a<=31?r>yt.afterFirstVcl?o=!0:r=yt.afterFirstVcl:a===36?r!==yt.afterFirstVcl?o=!0:r=yt.eoBitstreamAllowed:a===37?r<yt.afterFirstVcl?o=!0:r=yt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?r>yt.beforeFirstVcl?o=!0:r=yt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&r<yt.afterFirstVcl&&(o=!0),o&&n.add(s.offset)}if(n.size===0)return null;const i=[];for(const s of $s(t,e))n.has(s.offset)||i.push(t.subarray(s.offset,s.offset+s.length));return em(i,e)},lm={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Sl=t=>{const e=new Ee(t);if(e.readBits(2)!==2)return null;const r=e.readBits(1),s=(e.readBits(1)<<1)+r;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);const l=e.readBits(3);let f=0,d=0;if(l!==7)if(d=e.readBits(1),s===1||s===3){const S=e.readBits(1),P=e.readBits(1);f=!S&&!P?3:S&&!P?2:1,e.skipBits(1)}else f=1;else f=3,d=1;const h=e.readBits(16),p=e.readBits(16),m=h+1,g=p+1,w=m*g;let y=Rt(si).level;for(const T of si)if(w<=T.maxPictureSize){y=T.level;break}const b=lm[l],v=b?.colourPrimaries??2,k=b?.transferCharacteristics??2,A=b?.matrixCoefficients??2;return{profile:s,level:y,bitDepth:u,chromaSubsampling:f,videoFullRangeFlag:d,colourPrimaries:v,transferCharacteristics:k,matrixCoefficients:A}},um=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,Pl=function*(t){const e=new Ee(t),n=()=>{let r=0;for(let i=0;i<8;i++){const s=e.readAlignedByte();if(r+=(s&127)*2**(i*7),!(s&128))break;if(i===7&&s&128)return null}return r>2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){const o=n();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);R(e.pos%8===0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},vo=t=>{for(const{type:e,data:n}of Pl(t)){if(e!==1)continue;const r=new Ee(n),i=r.readBits(3);r.readBits(1);const s=r.readBits(1);let a=0,o=0,c=0;if(s)a=r.readBits(5);else{const P=r.readBits(1);let M=0;if(P){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let q=0;for(;q<32&&!r.readBits(1);)q++;q<32&&r.skipBits(q)}M=r.readBits(1),M&&(c=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}const B=r.readBits(1),N=r.readBits(5);for(let O=0;O<=N;O++){r.skipBits(12);const q=r.readBits(5);if(O===0&&(a=q),q>7){const H=r.readBits(1);O===0&&(o=H)}if(M&&r.readBits(1)){const G=c+1;r.skipBits(G),r.skipBits(G),r.skipBits(1)}B&&r.readBits(1)&&r.skipBits(4)}}const u=r.readBits(4),l=r.readBits(4),f=u+1;r.skipBits(f);const d=l+1;r.skipBits(d);let h=0;if(s?h=0:h=r.readBits(1),h&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const P=r.readBits(1);P&&(r.skipBits(1),r.skipBits(1));const M=r.readBits(1);let B=0;M?B=2:B=r.readBits(1),B>0&&(r.readBits(1)||r.skipBits(1)),P&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const p=r.readBits(1);let m=8;i===2&&p?m=r.readBits(1)?12:10:i<=2&&(m=p?10:8);let g=0;i!==1&&(g=r.readBits(1));let w=2,y=2,b=2;r.readBits(1)&&(w=r.readBits(8),y=r.readBits(8),b=r.readBits(8));let k=0,A=1,T=1,S=0;return g?k=r.readBits(1):w===1&&y===13&&b===0?(k=1,A=0,T=0):(k=r.readBits(1),i===0?(A=1,T=1):i===1?(A=0,T=0):m===12?(A=r.readBits(1),T=A?r.readBits(1):0):(A=1,T=0),A&&T&&(S=r.readBits(2))),{profile:i,level:a,tier:o,bitDepth:m,monochrome:g,chromaSubsamplingX:A,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:k,colourPrimaries:w,transferCharacteristics:y,matrixCoefficients:b}}return null},fm=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,_l=t=>{if(t.length<36)return null;const n=Me(t);return n.getUint32(4)!==1768124518||n.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:n.getUint8(22),transferCharacteristics:n.getUint8(23),matrixCoefficients:n.getUint8(24)}},dm=t=>{const e=Me(t),n=e.getUint8(9),r=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=t.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},hm=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],mm=t=>{const e=t[0]>>3,n=t[0]&3;let r;return n===0?r=1:n===1||n===2?r=2:r=t[1]&63,{durationInSamples:hm[e]*r}},pm=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const n=t.length,r=new Uint8Array(n);for(let f=0;f<n;f++)r[f]=t[n-1-f];const i=new Ee(r);let s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){const f=i.pos,d=i.readBits(8),h=i.readBits(16),p=i.readBits(16);if(d>63||h!==0||p!==0){i.pos=f;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const u=c;i.pos=0,i.skipBits(s);const l=Array(u).fill(0);for(let f=u-1;f>=0;f--)i.skipBits(40),l[f]=i.readBits(1);return{modeBlockflags:l}},ko=(t,e,n)=>{switch(t){case"avc":{for(const r of bl(n,e)){const i=n[r.offset],s=qs(i);if(s>=ut.NON_IDR_SLICE&&s<=ut.SLICE_DPC)return"delta";if(s===ut.IDR)return"key";if(s===ut.SEI&&!ao()){const a=n.subarray(r.offset,r.offset+r.length),o=Xs(a);let c=1;do{let u=0;for(;;){const d=o[c++];if(d===void 0||(u+=d,d<255))break}let l=0;for(;;){const d=o[c++];if(d===void 0||(l+=d,d<255))break}if(u===6){const d=new Ee(o);d.pos=8*c;const h=le(d),p=d.readBits(1);if(h===0&&p===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(const r of $s(n,e)){const i=ri(n[r.offset]);if(i<Ge.BLA_W_LP)return"delta";if(i<=Ge.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(n[0]&1)===0?"key":"delta";case"vp9":{const r=new Ee(n);if(r.readBits(2)!==2)return null;const i=r.readBits(1);return(r.readBits(1)<<1)+i===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:i,data:s}of Pl(n))if(i===1){const a=new Ee(s);a.skipBits(4),r=!!a.readBits(1)}else if(i===3||i===6||i===7){if(r)return"key";const a=new Ee(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Us(t),R(!1)}};var ii;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(ii||(ii={}));const Ao=(t,e)=>{const n=Me(t);let r=0;const i=n.getUint32(r,!0);r+=4;const s=Ft.decode(t.subarray(r,r+i));r+=i,i>0&&(e.raw??={},e.raw.vendor??=s);const a=n.getUint32(r,!0);r+=4;for(let o=0;o<a;o++){const c=n.getUint32(r,!0);r+=4;const u=Ft.decode(t.subarray(r,r+c));r+=c;const l=u.indexOf("=");if(l===-1)continue;const f=u.slice(0,l).toUpperCase(),d=u.slice(l+1);switch(e.raw??={},e.raw[f]??=d,f){case"TITLE":e.title??=d;break;case"DESCRIPTION":e.description??=d;break;case"ARTIST":e.artist??=d;break;case"ALBUM":e.album??=d;break;case"ALBUMARTIST":e.albumArtist??=d;break;case"COMMENT":e.comment??=d;break;case"LYRICS":e.lyrics??=d;break;case"TRACKNUMBER":{const h=d.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{const h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"DISCNUMBER":{const h=d.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{const h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DATE":{const h=new Date(d);Number.isNaN(h.getTime())||(e.date??=h)}break;case"GENRE":e.genre??=d;break;case"METADATA_BLOCK_PICTURE":{const h=ml(d),p=Me(h),m=p.getUint32(0,!1),g=p.getUint32(4,!1),w=String.fromCharCode(...h.subarray(8,8+g)),y=p.getUint32(8+g,!1),b=Ft.decode(h.subarray(12+g,12+g+y)),v=p.getUint32(g+y+28),k=h.subarray(g+y+32,g+y+32+v);e.images??=[],e.images.push({data:k,mimeType:w,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:b||void 0})}break}}},xo=[2,1,2,3,3,4,4,5],gm=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;const e=new Ee(t);e.skipBits(16),e.skipBits(16);const n=e.readBits(2);if(n===3)return null;const r=e.readBits(6),i=e.readBits(5);if(i>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(r/2);return{fscod:n,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},ym=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],bm=1536,El=[1,2,3,6],wm=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;const e=new Ee(t);e.skipBits(16);const n=e.readBits(2);if(e.skipBits(3),n!==0&&n!==2)return null;const r=e.readBits(11),i=e.readBits(2);let s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;const l=El[a];let f;return i<3?f=Ws[i]/1e3:f=gl[s]/1e3,{dataRate:Math.round((r+1)*f/(l*16)),substreams:[{fscod:i,fscod2:s,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},vm=t=>{if(t.length<2)return null;const e=new Ee(t),n=e.readBits(13),r=e.readBits(3),i=[];for(let s=0;s<=r&&!(Math.ceil(e.pos/8)+3>t.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),u=e.readBits(3),l=e.readBits(1);e.skipBits(3);const f=e.readBits(4);let d=0;f>0?d=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:f,chanLoc:d})}return i.length===0?null:{dataRate:n,substreams:i}},Cl=t=>{const e=t.substreams[0];return R(e),e.fscod<3?Ws[e.fscod]:e.fscod2!==null&&e.fscod2<3?gl[e.fscod2]:null},Il=t=>{const e=t.substreams[0];R(e);let n=xo[e.acmod]+e.lfeon;if(e.numDepSub>0){const r=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(n+=r[i])}return n},km=1683496997,Qs=18,To=10,Am=4096,Ml=32,Bl=20,xm=8,Tm=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Sm=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Pm=[16,16,20,20,0,24,24,0],Ys=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],_m=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Em=8,Cm=44646,Im=[32e3,44100,48e3,0],Mm=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Bm=[512,1024,2048,4096],Rl=t=>{const e=Dl(t),n=Me(t);let r=e?Math.ceil(e.frameSize/4)*4:0,i=null;for(;r+4<=t.length&&n.getUint32(r)===km;){const a=Ks(t.subarray(r));if(!a)break;i??=a,r+=a.frameSize}if(e)return{frameSize:i?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:i!==null};if(!i?.asset)return null;const{asset:s}=i;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Fl=t=>{const e=Rl(t);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},Dl=t=>{if(t.length<Qs||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;const e=new Ee(t);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==Ml-1)return null;const n=e.readBits(1),r=e.readBits(7)+1;if(r%xm!==0)return null;const i=e.readBits(14)+1;if(i<96)return null;const s=e.readBits(6);if(s>=Ys.length)return null;const a=Tm[e.readBits(4)];if(a===0)return null;const o=Sm[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const c=e.readBits(2);if(c===3)return null;e.skipBits(1),n&&e.skipBits(16),e.skipBits(7);const u=Pm[e.readBits(3)];if(u===0)return null;const l=c!==0;return{frameSize:i,sampleRate:a,numberOfChannels:Ys[s]+(l?1:0),sampleCount:r*Ml,channelLayout:_m[s]|(l?Em:0),amode:s,lfePresent:l,bitRate:o,pcmResolution:u}},Ks=t=>{if(t.length<To||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;const e=new Ee(t);e.skipBits(32),e.skipBits(8);const n=e.readBits(2),r=e.readBits(1),i=8+4*r,s=16+4*r;e.skipBits(i);const a=e.readBits(s)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=Im[e.readBits(2)],u=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,f=e.readBits(3)+1,d=[];for(let w=0;w<l;w++)d.push(e.readBits(n+1));for(const w of d)e.skipBits(8*eo(w));if(e.readBits(1)){e.skipBits(2);const w=e.readBits(2)+1<<2,y=e.readBits(2)+1;e.skipBits(y*w)}for(let w=0;w<f;w++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,p=Mm[e.readBits(4)],m=e.readBits(8)+1;let g=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const w=e.readBits(2)+1<<2;g=e.readBits(w)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(u*p/c),channelLayout:g,pcmResolution:h}}},Rm=t=>{if(t.length<Bl)return null;const e=Me(t),n=e.getUint32(0);if(n===0)return null;const r=new Ee(t);r.seekToByte(13);const i=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return o!==0?c=Fm(o):a<Ys.length&&(c=Ys[a]+s),{sampleRate:n,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:t[12],sampleCount:Bm[i],channelLayout:o,numberOfChannels:c}},Fm=t=>eo(t)+eo(t&Cm);const Nl=["avc","hevc","vp9","av1","vp8","prores"],Zs=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Dm=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Ll=[...Dm,...Zs],Ul=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],si=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Ol=".01.01.01.01.00",zl=".0.110.01.01.01.0",So=["ap4x","ap4h","apch","apcn","apcs","apco"],Hl=["dtsc","dtsh","dtsl","dtse"],Po=t=>{const{codec:e,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=t;if(e==="avc"){if(R(t.avcType!==null),i){const u=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${Ui(u)}`}if(!n||n.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Ui(n.subarray(1,4))}`}else if(e==="hevc"){let u,l,f,d,h,p;if(s)u=s.generalProfileSpace,l=s.generalProfileIdc,f=al(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const g=Me(n),w=g.getUint8(1);u=w>>6&3,l=w&31,f=al(g.getUint32(2)),d=w>>5&1,h=g.getUint8(12),p=[];for(let y=0;y<6;y++)p.push(g.getUint8(6+y))}let m="hev1.";for(m+=["","A","B","C"][u]+l,m+=".",m+=f.toString(16).toUpperCase(),m+=".",m+=d===0?"L":"H",m+=h;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(m+=".",m+=p.map(g=>g.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const y=t.width*t.height;let b=Rt(si).level;for(const v of si)if(y<=v.maxPictureSize){b=v.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}const u=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),f=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),m=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${u}.${l}.${f}.${d}`;return w+=`.${h}.${p}.${m}.${g}`,w.endsWith(Ol)&&(w=w.slice(0,-Ol.length)),w}else if(e==="av1"){if(!o){const v=t.width*t.height;let k=Rt(si).level;for(const A of si)if(v<=A.maxPictureSize){k=A.level;break}return`av01.0.${k.toString().padStart(2,"0")}M.08`}const u=o.profile,l=o.level.toString().padStart(2,"0"),f=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),m=r?.primaries?Xa[r.primaries]:1,g=r?.transfer?Ga[r.transfer]:1,w=r?.matrix?$a[r.matrix]:1,y=r?.fullRange?1:0;let b=`av01.${u}.${l}${f}.${d}`;return b+=`.${h}.${p.toString().padStart(3,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${w.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(zl)&&(b=b.slice(0,-zl.length)),b}else{if(e==="prores")return c??"apch";e!==null&&Us(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Vl=t=>{switch(t.codec){case"avc":{let e=t.avcCodecInfo?.sequenceParameterSets[0];if(!e&&t.codecDescription&&(e=kl(t.codecDescription)?.sequenceParameterSets[0]),e){const n=Gs(e);if(n)return{primaries:Dn[n.colourPrimaries],transfer:Nn[n.transferCharacteristics],matrix:Ln[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"hevc":{let e=t.hevcCodecInfo?.arrays.find(n=>n.nalUnitType===Ge.SPS_NUT)?.nalUnits[0];if(!e&&t.codecDescription&&(e=om(t.codecDescription)?.arrays.find(n=>n.nalUnitType===Ge.SPS_NUT)?.nalUnits[0]),e){const n=bo(e);if(n)return{primaries:Dn[n.colourPrimaries],transfer:Nn[n.transferCharacteristics],matrix:Ln[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(t.vp9CodecInfo)return{primaries:Dn[t.vp9CodecInfo.colourPrimaries],transfer:Nn[t.vp9CodecInfo.transferCharacteristics],matrix:Ln[t.vp9CodecInfo.matrixCoefficients],fullRange:!!t.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(t.av1CodecInfo)return{primaries:Dn[t.av1CodecInfo.colourPrimaries],transfer:Nn[t.av1CodecInfo.transferCharacteristics],matrix:Ln[t.av1CodecInfo.matrixCoefficients],fullRange:!!t.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(t.proresCodecInfo)return{primaries:Dn[t.proresCodecInfo.colourPrimaries],transfer:Nn[t.proresCodecInfo.transferCharacteristics],matrix:Ln[t.proresCodecInfo.matrixCoefficients],fullRange:t.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},_o=t=>{const{codec:e,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=t;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let s;return r.objectType!==null?s=r.objectType:s=pl(n).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return i??"dtsc";if(e&&Zs.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Js=48e3,Wl=/^pcm-([usf])(\d+)(be)?$/,Nm=t=>{if(R(Zs.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Wl.exec(t);R(e);let n;e[1]==="u"?n="unsigned":e[1]==="s"?n="signed":n="float";const r=Number(e[2])/8,i=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:s}},ji=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":So.includes(t)?"prores":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"||t==="mp4a.40.34"?"mp3":t.startsWith("mp4a.40.")||t==="mp4a.67"?"aac":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":Hl.includes(t)?"dts":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Wl.test(t)?t:t==="webvtt"?"webvtt":null;const Br=4,Lm=[44100,48e3,32e3],Um=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],jl=1483304551,ql=1231971951,Om=(t,e,n,r,i)=>e===0?0:e===1?Math.floor(144*n/(r<<t))+i:e===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,zm=(t,e,n,r)=>e===0?0:e===1?144*n/(r<<t):e===2?144*n/r:12*n/r*4,Xl=(t,e)=>t===3?e===3?21:36:e===3?13:21,Eo=(t,e)=>{const n=t>>>24,r=t>>>16&255,i=t>>>8&255,s=t&255;if(n!==255&&r!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(n!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;r&16?a=r&8?0:1:(a=1,o=1);const c=r>>3&3,u=r>>1&3,l=i>>4&15,f=(i>>2&3)%3,d=i>>1&1,h=s>>6&3,p=s>>4&3,m=s>>3&1,g=s>>2&1,w=s&3,y=Um[a*16*4+u*16+l];if(y===-1)return{header:null,bytesAdvanced:1};const b=y*1e3,v=Lm[f]>>a+o,k=Om(a,u,b,v,d);if(e!==null&&e<k)return{header:null,bytesAdvanced:1};let A;return c===3?A=u===3?384:1152:u===3?A=384:u===2?A=1152:A=576,{header:{totalSize:k,mpegVersionId:c,lowSamplingFrequency:a,layer:u,bitrate:b,frequencyIndex:f,sampleRate:v,channel:h,modeExtension:p,copyright:m,original:g,emphasis:w,audioSamplesInFrame:A},bytesAdvanced:1}},Co=t=>{let e=2130706432,n=0;for(;e!==0;)n>>=1,n|=t&e,e>>=8;return n};var ea;(function(t){t[t.FrameCount=1]="FrameCount",t[t.FileSize=2]="FileSize",t[t.Toc=4]="Toc"})(ea||(ea={}));const qi=t=>t===3?1:2;class On{constructor(e){this.input=e}dispose(){}}const Ht=new Uint8Array(0);class Ze{constructor(e,n,r,i,s=-1,a,o){if(this.data=e,this.type=n,this.timestamp=r,this.duration=i,this.sequenceNumber=s,e===Ht&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(n!=="key"&&n!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Ht}get microsecondTimestamp(){return Math.trunc(ti*this.timestamp)}get microsecondDuration(){return Math.trunc(ti*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,n){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Ze(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,n)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new Ze(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const Hm=t=>{let n=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const r=[...new Set(t.codecStrings)];n+=`; codecs="${r.join(", ")}"`}return n},Gl=t=>{const e=Me(t);let n=0;const r=e.getUint8(n);n+=1,n+=3;const i=Ui(t.subarray(n,n+16));n+=16;let s=null;if(r>0){const o=e.getUint32(n);if(n+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(Ui(t.subarray(n,n+16))),n+=16}}const a=e.getUint32(n);return n+=4,{systemId:i,keyIds:s,data:t.slice(n,n+a)}},$l=(t,e)=>t.systemId===e.systemId&&Kh(t.data,e.data);const ai=8,Xi=16,ar=t=>{let e=ae(t);const n=je(t,4);let r=8;e===1&&(e=Wt(t),r=16);const s=e-r;return s<0?null:{name:n,totalSize:e,headerSize:r,contentSize:s}},Rr=t=>Or(t)/65536,Io=t=>Or(t)/1073741824,Mo=t=>{let e=0;for(let n=0;n<4;n++){e<<=7;const r=de(t);if(e|=r&127,(r&128)===0)break}return e},kn=t=>{let e=$e(t);return t.skip(2),e=Math.min(e,t.remainingLength),Ft.decode(me(t,e))},Vm=t=>{const e=ar(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;const n=ae(t);t.skip(4);const r=me(t,e.contentSize-8);switch(n){case 1:return Ft.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Vs(r,"image/jpeg");case 14:return new Vs(r,"image/png");case 27:return new Vs(r,"image/bmp");default:return r}};const An=16,zn=new Uint32Array(256),oi=new Uint32Array(256),ci=new Uint32Array(256),li=new Uint32Array(256),ui=new Uint32Array(256),ft=new Uint32Array(256),Ql=new Uint32Array(10);let Yl=!1;const Wm=()=>{const t=new Uint8Array(256),e=new Uint8Array(256),n=new Uint8Array(256);for(let s=0,a=1;s<256;s++)n[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const r=(s,a)=>s&&a?n[(e[s]+e[a])%255]:0;t[0]=99;for(let s=1;s<256;s++){const a=n[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,t[s]=o}for(let s=0;s<256;s++){const a=t[s],o=t.indexOf(s);zn[s]=a<<24|a<<16|a<<8|a,ft[s]=o<<24|o<<16|o<<8|o;const c=r(o,14),u=r(o,9),l=r(o,13),f=r(o,11),d=c<<24|u<<16|l<<8|f;oi[s]=d,ci[s]=d>>>8|d<<24,li[s]=d>>>16|d<<16,ui[s]=d>>>24|d<<8}let i=1;for(let s=0;s<10;s++)Ql[s]=i<<24,i=i<<1^(i&128?283:0);Yl=!0};class Kl{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(An/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(An),this.out=new Uint8Array(An),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:n}){R(e.byteLength===16),R(n.byteLength===16),Yl||Wm();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(n.buffer,n.byteOffset,n.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^zn[a>>>16&255]&4278190080^zn[a>>>8&255]&16711680^zn[a>>>0&255]&65280^zn[a>>>24&255]&255^Ql[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=oi[zn[o>>>24&255]&255]^ci[zn[o>>>16&255]&255]^li[zn[o>>>8&255]&255]^ui[zn[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],n=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let u,l,f,d;for(let w=1;w<10;w++){const y=w*4;u=oi[e>>>24]^ci[i>>>16&255]^li[r>>>8&255]^ui[n&255]^this.roundkey[y],l=oi[n>>>24]^ci[e>>>16&255]^li[i>>>8&255]^ui[r&255]^this.roundkey[y+1],f=oi[r>>>24]^ci[n>>>16&255]^li[e>>>8&255]^ui[i&255]^this.roundkey[y+2],d=oi[i>>>24]^ci[r>>>16&255]^li[n>>>8&255]^ui[e&255]^this.roundkey[y+3],e=u,n=l,r=f,i=d}const h=ft[e>>>24&255]&4278190080^ft[i>>>16&255]&16711680^ft[r>>>8&255]&65280^ft[n>>>0&255]&255^this.roundkey[40],p=ft[n>>>24&255]&4278190080^ft[e>>>16&255]&16711680^ft[i>>>8&255]&65280^ft[r>>>0&255]&255^this.roundkey[41],m=ft[r>>>24&255]&4278190080^ft[n>>>16&255]&16711680^ft[e>>>8&255]&65280^ft[i>>>0&255]&255^this.roundkey[42],g=ft[i>>>24&255]&4278190080^ft[r>>>16&255]&16711680^ft[n>>>8&255]&65280^ft[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,g^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const jm=(t,e,n)=>{let r=!1,i=0;const s=2**16,a=16,o=new Kl;return new ReadableStream({pull:async c=>{r||(o.init(await e()),r=!0);const u=s+a;let l=t.requestSliceRange(i,0,u);if(ie(l)&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");const f=l.length;if(f%16!==0)throw new Error("Invalid ciphertext.");const d=f===u?f-a:f,h=me(l,d),p=new Uint8Array(d);for(let m=0;m<d;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(d<f)c.enqueue(p),i+=d;else{const m=p[d-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const g=p.subarray(0,d-m);c.enqueue(g),c.close(),n()}},cancel:()=>{n()}})};class jc extends On{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),n=await Promise.all(e.map(r=>r.getDecoderConfig().then(i=>i?.codec??null)));return Hm({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:n.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,n=!1,r=!1;for(;;){let i=this.reader.requestSliceRange(e,ai,Xi);if(ie(i)&&(i=await i),!i)break;const s=e,a=ar(i);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=je(i,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(i.filePos,a.contentSize);if(ie(o)&&(o=await o),!o)break;this.moovSlice=o,this.readContiguousBoxes(this.moovSlice);for(const c of this.tracks){const u=c.editListPreviousSegmentDurations/this.movieTimescale;c.editListOffset-=Math.round(u*c.timescale)}n=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,r=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),n=!1,r=!0;break}e=s+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),n){R(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);ie(i)&&(i=await i),R(i);const s=ae(i),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Xi){let o=this.reader.requestSliceRange(a,ai,Xi);if(ie(o)&&(o=await o),o){const c=ar(o);if(c&&c.name==="mfra"){let u=this.reader.requestSlice(o.filePos,c.contentSize);ie(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}})()}async copyMetadataFromInitInput(e){const n=await e._getDemuxer();if(n.constructor!==jc)throw new Error("Init input must match the input's format.");await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(const r of n.tracks){const i={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking){if(R(i.info),i.info.type==="video"&&i.info.width!==-1){const s=i;i.trackBacking=new Jl(s),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){const s=i;i.trackBacking=new eu(s),this.tracks.push(i)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const n={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=n,e.sampleTableByteOffset===null)return n;R(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Zs.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){R(e.info?.type==="audio");const s=Nm(e.info.codec),a=[],o=[];for(let c=0;c<n.sampleToChunk.length;c++){const u=n.sampleToChunk[c],l=n.sampleToChunk[c+1],f=(l?l.startChunkIndex:n.chunkOffsets.length)-u.startChunkIndex;for(let d=0;d<f;d++){const h=u.startSampleIndex+d*u.samplesPerChunk,p=h+u.samplesPerChunk,m=_e(n.sampleTimingEntries,h,S=>S.startIndex),g=n.sampleTimingEntries[m],w=_e(n.sampleTimingEntries,p,S=>S.startIndex),y=n.sampleTimingEntries[w],b=g.startDecodeTimestamp+(h-g.startIndex)*g.delta,k=y.startDecodeTimestamp+(p-y.startIndex)*y.delta-b,A=Rt(a);A&&A.delta===k?A.count++:a.push({startIndex:u.startChunkIndex+d,startDecodeTimestamp:b,count:1,delta:k});const T=u.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(T)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}n.sampleTimingEntries=a,n.sampleSizes=o}if(n.sampleCompositionTimeOffsets.length>0){n.presentationTimestamps=[];for(const s of n.sampleTimingEntries)for(let a=0;a<s.count;a++)n.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(const s of n.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){const o=s.startIndex+a,c=n.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}n.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),n.presentationTimestampIndexMap=Array(n.presentationTimestamps.length).fill(-1);for(let s=0;s<n.presentationTimestamps.length;s++)n.presentationTimestampIndexMap[n.presentationTimestamps[s].sampleIndex]=s}return n}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let n=this.reader.requestSliceRange(e,ai,Xi);ie(n)&&(n=await n),R(n);const r=ar(n);R(r?.name==="moof");let i=this.reader.requestSlice(e,r.totalSize);ie(i)&&(i=await i),R(i),this.traverseBox(i);const s=this.lastReadFragment;R(s&&s.moofOffset===e);for(const[,a]of s.trackData){const o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){const l=o.fragmentLookupTable.find(f=>f.moofOffset===s.moofOffset);if(l)Ro(a,l.timestamp);else{const f=_e(c,s.moofOffset-1,d=>d.moofOffset);if(f!==-1){const d=c[f];Ro(a,d.endTimestamp)}}a.startTimestampIsFinal=!0}const u=_e(c,a.startTimestamp,l=>l.startTimestamp);if((u===-1||c[u].moofOffset!==s.moofOffset)&&c.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const l=await ru(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let f=0;f<Math.min(a.samples.length,l.length);f++){const d=l[f];a.samples[f].encryption=d}}}return s}readContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-ai&&this.traverseBox(e););}*iterateContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-ai;){const r=e.filePos,i=ar(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=r+i.totalSize}}traverseBox(e){const n=e.filePos,r=ar(e);if(!r)return!1;const i=e.filePos,s=n+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mvhd":{const a=de(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=ae(e),this.movieDurationInTimescale=Wt(e)):(e.skip(8),this.movieTimescale=ae(e),this.movieDurationInTimescale=ae(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...Un,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Et,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,r.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new Jl(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new eu(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=de(e),u=!!(qn(e)&1);if(a.disposition.default=u,o===0)e.skip(8),a.id=ae(e),e.skip(4),a.durationInMovieTimescale=ae(e);else if(o===1)e.skip(16),a.id=ae(e),e.skip(4),a.durationInMovieTimescale=Wt(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const l=[Rr(e),Rr(e),Io(e),Rr(e),Rr(e),Io(e),Rr(e),Rr(e),Io(e)],f=ja(Za($m(l),90));R(f===0||f===90||f===180||f===270),a.rotation=f}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=de(e);e.skip(3);let c=!1,u=0;const l=ae(e);for(let f=0;f<l;f++){const d=o===1?Wt(e):ae(e),h=o===1?Ug(e):Or(e),p=Rr(e);if(c){pe._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){u+=d;continue}if(p!==1){pe._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=h,c=!0}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=de(e);e.skip(3),o===0?(e.skip(8),a.timescale=ae(e),a.durationInMediaTimescale=ae(e)):o===1&&(e.skip(16),a.timescale=ae(e),a.durationInMediaTimescale=Wt(e));let c=$e(e);if(c>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;fl(a.languageCode)||(a.languageCode=Et)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=je(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...sl},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=n,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=de(e);e.skip(3);const c=ae(e);for(let u=0;u<c;u++){const l=e.filePos,f=ar(e);if(!f)break;a.internalCodecId=f.name;const d=f.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=$e(e),a.info.height=$e(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,l+f.totalSize-e.filePos));const h=d==="encv"?a.frmaCodecString:d;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":So.includes(d)?(a.info.codec="prores",a.info.proresFormat=d):h===null?pe._warn("Unknown encrypted video codec due to missing frma box."):pe._warn(`Unsupported video codec (sample entry type '${f.name}').`)}else{e.skip(8);const h=$e(e);e.skip(6);let p=$e(e),m=$e(e);e.skip(4);let g=ae(e)/65536,w=null;o===0&&h>0&&(h===1?(e.skip(4),m=8*ae(e),e.skip(8)):h===2&&(e.skip(4),g=df(e),p=ae(e),e.skip(4),m=ae(e),w=ae(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=g,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,l+f.totalSize-e.filePos));const y=d==="enca"?a.frmaCodecString:d;if(a.frmaCodecString=null,y!=="mp4a")if(y==="opus")a.info.codec="opus",a.info.sampleRate=Js;else if(y==="flac")a.info.codec="flac";else if(y==="ulaw")a.info.codec="ulaw";else if(y==="alaw")a.info.codec="alaw";else if(y==="ac-3")a.info.codec="ac3";else if(y==="ec-3")a.info.codec="eac3";else if(Hl.includes(y))a.info.codec="dts",a.info.dtsFormat=y;else if(y==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(pe._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(y==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(pe._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(y==="raw ")a.info.codec="pcm-u8";else if(y==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(y==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(y==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(y==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(y==="ipcm"){const b=a.info.pcmSampleSize;a.info.pcmLittleEndian?b===16?a.info.codec="pcm-s16":b===24?a.info.codec="pcm-s24":b===32?a.info.codec="pcm-s32":(pe._warn(`Invalid ipcm sample size ${b}.`),a.info.codec=null):b===16?a.info.codec="pcm-s16be":b===24?a.info.codec="pcm-s24be":b===32?a.info.codec="pcm-s32be":(pe._warn(`Invalid ipcm sample size ${b}.`),a.info.codec=null)}else if(y==="fpcm"){const b=a.info.pcmSampleSize;a.info.pcmLittleEndian?b===32?a.info.codec="pcm-f32":b===64?a.info.codec="pcm-f64":(pe._warn(`Invalid fpcm sample size ${b}.`),a.info.codec=null):b===32?a.info.codec="pcm-f32be":b===64?a.info.codec="pcm-f64be":(pe._warn(`Invalid fpcm sample size ${b}.`),a.info.codec=null)}else if(y==="lpcm"&&w!==null){const b=m+7>>3,v=!!(w&1),k=!!(w&2),A=w&4?-1:0;m>0&&m<=64&&(v?m===32&&(a.info.codec=k?"pcm-f32be":"pcm-f32"):A&1<<b-1?b===1?a.info.codec="pcm-s8":b===2?a.info.codec=k?"pcm-s16be":"pcm-s16":b===3?a.info.codec=k?"pcm-s24be":"pcm-s24":b===4&&(a.info.codec=k?"pcm-s32be":"pcm-s32"):b===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&pe._warn("Unsupported PCM format.")}else y===null?pe._warn("Unknown encrypted audio codec due to missing frma box."):pe._warn(`Unsupported audio codec (sample entry type '${f.name}').`)}e.filePos=l+f.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const c=je(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=je(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:pe._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=de(e);e.skip(3),e.skip(1);const c=de(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=de(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=de(e),a.encryptionInfo.defaultKid=Ui(me(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const u=de(e),l=new Uint8Array(16);l.set(me(e,u),0),a.encryptionInfo.defaultConstantIv=l}}break;case"avcC":{const a=this.currentTrack;if(!a||(R(a.info),r.contentSize===0))break;a.info.codecDescription=me(e,r.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(R(a.info),r.contentSize===0))break;a.info.codecDescription=me(e,r.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="video"),e.skip(4);const o=de(e),c=de(e),u=de(e),l=u>>4,f=u>>1&7,d=u&1,h=de(e),p=de(e),m=de(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:l,chromaSubsampling:f,videoFullRangeFlag:d,colourPrimaries:h,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="video"),e.skip(1);const o=de(e),c=o>>5,u=o&31,l=de(e),f=l>>7,d=l>>6&1,h=l>>5&1,p=l>>4&1,m=l>>3&1,g=l>>2&1,w=l&3,y=c===2&&d?h?12:10:d?10:8;e.skip(1);const b=me(e,r.contentSize-4),v=vo(b);a.info.av1CodecInfo={profile:c,level:u,tier:f,bitDepth:y,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:w,videoFullRangeFlag:v?.videoFullRangeFlag??0,colourPrimaries:v?.colourPrimaries??2,transferCharacteristics:v?.transferCharacteristics??2,matrixCoefficients:v?.matrixCoefficients??2}}break;case"colr":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="video");const o=je(e,4);if(o!=="nclx"&&o!=="nclc")break;const c=$e(e),u=$e(e),l=$e(e);let f;o==="nclx"&&(f=!!(de(e)&128)),a.info.colorSpace={primaries:Dn[c],transfer:Nn[u],matrix:Ln[l],fullRange:f}}break;case"pasp":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="video");const o=ae(e),c=ae(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"esds":{const a=this.currentTrack;if(!a||a.info?.type!=="audio")break;e.skip(4);const o=de(e);R(o===3),Mo(e),e.skip(2);const c=de(e),u=(c&128)!==0,l=(c&64)!==0,f=(c&32)!==0;if(u&&e.skip(2),l){const g=de(e);e.skip(g)}f&&e.skip(2);const d=de(e);R(d===4);const h=Mo(e),p=e.filePos,m=de(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":m===169?a.info.codec="dts":pe._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),h>e.filePos-p){const g=de(e);R(g===5);const w=Mo(e);if(a.info.codecDescription=me(e,w),a.info.codec==="aac"){const y=pl(a.info.codecDescription);y.outputNumberOfChannels!==null&&(a.info.numberOfChannels=y.outputNumberOfChannels),y.outputSampleRate!==null&&(a.info.sampleRate=y.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio"),a.info.pcmLittleEndian=!!($e(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio"),e.skip(4);const o=de(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=de(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio"),e.skip(1);const o=de(e),c=$e(e),u=ae(e),l=tc(e),f=de(e);let d;f!==0?d=me(e,2+o):d=new Uint8Array(0);const h=new Uint8Array(19+d.byteLength),p=new DataView(h.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,u,!0),p.setInt16(16,l,!0),p.setUint8(18,f),h.set(d,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio"),e.skip(4);const o=127,c=128,u=e.filePos;for(;e.filePos<s;){const p=de(e),m=qn(e);if((p&o)===ii.STREAMINFO){e.skip(10);const w=ae(e),y=w>>>12,b=(w>>9&7)+1;a.info.sampleRate=y,a.info.numberOfChannels=b,e.skip(20)}else e.skip(m);if(p&c)break}const l=e.filePos;e.filePos=u;const f=me(e,l-u),d=new Uint8Array(4+f.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(f,4),a.info.codecDescription=d}break;case"dac3":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio");const o=me(e,3),c=new Ee(o),u=c.readBits(2);c.skipBits(8);const l=c.readBits(3),f=c.readBits(1);u<3&&(a.info.sampleRate=Ws[u]),a.info.numberOfChannels=xo[l]+f}break;case"dec3":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio");const o=me(e,r.contentSize),c=vm(o);if(!c){pe._warn("Invalid dec3 box contents, ignoring.");break}const u=Cl(c);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=Il(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio");const o=me(e,Math.min(r.contentSize,Bl)),c=Rm(o);if(!c){pe._warn("Invalid ddts box contents, ignoring.");break}a.info.sampleRate=c.sampleRate,c.numberOfChannels!==null&&(a.info.numberOfChannels=c.numberOfChannels)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e);let c=0,u=0;for(let l=0;l<o;l++){const f=ae(e),d=ae(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:u,count:f,delta:d}),c+=f,u+=f*d}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e);let c=0;for(let u=0;u<o;u++){const l=ae(e),f=Or(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:l,offset:f}),c+=l}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e),c=ae(e);if(o===0)for(let u=0;u<c;u++){const l=ae(e);a.sampleTable.sampleSizes.push(l)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);const o=de(e),c=ae(e),u=me(e,Math.ceil(c*o/8)),l=new Ee(u);for(let f=0;f<c;f++){const d=l.readBits(o);a.sampleTable.sampleSizes.push(d)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];const o=ae(e);for(let c=0;c<o;c++){const u=ae(e)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e);for(let u=0;u<o;u++){const l=ae(e)-1,f=ae(e),d=ae(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:l,samplesPerChunk:f,sampleDescriptionIndex:d})}let c=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=c,u<a.sampleTable.sampleToChunk.length-1){const f=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;c+=f*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e);for(let c=0;c<o;c++){const u=ae(e);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ae(e);for(let c=0;c<o;c++){const u=Wt(e);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mehd":{const a=de(e);e.skip(3);const o=a===1?Wt(e):ae(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const a=ae(e),o=ae(e),c=ae(e),u=ae(e),l=ae(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:u,defaultSampleFlags:l})}break;case"tfra":{const a=de(e);e.skip(3);const o=ae(e),c=this.tracks.find(y=>y.id===o);if(!c)break;const u=ae(e),l=(u&48)>>4,f=(u&12)>>2,d=u&3,h=[de,$e,qn,ae],p=h[l],m=h[f],g=h[d],w=ae(e);for(let y=0;y<w;y++){const b=a===1?Wt(e):ae(e),v=a===1?Wt(e):ae(e);p(e),m(e),g(e),c.fragmentLookupTable.push({timestamp:b,moofOffset:v})}c.fragmentLookupTable.sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<c.fragmentLookupTable.length-1;y++){const b=c.fragmentLookupTable[y],v=c.fragmentLookupTable[y+1];b.timestamp===v.timestamp&&(c.fragmentLookupTable.splice(y+1,1),y--)}}break;case"moof":this.currentFragment={moofOffset:n,moofSize:r.totalSize,implicitBaseDataOffset:n,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(R(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((l,f)=>({presentationTimestamp:l.presentationTimestamp,sampleIndex:f})).sort((l,f)=>l.presentationTimestamp-f.presentationTimestamp);for(let l=0;l<a.presentationTimestamps.length;l++){const f=a.presentationTimestamps[l],d=a.samples[f.sampleIndex];if(a.firstKeyFrameTimestamp===null&&d.isKeyFrame&&(a.firstKeyFrameTimestamp=d.presentationTimestamp),l<a.presentationTimestamps.length-1){const p=a.presentationTimestamps[l+1].presentationTimestamp-f.presentationTimestamp;d.duration=p}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[Rt(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:u}=this.currentTrack;R(u),u.startTimestamp!==null&&(Ro(a,u.startTimestamp),a.startTimestampIsFinal=!0),u.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=u.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=Gl(me(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{R(this.currentFragment),e.skip(1);const a=qn(e),o=!!(a&1),c=!!(a&2),u=!!(a&8),l=!!(a&16),f=!!(a&32),d=!!(a&65536),h=!!(a&131072),p=ae(e),m=this.tracks.find(w=>w.id===p);if(!m)break;const g=this.fragmentTrackDefaults.find(w=>w.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Wt(e):h&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=ae(e)),u&&(m.currentFragmentState.defaultSampleDuration=ae(e)),l&&(m.currentFragmentState.defaultSampleSize=ae(e)),f&&(m.currentFragmentState.defaultSampleFlags=ae(e)),d&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;R(a.currentFragmentState);const o=de(e);e.skip(3);const c=o===0?ae(e):Wt(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;R(this.currentFragment),R(a.currentFragmentState);const o=de(e),c=qn(e),u=!!(c&1),l=!!(c&4),f=!!(c&256),d=!!(c&512),h=!!(c&1024),p=!!(c&2048),m=ae(e);let g=null;u&&(g=Or(e));let w=null;l&&(w=ae(e));let y;this.currentFragment.trackData.has(a.id)?(y=this.currentFragment.trackData.get(a.id),g!==null&&(y.currentOffset=a.currentFragmentState.baseDataOffset+g)):(y={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(g??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,y));for(let b=0;b<m;b++){let v;f?v=ae(e):(R(a.currentFragmentState.defaultSampleDuration!==null),v=a.currentFragmentState.defaultSampleDuration);let k;d?k=ae(e):(R(a.currentFragmentState.defaultSampleSize!==null),k=a.currentFragmentState.defaultSampleSize);let A;h?A=ae(e):(R(a.currentFragmentState.defaultSampleFlags!==null),A=a.currentFragmentState.defaultSampleFlags),b===0&&w!==null&&(A=w);let T=0;p&&(o===0?T=ae(e):T=Or(e));const S=!(A&65536);y.samples.push({presentationTimestamp:y.currentTimestamp+T,duration:v,byteOffset:y.currentOffset,byteSize:k,isKeyFrame:S,encryption:null}),y.currentOffset+=k,y.currentTimestamp+=v}this.currentFragment.implicitBaseDataOffset=y.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),qn(e)&1){const d=je(e,4),h=ae(e);if(d!==a.encryptionInfo.scheme||h!==0)break}const c=de(e),u=ae(e);let l=null;c===0&&u>0&&(l=me(e,u));const f=nu(a);f.defaultSampleInfoSize=c,f.sampleSizes=l,f.sampleCount=u}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=de(e);if(qn(e)&1){const d=je(e,4),h=ae(e);if(d!==a.encryptionInfo.scheme||h!==0)break}const u=ae(e);if(u===0)break;u>1&&pe._warn("Multiple saio entries are not supported; using the first offset only.");let l=o===0?ae(e):Number(Wt(e));this.currentFragment&&(l+=this.currentFragment.moofOffset);const f=nu(a);f.offset=l}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;R(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const u=!!(qn(e)&2),l=ae(e),f=a.encryptionInfo.defaultPerSampleIvSize;R(f!==null);for(let d=0;d<Math.min(l,o.samples.length);d++){const h=new Uint8Array(16);f>0?h.set(me(e,f),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(u){const g=$e(e);p=[];for(let w=0;w<g;w++){const y=$e(e),b=ae(e);p.push({clearLen:y,protectedLen:b})}}const m=o.samples[d];m.encryption={iv:h,subsamples:p}}}break;case"udta":{const a=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){const u=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=kn(c):this.metadataTags.raw[o.name]??=me(c,o.contentSize),c.filePos=u}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=Ft.decode(me(c,o.contentSize)):this.metadataTags.title??=kn(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=kn(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=kn(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=kn(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=kn(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=kn(c));break;case"\xA9day":if(!this.currentTrack){const u=new Date(kn(c));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=kn(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=kn(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=ae(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const a=ae(e);for(let o=0;o<a;o++){const c=ae(e);e.skip(4);const u=Ft.decode(me(e,c-8));this.currentMetadataKeys.set(o+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:o,slice:c}of a){let u=o.name;const l=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(l)&&(u=this.currentMetadataKeys.get(l));const f=Vm(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=f,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof f=="string"&&(this.metadataTags.title??=f);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof f=="string"&&(this.metadataTags.description??=f);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof f=="string"&&(this.metadataTags.artist??=f);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof f=="string"&&(this.metadataTags.album??=f);break;case"aART":case"album_artist":typeof f=="string"&&(this.metadataTags.albumArtist??=f);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof f=="string"&&(this.metadataTags.comment??=f);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof f=="string"&&(this.metadataTags.genre??=f);break;case"\xA9lyr":case"lyrics":typeof f=="string"&&(this.metadataTags.lyrics??=f);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof f=="string"){const d=new Date(f);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"covr":case"com.apple.quicktime.artwork":f instanceof Vs?(this.metadataTags.images??=[],this.metadataTags.images.push({data:f.data,kind:"coverFront",mimeType:f.mimeType})):f instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:f,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof f=="string"){const d=f.split("/"),h=Number.parseInt(d[0],10),p=d[1]&&Number.parseInt(d[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(f instanceof Uint8Array&&f.length>=6){const d=Me(f),h=d.getUint16(2,!1),p=d.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(f instanceof Uint8Array&&f.length>=6){const d=Me(f),h=d.getUint16(2,!1),p=d.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}}class Zl{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,n=this.internalTrack.trackBacking.getType();let r=0;for(const i of e.tracks)if(i.trackBacking.getType()===n&&r++,i===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(R(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const n=await this.fetchPacketForSampleIndex(0,e);return n||!this.internalTrack.demuxer.isFragmented?n:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Hi(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,n){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Bo(i,r),a=await this.fetchPacketForSampleIndex(s,n);return!tu(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=_e(c.presentationTimestamps,r,d=>d.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,f=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:f}},r,r,n)}async getNextPacket(e,n){const r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,n);const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}async getKeyPacket(e,n){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=qm(i,r),a=await this.fetchPacketForSampleIndex(s,n);return!tu(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=Ka(c.presentationTimestamps,d=>c.samples[d.sampleIndex].isKeyFrame&&d.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,f=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:f}},r,r,n)}async getNextKeyPacket(e,n){const r=this.packetToSampleIndex.get(e);if(r!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Gm(s,r);return this.fetchPacketForSampleIndex(a,n)}const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,u)=>c.isKeyFrame&&u>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return R(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}async fetchPacketForSampleIndex(e,n){if(e===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Xm(r,e);if(!i)return null;let s;if(n.metadataOnly)s=Ht;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(ie(u)&&(u=await u),!u)return null;if(s=me(u,i.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){const f=await ru(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<f.length&&(l=f[e])}l??=iu(this.internalTrack.encryptionInfo),l&&(s=await su(this.internalTrack,l,s,null))}}const a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new Ze(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,n,r){if(n===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[n];R(s);let a;if(r.metadataOnly)a=Ht;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(ie(l)&&(l=await l),!l)return null;if(a=me(l,s.byteSize),this.internalTrack.encryptionInfo){const f=s.encryption??iu(this.internalTrack.encryptionInfo);f&&(a=await su(this.internalTrack,f,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,u=new Ze(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+n,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:n}),u}async performFragmentedLookup(e,n,r,i,s){const a=this.internalTrack.demuxer;let o=null,c=null,u=-1;if(e){const{sampleIndex:g,correctSampleFound:w}=n(e);if(w)return this.fetchPacketInFragment(e,g,s);g!==-1&&(c=e,u=g)}const l=_e(this.internalTrack.fragmentLookupTable,r,g=>g.timestamp),f=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,d=_e(this.internalTrack.fragmentPositionCache,r,g=>g.startTimestamp),h=d!==-1?this.internalTrack.fragmentPositionCache[d]:null,p=Math.max(f?.moofOffset??0,h?.moofOffset??0)||null;let m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){const b=o.trackData.get(this.internalTrack.id);if(b&&b.startTimestamp>i)break}let g=a.reader.requestSliceRange(m,ai,Xi);if(ie(g)&&(g=await g),!g)break;const w=m,y=ar(g);if(!y)break;if(y.name==="moof"){o=await a.readFragment(w);const{sampleIndex:b,correctSampleFound:v}=n(o);if(v)return this.fetchPacketInFragment(o,b,s);b!==-1&&(c=o,u=b)}m=w+y.totalSize}if(f&&(!c||c.moofOffset<f.moofOffset)){const g=this.internalTrack.fragmentLookupTable[l-1];R(!g||g.timestamp<f.timestamp);const w=g?.timestamp??-1/0;return this.performFragmentedLookup(null,n,w,i,s)}return c?this.fetchPacketInFragment(c,u,s):null}}class Jl extends Zl{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=n&&yo(n.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=n&&wo(n.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!um(this.internalTrack.info.vp9CodecInfo))){const n=await this.getFirstPacket({}),r=n&&Sl(n.data);r&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??r,videoFullRangeFlag:r.videoFullRangeFlag,colourPrimaries:r.colourPrimaries,transferCharacteristics:r.transferCharacteristics,matrixCoefficients:r.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!fm(this.internalTrack.info.av1CodecInfo))){const n=await this.getFirstPacket({}),r=n&&vo(n.data);r&&(this.internalTrack.info.av1CodecInfo=r)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const n=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=n&&_l(n.data)}if(!Qa(this.internalTrack.info.colorSpace)){const n=Vl(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=n.primaries,this.internalTrack.info.colorSpace.transfer??=n.transfer,this.internalTrack.info.colorSpace.matrix??=n.matrix,this.internalTrack.info.colorSpace.fullRange??=n.fullRange}const e={codec:Po(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}}class eu extends Zl{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Fl(e.data)}return{codec:_o(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const Bo=(t,e)=>{if(t.presentationTimestamps){const n=_e(t.presentationTimestamps,e,r=>r.presentationTimestamp);return n===-1?-1:t.presentationTimestamps[n].sampleIndex}else{const n=_e(t.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(n===-1)return-1;const r=t.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},qm=(t,e)=>{if(!t.keySampleIndices)return Bo(t,e);if(t.presentationTimestamps){const n=_e(t.presentationTimestamps,e,r=>r.presentationTimestamp);if(n===-1)return-1;for(let r=n;r>=0;r--){const i=t.presentationTimestamps[r].sampleIndex;if(Oi(t.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{const n=Bo(t,e),r=_e(t.keySampleIndices,n,i=>i);return t.keySampleIndices[r]??-1}},Xm=(t,e)=>{const n=_e(t.sampleTimingEntries,e,w=>w.startIndex),r=t.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=e)return null;let s=r.startDecodeTimestamp+(e-r.startIndex)*r.delta;const a=_e(t.sampleCompositionTimeOffsets,e,w=>w.startIndex),o=t.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],u=_e(t.sampleToChunk,e,w=>w.startSampleIndex),l=t.sampleToChunk[u];R(l);const f=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),d=t.chunkOffsets[f],h=l.startSampleIndex+(f-l.startChunkIndex)*l.samplesPerChunk;let p=0,m=d;if(t.sampleSizes.length===1)m+=c*(e-h),p+=c*l.samplesPerChunk;else for(let w=h;w<h+l.samplesPerChunk;w++){const y=t.sampleSizes[w];w<e&&(m+=y),p+=y}let g=r.delta;if(t.presentationTimestamps){const w=t.presentationTimestampIndexMap[e];R(w!==void 0),w<t.presentationTimestamps.length-1&&(g=t.presentationTimestamps[w+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:c,chunkOffset:d,chunkSize:p,isKeyFrame:t.keySampleIndices?Oi(t.keySampleIndices,e,w=>w)!==-1:!0}},Gm=(t,e)=>{if(!t.keySampleIndices)return e+1;const n=_e(t.keySampleIndices,e,r=>r);return t.keySampleIndices[n+1]??-1},Ro=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(const n of t.samples)n.presentationTimestamp+=e;for(const n of t.presentationTimestamps)n.presentationTimestamp+=e},$m=t=>{const[e,n]=t,r=Math.atan2(n,e);return Number.isFinite(r)?r*(180/Math.PI):0},tu=t=>t.sampleSizes.length===0,nu=t=>t.currentFragmentState?t.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:t.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},ru=async(t,e,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{R(n.sampleSizes);for(let o=0;o<n.sampleCount;o++)r+=n.sampleSizes[o]}let i=t.requestSlice(n.offset,r);if(ie(i)&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;R(s!==null);const a=[];for(let o=0;o<n.sampleCount;o++){const c=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[o],u=new Uint8Array(16);s>0?u.set(me(i,s),0):u.set(e.defaultConstantIv,0);let l=null;if(c>s){const f=$e(i);l=[];for(let d=0;d<f;d++){const h=$e(i),p=ae(i);l.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:l})}return n.resolved=a,a},iu=t=>t.defaultConstantIv?{iv:t.defaultConstantIv,subsamples:null}:null,su=async(t,e,n,r)=>{R(t.encryptionInfo);const i=t.encryptionInfo;R(i.defaultKid!==null);const s=i.defaultKid;let a;const o=t.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!t.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const c=(async()=>{let u=t.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(f=>f.keyIds===null||f.keyIds.includes(s));for(let f=0;f<u.length-1;f++)for(let d=f+1;d<u.length;d++)$l(u[f],u[d])&&(u.splice(d,1),d--)}const l=await t.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof l=="string"&&l.length===32&&zh.test(l)||l instanceof Uint8Array&&l.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return l instanceof Uint8Array?l:Hh(l)})();t.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?Qm(a,i,e,n):Ym(a,i,e,n)},Qm=async(t,e,n,r)=>{const i=new Uint8Array(16);i.set(n.iv,0);const s=await crypto.subtle.importKey("raw",t,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!n.subsamples)return a(r);R(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=au(n.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const p of o)for(const m of p.perSubsample)c+=m.length;const u=new Uint8Array(c);let l=0;for(const p of o)for(const m of p.perSubsample)u.set(r.subarray(m.offset,m.offset+m.length),l),l+=m.length;const f=await a(u),d=new Uint8Array(r);let h=0;for(const p of o)for(const m of p.perSubsample)d.set(f.subarray(h,h+m.length),m.offset),h+=m.length;return d},Ym=(t,e,n,r)=>{const i=new Kl;i.init({key:t,iv:n.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(R(s!==null&&a!==null),!n.subsamples){const l=new Uint8Array(r),f=Math.floor(r.length/16);for(let d=0;d<f;d++){const h=d*16;i.in.set(r.subarray(h,h+16)),i.decrypt(),l.set(i.out,h)}return l}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),c=au(n.subsamples,s,a),u=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(const l of c){i.iv[0]=u.getUint32(0,!1),i.iv[1]=u.getUint32(4,!1),i.iv[2]=u.getUint32(8,!1),i.iv[3]=u.getUint32(12,!1);for(const f of l.perSubsample){const d=f.length/16;for(let h=0;h<d;h++){const p=f.offset+h*16;i.in.set(r.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},au=(t,e,n)=>{const r=[],i=e!==0||n!==0;let s=0;for(const a of t){s+=a.clearLen;const o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,u=s;for(;c>0&&!(c<16*e);){const l=16*e;o.push({offset:u,length:l}),u+=l,c-=l;const f=Math.min(16*n,c);u+=f,c-=f}s+=a.protectedLen}r.push({perSubsample:o})}return r};var re;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(re||(re={}));const Km=[re.EBML,re.Segment],Gi=[re.SeekHead,re.Info,re.Cluster,re.Tracks,re.Cues,re.Attachments,re.Chapters,re.Tags],ta=[...Km,...Gi],Fo=8,Qt=2,Hn=2*Fo,ou=t=>{if(t.remainingLength<1)return null;const e=de(t);if(t.skip(-1),e===0)return null;let n=1,r=128;for(;(e&r)===0;)n++,r>>=1;return t.remainingLength<n?null:n},$i=t=>{if(t.remainingLength<1)return null;const e=de(t);if(e===0)return null;let n=1,r=128;for(;(e&r)===0;)n++,r>>=1;if(t.remainingLength<n-1)return null;let i=e&r-1;for(let s=1;s<n;s++)i*=256,i+=de(t);return i},xe=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let n=0;for(let r=0;r<e;r++)n*=256,n+=de(t);return n},Zm=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let n=0n;for(let r=0;r<e;r++)n<<=8n,n+=BigInt(de(t));return n},Do=t=>{const e=ou(t);return e===null||t.remainingLength<e?null:xe(t,e)},cu=t=>{if(t.remainingLength<1)return null;if(de(t)===255)return;t.skip(-1);const n=$i(t);if(n===null)return null;if(n!==72057594037927940)return n},Vn=t=>{R(t.remainingLength>=Qt);const e=Do(t);if(e===null)return null;const n=cu(t);return n===null?null:{id:e,size:n}},fi=(t,e)=>{const n=me(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Qi=(t,e)=>{const n=me(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return Ft.decode(n.subarray(0,r))},No=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?zg(t):df(t)},Lo=async(t,e,n,r)=>{const i=new Set(n);let s=e;for(;r===null||s<r;){let a=t.requestSliceRange(s,Qt,Hn);if(ie(a)&&(a=await a),!a)break;const o=Vn(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};or(o.size),s=a.filePos+o.size}return{pos:r!==null&&r>s?r:s,found:!1}},lu=async(t,e,n,r)=>{const s=new Set(n);let a=e;for(;a<r;){let o=t.requestSliceRange(a,0,Math.min(65536,r-a));if(ie(o)&&(o=await o),!o||o.length<Fo)break;for(let c=0;c<o.length-Fo;c++){o.filePos=a;const u=Do(o);if(u!==null&&s.has(u))return a;a++}}return null},Dt={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS"};function or(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const Jm=t=>{let n=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){const r=[...new Set(t.codecStrings.filter(Boolean))];n+=`; codecs="${r.join(", ")}"`}return n};var Wn;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Wn||(Wn={}));var na;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(na||(na={}));var Yi;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Yi||(Yi={}));const Uo=[{id:re.SeekHead,flag:"seekHeadSeen"},{id:re.Info,flag:"infoSeen"},{id:re.Tracks,flag:"tracksSeen"},{id:re.Cues,flag:"cuesSeen"}],uu=10*2**20;class ep extends On{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(n=>n.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),n=await Promise.all(e.map(r=>r.getDecoderConfig().then(i=>i?.codec??null)));return Jm({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(r=>r.tracks.some(i=>i.info?.type==="audio")),codecStrings:n.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const n of this.segments)n.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(n),n.metadataTagsCollected=!0);let e={};for(const n of this.segments)e={...e,...n.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSliceRange(e,Qt,Hn);if(ie(n)&&(n=await n),!n)break;const r=Vn(n);if(!r)break;const i=r.id;let s=r.size;const a=n.filePos;if(i===re.EBML){or(s);let o=this.reader.requestSlice(a,s);if(ie(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===re.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===re.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Lo(this.reader,a,ta,this.reader.fileSize)).pos-a);const o=Rt(this.segments);o&&(o.elementEndPos=a+s)}or(s),e=a+s}})()}async readSegment(e,n){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:n===void 0?null:e+n,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(r,Qt,Hn);if(ie(o)&&(o=await o),!o)break;const c=r,u=Vn(o);if(!u||!Gi.includes(u.id)&&u.id!==re.Void){const p=await lu(this.reader,c,Gi,Math.min(this.currentSegment.elementEndPos??1/0,c+uu));if(p){r=p;continue}else break}const{id:l,size:f}=u,d=o.filePos,h=Uo.findIndex(p=>p.id===l);if(h!==-1){const p=Uo[h].flag;this.currentSegment[p]=!0,or(f);let m=this.reader.requestSlice(d,f);ie(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(l===re.Tags||l===re.Attachments){l===re.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,or(f);let p=this.reader.requestSlice(d,f);ie(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(l===re.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(f===void 0)break;r=d+f}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Uo.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,Qt,Hn);if(ie(u)&&(u=await u),!u)continue;const l=Vn(u);if(!l)continue;const{id:f,size:d}=l;if(f!==c.id)continue;or(d),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(u.filePos,d);ie(h)&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,u)=>c.time-u.time);for(let c=0;c<o.cuePoints.length-1;c++){const u=o.cuePoints[c],l=o.cuePoints[c+1];u.time===l.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,n){if(n.lastReadCluster?.elementStartPos===e)return n.lastReadCluster;let r=this.reader.requestSliceRange(e,Qt,Hn);ie(r)&&(r=await r),R(r);const i=e,s=Vn(r);R(s);const a=s.id;R(a===re.Cluster);let o=s.size;const c=r.filePos;o===void 0&&(o=(await Lo(this.reader,c,ta,n.elementEndPos)).pos-c);let u=this.reader.requestSlice(c,o);ie(u)&&(u=await u);const l={segment:n,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=l,u){const f=this.readContiguousElements(u,ta);l.elementEndPos=f}for(const[,f]of l.trackData){const d=f.track;R(f.blocks.length>0);let h=!1;for(let w=0;w<f.blocks.length;w++){const y=f.blocks[w];y.timestamp+=l.timestamp,h||=y.lacing!==Wn.None}f.presentationTimestamps=f.blocks.map((w,y)=>({timestamp:w.timestamp,blockIndex:y})).sort((w,y)=>w.timestamp-y.timestamp);for(let w=0;w<f.presentationTimestamps.length;w++){const y=f.presentationTimestamps[w],b=f.blocks[y.blockIndex];if(f.firstKeyFrameTimestamp===null&&b.isKeyFrame&&(f.firstKeyFrameTimestamp=b.timestamp),w<f.presentationTimestamps.length-1){const v=f.presentationTimestamps[w+1];b.duration=v.timestamp-b.timestamp}else b.duration===0&&d.defaultDuration!=null&&b.lacing===Wn.None&&(b.duration=d.defaultDuration)}h&&(this.expandLacedBlocks(f.blocks,d),f.presentationTimestamps=f.blocks.map((w,y)=>({timestamp:w.timestamp,blockIndex:y})).sort((w,y)=>w.timestamp-y.timestamp));const p=f.blocks[f.presentationTimestamps[0].blockIndex],m=f.blocks[Rt(f.presentationTimestamps).blockIndex];f.startTimestamp=p.timestamp,f.endTimestamp=m.timestamp+m.duration;const g=_e(d.clusterPositionCache,f.startTimestamp,w=>w.startTimestamp);(g===-1||d.clusterPositionCache[g].elementStartPos!==i)&&d.clusterPositionCache.splice(g+1,0,{elementStartPos:l.elementStartPos,startTimestamp:f.startTimestamp})}return n.lastReadCluster=l,l}getTrackDataInCluster(e,n){let r=e.trackData.get(n);if(!r){const i=e.segment.tracks.find(s=>s.id===n);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(n,r)}return r}expandLacedBlocks(e,n){for(let r=0;r<e.length;r++){const i=e[r];if(i.lacing===Wn.None)continue;i.decoded||(i.data=this.decodeBlockData(n,i.data),i.decoded=!0);const s=cn.tempFromBytes(i.data),a=[],o=de(s)+1;switch(i.lacing){case Wn.Xiph:{let u=0;for(let l=0;l<o-1;l++){let f=0;for(;s.bufferPos<s.length;){const d=de(s);if(f+=d,d<255){a.push(f),u+=f;break}}}a.push(s.length-(s.bufferPos+u))}break;case Wn.FixedSize:{const u=s.length-1,l=Math.floor(u/o);for(let f=0;f<o;f++)a.push(l)}break;case Wn.Ebml:{const u=$i(s);R(u!==null);let l=u;a.push(l);let f=l;for(let d=1;d<o-1;d++){const h=s.bufferPos,p=$i(s);R(p!==null);const m=p,w=(1<<(s.bufferPos-h)*7-1)-1,y=m-w;l+=y,a.push(l),f+=l}a.push(s.length-(s.bufferPos+f))}break;default:R(!1)}R(a.length===o),e.splice(r,1);const c=i.duration||o*(n.defaultDuration??0);for(let u=0;u<o;u++){const l=a[u],f=me(s,l),d=i.timestamp+c*u/o,h=c/o;e.splice(r+u,0,{timestamp:d,duration:h,isKeyFrame:i.isKeyFrame,data:f,lacing:Wn.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const n of e.seekEntries){if(!(n.id===re.Tags&&!e.tagsSeen)){if(!(n.id===re.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+n.segmentPosition,Qt,Hn);if(ie(r)&&(r=await r),!r)continue;const i=Vn(r);if(!i||i.id!==n.id)continue;const{size:s}=i;or(s),R(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(r.filePos,s);ie(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,n.id===re.Tags?e.tagsSeen=!0:n.id===re.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,n){for(;e.remainingLength>=Qt;){const r=e.filePos;if(!this.traverseElement(e,n))return r}return e.filePos}traverseElement(e,n){const r=Vn(e);if(!r||n&&n.includes(r.id))return!1;const{id:i,size:s}=r,a=e.filePos;switch(or(s),i){case re.DocType:this.isWebM=fi(e,s)==="webm";break;case re.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case re.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=xe(e,s)}break;case re.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=xe(e,s)}break;case re.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=xe(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case re.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=No(e,s)}break;case re.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Un,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==na.Block||o.data.algorithm!==Yi.HeaderStripping)&&(pe._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const l=this.currentTrack.info.displayWidth*this.currentTrack.info.height,f=this.currentTrack.info.displayHeight*this.currentTrack.info.width;l>0&&f>0&&(l>f?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*l/f):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*f/l))}if(this.currentTrack.codecId===Dt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Dt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===Dt.vp8)this.currentTrack.info.codec="vp8";else if(c===Dt.vp9)this.currentTrack.info.codec="vp9";else if(c===Dt.av1)this.currentTrack.info.codec="av1";else if(c===Dt.prores){const l=this.currentTrack.codecPrivate?Ft.decode(this.currentTrack.codecPrivate):"";So.includes(l)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=l)}const u=this.currentTrack;this.currentTrack.trackBacking=new tp(u),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Dt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Dt.mp3?this.currentTrack.info.codec="mp3":c===Dt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Js):c===Dt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Dt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Dt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Dt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Dt.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const u=this.currentTrack;this.currentTrack.trackBacking=new np(u),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case re.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=xe(e,s)}break;case re.TrackType:{if(!this.currentTrack)break;const o=xe(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...sl},alphaMode:!1,proresFormat:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case re.FlagEnabled:{if(!this.currentTrack)break;xe(e,s)||(this.currentTrack=null)}break;case re.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!xe(e,s)}break;case re.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!xe(e,s)}break;case re.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!xe(e,s)}break;case re.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!xe(e,s)}break;case re.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!xe(e,s)}break;case re.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!xe(e,s)}break;case re.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=fi(e,s)}break;case re.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=me(e,s)}break;case re.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=xe(e,s)}break;case re.Name:{if(!this.currentTrack)break;this.currentTrack.name=Qi(e,s)}break;case re.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=fi(e,s),fl(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Et)}break;case re.LanguageBCP47:{if(!this.currentTrack)break;const c=fi(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Et,this.currentTrack.hasLanguageBcp47=!0}break;case re.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case re.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=xe(e,s)}break;case re.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=xe(e,s)}break;case re.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=xe(e,s)}break;case re.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=xe(e,s)}break;case re.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=xe(e,s)}break;case re.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=xe(e,s)===1}break;case re.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case re.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=xe(e,s),c=Ln[o];this.currentTrack.info.colorSpace.matrix=c}break;case re.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=xe(e,s);this.currentTrack.info.colorSpace.fullRange=o===1||o===2?o===2:void 0}break;case re.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=xe(e,s),c=Nn[o];this.currentTrack.info.colorSpace.transfer=c}break;case re.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=xe(e,s),c=Dn[o];this.currentTrack.info.colorSpace.primaries=c}break;case re.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case re.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-No(e,s);try{this.currentTrack.info.rotation=ja(c)}catch{}}break;case re.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case re.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=No(e,s)}break;case re.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=xe(e,s)}break;case re.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=xe(e,s)}break;case re.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case re.CueTime:this.currentCueTime=xe(e,s);break;case re.CueTrackPositions:{if(this.currentCueTime===null)break;R(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case re.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=xe(e,s)}break;case re.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;R(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+xe(e,s)}break;case re.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=xe(e,s)}break;case re.SimpleBlock:{if(!this.currentCluster)break;const o=$i(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=tc(e),l=de(e),f=l>>1&3;let d=!!(l&128);c.track.info?.type==="audio"&&c.track.info.codec&&(d=!0);const h=me(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:u,duration:0,isKeyFrame:d,data:h,lacing:f,decoded:!p,postProcessed:!1,mainAdditional:null})}break;case re.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case re.Block:{if(!this.currentCluster)break;const o=$i(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=tc(e),f=de(e)>>1&3,d=me(e,s-(e.filePos-a)),h=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:u,duration:0,isKeyFrame:!0,data:d,lacing:f,decoded:!h,postProcessed:!1,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case re.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case re.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case re.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=me(e,s)}break;case re.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=xe(e,s)}break;case re.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=xe(e,s)}break;case re.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case re.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case re.Targets:this.readContiguousElements(e.slice(a,s));break;case re.TargetTypeValue:xe(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case re.TagTrackUID:case re.TagEditionUID:case re.TagChapterUID:case re.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case re.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case re.TagName:this.currentSimpleTagName=Qi(e,s);break;case re.TagString:{if(!this.currentSimpleTagName)break;const o=Qi(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case re.TagBinary:{if(!this.currentSimpleTagName)break;const o=me(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case re.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new Zh(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const c=this.currentAttachedFile.fileName;let u="unknown";if(c){const l=c.toLowerCase();l.startsWith("cover.")?u="coverFront":l.startsWith("back.")&&(u="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case re.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Zm(e,s)}break;case re.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Qi(e,s)}break;case re.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=fi(e,s)}break;case re.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=me(e,s)}break;case re.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Qi(e,s)}break;case re.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case re.ContentEncoding:this.currentDecodingInstruction={order:0,scope:na.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case re.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=xe(e,s)}break;case re.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=xe(e,s)}break;case re.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Yi.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case re.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=xe(e,s)}break;case re.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=me(e,s)}break;case re.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,n){R(e.decodingInstructions.length>0);let r=n;for(const i of e.decodingInstructions)switch(R(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Yi.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){const s=i.data.settings,a=new Uint8Array(s.length+r.length);a.set(s,0),a.set(r,s.length),r=a}break}break}return r}processTagValue(e,n){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=n,typeof n=="string")switch(e.toLowerCase()){case"title":r.title??=n;break;case"description":r.description??=n;break;case"artist":r.artist??=n;break;case"album":r.album??=n;break;case"album_artist":r.albumArtist??=n;break;case"genre":r.genre??=n;break;case"comment":r.comment??=n;break;case"lyrics":r.lyrics??=n;break;case"date":{const i=new Date(n);Number.isNaN(i.getTime())||(r.date??=i)}break;case"track_number":case"part_number":{const i=n.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(r.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{const i=n.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(r.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}break}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let n=null;for(const i of e.tracks){R(i.trackBacking);const s=await i.trackBacking.getFirstPacket({metadataOnly:!0});s&&(n=Math.min(n??1/0,s.timestamp))}let r=e.duration/e.timestampFactor;return r+=n??0,r}}class fu{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,n=this.internalTrack.trackBacking.getType();let r=0;for(const i of e.segments)for(const s of i.tracks)if(s.trackBacking.getType()===n&&r++,s===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,n=>n.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Hi(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,n){const r=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=_e(s.presentationTimestamps,r,u=>u.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,n)}async getNextPacket(e,n){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,i=>{if(i===r.cluster){const s=i.trackData.get(this.internalTrack.id);if(r.blockIndex+1<s.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async getKeyPacket(e,n){const r=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=Ka(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,n)}async getNextKeyPacket(e,n){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,i=>{if(i===r.cluster){const a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return R(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async fetchPacketInCluster(e,n,r){if(n===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[n];if(R(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(s.data.length>=8&&s.data[4]===105&&s.data[5]===99&&s.data[6]===112&&s.data[7]===102)){const d=new Uint8Array(s.data.length+8);Me(d).setUint32(0,d.length,!1),d[4]=105,d[5]=99,d[6]=112,d[7]=102,d.set(s.data,8),s.data=d}s.postProcessed=!0}const a=r.metadataOnly?Ht:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,u={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?Ht:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);const l=new Ze(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+n,s.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:n}),l}async performClusterLookup(e,n,r,i,s){const{demuxer:a,segment:o}=this.internalTrack;let c=null,u=null,l=-1;if(e){const{blockIndex:w,correctBlockFound:y}=n(e);if(y)return this.fetchPacketInCluster(e,w,s);w!==-1&&(u=e,l=w)}const f=_e(this.internalTrack.cuePoints,r,w=>w.time),d=f!==-1?this.internalTrack.cuePoints[f]:null,h=_e(this.internalTrack.clusterPositionCache,r,w=>w.startTimestamp),p=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null;let g;for(e?m===null||e.elementStartPos>=m?(g=e.elementEndPos,c=e):g=m:g=m??o.clusterSeekStartPos;o.elementEndPos===null||g<=o.elementEndPos-Qt;){if(c){const S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>i)break}let w=a.reader.requestSliceRange(g,Qt,Hn);if(ie(w)&&(w=await w),!w)break;const y=g,b=Vn(w);if(!b||!Gi.includes(b.id)&&b.id!==re.Void){const S=await lu(a.reader,y,Gi,Math.min(o.elementEndPos??1/0,y+uu));if(S){g=S;continue}else break}const v=b.id;let k=b.size;const A=w.filePos;if(v===re.Cluster){c=await a.readCluster(y,o),k=c.elementEndPos-A;const{blockIndex:S,correctBlockFound:P}=n(c);if(P)return this.fetchPacketInCluster(c,S,s);S!==-1&&(u=c,l=S)}k===void 0&&(R(v!==re.Cluster),k=(await Lo(a.reader,A,ta,o.elementEndPos)).pos-A);const T=A+k;if(o.elementEndPos===null){let S=a.reader.requestSliceRange(T,Qt,Hn);if(ie(S)&&(S=await S),!S)break;if(Do(S)===re.Segment){o.elementEndPos=T;break}}g=T}if(d&&(!u||u.elementStartPos<d.clusterPosition)){const w=this.internalTrack.cuePoints[f-1];R(!w||w.time<d.time);const y=w?.time??-1/0;return this.performClusterLookup(null,n,y,i,s)}return u?this.fetchPacketInCluster(u,l,s):null}}class tp extends fu{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const r={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?yo(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?wo(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Sl(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?vo(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?_l(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Qa(this.internalTrack.info.colorSpace)){const s=Vl(r);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}const i={codec:Po(r),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})():null}}class np extends fu{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Fl(e.data)}return{codec:_o({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const Oo=async(t,e,n,r=null)=>{let s=e;for(;n===null||s<n;){const a=n!==null?Math.min(65536,n-s):65536;let o=t.requestSliceRange(s,Br,a);if(ie(o)&&(o=await o),!o||o.length<Br)break;for(;o.remainingLength>=Br;){const c=o.filePos,u=ae(o),l=t.fileSize!==null?t.fileSize-s:null,f=Eo(u,l);if(f.header&&(!r||f.header.sampleRate===r.sampleRate&&f.header.mpegVersionId===r.mpegVersionId&&f.header.layer===r.layer&&qi(f.header.channel)===qi(r.channel)))return{header:f.header,startPos:s};o.filePos=c+f.bytesAdvanced,s=o.filePos}}return null};class rp extends On{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new Ls,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new ip(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Yt);if(ie(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=Xn(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Oo(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const n=e.header;this.lastLoadedPos=e.startPos+n.totalSize-1;const r=Xl(n.mpegVersionId,n.channel);let i=this.reader.requestSlice(e.startPos+r,4);if(ie(i)&&(i=await i),i){const o=ae(i);if(o===jl||o===ql){if(this.xingFrameHeader||(this.xingFrameHeader=n,this.xingFrameHeaderPos=e.startPos),!this.xingData){let u=this.reader.requestSlice(e.startPos+r+4,12);if(ie(u)&&(u=await u),u){const l=me(u,12),f=Me(l),d=f.getUint32(0,!1);this.xingData={frameCount:d&ea.FrameCount?f.getUint32(4,!1):null,fileSize:d&ea.FileSize?f.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=n,this.firstFrameHeaderPos=e.startPos);const s=n.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:n.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=n.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let n=0,r=!1;for(;;){let i=this.reader.requestSlice(n,Yt);if(ie(i)&&(i=await i),!i)break;const s=Xn(i);if(!s)break;r=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(ie(a)&&(a=await a),!a)break;ca(a,s,this.metadataTags),n=i.filePos+s.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=oa){let i=this.reader.requestSlice(this.reader.fileSize-oa,oa);ie(i)&&(i=await i),R(i),je(i,3)==="TAG"&&Hg(i,this.metadataTags)}return this.metadataTags}finally{e()}}}class ip{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return R(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(R(e.firstFrameHeader!==null),R(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const n=zm(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),r=(e.reader.fileSize-e.firstFrameHeaderPos)/n;return Math.round(r)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Et}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return R(this.demuxer.firstFrameHeader),qi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return R(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Un}}async getDecoderConfig(){return R(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:qi(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,n){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=Ht;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(ie(s)&&(s=await s),!s)return null;i=me(s,r.dataSize)}return new Ze(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=Oi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,n)}finally{r()}}async getPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,n);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,n);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const du=1399285583,sp=79764919,hu=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let n=0;n<8;n++)e=e&2147483648?e<<1^sp:e<<1;hu[t]=e>>>0&4294967295}const ap=t=>{const e=Me(t),n=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let i=0;i<t.length;i++){const s=t[i];r=(r<<8^hu[r>>>24^s])>>>0}return e.setUint32(22,n,!0),r},op=(t,e,n)=>{let r=0,i=null;if(t.length>0)if(e.codec==="vorbis"){R(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<qh(s-1))-1<<1,c=(t[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=n;const l=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[l],l===1){const f=(o|1)+1,d=t[0]&f?1:0;u=e.vorbisInfo.blocksizes[d]}r=u!==null?u+i>>2:0}else e.codec==="opus"&&(r=mm(t).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},cp=t=>{let e="audio/ogg";if(t.codecStrings){const n=[...new Set(t.codecStrings)];e+=`; codecs="${n.join(", ")}"`}return e};const Fr=27,di=282,lp=di+65025,Ki=t=>{const e=t.filePos;if(bi(t)!==du)return null;t.skip(1);const r=de(t),i=Og(t),s=bi(t),a=bi(t),o=bi(t),c=de(t),u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=de(t);const l=27+c,f=u.reduce((h,p)=>h+p,0),d=l+f;return{headerStartPos:e,totalSize:d,dataStartPos:e+l,dataSize:f,headerType:r,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:u}},up=(t,e)=>{for(;t.filePos<e-3;){const n=bi(t),r=n&255,i=n>>>8&255,s=n>>>16&255,a=n>>>24&255,o=79;if(!(r!==o&&i!==o&&s!==o&&a!==o)){if(t.skip(-4),n===du)return!0;t.skip(1)}}return!1};class fp extends On{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSliceRange(e,Fr,di);if(ie(n)&&(n=await n),!n)break;const r=Ki(n);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const n of this.bitstreams){const r=await this.readPacket(n.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,n):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,n),n.codecInfo.codec!==null&&this.trackBackings.push(new dp(n,this)))}})()}async readVorbisMetadata(e,n){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||(r=await this.findNextPacketStart(i),!r))return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;const a=[],o=f=>{for(;a.push(Math.min(255,f)),!(f<255);)f-=255};o(e.data.length),o(i.data.length);const c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),n.codecInfo.codec="vorbis",n.description=c,n.lastMetadataPacket=s;const u=Me(e.data);n.numberOfChannels=u.getUint8(11),n.sampleRate=u.getUint32(12,!0);const l=u.getUint8(28);n.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:pm(s.data).modeBlockflags},Ao(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,n){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;n.codecInfo.codec="opus",n.description=e.data,n.lastMetadataPacket=i;const s=dm(e.data);n.numberOfChannels=s.outputChannelCount,n.sampleRate=Js,n.codecInfo.opusInfo={preSkip:s.preSkip},Ao(i.data.subarray(8),this.metadataTags)}async readPacket(e,n){R(n<e.lacingValues.length);let r=0;for(let f=0;f<n;f++)r+=e.lacingValues[f];let i=e,s=r,a=n;const o=[];e:for(;;){let f=this.reader.requestSlice(i.dataStartPos,i.dataSize);ie(f)&&(f=await f),R(f);const d=me(f,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(d.subarray(r,s));break}const p=i.lacingValues[a];if(s+=p,p<255){o.push(d.subarray(r,s));break e}a++}let h=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(h,Fr,di);if(ie(p)&&(p=await p),!p)return null;const m=Ki(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;h=i.headerStartPos+i.totalSize}r=0,s=0,a=0}const c=o.reduce((f,d)=>f+d.length,0);if(c===0)return null;const u=new Uint8Array(c);let l=0;for(let f=0;f<o.length;f++){const d=o[f];u.set(d,l),l+=d.length}return{data:u,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(r,Fr,di);if(ie(i)&&(i=await i),!i)return null;const s=Ki(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};r=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(n=>n.getDecoderConfig().then(r=>r?.codec??null)));return cp({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class dp{constructor(e,n){this.bitstream=e,this.demuxer=n,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Ls,this.internalSampleRate=e.codecInfo.codec==="opus"?Js:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(n=>n.bitstream===this.bitstream);return R(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return R(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Et}getDisposition(){return{...Un,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(R(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,n,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:s}=op(e.data,this.bitstream.codecInfo,n.vorbisLastBlocksize),a=new Ze(r.metadataOnly?Ht:e.data,"key",Math.max(0,n.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:n.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:n.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){R(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(R(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const i=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,n){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const s=r.timestampInSamples+r.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:r.vorbisBlockSize},n)}async getPacket(e,n){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,n);const r=Hi(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(n);if(r<0)return null;R(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<a;){const y=s.headerStartPos,b=Math.floor((y+a)/2);let v=b;for(;;){const k=Math.min(v+lp,a-Fr);let A=this.demuxer.reader.requestSlice(v,k-v);if(ie(A)&&(A=await A),R(A),!up(A,k)){a=b+Fr;continue e}let S=this.demuxer.reader.requestSliceRange(A.filePos,Fr,di);ie(S)&&(S=await S),R(S);const P=Ki(S);R(P);let M=!1;if(P.serialNumber===this.bitstream.serialNumber)M=!0;else{let N=this.demuxer.reader.requestSlice(P.headerStartPos,P.totalSize);ie(N)&&(N=await N),R(N);const O=me(N,P.totalSize);M=ap(O)===P.checksum}if(!M){v=P.headerStartPos+4;continue}if(M&&P.serialNumber!==this.bitstream.serialNumber){v=P.headerStartPos+P.totalSize;continue}if(P.granulePosition===-1){v=P.headerStartPos+P.totalSize;continue}this.granulePositionToTimestampInSamples(P.granulePosition)>r?a=P.headerStartPos:(s=P,o.push(P));continue e}}let c=i.startPage;for(const y of o){if(y.granulePosition===s.granulePosition)break;(!c||y.headerStartPos>c.headerStartPos)&&(c=y)}let u=c;const l=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){const y=u.headerStartPos+u.totalSize;let b=this.demuxer.reader.requestSliceRange(y,Fr,di);ie(b)&&(b=await b),R(b);const v=Ki(b);R(v),u=v,u.serialNumber===this.bitstream.serialNumber&&l.push(u)}R(u.granulePosition!==-1);let f=null,d,h,p=u,m=0;if(u.headerStartPos===i.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),h=!0,f=0;else{d=0,h=!1;for(let v=u.lacingValues.length-1;v>=0;v--)if(u.lacingValues[v]<255){f=v+1;break}if(f===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=f-1;const y={data:Ht,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(y)){const v=pu(l,u,f);R(v);const k=mu(l,v.page,v.segmentIndex);k&&(u=k.page,f=k.segmentIndex)}else for(;;){const v=pu(l,u,f);if(!v)break;const k=mu(l,v.page,v.segmentIndex);if(!k)break;if(u=k.page,f=k.segmentIndex,v.page.headerStartPos!==p.headerStartPos){p=v.page,m=v.segmentIndex;break}}}let g=null,w=null;for(;u!==null;){R(f!==null);const y=await this.demuxer.readPacket(u,f);if(!y)break;if(!(u.headerStartPos===i.startPage.headerStartPos&&f<i.startSegmentIndex)){let k=this.createEncodedPacketFromOggPacket(y,{timestampInSamples:d,vorbisLastBlocksize:w?.vorbisBlockSize??null},n);R(k);let A=this.encodedPacketToMetadata.get(k);if(R(A),!h&&y.endPage.headerStartPos===p.headerStartPos&&y.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(u.granulePosition),h=!0,k=this.createEncodedPacketFromOggPacket(y,{timestampInSamples:d-A.durationInSamples,vorbisLastBlocksize:w?.vorbisBlockSize??null},n),R(k),A=this.encodedPacketToMetadata.get(k),R(A)):d+=A.durationInSamples,g=k,w=A,h&&(Math.max(d,0)>r||Math.max(A.timestampInSamples,0)===r))break}const v=await this.demuxer.findNextPacketStart(y);if(!v)break;u=v.startPage,f=v.startSegmentIndex}return g}async getPacketSequential(e,n){const r=await this.sequentialScanMutex.acquire();try{const i=Hi(e*this.internalSampleRate);e=i/this.internalSampleRate;const s=_e(this.sequentialScanCache,i,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},n)}else a=await this.getFirstPacket(n);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,n);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const u=this.encodedPacketToMetadata.get(a);R(u),this.sequentialScanCache.length>0&&R(Rt(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const mu=(t,e,n)=>{let r=e,i=n;e:for(;;){for(i--,i;i>=0;i--)if(r.lacingValues[i]<255){i++;break e}if(R(i===-1),!(r.headerType&1)){i=0;break}const a=cl(t,o=>o.headerStartPos<r.headerStartPos);if(!a)return null;r=a,i=r.lacingValues.length}if(R(i!==-1),i===r.lacingValues.length){const s=t[t.indexOf(r)+1];R(s),r=s,i=0}return{page:r,segmentIndex:i}},pu=(t,e,n)=>{if(n>0)return{page:e,segmentIndex:n-1};const r=cl(t,i=>i.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Ct;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(Ct||(Ct={}));class hp extends On{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);ie(e)&&(e=await e),R(e);const n=je(e,4),r=n!=="RIFX",i=n==="RF64",s=cr(e,r);let a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(je(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,u=null,l=e.filePos;for(;a===null||l<a;){let d=this.reader.requestSlice(l,8);if(ie(d)&&(d=await d),!d)break;const h=je(d,4),p=cr(d,r),m=d.filePos;if(i&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,p,r);else if(h==="data"){if(u??=p,this.dataStart=d.filePos,this.dataSize=Math.min(u,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let g=this.reader.requestSlice(m,p);if(ie(g)&&(g=await g),!g)break;const w=ff(g,r);u=ff(g,r),a=Math.min(w+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,p,r):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,p);l=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const f=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/f)*f,this.trackBackings.push(new mp(this))})()}async parseFmtChunk(e,n,r){let i=this.reader.requestSlice(e,n);if(ie(i)&&(i=await i),!i)return;let s=ss(i,r);const a=ss(i,r),o=cr(i,r);i.skip(4);const c=ss(i,r);let u;if(n===14?u=8:u=ss(i,r),n>=18&&s!==357){const l=ss(i,r),f=n-18;if(Math.min(f,l)>=22&&s===Ct.EXTENSIBLE){i.skip(6);const h=me(i,16);s=h[0]|h[1]<<8}}if((s===Ct.MULAW||s===Ct.ALAW)&&(u=8),s!==Ct.PCM&&s!==Ct.IEEE_FLOAT&&s!==Ct.ALAW&&s!==Ct.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===Ct.PCM&&![8,16,24,32].includes(u))throw new Error(`Unsupported WAVE PCM bit depth (${u}). Only 8, 16, 24, and 32 bits are supported.`);if(s===Ct.IEEE_FLOAT&&![32,64].includes(u))throw new Error(`Unsupported WAVE float bit depth (${u}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,n,r){let i=this.reader.requestSlice(e,n);if(ie(i)&&(i=await i),!i)return;const s=je(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+n-8;){i.filePos=a;const o=je(i,4),c=cr(i,r),u=me(i,c);let l=0;for(let d=0;d<u.length&&u[d]!==0;d++)l++;const f=String.fromCharCode(...u.subarray(0,l));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=f,o){case"INAM":case"TITL":this.metadataTags.title??=f;break;case"TIT3":this.metadataTags.description??=f;break;case"IART":this.metadataTags.artist??=f;break;case"IPRD":this.metadataTags.album??=f;break;case"IPRT":case"ITRK":case"TRCK":{const d=f.split("/"),h=Number.parseInt(d[0],10),p=d[1]&&Number.parseInt(d[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{const d=new Date(f);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"YEAR":{const d=Number.parseInt(f,10);Number.isInteger(d)&&d>0&&(this.metadataTags.date??=new Date(d,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=f;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=f;break}a+=8+c+(c&1)}}async parseId3Chunk(e,n){let r=this.reader.requestSlice(e,n);if(ie(r)&&(r=await r),!r)return;const i=Xn(r);if(i){const s=n-Yt;if(i.size=Math.min(i.size,s),i.size>0){const a=r.slice(e+Yt,i.size);ca(a,i,this.metadataTags)}}}getCodec(){if(R(this.audioInfo),this.audioInfo.format===Ct.MULAW)return"ulaw";if(this.audioInfo.format===Ct.ALAW)return"alaw";if(this.audioInfo.format===Ct.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===Ct.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}R(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const hi=2048;class mp{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(R(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return R(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Et}getDisposition(){return{...Un}}async getPacketAtIndex(e,n){R(e>=0),R(this.demuxer.audioInfo);const r=e*hi*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(hi*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(ie(c)&&(c=await c),!c)return null}let s;if(n.metadataOnly)s=Ht;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);ie(c)&&(c=await c),R(c),s=me(c,i)}const a=e*hi/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Ze(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,n){R(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hi,(this.demuxer.dataSize-1)/(hi*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const i=await this.getPacketAtIndex(r,n);if(i)return i;if(r===0)return null;R(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,n);for(;s;){const a=await this.getNextPacket(s,n);if(!a)break;s=a}return s}getNextPacket(e,n){R(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hi);return this.getPacketAtIndex(r+1,n)}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const zo=7,mi=9,Zi=t=>{const e=t.filePos,n=me(t,9),r=new Ee(n);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const a=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);const u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const f=r.readBits(2)+1;if(f!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let d=null;return a===1?t.filePos-=2:d=r.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:f,crcCheck:d,startPos:e}};const ra=1024;class pp extends On{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Ls,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();R(this.firstFrameHeader),this.trackBackings=[new gp(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Yt);if(ie(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=Xn(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,zo,mi);if(ie(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const n=Zi(e);if(!n){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&n.startPos+n.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=n);const r=Wi[n.samplingFrequencyIndex];R(r!==void 0);const i=ra/r,s={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ra,this.lastLoadedPos=n.startPos+n.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let n=0;for(;;){let r=this.reader.requestSlice(n,Yt);if(ie(r)&&(r=await r),!r)break;const i=Xn(r);if(!i)break;let s=this.reader.requestSlice(r.filePos,i.size);if(ie(s)&&(s=await s),!s)break;ca(s,i,this.metadataTags),n=r.filePos+i.size}return this.metadataTags}finally{e()}}}class gp{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ra}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Et}getCodec(){return"aac"}getInternalCodecId(){return R(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){R(this.demuxer.firstFrameHeader);const e=ho[this.demuxer.firstFrameHeader.channelConfiguration];return R(e!==void 0),e}getSampleRate(){R(this.demuxer.firstFrameHeader);const e=Wi[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return R(e!==void 0),e}getDisposition(){return{...Un}}async getDecoderConfig(){return R(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,n){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=Ht;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(ie(s)&&(s=await s),!s)return null;i=me(s,r.dataSize)}return new Ze(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=Oi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,n)}finally{r()}}async getPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,n);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,n);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const yp=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,bp=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},wp=t=>{let e=0;const n=new Ee(me(t,1));for(;n.readBits(1)===1;)e++;if(e===0)return n.readBits(7);const r=[],i=e-1,s=new Ee(me(t,i)),a=8-e-1;for(let c=0;c<a;c++)r.unshift(n.readBits(1));for(let c=0;c<i;c++)for(let u=0;u<8;u++){const l=s.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c|u<<l,0)},vp=(t,e)=>{if(e==="uncommon-u16")return $e(t)+1;if(e==="uncommon-u8")return de(t)+1;if(typeof e=="number")return e;Us(e),R(!1)},kp=(t,e)=>e==="uncommon-u16"?$e(t):e==="uncommon-u16-10"?$e(t)*10:e==="uncommon-u8"?de(t):typeof e=="number"?e:null,Ap=t=>{let n=0;for(const r of t){n^=r;for(let i=0;i<8;i++)(n&128)!==0?n=n<<1^7:n<<=1,n&=255}return n};class xp extends On{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Ls,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),R(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSlice(e,Yt);if(ie(n)&&(n=await n),!n){this.lastSampleLoaded=!0;return}const r=Xn(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);ie(i)&&(i=await i),R(i),ca(i,r,this.metadataTags),e=n.filePos+r.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let n=this.reader.requestSlice(e,4);if(ie(n)&&(n=await n),e+=4,n===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);R(n);const r=de(n),i=qn(n),s=(r&128)!==0;switch(r&127){case ii.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(ie(o)&&(o=await o),R(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=me(o,34),u=new Ee(c),l=u.readBits(16),f=u.readBits(16),d=u.readBits(24),h=u.readBits(24),p=u.readBits(20),m=u.readBits(3)+1;u.readBits(5);const g=u.readBits(36);u.skipBits(128);const w=new Uint8Array(42);w.set(new Uint8Array([102,76,97,67]),0),w.set(new Uint8Array([128,0,0,34]),4),w.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:g,minimumBlockSize:l,maximumBlockSize:f,minimumFrameSize:d,maximumFrameSize:h,description:w},this.trackBacking=new Tp(this);break}case ii.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);ie(o)&&(o=await o),R(o),Ao(me(o,i),this.metadataTags);break}case ii.PICTURE:{let o=this.reader.requestSlice(e,i);ie(o)&&(o=await o),R(o);const c=ae(o),u=ae(o),l=Ft.decode(me(o,u)),f=ae(o),d=Ft.decode(me(o,f));o.skip(16);const h=ae(o),p=me(o,h);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:l,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:d});break}}if(e+=i,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:n}){R(this.audioInfo);const r=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,u=(this.audioInfo.maximumFrameSize||a)+i,l=await this.reader.requestSliceRange(e,i,u);if(!l)return null;const f=this.readFlacFrameHeader({slice:l,isFirstPacket:n});if(!f)return null;for(l.filePos=e+o;;){if(l.filePos>l.end-r)return{num:f.num,blockSize:f.blockSize,sampleRate:f.sampleRate,size:l.end-e,isLastFrame:!0};if(de(l)===255){const h=l.filePos,p=de(l),m=this.blockingBit===1?249:248;if(p!==m){l.filePos=h;continue}l.skip(-2);const g=l.filePos-e,w=this.readFlacFrameHeader({slice:l,isFirstPacket:!1});if(!w){l.filePos=h;continue}if(this.blockingBit===0){if(w.num-f.num!==1){l.filePos=h;continue}}else if(w.num-f.num!==f.blockSize){l.filePos=h;continue}return{num:f.num,blockSize:f.blockSize,sampleRate:f.sampleRate,size:g,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:n}){const r=e.filePos,i=me(e,4),s=new Ee(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){R(n);const g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(R(!n),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(R(!n),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=yp(s.readBits(4));if(!o)return null;R(this.audioInfo);const c=bp(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const l=wp(e),f=vp(e,o),d=kp(e,c);if(d===null||d!==this.audioInfo.sampleRate)return null;const h=e.filePos-r,p=de(e);e.skip(-h),e.skip(-1);const m=Ap(me(e,h));return p!==m?null:{num:l,blockSize:f,sampleRate:d}}async advanceReader(){await this.readMetadata(),R(this.lastLoadedPos!==null),R(this.audioInfo);const e=this.lastLoadedPos,n=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!n){this.lastSampleLoaded=!0;return}const r=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:n.blockSize,byteOffset:e,byteSize:n.size};if(this.lastLoadedPos=this.lastLoadedPos+n.size,this.loadedSamples.push(s),n.isLastFrame){this.lastSampleLoaded=!0;return}}}class Tp{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Et}getTimeResolution(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return R(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Un}}async getDecoderConfig(){return R(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,n){if(R(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=_e(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,n);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,n)}}finally{r()}}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,n)}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}async getPacketAtIndex(e,n){const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=Ht;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(ie(o)&&(o=await o),!o)return null;i=me(o,r.byteSize)}R(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,a=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Ze(i,"key",s,a,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const rn=9e4,Ho=2**33,Vt=188,Sp=t=>{let e="video/MP2T";const n=[...new Set(t.filter(Boolean))];return n.length>0&&(e+=`; codecs="${n.join(", ")}"`),e};const gu="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",yu=5,Pp=1212435798,_p=1212436562,Ep=1146376960,Cp=new Set([133,134,162]),bu=new Set;class Ip extends On{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{const e=Vt+16+1;let n=this.reader.requestSlice(0,e);ie(n)&&(n=await n),R(n);const r=me(n,e);if(r[0]===71&&r[Vt]===71)this.packetOffset=0,this.packetStride=Vt;else if(r[0]===71&&r[Vt+16]===71)this.packetOffset=0,this.packetStride=Vt+16;else if(r[4]===71&&r[4+Vt+4]===71)this.packetOffset=4,this.packetStride=Vt+4;else throw new Error("Unreachable.");const i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===u.pid)){s+=this.packetStride;continue}const l=await this.readSection(s,!0,!c);if(!l)break;const f=3,d=32;let h=!1;if(!c&&l.pid!==0&&!(l.payload[0]===0&&l.payload[1]===0&&l.payload[2]===1)){const g=new Ee(l.payload),w=g.readAlignedByte();g.skipBits(8*w),h=g.readBits(8)===2}if(l.pid===0&&!o){const m=new Ee(l.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);const w=m.readBits(10);for(m.skipBits(40);8*(w+f)-m.pos>d;){const y=m.readBits(16);m.skipBits(3);const b=m.readBits(13);if(y!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=b}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((l.pid===a||h)&&!c){const m=new Ee(l.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);const w=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const y=m.readBits(10),b=m.pos+8*y;let v=!1;for(;m.pos<b;){const k=m.readBits(8),A=m.readBits(8),T=m.pos+8*A;if(k===yu&&A>=4){const S=m.readBits(32);v||=S===Pp||S===_p}m.pos=T}for(m.pos=b;8*(w+f)-m.pos>d;){const k=m.readBits(8);m.skipBits(3);const A=m.readBits(13);m.skipBits(6);const T=m.readBits(10),S=m.pos+8*T;let P=!1,M=!1,B=!1;for(;m.pos<S;){const q=m.readBits(8),H=m.readBits(8),G=m.pos+8*H;if(q===106)P=!0;else if(q===122||q===204)M=!0;else if(q===123)B=!0;else if(q===yu&&H>=4){const Y=m.readBits(32);B||=(Y&4294967040)===Ep}m.pos=G}let N=null;const O=v&&Cp.has(k)?130:k;switch(O){case 27:case 36:N={type:"video",codec:k===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let q;O===3||O===4?q="mp3":O===15?q="aac":O===129?q="ac3":O===135?q="eac3":q="dts",N={type:"audio",codec:q,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:M?N={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:P?N={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:B&&(N={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:bu.has(k)||(pe._warn(`Note: MPEG-TS streams with stream_type 0x${k.toString(16)} are not currently supported.`),bu.add(k))}N&&this.elementaryStreams.push({demuxer:this,pid:A,streamType:k,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:N,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(g=>g.pid===l.pid);e:if(m&&!m.initialized){const g=pi(this,l,!0);if(!g)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=l,m.canBeTrustedWithKeyPackets=l.randomAccessIndicator===1,this.input._initInput){const b=(await this.input._initInput._getDemuxer()).elementaryStreams.find(v=>v.pid===l.pid&&v.info.codec===m.info.codec);if(b){m.info=b.info,m.initialized=!0;break e}}const w=new Ji(m,g);if(m.info.type==="video"){for(;;){const y=w;if(y.suppliedPacket=null,await w.markNextPacket(),m.info.codec==="avc"){if(!w.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=yo(w.suppliedPacket.data),!m.info.avcCodecInfo)continue;const b=m.info.avcCodecInfo.sequenceParameterSets[0];R(b);const v=Gs(b);m.info.width=v.displayWidth,m.info.height=v.displayHeight;const k=v.pixelAspectRatio.num,A=v.pixelAspectRatio.den;k>0&&A>0&&(k>A?(m.info.squarePixelWidth=Math.round(m.info.width*k/A),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*A/k))),m.info.colorSpace={primaries:Dn[v.colourPrimaries],transfer:Nn[v.transferCharacteristics],matrix:Ln[v.matrixCoefficients],fullRange:!!v.fullRangeFlag},m.info.reorderSize=v.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!w.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=wo(w.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const v=m.info.hevcCodecInfo.arrays.find(A=>A.nalUnitType===Ge.SPS_NUT).nalUnits[0];R(v);const k=bo(v);m.info.width=k.displayWidth,m.info.height=k.displayHeight,k.pixelAspectRatio.num>k.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*k.pixelAspectRatio.num/k.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*k.pixelAspectRatio.den/k.pixelAspectRatio.num)),m.info.colorSpace={primaries:Dn[k.colourPrimaries],transfer:Nn[k.transferCharacteristics],matrix:Ln[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},m.info.reorderSize=k.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Po({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await w.markNextPacket(),!w.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const y=cn.tempFromBytes(w.suppliedPacket.data),b=Zi(y);if(!b)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:b.objectType},m.info.numberOfChannels=ho[b.channelConfiguration],m.info.sampleRate=Wi[b.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const y=ae(cn.tempFromBytes(w.suppliedPacket.data)),b=Eo(y,w.suppliedPacket.data.byteLength);if(!b.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=qi(b.header.channel),m.info.sampleRate=b.header.sampleRate}else if(m.info.codec==="ac3"){const y=gm(w.suppliedPacket.data);if(!y)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(y.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=xo[y.acmod]+y.lfeon,m.info.sampleRate=Ws[y.fscod]}else if(m.info.codec==="eac3"){const y=wm(w.suppliedPacket.data);if(!y)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const b=Cl(y);if(b===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Il(y),m.info.sampleRate=b}else if(m.info.codec==="dts"){const y=Rl(w.suppliedPacket.data);if(!y)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=y.numberOfChannels,m.info.sampleRate=y.sampleRate,y.core&&(m.info.dtsFormat=y.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:_o({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo,dtsFormat:m.info.dtsFormat}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const u of this.elementaryStreams)u.initialized&&(u.info.type==="video"?this.trackBackingEntries.push(new Mp(u)):this.trackBackingEntries.push(new Bp(u)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(n=>n.getDecoderConfig().then(r=>r?.codec??null)));return Sp(e)}async readSection(e,n,r=!1){let i=e,s=e;const a=[];let o=0,c=null,u=!0,l=0;for(;;){const d=await this.readPacket(s);if(s+=this.packetStride,!d)break;if(c){if(d.pid!==c.pid){if(r)break;continue}if(d.payloadUnitStartIndicator===1)break}else{if(d.payloadUnitStartIndicator===0)break;c=d}const h=!!(d.adaptationFieldControl&2),p=!!(d.adaptationFieldControl&1);let m=0;if(h&&(m=1+d.body[0],d===c&&m>1&&(l=d.body[1]>>6&1)),p&&(m===0?(a.push(d.body),o+=d.body.byteLength):(a.push(d.body.subarray(m)),o+=d.body.byteLength-m)),i=s,!n&&o>=64){u=!1;break}if(Oi(this.sectionEndPositions,i,w=>w)!==-1){u=!1;break}}if(u){const d=_e(this.sectionEndPositions,i,h=>h);this.sectionEndPositions.splice(d+1,0,i)}if(!c)return null;let f;if(a.length===1)f=a[0];else{const d=a.reduce((p,m)=>p+m.length,0);f=new Uint8Array(d);let h=0;for(const p of a)f.set(p,h),h+=p.length}return{startPos:e,endPos:n?i:null,pid:c.pid,payload:f,randomAccessIndicator:l}}async readPacketHeader(e){let n=this.reader.requestSlice(e,4);if(ie(n)&&(n=await n),!n)return null;if(de(n)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=$e(n),s=i>>14&1,a=i&8191,c=de(n)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let n=this.reader.requestSlice(e,Vt);if(ie(n)&&(n=await n),!n)return null;const r=me(n,Vt);if(r[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=(r[1]<<8)+r[2],a=s>>14&1,o=s&8191,u=r[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:u,body:r.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const i=60*rn;this.timestampWrapInfo={reference:e-i,offset:e>=Ho-i?-Ho:Ho}}const{reference:n,offset:r}=this.timestampWrapInfo;return r<0&&e>=n||r>0&&e<n?e+r:e}}const Dr=(t,e,n)=>{if(e.payload.byteLength<3)return null;const r=new Ee(e.payload);if(r.readBits(24)!==1)return null;const s=r.readBits(8);if(r.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;r.skipBits(8);const a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=t.normalizeTimestamp(o);else if(n)throw new Error(gu);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}},pi=(t,e,n)=>{R(e.endPos!==null);const r=Dr(t,e,n);if(!r)return null;const i=new Ee(e.payload);i.skipBits(32);const s=i.readBits(16),a=6;i.skipBits(16);const o=i.readBits(8),c=i.pos+8*o;i.pos=c;const u=c/8;R(Number.isInteger(u));const l=e.payload.subarray(u,s>0?a+s:e.payload.byteLength);return{...r,data:l}};class Na{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,n=this.elementaryStream.info.type;let r=0;for(const i of e.trackBackingEntries)if(i.getType()===n&&r++,R(i instanceof Na),i.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Et}getDisposition(){return{...Un,primary:!1}}getTimeResolution(){return rn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,n,r){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new Ze(r.metadataOnly?Ht:e.data,i,e.pts/rn,Math.max(n/rn,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const n=this.elementaryStream.firstSection;R(n);const r=pi(this.elementaryStream.demuxer,n,!0);R(r);const i=new Ji(this.elementaryStream,r),s=new Wo(this,i),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,n){let r=this.packetBuffers.get(e);if(r){const l=await r.readNext();if(!l)return null;this.packetBuffers.delete(e);const f=this.createEncodedPacket(l.packet,l.duration,n);return this.packetBuffers.set(f,r),this.packetSectionStarts.set(f,l.packet.sectionStartPos),f}const i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,a=await s.readSection(i,!0);R(a);const o=pi(s,a,!0);R(o);const c=new Ji(this.elementaryStream,o);r=new Wo(this,c);const u=e.sequenceNumber;for(;;){const l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){const f=this.createEncodedPacket(l.packet,l.duration,n);return this.packetBuffers.set(f,r),this.packetSectionStarts.set(f,l.packet.sectionStartPos),f}}}async getNextKeyPacket(e,n){let r=e;for(;;){if(r=await this.getNextPacket(r,n),!r)return null;if(r.type==="key")return r}}getPacket(e,n){return this.doPacketLookup(e,!1,n)}getKeyPacket(e,n){return this.doPacketLookup(e,!0,n)}async doPacketLookup(e,n,r){const i=Hi(e*rn),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,u=async(v,k,A)=>{let T=v;for(;T<k;){const S=await s.readPacketHeader(T);if(!S)return null;if(S.pid===c&&S.payloadUnitStartIndicator===1){const P=await s.readSection(T,A);if(!P)return null;const M=Dr(s,P,!1);if(M&&M.pts!==null)return{pesPacketHeader:M,section:P}}T+=s.packetStride}return null},l=this.elementaryStream.firstSection;R(l);const f=Dr(s,l,!0);if(R(f),i<f.pts)return null;let d;const h=this.elementaryStream.referencePesPackets,p=_e(h,i,v=>v.pts),m=p!==-1?h[p]:null;if(m&&i-m.pts<rn/2)d=m.sectionStartPos;else{let v=0;if(a.fileSize!==null){const k=Math.ceil(a.fileSize/o);if(k>1){let A=0,T=k-1;for(v=A;A<=T;){const S=Math.floor((A+T)/2),P=Ja(S*o,s.packetStride)+f.sectionStartPos,M=P+o,B=await u(P,M,!1);if(!B){T=S-1;continue}B.pesPacketHeader.pts<=i?(v=S,A=S+1):T=S-1}}}d=Ja(v*o,s.packetStride)+f.sectionStartPos}let w=(await u(d,a.fileSize??1/0,!1))?.pesPacketHeader??null;w||(w=f);const y=this.getReorderSize(),b=async(v,k)=>{const A=await s.readSection(v,!0);R(A);const T=pi(s,A,!0);R(T);const S=new Ji(this.elementaryStream,T),P=new Wo(this,S);for(;!((Rt(P.presentationOrderPackets)?.pts??-1/0)>=i||!await P.readNextPacket()););const M=Ka(P.presentationOrderPackets,k);if(M===-1)return null;const B=P.presentationOrderPackets[M],N=M===0?0:B.pts-P.presentationOrderPackets[M-1].pts;for(;P.decodeOrderPackets[0]!==B;)P.decodeOrderPackets.shift();P.lastDuration=N;const O=await P.readNext();R(O);const q=this.createEncodedPacket(O.packet,O.duration,r);return this.packetBuffers.set(q,P),this.packetSectionStarts.set(q,O.packet.sectionStartPos),q};if(!n||this.allPacketsAreKeyPackets()){e:for(;;){let v=w.sectionStartPos+s.packetStride;for(;;){const k=await s.readPacketHeader(v);if(!k)break e;if(k.pid===c&&k.payloadUnitStartIndicator===1){const A=await s.readSection(v,!1);if(A){const T=Dr(s,A,!1);if(T&&T.pts!==null){if(T.pts>i)break e;w=T,Vo(this.elementaryStream,w);break}}}v+=s.packetStride}}e:for(let v=0;v<y+1;v++){let k=w.sectionStartPos-s.packetStride;for(;k>=s.packetOffset;){const A=await s.readPacketHeader(k);if(!A)break e;if(A.pid===c&&A.payloadUnitStartIndicator===1){const T=await s.readSection(k,!1);if(T){const S=Dr(s,T,!1);if(S&&S.pts!==null){w=S;break}}}k-=s.packetStride}}return b(w.sectionStartPos,v=>v.pts<=i)}else{let v=d,k=null;const A=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let T=null;const S=v<=f.sectionStartPos;let P,M=null;if(S)P=f,M=l;else{const O=await u(v,a.fileSize??1/0,A);P=O?.pesPacketHeader??null,M=O?.section??null}let B=!1,N=0;e:for(;P&&!(k!==null&&P.sectionStartPos>=k);){if(P.pts<=i){let q;if(this.elementaryStream.canBeTrustedWithKeyPackets)q=P.randomAccessIndicator===1;else{R(M);const H=pi(s,M,!0);R(H);const G=new Ji(this.elementaryStream,H);await G.markNextPacket(),q=G.suppliedPacket?.randomAccessIndicator===1}q&&(T=P)}if(P.pts>i&&(B=!0),B&&(N++,N>y))break;let O=P.sectionStartPos+s.packetStride;for(;;){const q=await s.readPacketHeader(O);if(!q)break e;if(q.pid===c&&q.payloadUnitStartIndicator===1){const H=await s.readSection(O,A);if(H){const G=Dr(s,H,!1);if(G&&G.pts!==null){P=G,M=H,Vo(this.elementaryStream,P);break}}}O+=s.packetStride}}if(T){let O=T;if(N===0)e:for(let H=0;H<y;H++){let G=O.sectionStartPos-s.packetStride;for(;G>=s.packetOffset;){const Y=await s.readPacketHeader(G);if(!Y)break e;if(Y.pid===c&&Y.payloadUnitStartIndicator===1){const J=await s.readSection(G,A);if(J){const ne=Dr(s,J,!1);if(ne&&ne.pts!==null){O=ne;break}}}G-=s.packetStride}}const q=await b(O.sectionStartPos,H=>H.pts<=i&&H.randomAccessIndicator===1);return R(q),q}if(S)return null;k=v,v=Math.max(Ja(v-f.sectionStartPos-o,s.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}}class Mp extends Na{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return R(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Bp extends Na{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return R(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Vo=(t,e)=>{const n=t.referencePesPackets,r=_e(n,e.sectionStartPos,i=>i.sectionStartPos);if(r>=0){const i=n[r];if(e.pts<=i.pts)return!1;const s=t.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(r<n.length-1){const a=n[r+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return n.splice(r+1,0,e),!0};class Ji{constructor(e,n){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=n}ensureBuffered(e){const n=this.endPos-this.currentPos;return n>=e?e:this.bufferData(e-n).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return R(e),e}async bufferData(e){const n=this.endPos+e;for(;this.endPos<n;){let r;if(this.pesPackets.length===0)r=this.startingPesPacket;else{let i=Rt(this.pesPackets).sectionEndPos;for(R(i!==null);;){const s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(i,!0);if(!a)return;const o=pi(this.demuxer,a,!1);if(o){r=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(r),this.endPos+=r.data.byteLength}}readBytes(e){const n=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,i=r+e;if(this.currentPos+=e,i<=n.data.byteLength)return n.data.subarray(r,i);const s=new Uint8Array(e);s.set(n.data.subarray(r));let a=n.data.byteLength-r;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const n=this.currentPos-this.currentPesPacketPos;return this.currentPos++,n<e.data.byteLength?e.data[n]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const n=this.getCurrentPesPacket();this.currentPesPacketPos-=n.data.byteLength}else for(;;){const n=this.getCurrentPesPacket(),r=this.currentPesPacketPos+n.data.byteLength;if(e<r)break;this.currentPesPacketPos+=n.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){R(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const n=e.info.codec,r=1024;if(n!=="avc"&&n!=="hevc")throw new Error("Unhandled.");const i=n==="avc"?1:2;let s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(r);if(ie(c)&&(c=await c),c===0)break;const u=this.currentPos,l=this.readBytes(c),f=l.byteLength;let d=0;for(;d<f;){const h=l.indexOf(0,d);if(h===-1||h>=f)break;d=h;const p=u+d;if(d+3>=f){this.seekTo(p);break}const m=l[d+1],g=l[d+2],w=l[d+3];let y=0;if(m===0&&g===0&&w===1?y=4:m===0&&g===1&&(y=3),y===0){d++;continue}const b=p;s??=b;const v=d+y,k=v+i,A=6;if(k+(n==="avc"?A:1)>f){this.seekTo(p);break}const S=l[v];let P,M,B;if(n==="avc")P=qs(S),M=P===ut.NON_IDR_SLICE||P===ut.SLICE_DPA||P===ut.IDR,B=P===ut.SEI||P===ut.SPS||P===ut.PPS||P===ut.AUD;else{if(P=ri(S),((S&1)<<5|l[v+1]>>3)>0){d+=y;continue}M=P<=Ge.RASL_R||P>=Ge.BLA_W_LP&&P<=21,B=P>=Ge.VPS_NUT&&P<=37||P===Ge.PREFIX_SEI_NUT||P>=41&&P<=44||P>=48&&P<=55}let N=!1;if(M){let O;if(n==="avc"){const q=l.subarray(k,k+A),H=le(new Ee(q));O=!a||H<=o,o=H}else O=l[k]>>7===1;O&&(a?N=!0:a=!0)}else B&&a&&(N=!0);if(N){const O=b-s;return this.seekTo(s),this.supplyPacket(O,0)}d+=y}if(c<r)break}if(s!==null&&this.endPos>s){const c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{const n=e.info.codec,r=128;for(;;){let i=this.ensureBuffered(r);ie(i)&&(i=await i);const s=this.currentPos;for(;this.currentPos-s<i;){const a=this.readU8();if(n==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(mi);if(ie(c)&&(c=await c),c<mi)return;const u=this.readBytes(mi),l=Zi(cn.tempFromBytes(u));if(l){this.seekTo(o);let f=this.ensureBuffered(l.frameLength);return ie(f)&&(f=await f),this.supplyPacket(f,Math.round(ra*rn/e.info.sampleRate))}else this.seekTo(o+1)}else if(n==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Br);if(ie(c)&&(c=await c),c<Br)return;const u=this.readBytes(Br),l=Me(u).getUint32(0),f=Eo(l,null);if(f.header){this.seekTo(o);let d=this.ensureBuffered(f.header.totalSize);ie(d)&&(d=await d);const h=f.header.audioSamplesInFrame*rn/e.info.sampleRate;return this.supplyPacket(d,Math.round(h))}else this.seekTo(o+1)}else if(n==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(ie(c)&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const l=u[4]>>6,f=u[4]&63;if(l===3||f>37){this.seekTo(o+1);continue}const d=ym[3*f+l];R(d!==void 0),this.seekTo(o),c=this.ensureBuffered(d),ie(c)&&(c=await c);const h=Math.round(bm*rn/e.info.sampleRate);return this.supplyPacket(c,h)}else if(n==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(ie(c)&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const f=(((u[2]&7)<<8|u[3])+1)*2,h=u[4]>>6===3?3:u[4]>>4&3,p=El[h];this.seekTo(o),c=this.ensureBuffered(f),ie(c)&&(c=await c);const m=p*256,g=Math.round(m*rn/e.info.sampleRate);return this.supplyPacket(c,g)}else if(n==="dts"){if(a!==127&&a!==100)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Qs);if(ie(c)&&(c=await c),c<Qs)return;const u=this.readBytes(Qs),l=Dl(u);let f=l?null:Ks(u);if(!l&&!f){this.seekTo(o+1);continue}if(f&&!f.asset){this.seekTo(o);const m=Math.min(f.frameSize,Am);let g=this.ensureBuffered(m);ie(g)&&(g=await g),f=Ks(this.readBytes(g))??f}let d=l?l.frameSize:f.frameSize;if(l){let m=Math.ceil(l.frameSize/4)*4;for(;;){this.seekTo(o);const g=m+To;let w=this.ensureBuffered(g);if(ie(w)&&(w=await w),w<g)break;this.seekTo(o+m);const y=Ks(this.readBytes(To));if(!y)break;m+=y.frameSize,d=m}}const h=l?.sampleCount??f.asset?.sampleCount;if(h===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(d),ie(c)&&(c=await c);const p=Math.round(h*rn/e.info.sampleRate);return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(i<r)break}}}supplyPacket(e,n){const r=this.getCurrentPesPacket();let i;if(this.lastSuppliedPesPacket===r)R(this.nextPts!==null),i=this.nextPts;else{if(r.pts===null)throw new Error(gu);i=r.pts,Vo(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=i+n;const s=r.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const u=ko(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Wo{constructor(e,n){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=n,this.reorderSize=e.getReorderSize(),R(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],n=this.presentationOrderPackets.indexOf(e);R(n!==-1);let r;for(n===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[n+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(R(e);;){const n=this.presentationOrderPackets.indexOf(e);if(n!==-1&&n<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let n=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[n].pts&&(n=i);const r=this.reorderBuffer[n];this.presentationOrderPackets.push(r),this.reorderBuffer.splice(n,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,n)=>e.pts-n.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const wu="application/vnd.apple.mpegurl",vu="#EXT-X-STREAM-INF:",ku="#EXT-X-I-FRAME-STREAM-INF:",Au="#EXT-X-MEDIA:",jo="#EXTINF:",xu="#EXT-X-MAP:",Tu="#EXT-X-KEY:",Su="#EXT-X-MEDIA-SEQUENCE:",Pu="#EXT-X-BYTERANGE:",_u="#EXT-X-PROGRAM-DATE-TIME:",Rp="#EXT-X-DISCONTINUITY",Eu="#EXT-X-TARGETDURATION:",Fp="#EXT-X-ENDLIST",Cu="#EXT-X-PLAYLIST-TYPE:",Dp="#EXT-X-I-FRAMES-ONLY",Iu=t=>t.length===0||t.startsWith("#")&&!t.startsWith("#EXT");class es{constructor(e){this._attributes={};let n="",r="",i=!1,s=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(n&&(this._attributes[n.trim().toLowerCase()]=r),n="",r="",i=!1):i?r+=o:n+=o}n&&(this._attributes[n.trim().toLowerCase()]=r)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const n=this.get(e);if(n===null)return null;const r=Number(n);return Number.isFinite(r)?r:null}merge(e){Object.assign(this._attributes,e._attributes)}}class Np{constructor(e,n,r){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=n,this.trackDeclarations=r}async getDurationFromMetadata(e){const n=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return n?n.timestamp+n.duration:null}async getUnixTimeForTimestamp(e){let n=await this.getSegmentAt(e,{});if(n??=await this.getFirstSegment({}),!n||n.unixEpochTimestamp===null)return null;const r=e-n.timestamp;return n.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{const e=[];if(this.trackDeclarations){for(const n of this.trackDeclarations)if(n.type==="video"){const r=Vi(e,i=>i.getType()==="video")+1;e.push(new Bu(this,n,r))}else if(n.type==="audio"){const r=Vi(e,i=>i.getType()==="audio")+1;e.push(new Ru(this,n,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const r=await this.getInputForSegment(this.firstSegment).getTracks();for(const i of r)if(i.type==="video"){const s=Vi(e,a=>a.getType()==="video")+1;e.push(new Bu(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){const s=Vi(e,a=>a.getType()==="audio")+1;e.push(new Ru(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){const n=this.firstTimestampCache.get(e);if(n!==void 0)return n;const r=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,r),r}async getMediaOffset(e,n){const r=e.firstSegment??e;let i;if(this.firstSegmentFirstTimestamps.has(r))i=this.firstSegmentFirstTimestamps.get(r);else{const u=this.getInputForSegment(r);i=await this.getFirstTimestampForInput(u),this.firstSegmentFirstTimestamps.set(r,i)}if(r===e)return r.timestamp-i;const s=await this.getFirstTimestampForInput(n),a=e.timestamp-r.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?r.timestamp-i:e.timestamp-s}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class Mu{constructor(e,n,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=n,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let e=this.segmentedInput.firstSegment,n=null;for(;e&&(n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number)??null,!n);)e=await this.segmentedInput.getNextSegment(e,{});if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),R(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,n,r){R(e.sequenceNumber>=0),R(this.segmentedInput.firstSegment);const i=await this.segmentedInput.getMediaOffset(n,r.input),s=n.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:ul(e.timestamp+i,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:n,track:r,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),R(this.firstInputTrack),R(this.firstSegment);let n=this.firstInputTrack,r=this.firstSegment;for(;;){if(n){const a=await n._backing.getFirstPacket(e);if(a)return this.createAdjustedPacket(a,r,n)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;n=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(a=>a.type===this.firstInputTrack.type&&a.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,n){return this._getNextInternal(e,n,!1)}getNextKeyPacket(e,n){return this._getNextInternal(e,n,!0)}async _getNextInternal(e,n,r){const i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");const s=r?await i.track._backing.getNextKeyPacket(i.sourcePacket,n):await i.track._backing.getNextPacket(i.sourcePacket,n);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:n.skipLiveWait});if(!o)return null;const l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(d=>d.type===i.track.type&&d.number===i.track.number);if(!l){a=o;continue}const f=await l._backing.getFirstPacket(n);return f?this.createAdjustedPacket(f,o,l):null}}getPacket(e,n){return this._getPacketInternal(e,n,!1)}getKeyPacket(e,n){return this._getPacketInternal(e,n,!0)}async _getPacketInternal(e,n,r){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:n.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){const s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(f=>f.type===this.firstInputTrack.type&&f.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(i,s),u=e-c,l=r?await o._backing.getKeyPacket(u,n):await o._backing.getPacket(u,n);if(!l){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}return this.createAdjustedPacket(l,i,o)}return null}}class Bu extends Mu{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ru extends Mu{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}co();const Fu=0,Du=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});class jn extends fo{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new bt;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Fu,Du),e=this._getFileSize(),R(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new bt;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,n){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new jp(this,e,n)}_dispatchRead(e,n){this.onread?.(e,n),this._emit("read",{start:e,end:n})}ref(){return new qo(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class qo{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;R(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class gi extends jn{constructor(e,n){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof n!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=n}_resolveRequest(e){const n=this.requestHandler(e),r=i=>{if(!(i instanceof jn||i instanceof qo))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=i instanceof jn?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return ie(n)?n.then(r):r(n)}}const Nu=(t,e)=>t.path===e.path;class Lp extends gi{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,n,r,i){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof jn?o.ref():o;return this._root=c,this._rootRequest=null,c};ie(s)?this._rootRequest=s.then(a):(a(s),R(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,n,r,i))}return this._root.source._read(e,n,r,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t.cancel().catch(()=>{})});const Up=.5*2**20,Op=(t,e,n)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return pe._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)},Lu=new Set;class qc extends gi{constructor(e,n={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.requestInit!==void 0&&(!n.requestInit||typeof n.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(n.getRetryDelay!==void 0&&typeof n.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(n.maxCacheSize!==void 0&&(!Os(n.maxCacheSize)||n.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(n.parallelism!==void 0&&(!Number.isInteger(n.parallelism)||n.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(n.fetchFn!==void 0&&typeof n.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");const r=e instanceof Request?e.url:e instanceof URL?e.href:e;super(r,a=>new qc(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=n,this._getRetryDelay=n.getRetryDelay??Op,this._requestInit={...n.requestInit};let i=null;if(n.requestInit?.headers){const a={...to(n.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(i=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){const a=e.headers.get("Range");if(a!==null){i??=a;const o=new Request(e);o.headers.delete("Range"),this._url=o}}if(i!==null){const a=Hp(i);a&&(this._offset=a.offset,this._length=a.length)}const s=2;this._orchestrator=new Wp({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:Vp.network,handleUnhandledError:n.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:zi(e-this._offset,0,this._length??1/0)}_read(e,n,r,i){if(this._length!==null&&n>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+n):this._orchestrator.read(s+e,s+n,Math.max(s+r,s),s+Math.min(i,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return ie(a)?a.then(o):o(a)}async _runWorker(e){for(;;){const n=new AbortController,r=await hl(this._options.fetchFn??fetch,this._url,dl(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(this._orchestrator.fileSize===null&&(r.status===206||r.type==="basic"&&!r.headers.has("Content-Encoding"))){const s=r.headers.get("Content-Range");if(s){const o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=r.headers.get("Content-Length");if(a){const o=r.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(o+Number(a))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(r.status!==206){if(this._sequentialBacking){r.body.cancel();return}if(!this._usedForHls){const s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Lu.has(s.origin)||(pe._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),Lu.add(s.origin)))}this._transitionToSequentialMode(r.body);return}const i=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;const u=this._getRetryDelay(1,c,this._url);if(u!==null){pe._error("Error while reading response stream. Attempting to resume.",c),await Hs(1e3*u);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_transitionToSequentialMode(e){let n=e.getReader(),r=0,i=0;const s=new ReadableStream({pull:async c=>{for(;;){let u;try{u=await n.read()}catch(f){if(this._disposed)throw f;const d=this._getRetryDelay(1,f,this._url);if(d===null)throw f;pe._error("Error while reading response stream. Attempting to resume.",f),await Hs(1e3*d);const h=await hl(this._options.fetchFn??fetch,this._url,dl(this._requestInit,{headers:{Range:`bytes=${r}-`}}),this._getRetryDelay,()=>this._disposed);if(!h.ok)throw new Error(`Error fetching ${String(this._url)}: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=h.body.getReader(),i=h.status===206?0:r;continue}if(u.done){c.close();return}let l=u.value;if(i>0){const f=Math.min(i,l.length);i-=f,l=l.subarray(f)}if(l.length!==0){r+=l.length,c.enqueue(l);return}}},cancel:()=>n.cancel()}),a=new Uu(s,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});a._endIndex=this._orchestrator.fileSize,a._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",a.on("read",({start:c,end:u})=>this._dispatchRead(c,u)),this._sequentialBacking=a;const o=new Set;for(const c of this._orchestrator.workers){for(const u of c.pendingSlices)o.add(u);c.aborted=!0,c.pendingSlices.length=0}for(const c of this._orchestrator.queuedReads)for(const u of c.pendingSlices)o.add(u);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const u=a._read(c.start,c.start+c.bytes.length);ie(u)?u.then(l=>{l?(R(l.offset===c.start),c.resolve(l.bytes)):c.resolve(null)},l=>c.reject(l)):(R(u===null),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const zp=/^bytes=(\d+)-(\d*)$/,Hp=t=>{const e=zp.exec(t.trim());if(!e)return null;const n=Number(e[1]),r=e[2]===""?null:Number(e[2]);return r!==null&&r<n?null:{offset:n,length:r!==null?r-n+1:null}};class Uu extends jn{constructor(e,n={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(n.maxCacheSize!==void 0&&(!Os(n.maxCacheSize)||n.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.",this._stream=e,this._maxCacheSize=n.maxCacheSize??32*2**20,this._handleUnhandledError=n.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,n){if(this._endIndex!==null&&n>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,n);const r=_e(this._cache,e,l=>l.start),i=r!==-1?this._cache[r]:null;if(i&&i.start<=e&&n<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e;const a=new Uint8Array(n-e);if(r!==-1)for(let l=r;l<this._cache.length;l++){const f=this._cache[l];if(f.start>=n)break;const d=Math.max(e,f.start);d>s&&this._throwDueToCacheMiss();const h=Math.min(n,f.end);d<h&&(a.set(f.bytes.subarray(d-f.start,h-f.start),d-e),s=h)}if(s===n)return{bytes:a,view:Me(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=gt();return this._pendingSlices.push({start:e,end:n,bytes:a,resolve:c,reject:u}),this._targetIndex=Math.max(this._targetIndex,n),this._pulling||(this._pulling=!0,this._pull().catch(l=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(f=>f.reject(l)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(l);else throw l})),o}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:n}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const r=this._currentIndex,i=this._currentIndex+n.byteLength;this._dispatchRead(r,i);for(let s=0;s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(r,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(n.subarray(o-r,c-r),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:Me(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:r,end:i,bytes:n,view:Me(n),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=n.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new bt);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Vp={network:(t,e,n)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(const i of n){const a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(oo(t,e,a,i.targetPos)){const o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);e=Math.max(e,i.startPos+l)}}return e=Math.max(e,t+Up),{start:t,end:e}}};class Wp{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,n,r,i){R(!this.disposed);const s=this.options.prefetchProfile(e,n,this.workers),a=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,i);R(a<=e&&n<=o);let c=null;const u=_e(this.cache,e,k=>k.start),l=u!==-1?this.cache[u]:null;l&&l.start<=e&&n<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});const f=_e(this.cache,a,k=>k.start),d=c?null:new Uint8Array(n-e);let h=0,p=a;const m=[];if(f!==-1){for(let k=f;k<this.cache.length;k++){const A=this.cache[k];if(A.start>=o)break;if(A.end<=a)continue;const T=Math.max(a,A.start),S=Math.min(o,A.end);if(R(T<=S),p<T&&m.push({start:p,end:T}),p=S,d){const P=Math.max(e,A.start),M=Math.min(n,A.end);if(P<M){const B=P-e;d.set(A.bytes.subarray(P-A.start,M-A.start),B),B===h&&(h=M-e)}}A.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(d&&h>=d.length&&(c={bytes:d,view:Me(d),offset:e}),m.length===0)return R(c),c;const{promise:g,resolve:w,reject:y}=gt(),b=[];for(const k of m){const A=Math.max(e,k.start),T=Math.min(n,k.end);A===k.start&&T===k.end?b.push(k):A<T&&b.push({start:A,end:T})}const v=d&&{start:e,bytes:d,holes:b,resolve:w,reject:y};e:for(const k of m){for(const S of this.workers)if(this.checkHoleAgainstWorker(S,k,v?[v]:[])){this.checkQueuedReadsAgainstWorker(S);continue e}const A=k.end<o||this.fileSize!==null,T=this.createWorker(k.start,k.end,A);if(T)v&&(T.pendingSlices=[v]),this.runWorker(T);else{let S=_e(this.queuedReads,k.start,M=>M.hole.start),P=S!==-1?this.queuedReads[S]:null;for(P&&k.start<=P.hole.end?(P.hole.end=Math.max(P.hole.end,k.end),P.strictTarget&&=A,v&&P.pendingSlices.push(v)):(S++,P={hole:{start:k.start,end:k.end},strictTarget:A,pendingSlices:v?[v]:[],age:this.nextAge++},this.queuedReads.splice(S,0,P));S+1<this.queuedReads.length;){const M=this.queuedReads[S+1];if(M.hole.start>P.hole.end)break;P.hole.end=Math.max(P.hole.end,M.hole.end),P.pendingSlices.push(...M.pendingSlices),P.strictTarget&&=M.strictTarget,P.age=Math.min(P.age,M.age),this.queuedReads.splice(S+1,1)}}}return c?g.catch(k=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(k);else throw k}):(R(d),c=g.then(k=>k&&{bytes:k,view:Me(k),offset:e})),c}checkHoleAgainstWorker(e,n,r){if(oo(n.start-131072,n.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,n.end);for(let s=0;s<r.length;s++){const a=r[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let n=!1;for(let r=0;r<this.queuedReads.length;r++){const i=this.queuedReads[r];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(r,1),r--,n=!0;else if(n)break}}createWorker(e,n,r){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)R(a!==null),R(s.pendingSlices.length===0),this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(s);else return null}const i={startPos:e,currentPos:e,targetPos:n,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){R(!e.running),R(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(n=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(n)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(n);else throw n}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let n=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[n].age&&(n=s);const r=this.queuedReads[n],i=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);if(!i)return;this.queuedReads.splice(n,1),i.pendingSlices=r.pendingSlices,this.runWorker(i)}})}supplyWorkerData(e,n){R(!e.aborted);const r=e.currentPos,i=r+n.length;this.insertIntoCache({start:r,end:i,bytes:n,view:Me(n),age:this.nextAge++}),e.currentPos+=n.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){const a=e.pendingSlices[s],o=Math.max(r,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(n.subarray(o-r,c-r),o-a.start);for(let u=0;u<a.holes.length;u++){const l=a.holes[u];r<=l.start&&i>l.start&&(l.start=i),l.end<=l.start&&(a.holes.splice(u,1),u--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const a=this.workers[s];e===a||a.running||oo(r,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a),s--)}}supplyFileSize(e){R(this.fileSize===null),this.fileSize=e;for(const n of this.workers){n.targetPos=Math.min(n.targetPos,e),n.strictTarget=!0;for(let r=0;r<n.pendingSlices.length;r++){const i=n.pendingSlices[r];for(const s of i.holes)if(s.end>e){i.resolve(null),n.pendingSlices.splice(r,1),r--;break}}}for(let n=0;n<this.queuedReads.length;n++){const r=this.queuedReads[n];if(r.hole.start>=e){for(const i of r.pendingSlices)i.resolve(null);this.queuedReads.splice(n,1),n--}else if(r.hole.end>e){r.hole.end=e,r.strictTarget=!0;for(let i=0;i<r.pendingSlices.length;i++){const s=r.pendingSlices[i];s.start>=e&&(s.resolve(null),r.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const n=this.workers.indexOf(e);R(n!==-1),e.running=!1,this.workers.splice(n,1),this.options.onIdleWorkerRemoved?.(e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const r of e.pendingSlices)r.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let n=_e(this.cache,e.start,r=>r.start)+1;if(n>0){const r=this.cache[n-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=Me(i),r.end=e.end,n--,e=r}else this.cache.splice(n,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(n,0,e),this.currentCacheSize+=e.bytes.length;for(let r=n+1;r<this.cache.length;r++){const i=this.cache[r];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(r,1),this.currentCacheSize-=i.bytes.length,r--;continue}const s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=Me(s),e.end=i.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<i.age&&(r=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(const e of this.workers){for(const n of e.pendingSlices)n.reject(new bt);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(const e of this.queuedReads)for(const n of e.pendingSlices)n.reject(new bt);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class jp extends jn{constructor(e,n,r){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=n,this._length=r??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:zi(e-this._offset,0,this._length??1/0)}_read(e,n,r,i){if(this._length!==null&&n>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+n,this._offset+r,this._offset+i),a=o=>o?(o.offset-=this._offset,o):null;return ie(s)?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var Ou=function(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],n&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:n})}else n&&t.stack.push({async:!0});return e},zu=(function(t){return function(e){function n(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,i=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&i===1)return i=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(a).then(s,function(o){return n(o),s()})}else i|=1}catch(o){n(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var r=new Error(n);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});const qp=/^0[xX][0-9a-fA-F]+$/,Xp=/^data:.*;base64,/i;class Hu extends Np{constructor(e,n,r,i){super(e.input,n,r),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=n,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await Hs(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,n=Math.max(0,1e3*this.refreshInterval-e);return n<=50?0:n}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const b={stack:[],error:void 0,hasError:!1};try{const v=Ou(b,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),A=await new aa(v.source).requestEntireFile();R(A),e=hf(A,A.length,{ignore:Iu}),v.source instanceof gi&&(this.rootPath=v.source.rootPath)}catch(v){b.error=v,b.hasError=!0}finally{zu(b)}}const n=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1;let r=!1,i=0,s=null,a=null,o=null,c=0,u=null,l=null,f=null,d=null,h=null,p=null,m=!1,g=Rt(this.segments)??null;const w=b=>{const v=b.indexOf("@"),k=Number(v===-1?b:b.slice(0,v));if(!Number.isInteger(k)||k<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${b}'.`);let A=null;if(v!==-1&&(A=Number(b.slice(v+1)),!Number.isInteger(A)||A<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${b}'.`);return{length:k,offset:A}},y=b=>{c=b,g&&(R(g.sequenceNumber!==null),g.sequenceNumber<b&&(i=g.timestamp+g.duration,u=g.firstSegment,l=g.initSegment,h=g.lastProgramDateTimeSeconds,s=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+g.duration:null,g=null))};for(let b=0;b<e.length;b++){const v=e[b];if(!r){if(v!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");r=!0;continue}if(!v.startsWith("#")){if(!g){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let k=o;if(k&&k.method==="AES-128"&&!k.iv){const P=new Uint8Array(An),M=Me(P);M.setUint32(8,Math.floor(c/2**32)),M.setUint32(12,c),k={...k,iv:P}}const T={path:sr(this.rootPath,v),offset:d?.offset??0,length:d?.length??null},S={timestamp:i,unixEpochTimestamp:s,firstSegment:u,sequenceNumber:c,location:T,duration:a,encryption:k,initSegment:l,lastProgramDateTimeSeconds:h};u??=S,i+=a,s!==null&&(s+=a),this.segments.push(S)}a=null,d===null?f=null:d=null,y(c+1)}if(v.startsWith(jo)){if(g){m=!0;continue}m||(h===null&&c>0&&p!==null&&(i=c*p),m=!0);const k=v.slice(jo.length),A=k.indexOf(","),T=A===-1?k:k.slice(0,A),S=Number(T);if(!Number.isFinite(S)||S<0)throw new Error(`Invalid #EXTINF tag duration '${T}'.`);a=S}else if(v.startsWith(xu)){const k=new es(v.slice(xu.length)),A=k.get("uri");if(!A)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const T=k.get("byterange");let S=null;if(T!==null&&(S=w(T)),S&&S.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const M={path:sr(this.rootPath,A),offset:S?.offset??0,length:S?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:i,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:M,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,d===null?f=null:d=null}else if(v.startsWith(Tu)){const k=new es(v.slice(Tu.length)),A=k.get("method");if(A==="NONE")o=null;else if(A==="AES-128"){const T=k.get("uri");if(!T)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let S=null;const P=k.get("iv");if(P){if(!qp.test(P))throw new Error(`Unsupported IV format '${P}'.`);let B=P.slice(2);B=B.padStart(An*2,"0"),S=new Uint8Array(An);for(let N=0;N<An;N++){const O=-An*2+N;S[N]=parseInt(B.slice(O,O+2),16)}}const M=k.get("keyformat")??"identity";if(M!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:sr(this.rootPath,T),iv:S,keyFormat:M}}else if(A==="SAMPLE-AES"||A==="SAMPLE-AES-CTR"){const T=k.get("uri");if(!T)throw new Error(`Invalid #EXT-X-KEY: ${A} requires a URI attribute.`);if((k.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let P=null;if(Xp.test(T)){const M=T.indexOf(","),B=ml(T.slice(M+1));if(B.length>=8&&B[4]===112&&B[5]===115&&B[6]===115&&B[7]===104){const N=Me(B).getUint32(0);P=Gl(B.subarray(8,Math.min(N,B.length)))}}o={method:A,psshBox:P}}else throw new Error(`Unsupported encryption method '${A}'. If you think this method should be supported, please raise an issue.`)}else if(v.startsWith(Su)){const k=v.slice(Su.length),A=Number(k);if(!Number.isInteger(A)||A<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${k}'.`);y(A)}else if(v.startsWith(Pu)){const k=w(v.slice(Pu.length));if(k.offset===null){if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");k.offset=f}d=k,f=k.offset+k.length}else if(v.startsWith(_u)){if(g)continue;const k=v.slice(_u.length),A=Date.parse(k);if(!Number.isFinite(A))continue;const T=A/1e3;if(h===T)continue;if(h===null&&this.segments.length>0){const S=Rt(this.segments),P=S.timestamp+S.duration,M=T-P;for(const B of this.segments)B.unixEpochTimestamp=B.timestamp+M,n&&(B.timestamp=B.unixEpochTimestamp)}h=T,s=T,n&&(i=T)}else if(v===Rp)u=null;else if(v.startsWith(Eu)){const k=v.slice(Eu.length),A=Number(k);if(!Number.isFinite(A)||A<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${k}'.`);this.refreshInterval=A,p=A}else if(v===Fp){this.streamHasEnded=!0;break}else v.startsWith(Cu)&&v.slice(Cu.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!r)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,n){this.segments.length===0&&await this.runUpdateSegments();let r=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const i=_e(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||r)return this.segments[i];const s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),n.skipLiveWait&&(r=!0)}}async getNextSegment(e,n){const r=this.segments.indexOf(e);R(r!==-1);const i=r+1;let s=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),n.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const n=this.segments.indexOf(e);return R(n!==-1),this.segments[n-1]??null}getInputForSegment(e){const n=e,r=this.inputCache.find(c=>c.segment===n);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(n.initSegment||n.firstSegment)&&(i=this.getInputForSegment(n.initSegment??n.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!n.encryption||!(n.encryption.method==="SAMPLE-AES"||n.encryption.method==="SAMPLE-AES-CTR")||!n.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let u=c.psshBoxes;const{psshBox:l}=n.encryption;return(l.keyIds===null||l.keyIds.includes(c.keyId))&&!u.some(f=>$l(f,l))&&(u=[...u,l]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:u})})}},a=new La({source:new Lp(n.location.path,async c=>{R(c.isRoot);const u={...c,isRoot:!1};let l;const f=n.location.offset>0||n.location.length!==null;if(!n.encryption||n.encryption.method==="SAMPLE-AES"||n.encryption.method==="SAMPLE-AES-CTR"){if(l=await this.input._getSourceCached(u),f){const h=l.source.slice(n.location.offset,n.location.length??void 0).ref();l.free(),l=h}}else if(n.encryption.method==="AES-128"){const d=n.encryption;R(d.iv);let h=await this.input._getSourceCached(u);if(f){const w=h.source.slice(n.location.offset,n.location.length??void 0).ref();h.free(),h=w}const p=new aa(h.source),m=jm(p,async()=>{const g={stack:[],error:void 0,hasError:!1};try{const w=Ou(g,await this.input._getSourceCached({path:d.keyUri,isRoot:!1},Ng),!1),b=await new aa(w.source).requestSlice(0,An);if(!b)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:me(b,An),iv:d.iv}}catch(w){g.error=w,g.hasError=!0}finally{zu(g)}},()=>{h.free()});l=new Uu(m).ref()}else R(!1);return l}),formats:this.input._formats.filter(c=>!(c instanceof Qu)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((n.encryption?.method==="SAMPLE-AES"||n.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:n,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const c=lo(this.inputCache,u=>u.age);R(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Gp extends On{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{R(this.input._rootSource instanceof gi);const e=await this.input._reader.requestEntireFile();R(e);const n=hf(e,e.length,{ignore:Iu}),{rootPath:r}=this.input._rootSource,i=[],s=[];for(let f=1;f<n.length;f++){const d=n[f];if(d.startsWith(vu)){const h=f,p=n[++f];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const m=sr(r,p),g=new es(d.slice(vu.length));if(g.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:g,lineNumber:h,hasOnlyKeyPackets:!1})}else if(d.startsWith(ku)){const h=new es(d.slice(ku.length)),p=h.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const g=sr(r,p);i.push({fullPath:g,attributes:h,lineNumber:f,hasOnlyKeyPackets:!0})}else if(d.startsWith(Au)){const h=new es(d.slice(Au.length));if(h.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(h.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null;const w=h.get("uri");w!==null&&(g=sr(r,w)),s.push({fullPath:g,attributes:h,lineNumber:f})}else if(d!==Dp){if(d.startsWith(jo)){const h=new Hu(this,r,null,n);this.segmentedInputs=[h],this.hasMasterPlaylist=!1,this.trackBackings=await h.getTrackBackings();return}}}const a=[...new Set(s.filter(f=>f.attributes.get("type").toLowerCase()==="video").map(f=>f.attributes.get("group-id")))],o=[...new Set(s.filter(f=>f.attributes.get("type").toLowerCase()==="audio").map(f=>f.attributes.get("group-id")))],c=await Promise.all(i.map(async(f,d)=>{const h=[],p=f.attributes.get("codecs");let m;if(p)m=p.split(",").map(P=>P.trim());else{const M=await this.getSegmentedInputForPath(f.fullPath).getTrackBackings(),B=await Promise.all(M.map(async N=>({track:N,codec:await N.getCodec()})));m=await Promise.all(B.filter(N=>N.codec!==null).map(N=>N.track.getDecoderConfig().then(O=>O.codec)))}const g=f.attributes.get("video"),w=f.attributes.get("audio"),y=m.some(P=>Nl.includes(ji(P))),b=m.some(P=>Ll.includes(ji(P)));if(g!==null&&!y){if(!a.includes(g))throw new Error(`Invalid M3U8 file; variant stream references video group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);const P=s.find(M=>{const B=M.attributes.get("group-id"),N=M.attributes.get("type");return B===g&&N.toLowerCase()==="video"});e:if(P){const M=P.attributes.get("uri");if(M===null)break e;const B=sr(r,M),q=(await this.getSegmentedInputForPath(B).getTrackBackings()).find(G=>G.getType()==="video");if(!q||await q.getCodec()===null)break e;const H=await q.getDecoderConfig().then(G=>G?.codec??null);R(H!==null),m.push(H)}}if(w!==null&&!b){if(!o.includes(w))throw new Error(`Invalid M3U8 file; variant stream references audio group "${w}" which is not defined in any #EXT-X-MEDIA tags.`);const P=s.find(M=>{const B=M.attributes.get("group-id"),N=M.attributes.get("type");return B===w&&N.toLowerCase()==="audio"});e:if(P){const M=P.attributes.get("uri");if(M===null)break e;const B=sr(r,M),q=(await this.getSegmentedInputForPath(B).getTrackBackings()).find(G=>G.getType()==="audio");if(!q||await q.getCodec()===null)break e;const H=await q.getDecoderConfig().then(G=>G?.codec??null);R(H!==null),m.push(H)}}m=[...new Set(m)];let v=null,k=null;const A=f.attributes.getAsNumber("bandwidth");R(A!==null);const T=f.attributes.getAsNumber("average-bandwidth"),S=f.attributes.get("name");for(const P of m){const M=ji(P);if(M!==null){if(Nl.includes(M)){if(v!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");v=P;const B=f.attributes.get("video");if(B===null){const N=f.attributes.get("resolution");let O=null,q=null;if(N){const H=N.match(/^(\d+)x(\d+)$/);H&&(O=Number(H[1]),q=Number(H[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Et,lineNumber:f.lineNumber,fullPath:f.fullPath,fullCodecString:v,pairingMask:1n<<BigInt(d),peakBitrate:A,averageBitrate:T,name:S,hasOnlyKeyPackets:f.hasOnlyKeyPackets,info:{type:"video",width:O,height:q}})}else{if(!a.includes(B))throw new Error(`Invalid M3U8 file; variant stream references video group "${B}" which is not defined in any #EXT-X-MEDIA tags.`);for(const N of s){const O=N.attributes.get("group-id"),q=N.attributes.get("type");if(O!==B||q.toLowerCase()!=="video")continue;const H=N.attributes.get("resolution")??f.attributes.get("resolution");let G=null,Y=null;if(H){const J=H.match(/^(\d+)x(\d+)$/);J&&(G=Number(J[1]),Y=Number(J[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:ia(N.attributes),autoselect:ia(N.attributes)||qu(N.attributes),languageCode:Xu(N.attributes.get("language")),lineNumber:N.lineNumber,fullPath:N.fullPath??f.fullPath,fullCodecString:v,pairingMask:1n<<BigInt(d),peakBitrate:null,averageBitrate:null,name:N.attributes.get("name"),hasOnlyKeyPackets:f.hasOnlyKeyPackets,info:{type:"video",width:G,height:Y}})}}}else if(Ll.includes(M)){if(k!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");k=P;const B=f.attributes.get("audio");if(B===null){const N=f.attributes.get("channels"),O=N!==null?Number(N.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Et,lineNumber:f.lineNumber,fullPath:f.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(d),peakBitrate:A,averageBitrate:T,name:S,hasOnlyKeyPackets:f.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:O!==null&&Number.isInteger(O)&&O>0?O:null}})}else{if(!o.includes(B))throw new Error(`Invalid M3U8 file; variant stream references audio group "${B}" which is not defined in any #EXT-X-MEDIA tags.`);for(const N of s){const O=N.attributes.get("group-id"),q=N.attributes.get("type");if(O!==B||q.toLowerCase()!=="audio")continue;const H=N.attributes.get("channels")??f.attributes.get("channels"),G=H!==null?Number(H.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:ia(N.attributes),autoselect:ia(N.attributes)||qu(N.attributes),languageCode:Xu(N.attributes.get("language")),lineNumber:N.lineNumber,fullPath:N.fullPath??f.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(d),peakBitrate:null,averageBitrate:null,name:N.attributes.get("name"),hasOnlyKeyPackets:f.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:G!==null&&Number.isInteger(G)&&G>0?G:null}})}}}}}return h})),u=[],l=f=>{const d=u.find(h=>h.fullPath===f.fullPath&&h.info.type===f.info.type);d?(d.pairingMask|=f.pairingMask,d.default||=f.default,d.autoselect||=f.autoselect,d.lineNumber=Math.min(d.lineNumber,f.lineNumber),f.peakBitrate!==null&&(d.peakBitrate=Math.max(d.peakBitrate??-1/0,f.peakBitrate)),f.averageBitrate!==null&&(d.averageBitrate=Math.max(d.averageBitrate??-1/0,f.averageBitrate)),d.languageCode===Et&&(d.languageCode=f.languageCode)):(f.id=u.length+1,u.push(f))};for(const f of c)for(const d of f)l(d);u.sort((f,d)=>f.lineNumber-d.lineNumber),this.trackBackings=[];for(const f of u)f.info.type==="video"?this.trackBackings.push(new Wu(f)):this.trackBackings.push(new ju(f));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),R(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let n=this.segmentedInputs.find(i=>i.path===e);if(n)return n;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),n=new Hu(this,e,r,null),this.segmentedInputs.push(n),n}async getMetadataTags(){return{}}async getMimeType(){return wu}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Vu{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let n=null;const i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)n=i[0];else if(this instanceof Wu){for(const s of i)if(await s.getCodec()===this.getCodec()){n=s;break}}else{R(this instanceof ju);for(const s of i)if(await s.getCodec()===this.getCodec()){n=s;break}}if(!n)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=n})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Un,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){R(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let n=0;for(const r of this.internalTrack.demuxer.internalTracks)if(r.info.type===e&&n++,r===this.internalTrack)break;return n}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,n)}async getKeyPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,n)}async getNextPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,n)}async getNextKeyPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,n)}}class Wu extends Vu{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ji(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class ju extends Vu{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ji(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const ia=t=>{const e=t.get("default");if(e===null)return!1;const n=e.toUpperCase();if(n==="YES")return!0;if(n==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},qu=t=>{const e=t.get("autoselect");if(e===null)return!1;const n=e.toUpperCase();if(n==="YES")return!0;if(n==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},Xu=t=>{if(t===null)return Et;const e=t.split("-")[0];return e||Et};class xn{constructor(){this._isIsobmff=!1}}class Gu extends xn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let n=e._reader.requestSlice(0,12);if(ie(n)&&(n=await n),!n)return null;n.skip(4);const r=je(n,4);return r!=="ftyp"&&r!=="styp"?null:je(n,4)}_createDemuxer(e){return new jc(e)}}class $p extends Gu{async _canReadInput(e){const n=await this._getMajorBrand(e);if(n!==null)return n!=="qt ";let r=0;for(let i=0;i<10;i++){let s=e._reader.requestSlice(r,8);if(ie(s)&&(s=await s),!s)return!1;let a=ae(s),o=8;if(a===1){let u=e._reader.requestSlice(r+8,8);if(ie(u)&&(u=await u),!u)return!1;a=Wt(u),o=16}if(a<o)return!1;const c=je(s,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")r+=a;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Qp extends Gu{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class $u extends xn{async isSupportedEBMLOfDocType(e,n){let r=e._reader.requestSlice(0,Hn);if(ie(r)&&(r=await r),!r)return!1;const i=ou(r);if(i===null||i<1||i>8||xe(r,i)!==re.EBML)return!1;const a=cu(r);if(typeof a!="number")return!1;let o=e._reader.requestSlice(r.filePos,a);if(ie(o)&&(o=await o),!o)return!1;const c=r.filePos;for(;o.filePos<=c+a-Qt;){const u=Vn(o);if(!u)break;const{id:l,size:f}=u,d=o.filePos;if(f===void 0)return!1;switch(l){case re.EBMLVersion:if(xe(o,f)!==1)return!1;break;case re.EBMLReadVersion:if(xe(o,f)!==1)return!1;break;case re.DocType:if(fi(o,f)!==n)return!1;break;case re.DocTypeVersion:if(xe(o,f)>4)return!1;break}o.filePos=d+f}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ep(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Yp extends $u{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Kp extends xn{async _canReadInput(e){let n=0;for(;;){let f=e._reader.requestSlice(n,Yt);if(ie(f)&&(f=await f),!f)break;const d=Xn(f);if(!d)break;n=f.filePos+d.size}const r=await Oo(e._reader,n,n+4096);if(!r)return!1;const i=r.header,s=Xl(i.mpegVersionId,i.channel);let a=e._reader.requestSlice(r.startPos+s,4);if(ie(a)&&(a=await a),!a)return!1;const o=ae(a);if(o===jl||o===ql)return!0;n=r.startPos+r.header.totalSize;const u=await Oo(e._reader,n,n+Br);if(!u)return!1;const l=u.header;return!(i.channel!==l.channel||i.sampleRate!==l.sampleRate)}_createDemuxer(e){return new rp(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Zp extends xn{async _canReadInput(e){let n=e._reader.requestSlice(0,12);if(ie(n)&&(n=await n),!n)return!1;const r=je(n,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(n.skip(4),je(n,4)==="WAVE")}_createDemuxer(e){return new hp(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Jp extends xn{async _canReadInput(e){let n=e._reader.requestSlice(0,4);return ie(n)&&(n=await n),n?je(n,4)==="OggS":!1}_createDemuxer(e){return new fp(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class eg extends xn{async _canReadInput(e){let n=0;for(;;){let i=e._reader.requestSlice(n,Yt);if(ie(i)&&(i=await i),!i)break;const s=Xn(i);if(!s)break;n=i.filePos+s.size}let r=e._reader.requestSlice(n,4);return ie(r)&&(r=await r),r?je(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new xp(e)}}class tg extends xn{async _canReadInput(e){let n=0;for(;;){let a=e._reader.requestSlice(n,Yt);if(ie(a)&&(a=await a),!a)break;const o=Xn(a);if(!o)break;n=a.filePos+o.size}let r=e._reader.requestSliceRange(n,zo,mi);if(ie(r)&&(r=await r),!r)return!1;const i=Zi(r);if(!i||(n+=i.frameLength,r=e._reader.requestSliceRange(n,zo,mi),ie(r)&&(r=await r),!r))return!1;const s=Zi(r);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new pp(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class ng extends xn{async _canReadInput(e){const n=Vt+16+1;let r=e._reader.requestSlice(0,n);if(ie(r)&&(r=await r),!r)return!1;const i=me(r,n);return i[0]===71&&i[Vt]===71||i[0]===71&&i[Vt+16]===71?!0:i[4]===71&&i[4+Vt+4]===71}_createDemuxer(e){return new Ip(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Qu extends xn{async _canReadInput(e){let n=e._reader.requestSlice(0,7);if(ie(n)&&(n=await n),!n||!(je(n,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof gi))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Gp(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return wu}}const rg=new $p,ig=new Qp,sg=new $u,ag=new Yp,og=new Kp,cg=new Zp,lg=new Jp,ug=new tg,fg=new eg,dg=new ng,hg=new Qu,mg=[hg,rg,ig,sg,ag,cg,lg,fg,og,ug,dg],pg=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(t.isobmff!==void 0){if(!t.isobmff||typeof t.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(t.isobmff.resolveKeyId!==void 0&&typeof t.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(t.hls!==void 0){if(!t.hls||typeof t.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(t.hls.offsetTimestampsByDateTime!==void 0&&typeof t.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var gg=function(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],n&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:n})}else n&&t.stack.push({async:!0});return e},yg=(function(t){return function(e){function n(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,i=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&i===1)return i=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(a).then(s,function(o){return n(o),s()})}else i|=1}catch(o){n(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var r=new Error(n);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});co();let Yu=-1/0,Ku=-1/0,Xo=null;typeof FinalizationRegistry<"u"&&(Xo=new FinalizationRegistry(t=>{const e=performance.now();t.type==="video"?(e-Yu>=1e3&&(pe._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Yu=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Ku>=1e3&&(pe._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Ku=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class Nr{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Go=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],bg=new Set(Go);class ln{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ti*this.timestamp)}get microsecondDuration(){return Math.trunc(ti*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,n){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.format===void 0||!bg.has(n.format))throw new TypeError("init.format must be one of: "+Go.join(", "));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(n.layout!==void 0){if(!Array.isArray(n.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const s of n.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(n.visibleRect!==void 0&&uo(n.visibleRect,"init.visibleRect"),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0;const r=n.layout??kg(n.format,n.codedWidth,n.codedHeight);let i=n.colorSpace??null;i===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?i={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:i={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180===0?n.displayHeight:n.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=n._doNotCopy?Fn(e):Fn(e).slice(),this._layout=r,this.colorSpace=new $o(i)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");n?.visibleRect!==void 0&&uo(n.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=n?.timestamp??e.timestamp/1e6,this.duration=n?.duration??(e.duration??0)/1e6,this.colorSpace=new $o(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(n.visibleRect!==void 0&&uo(n.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new ln(new VideoFrame(e,{timestamp:Math.trunc(n.timestamp*ti),duration:Math.trunc((n.duration??0)*ti)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw new TypeError("Could not determine dimensions.");const s=n.visibleRect??{left:0,top:0,width:r,height:i},a=new OffscreenCanvas(s.width,s.height),o=a.getContext("2d",{alpha:$h(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(e,-s.left,-s.top),this._data=a,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:s.width,height:s.height},this.squarePixelWidth=s.width,this.squarePixelHeight=s.height,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new $o({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Nr){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Go.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=zs({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Xo?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return R(this._data!==null),this._data instanceof Nr?new ln(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ns(this._data)?new ln(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(R(this._layout),new ln(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new ln(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Xo?.unregister(this),this._data instanceof Nr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ns(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(nf(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ns(this._data)?this._data.allocationSize(e):rf(this,e).allocationSize}async copyTo(e,n={}){if(!Oh(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(nf(n),this._closed)throw new Error("VideoSample is closed.");if((n.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(R(this._data!==null),ns(this._data))return this._data.copyTo(e,n);if(n.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(n.format))if(this._data instanceof Nr){const u={stack:[],error:void 0,hasError:!1};try{const l=gg(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},n.colorSpace??"srgb"),!1);if(!(l instanceof ln))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(l.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${l.format}' instead.`);return await l.copyTo(e,n)}catch(l){u.error=l,u.hasError=!0}finally{yg(u)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const u=this.toVideoFrame(),l=await u.copyTo(e,n);return u.close(),l}const r=rf(this,n);R(this.format);const i=Fn(e);if(i.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);const s=sa(this.format);let a;if(this._data instanceof Nr){let u=this._data.getDataPlanes();if(ie(u)&&(u=await u),!Array.isArray(u)||u.some(l=>!(l.data instanceof Uint8Array)||!Number.isInteger(l.stride)||l.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=u}else if(this._data instanceof Uint8Array)R(this._layout),R(this._layout.length===s.length),a=this._layout.map((u,l)=>{const f=Math.ceil(this.codedHeight/s[l].heightDivisor);return{data:this._data.subarray(u.offset,u.offset+u.stride*f),stride:u.stride}});else{const l=this._data.getContext("2d");R(l);const f=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:Fn(f.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let u=0;u<c;u++){const l=r.computedLayouts[u],f=a[u].stride,d=a[u].data;let h=l.sourceTop*f;h+=l.sourceLeftBytes;let p=l.destinationOffset;const m=l.sourceWidthBytes,g={offset:p,stride:l.destinationStride};for(let w=0;w<l.sourceHeight;w++){if(h+m>d.byteLength)throw new Error("Source buffer OOB read.");if(p+m>i.byteLength)throw new Error("Destination buffer OOB write.");const y=d.subarray(h,h+m);i.set(y,p),h+=f,p+=l.destinationStride}o.push(g)}if(n.format!==void 0){const u=this.format.startsWith("RGB")!==n.format.startsWith("RGB"),l=this.format.includes("X")&&n.format.includes("A");if(u||l)for(let f=0;f<r.allocationSize;f+=4){if(u){const d=i[f],h=i[f+2];i[f]=h,i[f+2]=d}l&&(i[f+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(R(this._data!==null),this._data instanceof Nr){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(ie(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const n=e.reduce((a,o)=>a+o.data.byteLength,0),r=new Uint8Array(n);let i=0;const s=[];for(const a of e)r.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(r,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ns(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(R(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,n,r,i,s,a,o,c,u){let l=0,f=0,d=this.displayWidth,h=this.displayHeight,p=0,m=0,g=this.displayWidth,w=this.displayHeight;if(a!==void 0?(l=n,f=r,d=i,h=s,p=a,m=o,c!==void 0?(g=c,w=u):(g=d,w=h)):(p=n,m=r,i!==void 0&&(g=i,w=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(f))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:f,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,f,d,h,this.rotation));const y=this.toCanvasImageSource();e.save();const b=p+g/2,v=m+w/2;e.translate(b,v),e.rotate(this.rotation*Math.PI/180);const k=this.rotation%180===0?1:g/w;e.scale(1/k,k),e.drawImage(y,l,f,d,h,-g/2,-w/2,g,w),e.restore()}drawWithFit(e,n){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(n.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");n.crop!==void 0&&tf(n.crop,"options.");const r=e.canvas.width,i=e.canvas.height,s=n.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=n.crop;c&&(c=ef(c,a,o));let u,l,f,d;const{sx:h,sy:p,sWidth:m,sHeight:g}=this._rotateSourceRegion(n.crop?.left??0,n.crop?.top??0,n.crop?.width??a,n.crop?.height??o,s);if(n.fit==="fill")u=0,l=0,f=r,d=i;else{const[y,b]=n.crop?[n.crop.width,n.crop.height]:[a,o],v=n.fit==="contain"?Math.min(r/y,i/b):Math.max(r/y,i/b);f=y*v,d=b*v,u=(r-f)/2,l=(i-d)/2}e.save();const w=s%180===0?1:f/d;e.translate(r/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/w,w),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,p,m,g,u,l,f,d),e.restore()}_rotateSourceRegion(e,n,r,i,s){return s===90?[e,n,r,i]=[n,this.squarePixelHeight-e-r,i,r]:s===180?[e,n]=[this.squarePixelWidth-e-r,this.squarePixelHeight-n-i]:s===270&&([e,n,r,i]=[this.squarePixelWidth-n-i,e,i,r]),{sx:e,sy:n,sWidth:r,sHeight:i}}_drawWithFitAndMipmapping(e,n,r){const i=e.width,s=e.height,[a,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:a,u=r.crop?r.crop.height:o;let l=0;2*i<c&&2*s<u&&(l=Math.floor(Math.log2(Math.min(c/i,u/s))));const f=i*2**l,d=s*2**l,{canvas:h,context:p,isNew:m}=l>0?Ju(f,d):{canvas:e,context:n,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,f,d)):m||p.clearRect(0,0,f,d),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,crop:r.crop}),p.globalCompositeOperation="copy";for(let g=l;g>1;g--){const w=i*2**g,y=s*2**g;p.drawImage(h,0,0,w,y,0,0,w/2,y/2)}p.globalCompositeOperation="source-over",l>0&&(n.imageSmoothingQuality="high",n.globalCompositeOperation="copy",n.drawImage(h,0,0,2*i,2*s,0,0,i,s),n.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(R(this._data!==null),this._data instanceof Nr||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&tf(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const n=ja(this.rotation+(e.rotate??0)),[r,i]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=ef(s,r,i));const a=s?s.width:r,o=s?s.height:i,c=a/o;let u,l;e.width!==void 0&&e.height===void 0?(u=e.width,l=u/c):e.width===void 0&&e.height!==void 0?(l=e.height,u=l*c):e.width!==void 0&&e.height!==void 0?(u=e.width,l=e.height):(u=a,l=o),u=Za(u,e.roundDimensionsTo??1),l=Za(l,e.roundDimensionsTo??1);const f={width:u,height:l,fit:e.fit??"fill",rotation:n,crop:s??{left:0,top:0,width:r,height:i},alpha:e.alpha??"keep"};for(const m of wg){let g=m(this,f);if(ie(g)&&(g=await g),g!==null)return g}const{canvas:d,context:h,isNew:p}=Ju(f.width,f.height);return this._drawWithFitAndMipmapping(d,h,{fit:f.fit,rotation:f.rotation,crop:f.crop,targetIsFresh:p,fillBlack:f.alpha==="discard"}),new ln(d,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const wg=[],vg=3,ts=[];let Zu=0;const Ju=(t,e)=>{for(const i of ts)if(i.canvas.width===t&&i.canvas.height===e)return i.age=Zu++,{canvas:i.canvas,context:i.context,isNew:!1};let n;if(typeof OffscreenCanvas<"u")n=new OffscreenCanvas(t,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");n=document.createElement("canvas"),n.width=t,n.height=e}const r=n.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return ts.length>=vg&&ts.splice(lo(ts,i=>i.age),1),ts.push({canvas:n,context:r,age:Zu++}),{canvas:n,context:r,isNew:!0}};class $o{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const n=Object.keys(Xa);if(e.primaries!=null&&!n.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${n.join(", ")}.`);const r=Object.keys(Ga);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const i=Object.keys($a);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const ns=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,ef=(t,e,n)=>{const r=Math.min(t.left,e),i=Math.min(t.top,n),s=Math.min(t.width,e-r),a=Math.min(t.height,n-i);return R(s>=0),R(a>=0),{left:r,top:i,width:s,height:a}},tf=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},nf=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},kg=(t,e,n)=>{const r=sa(t),i=[];let s=0;for(const a of r){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(n/a.heightDivisor),u=o*a.sampleBytes,l=u*c;i.push({offset:s,stride:u}),s+=l}return i},sa=t=>{const e=(n,r,i,s,a)=>{const o=[{sampleBytes:n,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:i,heightDivisor:s},{sampleBytes:r,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:n,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Us(t),R(!1)}},rf=(t,e)=>{const n={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,i=Ag(n,r,t.codedWidth,t.codedHeight,t.format),s=e.layout;let a;if(!e.format||e.format===t.format)a=t.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Tg(i,a,s)},Ag=(t,e,n,r,i)=>{const s={...t};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>n)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!xg(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},xg=(t,e)=>{if(t===null)return!0;const n=sa(t);for(let r=0;r<n.length;r++){const i=n[r],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},Tg=(t,e,n)=>{const r=sa(e),i=r.length;if(n!==void 0&&n.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0;const a=[],o=[];for(let c=0;c<i;c++){const u=r[c],l=u.sampleBytes,f=u.widthDivisor,d=u.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(t.y||0)/d),h.sourceHeight=Math.ceil(Math.trunc(t.height||0)/d),h.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/f)*l,h.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/f)*l,n!==void 0){const g=n[c];if(g.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=g.offset,h.destinationStride=g.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let g=0;g<c;g++){const w=a[g];if(!(o[c]<=w.destinationOffset||o[g]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}};const sf=[],Sg=[];const Lr=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(t.skipLiveWait!==void 0&&typeof t.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},yi=t=>{if(!Os(t))throw new TypeError("timestamp must be a number.")},Qo=(t,e,n)=>n.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;const i=await t.determinePacketType(r);return i&&(r.type=i),r}):e;class Yo{constructor(e){if(!(e instanceof Ss))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Lr(e),this._track.input._disposed)throw new bt;return Qo(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Lr(e);const n=await this.getFirstPacket(e);return n?n.type==="key"?n:this.getNextKeyPacket(n,e):null}async getPacket(e,n={}){if(yi(e),Lr(n),this._track.input._disposed)throw new bt;return Qo(this._track,this._track._backing.getPacket(e,n),n)}async getNextPacket(e,n={}){if(!(e instanceof Ze))throw new TypeError("packet must be an EncodedPacket.");if(Lr(n),this._track.input._disposed)throw new bt;return Qo(this._track,this._track._backing.getNextPacket(e,n),n)}async getKeyPacket(e,n={}){if(yi(e),Lr(n),this._track.input._disposed)throw new bt;if(!n.verifyKeyPackets)return this._track._backing.getKeyPacket(e,n);const r=await this._track._backing.getKeyPacket(e,n);return r&&(R(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),n):r)}async getNextKeyPacket(e,n={}){if(!(e instanceof Ze))throw new TypeError("packet must be an EncodedPacket.");if(Lr(n),this._track.input._disposed)throw new bt;if(!n.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,n);const r=await this._track._backing.getNextKeyPacket(e,n);return r&&(R(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,n):r)}packets(e,n,r={}){if(e!==void 0&&!(e instanceof Ze))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(n!==void 0&&!(n instanceof Ze))throw new TypeError("endPacket must be an EncodedPacket.");if(Lr(r),this._track.input._disposed)throw new bt;const i=[];let{promise:s,resolve:a}=gt(),{promise:o,resolve:c}=gt(),u=!1,l=!1,f=null,d=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let g=e??await this.getFirstPacket(r);for(;g&&!l&&!this._track.input._disposed&&!(n&&g.sequenceNumber>=n?.sequenceNumber);){if(i.length>p()){({promise:o,resolve:c}=gt()),await o;continue}i.push(g),a(),{promise:s,resolve:a}=gt(),g=await this.getNextPacket(g,r)}u=!0,a()})().catch(g=>{d||(f=g,d=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new bt;if(l)return{value:void 0,done:!0};if(d)throw f;if(i.length>0){const g=i.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return l=!0,c(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}class Pg{constructor(e,n){this.onSample=e,this.onError=n}}class _g{mediaSamplesInRange(e=-1/0,n=1/0,r){yi(e),yi(n);const i=[];let s=!1,a=null,{promise:o,resolve:c}=gt(),{promise:u,resolve:l}=gt(),f=!1,d=!1,h=!1,p=null,m=null,g=!1;const w={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(P=>{if(l(),P.timestamp>=n&&(d=!0),d){P.close();return}a&&(P.timestamp>e?(i.push(a),s=!0):a.close()),P.timestamp>=e&&(i.push(P),s=!0),a=s?null:P,i.length>0&&(c(),{promise:o,resolve:c}=gt())},P=>{g||(m=P,g=!0,c())});const v=this._createPacketSink(),k=await v.getKeyPacket(e,w)??await v.getFirstKeyPacket(w);let A=k;const S=v.packets(k??void 0,void 0,w);for(await S.next();A&&!d&&!this._track.input._disposed;){const P=af(i.length);if(i.length+p.getDecodeQueueSize()>P){({promise:u,resolve:l}=gt()),await u;continue}p.decode(A);const M=await S.next();if(M.done)break;A=M.value}await S.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&i.push(a),f=!0,c()})().catch(v=>{g||(m=v,g=!0,c())}).finally(()=>{p?.close()});const y=this._track,b=()=>{a?.close();for(const v of i)v.close()};return{async next(){for(;;){if(y.input._disposed)throw h=!0,d=!0,b(),new bt;if(h)return{value:void 0,done:!0};if(g)throw h=!0,d=!0,b(),m;if(i.length>0){const v=i.shift();return l(),{value:v,done:!1}}else if(!f)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,d=!0,l(),c(),b(),{value:void 0,done:!0}},async throw(v){throw v},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,n){Wh(e);const r=Vh(e),i=[],s=[];let{promise:a,resolve:o}=gt(),{promise:c,resolve:u}=gt(),l=!1,f=!1,d=null,h=null,p=!1;const m=b=>{s.push(b),o(),{promise:a,resolve:o}=gt()},g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{d=await this._createDecoder(P=>{if(u(),f){P.close();return}let M=0;for(;i.length>0&&P.timestamp-i[0]>-1e-10;)M++,i.shift();if(M>0)for(let B=0;B<M;B++)m(B<M-1?P.clone():P);else P.close()},P=>{p||(h=P,p=!0,o())});const b=this._createPacketSink();let v=null,k=null,A=-1;const T=async()=>{R(k),R(d);let P=k;for(d.decode(P);P.sequenceNumber<A;){const M=af(s.length);for(;s.length+d.getDecodeQueueSize()>M&&!f;)({promise:c,resolve:u}=gt()),await c;if(f)break;const B=await b.getNextPacket(P,g);R(B),d.decode(B),P=B}A=-1},S=async()=>{R(d),await d.flush();for(let P=0;P<i.length;P++)m(null);i.length=0};for await(const P of r){if(yi(P),f||this._track.input._disposed)break;const M=await b.getPacket(P,g),B=M&&await b.getKeyPacket(P,g);if(!B){A!==-1&&(await T(),await S()),m(null),v=null;continue}v&&(B.sequenceNumber!==k.sequenceNumber||M.timestamp<v.timestamp)&&(await T(),await S()),i.push(M.timestamp),A=Math.max(M.sequenceNumber,A),v=M,k=B}!f&&!this._track.input._disposed&&(A!==-1&&await T(),await S()),l=!0,o()})().catch(b=>{p||(h=b,p=!0,o())}).finally(()=>{d?.close()});const w=this._track,y=()=>{for(const b of s)b?.close()};return{async next(){for(;;){if(w.input._disposed)throw f=!0,y(),new bt;if(f)return{value:void 0,done:!0};if(p)throw f=!0,y(),h;if(s.length>0){const b=s.shift();return R(b!==void 0),u(),{value:b,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}}},async return(){return f=!0,u(),o(),y(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}const af=t=>t===0?40:8;class Eg extends Pg{constructor(e,n,r,i,s,a){super(e,n),this.codec=r,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Gh,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=sf.find(c=>c.supports(r,i));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof ln))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoder.onError=c=>{n(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>n(c));else{const c=l=>{if(this.alphaQueue.length>0){const f=this.alphaQueue.shift();R(f!==void 0),this.mergeAlpha(l,f)}else this.colorQueue.push(l)};if(ao()){if(r==="avc"&&this.decoderConfig.description){const l=kl(Fn(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const f=Gs(l.sequenceParameterSets[0]);f&&f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}Qa(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:l=>{try{c(l)}catch(f){this.onError(f)}},error:l=>{l.stack=u,this.onError(l)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(R(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(n=>this.onError(n)).finally(()=>this.customDecoderQueueSize--);else{if(R(this.decoder),ro()||ol(this.inputTimestamps,e.timestamp,n=>n),ao()&&this.currentPacketIndex===0){if(this.codec==="avc"){const n=[];let r=!1;for(const s of bl(e.data,this.decoderConfig)){const a=qs(e.data[s.offset]);if(r||=a>=1&&a<=5,a===ut.AUD){if(r)break;n.length=0}a>=20&&a<=31||n.push(e.data.subarray(s.offset,s.offset+s.length))}const i=Jh(n,this.decoderConfig);e=new Ze(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const n=cm(e.data,this.decoderConfig);n&&(e=new Ze(n,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Cg),!this.alphaDecoder){const r=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();R(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();R(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{r(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const n=ko(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=n==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(n??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const n of $s(e,this.decoderConfig)){const r=ri(e[n.offset]);if(r===Ge.RASL_N||r===Ge.RASL_R)return!0}return!1}sampleHandler(e){if(ro()){if(this.sampleQueue.length>0&&e.timestamp>=Rt(this.sampleQueue).timestamp){for(const n of this.sampleQueue)this.finalizeAndEmitSample(n);this.sampleQueue.length=0}ol(this.sampleQueue,e,n=>n.timestamp)}else{const n=this.inputTimestamps.shift();R(n!==void 0),e.setTimestamp(n),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,n){const r=gt();this.mergeAlphaPromises.push(r.promise);const i={sample:null};this.finalSamples.push(i);try{if(!n)i.sample=new ln(e);else{R(this.merger);const s=await this.merger.merge(e,n);i.sample=new ln(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Ya(this.finalSamples,i),this.onError(s)}finally{Ya(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(R(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),ro()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(R(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Ko=null;class Cg{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,n){if(this.workers.length===0){if(!Ko){const o=new Blob([`(${Ig.toString()})()`],{type:"application/javascript"});Ko=URL.createObjectURL(o)}const a=zi(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(Ko);c.addEventListener("message",u=>{const l=u.data,f=this.pendingRequests.get(l.id);f&&(this.pendingRequests.delete(l.id),"error"in l?f.reject(new Error(l.error)):f.resolve(l.frame))}),c.addEventListener("error",u=>{const l=new Error(u.message||"Color/alpha merge worker error.");for(const f of this.pendingRequests.values())f.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}const r=this.nextRequestId++,i=gt();this.pendingRequests.set(r,i);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:r,color:e,alpha:n},{transfer:[e,n]}),i.promise}close(){for(const n of this.workers)n.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const n of this.pendingRequests.values())n.reject(e);this.pendingRequests.clear()}}const Ig=()=>{let t=null,e=null,n=Promise.resolve();self.addEventListener("message",c=>{const{id:u,color:l,alpha:f}=c.data;n=n.then(async()=>{try{const d=await r(l,f);self.postMessage({id:u,frame:d},{transfer:[d]})}catch(d){self.postMessage({id:u,error:d.message})}finally{l.close(),f.close()}})});const r=async(c,u)=>{const l=c.format,f=u.format;if(!l||!f)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const d=l.includes("P10"),h=l.includes("P12"),p=f.includes("P10"),m=f.includes("P12");if(p!==d||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${f}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await i(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await s(c,u,l);if(l==="NV12")return await a(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},i=async(c,u,l)=>{const f=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,h=f*d,p=new Uint8Array(h*4);await c.copyTo(p);const m=await o(u,f,d,1);for(let y=0,b=3;y<h;y++,b+=4)p[b]=m[y];const w={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:f,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,w)},s=async(c,u,l)=>{const f=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,h=l.includes("P10"),p=l.includes("P12"),m=h||p?2:1;let g,w;l.startsWith("I420")?(g=Math.ceil(f/2),w=Math.ceil(d/2)):l.startsWith("I422")?(g=Math.ceil(f/2),w=d):(g=f,w=d);const y=f*d,b=g*w,v=y*m,k=b*m,A=y*m,T=v+2*k+A,S=new Uint8Array(T);await c.copyTo(S);const P=await o(u,f,d,m),M=v+2*k;S.set(P,M);const N={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:f,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[S.buffer]};return new VideoFrame(S,N)},a=async(c,u)=>{const l=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,d=l*f,h=Math.ceil(l/2),p=Math.ceil(f/2),m=h*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);const w=new Uint8Array(d+2*m+d);w.set(e.subarray(0,d),0);const y=d,b=d+m,v=d;for(let T=0;T<m;T++)w[y+T]=e[v+T*2],w[b+T]=e[v+T*2+1];const k=await o(u,l,f,1);w.set(k,d+2*m);const A={format:"I420A",codedWidth:l,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,A)},o=async(c,u,l,f)=>{const d=c.allocationSize();(!t||t.byteLength!==d)&&(t=new Uint8Array(d)),await c.copyTo(t);const h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,m=u*l;for(let g=0;g<m;g++)t[g]=t[g*4+p];return t.subarray(0,m)}else return t.subarray(0,u*l*f)}},Mg=t=>{if(!t||typeof t!="object")throw new TypeError("decoderOptions must be an object.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Bg extends _g{constructor(e,n={}){if(!(e instanceof Jo))throw new TypeError("videoTrack must be an InputVideoTrack.");Mg(n),super(),this._track=e,this._decoderOptions=n}async _createDecoder(e,n){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Qh("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),i=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return R(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Eg(e,n,r,s,i,a)}_createPacketSink(){return new Yo(this._track)}async getSample(e,n={}){yi(e);for await(const r of this.mediaSamplesAtTimestamps([e],n))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,n,r={}){return this.mediaSamplesInRange(e,n,r)}samplesAtTimestamps(e,n={}){return this.mediaSamplesAtTimestamps(e,n)}}class Ss{constructor(e,n){this.input=e,this._backing=n}isVideoTrack(){return this instanceof Jo}isAudioTrack(){return this instanceof of}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return He(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return He(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return He(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return He(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return He(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){const n=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),r=(n?.timestamp??0)+(n?.duration??0);return ul(r,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,n){const r=new Yo(this);let i=1/0,s=-1/0,a=0,o=0;for await(const c of r.packets(void 0,void 0,{metadataOnly:!0,...n})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Ss))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Ur({filter:n=>n.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Ur({filter:n=>n.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Ur({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Ur({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Ur({filter:n=>n.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Zo(e);const n=await this.input.getTracks();for(const r of n)if(this.canBePairedWith(r)&&(!e||await e(r)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Zo(e),this.hasPairableTrack(async n=>n.isVideoTrack()&&(!e||await e(n)))}hasPairableAudioTrack(e){return e&&=Zo(e),this.hasPairableTrack(async n=>n.isAudioTrack()&&(!e||await e(n)))}}const He=(t,e,n)=>{if(ie(t))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return t},Zo=t=>{if(t!==void 0&&typeof t!="function")throw new TypeError("predicate, when provided, must be a function.");return t?e=>{const n=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},r=t(e);return ie(r)?r.then(n):n(r)}:void 0};class Jo extends Ss{constructor(e,n){super(e,n),this._pixelAspectRatioCache=null,this._backing=n}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return He(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return He(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return He(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return He(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return He(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return He(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=zs({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=zs({num:He(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*He(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:He(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*He(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){const i=He(e,"displayWidth","getDisplayWidth");if(i!==null)return i}const r=He(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return He(r,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){const i=He(e,"displayHeight","getDisplayHeight");if(i!==null)return i}const r=He(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return He(r,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const n=await this._backing.getCodec();return R(n!==null),sf.some(i=>i.supports(n,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return pe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ze))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const n=await this.getCodec();if(n===null)return null;const r=await this.getDecoderConfig();return R(r),ko(n,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!Os(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const n=await this.getTimeResolution(),r=e.targetPacketCount??256,i=new Yo(this),s=[];let a=-1/0,o=0;for await(const M of i.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=r&&M.timestamp>=a)break;s.push(M.timestamp),a=Math.max(a,M.timestamp),o++}const c=new Float64Array(s.length);for(let M=0;M<s.length;M++)c[M]=Math.round(s[M]*n);c.sort();let u=1;for(let M=1;M<c.length;M++)c[M]!==c[u-1]&&(c[u++]=c[M]);if(u<2)return{underlyingFrameRate:null,bestGuessFrameRate:n,minFrameRate:n,maxFrameRate:n,averageFrameRate:n,medianFrameRate:n,frameRateIsConstant:!0,probedPacketCount:o};const l=c.subarray(0,u),f=Rg(l,n),d=f??n,h=f!==null?n/f:null,p=new Map;let m=1/0,g=-1/0,w=0;for(let M=1;M<u;M++){const B=l[M]-l[M-1],N=h!==null?Math.max(1,Math.round(B/h)):B;p.set(N,(p.get(N)??0)+1),m=Math.min(m,N),g=Math.max(g,N),w+=N}const y=u-1,b=[...p.keys()].sort((M,B)=>M-B),v=y-1>>1,k=y>>1;let A=0,T=0,S=0;for(const M of b)if(S+=p.get(M),A===0&&S>v&&(A=M),S>k){T=M;break}const P=(d/A+d/T)/2;return{underlyingFrameRate:f,bestGuessFrameRate:f!==null?f:Fg(P),minFrameRate:d/g,maxFrameRate:d/m,averageFrameRate:d*y/w,medianFrameRate:P,frameRateIsConstant:f!==null&&m===1&&g===1,probedPacketCount:o}}}class of extends Ss{constructor(e,n){super(e,n),this._backing=n}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return He(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return He(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return He(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const n=await this._backing.getCodec();return R(n!==null),Sg.some(r=>r.supports(n,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return pe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ze))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const cf=t=>-(t??-1/0),rs=t=>-t,is=t=>{if(typeof t!="object"||!t)throw new TypeError("query must be an object.");if(t.filter!==void 0&&typeof t.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(t.sortBy!==void 0&&typeof t.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:t.filter?e=>{const n=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},r=t.filter(e);return ie(r)?r.then(n):n(r)}:void 0,sortBy:t.sortBy?e=>{const n=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},r=t.sortBy(e);return ie(r)?r.then(n):n(r)}:void 0}},Ur=(t,e)=>({filter:t?.filter||e?.filter?n=>{const r=t?.filter?.(n)??!0,i=s=>s===!1?!1:e?.filter?.(n)??!0;return ie(r)?r.then(i):i(r)}:void 0,sortBy:t?.sortBy||e?.sortBy?n=>{const r=t?.sortBy?.(n)??[],i=e?.sortBy?.(n)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return ie(r)||ie(i)?Promise.all([r,i]).then(([a,o])=>s(a,o)):s(r,i)}:void 0}),ec=async(t,e)=>{let n=t;if(e?.filter){const a=t.map(c=>e.filter(c));if(a.some(c=>ie(c))){const c=await Promise.all(a);n=t.filter((u,l)=>c[l])}else n=t.filter((c,u)=>a[u])}if(!e?.sortBy)return n;const r=n.map(a=>e.sortBy(a)),s=r.some(a=>ie(a))?await Promise.all(r):r;return n.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let f=0;f<l;f++){const d=c[f]??0,h=u[f]??0;if(d!==h)return d-h}return 0}).map(a=>a.track)},Rg=(t,e)=>{const i=1.000000001,s=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(t.length<2)return null;const o=new Float64Array(t.length-1);for(let T=1;T<t.length;T++){const S=t[T]-t[T-1];if(!(S>0))return null;o[T-1]=S}const c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let T=0;T<6;T++){let S=0,P=0;for(const B of o){const N=Math.max(1,Math.round(B/u));Math.abs(B-N*u)>=i||(S+=B,P+=N)}if(P===0)return null;const M=S/P;if(Math.abs(M-u)<=1e-12*Math.max(1,u)){u=M;break}u=M}let l=0,f=0,d=0;for(const T of o){const S=Math.max(1,Math.round(T/u));Math.abs(T-S*u)>=i||(l++,f+=T,d+=S)}if(l/o.length<.98)return null;u=f/d;const h=1/Math.min(d,s),p=Math.max(Number.EPSILON,u-h),m=u+h,g=e/m,w=e/p,y=e/u;let b=null,v=1/0;for(const T of a){if(T<g||T>w)continue;const S=Math.abs(T/y-1);S<v&&(b=T,v=S)}if(b===null){const T=lf(p,m,1e6),S=lf(g,w,1e6);if(S&&(!T||S.den<T.den||S.den===T.den&&S.num<=T.num))b=S.num/S.den;else if(T)b=e*T.den/T.num;else return null}const k=e/b;let A=0;for(const T of o){const S=Math.max(1,Math.round(T/k));Math.abs(T-S*k)<i&&A++}return A/o.length<.98?null:b},lf=(t,e,n)=>{for(let r=1;r<=n;r++){const i=Math.floor(t*r)+1;if(i/r<e)return zs({num:i,den:r})}return null},Fg=t=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],n=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,i=.025;for(const o of e)if(Math.abs(o/t-1)<=r)return o;let s=t,a=1/0;for(const o of n){const c=Math.abs(o/t-1);c<=i&&c<a&&(s=o,a=c)}return s};co();const Dg=1,Ng=2;class La extends fo{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(n=>!(n instanceof xn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof jn||e.source instanceof qo))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof jn&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof La))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&pg(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof jn?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){R(this._rootSource instanceof gi);const n=await this._rootSource._resolveRequest(e);return this._emit("source",{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=Dg){const r=this._sourceCache.find(a=>a.cacheGroup===n&&Nu(a.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const i=this._sourceCachePromises.find(a=>a.cacheGroup===n&&Nu(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(Vi(this._sourceCache,f=>f.cacheGroup===n&&f.sourceRef.source._refCount===1)>=4){const f=lo(this._sourceCache,h=>h.cacheGroup===n&&h.sourceRef.source._refCount===1?h.age:1/0);R(f!==-1);const d=this._sourceCache[f];this._sourceCache.splice(f,1),d.sourceRef.free(),Ya(this._sourceRefs,d.sourceRef)}this._sourceRefs.push(a);const u=this._sourceCachePromises.findIndex(f=>f.request===e);return R(u!==-1),this._sourceCachePromises.splice(u,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:n}})();return this._sourceCachePromises.push({request:e,cacheGroup:n,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new aa(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new uf})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),R(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof uf)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const n=e.filter(s=>s!==null);if(n.length===0)return 0;const r=await Promise.all(n.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),i=Math.min(...r.map(s=>s?.timestamp??1/0));return i===1/0?0:i}async computeDuration(e,n){e??=await this.getTracks();const r=e.filter(s=>s!==null);if(r.length===0)return 0;const i=await Promise.all(r.map(s=>s.computeDuration(n)));return Math.max(...i)}async getDurationFromMetadata(e,n){e??=await this.getTracks();const r=e.filter(a=>a!==null),s=(await Promise.all(r.map(a=>a.getDurationFromMetadata(n)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=is(e);const r=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return ec(r,e)}async getVideoTracks(e){e&&=is(e);const r=(await this.getTracks()).filter(i=>i.isVideoTrack());return ec(r,e)}async getAudioTracks(e){e&&=is(e);const r=(await this.getTracks()).filter(i=>i.isAudioTrack());return ec(r,e)}async getPrimaryVideoTrack(e){e&&=is(e);const n=Ur(e,{sortBy:async i=>[rs((await i.getDisposition()).default),rs(await i.hasPairableAudioTrack()),rs(!await i.hasOnlyKeyPackets()),cf(await i.getBitrate())]});return(await this.getVideoTracks(n))[0]??null}async getPrimaryAudioTrack(e){e&&=is(e);const n=await this.getPrimaryVideoTrack(),r=Ur(e,{sortBy:async s=>[rs(!n||s.canBePairedWith(n)),rs((await s.getDisposition()).default),cf(await s.getBitrate())]});return(await this.getAudioTracks(r))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){const n=this._backingToTrack.get(e);if(n)return n;const i=e.getType()==="video"?new Jo(this,e):new of(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class uf extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class bt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class aa{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,n){if(this.source._disposed)throw new bt;if(e<0||this.fileSizeNonStrict!==null&&e+n>this.fileSizeNonStrict)return null;if(n===0){const s=new Uint8Array(0);return new cn(s,Me(s),0,e,e)}const r=e+n,i=this.source._read(e,r,Fu,Du);return ie(i)?i.then(s=>s?new cn(s.bytes,s.view,s.offset,e,r):null):i?new cn(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new bt;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,zi(this.fileSizeNonStrict-e,n,r));{const i=this.requestSlice(e,r),s=a=>a||(R(this.fileSizeNonStrict!==null),this.requestSlice(e,zi(this.fileSizeNonStrict-e,n,r)));return ie(i)?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const n=[];let r=0;for(;;){if(n.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(r,0,e);if(ie(a)&&(a=await a),!a||a.length===0)break;const o=me(a,a.length);n.push(o),r+=a.length}const i=new Uint8Array(r);let s=0;for(const a of n)i.set(a,s),s+=a.length;return new cn(i,Me(i),0,0,r)})()}}class cn{constructor(e,n,r,i,s){this.bytes=e,this.view=n,this.offset=r,this.start=i,this.end=s,this.bufferPos=i-r}static tempFromBytes(e){return new cn(e,Me(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,n=this.end-e){if(e<this.start||e+n>this.end)throw new RangeError("Slicing outside of original slice.");return new cn(this.bytes,this.view,this.offset,e,e+n)}}const Nt=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},me=(t,e)=>{Nt(t,e);const n=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,n},de=t=>(Nt(t,1),t.view.getUint8(t.bufferPos++)),ss=(t,e)=>{Nt(t,2);const n=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,n},$e=t=>{Nt(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},qn=t=>{Nt(t,3);const e=ll(t.view,t.bufferPos);return t.bufferPos+=3,e},tc=t=>{Nt(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},cr=(t,e)=>{Nt(t,4);const n=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,n},ae=t=>{Nt(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},bi=t=>{Nt(t,4);const e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},Or=t=>{Nt(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},Lg=t=>{Nt(t,4);const e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},ff=(t,e)=>{let n,r;return e?(n=cr(t,!0),r=cr(t,!0)):(r=cr(t,!1),n=cr(t,!1)),r*4294967296+n},Wt=t=>{const e=ae(t),n=ae(t);return e*4294967296+n},Ug=t=>{const e=Or(t),n=ae(t);return e*4294967296+n},Og=t=>{const e=bi(t);return Lg(t)*4294967296+e},zg=t=>{Nt(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},df=t=>{Nt(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},je=(t,e)=>{Nt(t,e);let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t.bytes[t.bufferPos++]);return n},hf=(t,e,n)=>Ft.decode(me(t,e)).split(`
2
- `).map(s=>s.trim()).filter(s=>s.length>0&&!n?.ignore?.(s));var zr;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(zr||(zr={}));var wi;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(wi||(wi={}));const oa=128,Yt=10,vi=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Hg=(t,e)=>{const n=t.filePos;e.raw??={},e.raw.TAG??=me(t,oa-3),t.filePos=n;const r=ki(t,30);r&&(e.title??=r);const i=ki(t,30);i&&(e.artist??=i);const s=ki(t,30);s&&(e.album??=s);const a=ki(t,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));const c=me(t,30);let u;if(c[28]===0&&c[29]!==0){const f=c[29];f>0&&(e.trackNumber??=f),t.skip(-30),u=ki(t,28),t.skip(2)}else t.skip(-30),u=ki(t,30);u&&(e.comment??=u);const l=de(t);l<vi.length&&(e.genre??=vi[l])},ki=(t,e)=>{const n=me(t,e),r=ni(n.indexOf(0),n.length),i=n.subarray(0,r);let s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},Xn=t=>{const e=t.filePos,n=je(t,3),r=de(t),i=de(t),s=de(t),a=ae(t);if(n!=="ID3"||r===255||i===255||(a&2155905152)!==0)return t.filePos=e,null;let o=Co(a);return s&zr.Footer&&(o+=Yt),{majorVersion:r,revision:i,flags:s,size:o}},ca=(t,e,n)=>{if(![2,3,4].includes(e.majorVersion)){pe._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const r=e.flags&zr.Footer?e.size-Yt:e.size,i=me(t,r),s=new Vg(e,i);if(e.flags&zr.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&zr.ExtendedHeader){const a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const a=s.readId3V2Frame();if(!a)break;const o=s.pos,c=s.pos+a.size;let u=!1,l=!1,f=!1;if(e.majorVersion===3?(u=!!(a.flags&64),l=!!(a.flags&128)):e.majorVersion===4&&(u=!!(a.flags&4),l=!!(a.flags&8),f=!!(a.flags&2)||!!(e.flags&zr.Unsynchronisation)),u){pe._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(l){pe._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(f&&s.ununsynchronizeRegion(s.pos,c),n.raw??={},a.id==="TXXX"){const d=n.raw.TXXX??={},h=s.readId3V2TextEncoding(),p=s.readId3V2Text(h,c),m=s.readId3V2Text(h,c);d[p]??=m}else a.id[0]==="T"?n.raw[a.id]??=s.readId3V2EncodingAndText(c):n.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":n.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":n.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":n.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":n.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":n.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(n.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(n.tracksTotal??=m)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(n.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(n.discsTotal??=m)}break;case"TCON":case"TCO":{const d=s.readId3V2EncodingAndText(c);let h=/^\((\d+)\)/.exec(d);if(h){const p=Number.parseInt(h[1]);if(vi[p]!==void 0){n.genre??=vi[p];break}}if(h=/^\d+$/.exec(d),h){const p=Number.parseInt(h[0]);if(vi[p]!==void 0){n.genre??=vi[p];break}}n.genre??=d}break;case"TDRC":case"TDAT":{const d=s.readId3V2EncodingAndText(c),h=new Date(d);Number.isNaN(h.getTime())||(n.date??=h)}break;case"TYER":case"TYE":{const d=s.readId3V2EncodingAndText(c),h=Number.parseInt(d,10);Number.isInteger(h)&&(n.date??=new Date(String(h)))}break;case"USLT":case"ULT":{const d=s.readU8();s.pos+=3,s.readId3V2Text(d,c),n.lyrics??=s.readId3V2Text(d,c)}break;case"COMM":case"COM":{const d=s.readU8();s.pos+=3,s.readId3V2Text(d,c),n.comment??=s.readId3V2Text(d,c)}break;case"APIC":case"PIC":{const d=s.readId3V2TextEncoding();let h;if(e.majorVersion===2){const w=s.readAscii(3);h=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(d,c);const p=s.readU8(),m=s.readId3V2Text(d,c).trimEnd(),g=c-s.pos;if(g>=0){const w=s.readBytes(g);n.images||(n.images=[]),n.images.push({data:w,mimeType:h,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}};class Vg{constructor(e,n){this.header=e,this.bytes=n,this.pos=0,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let n=0;n<this.bytes.length;n++){const r=this.bytes[n];e.push(r),r===255&&n!==this.bytes.length-1&&this.bytes[n]===0&&n++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,n){const r=[];for(let a=e;a<n;a++){const o=this.bytes[a];r.push(o),o===255&&a!==n-1&&this.bytes[a+1]===0&&a++}const i=this.bytes.subarray(0,e),s=this.bytes.subarray(n);this.bytes=new Uint8Array(i.length+r.length+s.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(s,i.length+r.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){const n=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,n}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),n=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+n}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,n}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const n=this.readU24();return{id:e,size:n,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const n=this.readU32();let r=this.header.majorVersion===4?Co(n):n;const i=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!a(r)){const o=this.header.majorVersion===4?n:Co(n);a(o)&&(r=o)}return this.pos=s,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,n){const r=this.pos,i=this.readBytes(n-this.pos);switch(e){case wi.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){const o=i[a];if(o===0){this.pos=r+a+1;break}s+=String.fromCharCode(o)}return s}case wi.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){const s=new TextDecoder("utf-16le"),a=ni(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){const s=new TextDecoder("utf-16be"),a=ni(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{const s=ni(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Ft.decode(i.subarray(0,s))}case wi.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=ni(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case wi.UTF_8:{const s=ni(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Ft.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const n=this.readId3V2TextEncoding();return this.readId3V2Text(n,e)}}function mf(){return typeof VideoDecoder=="function"&&typeof VideoFrame=="function"}const pf=6,gf=16;function Wg(t){const e=document.createElement("canvas");e.style.cssText=t.cssText,t.container.appendChild(e);const n=e.getContext("2d",{alpha:!1});if(!n)return e.remove(),queueMicrotask(()=>t.onFatal("2d \u4E0A\u4E0B\u6587\u521B\u5EFA\u5931\u8D25")),{canvas:e,pause(){},resume(){},destroy(){}};n.imageSmoothingEnabled=!0,n.imageSmoothingQuality="high";let r=!1,i=0,s=performance.now(),a=0,o=!1;const c=()=>{const B=Math.min(window.devicePixelRatio||1,t.renderDpr||1),N=Math.max(1,Math.round((t.container.clientWidth||window.innerWidth)*B)),O=Math.max(1,Math.round((t.container.clientHeight||window.innerHeight)*B));e.width!==N&&(e.width=N),e.height!==O&&(e.height=O)};c(),window.addEventListener("resize",c);const u=[];let l=null,f=null,d=null,h=0,p=0,m=pf,g=0,w=!1,y=-1,b=0,v=!1;const k=B=>{const N=e.width,O=e.height,q=B.displayWidth,H=B.displayHeight;if(N<=0||O<=0||q<=0||H<=0)return;const G=t.fit();if(G==="stretch"){B.draw(n,0,0,N,O);return}const Y=G==="cover"?Math.max(N/q,O/H):Math.min(N/q,O/H),J=Math.round(q*Y),ne=Math.round(H*Y),fe=Math.round((N-J)/2),Ne=Math.round((O-ne)/2);G==="contain"&&(n.fillStyle="#000",n.fillRect(0,0,N,O)),B.draw(n,fe,Ne,J,ne)},A=()=>h+(performance.now()-s)/1e3%p,T=()=>{g++,m<gf&&g%30===1&&(m=Math.min(gf,m+2),!w&&m>=pf+4&&(w=!0,t.onDiag?.(`\u5FAA\u73AF\u70B9\u89E3\u7801\u7A7A\u7A97\uFF0C\u524D\u77BB\u52A0\u6DF1\u81F3 ${m} \u5E27`)))},S=()=>{if(r||(i=requestAnimationFrame(S),o||t.paused()||p<=0))return;const B=A();for(;u.length>0;){const H=u[0],G=u[1];if(H.timestamp-B>p/2){H.close(),u.shift();continue}if(G&&G.timestamp<=B+1e-4){H.close(),u.shift();continue}break}const N=u[0];if(!N){T();return}if(N.timestamp>B+1e-4||N.timestamp===y)return;const O=t.fps(),q=performance.now();if(!(O>0&&q-b<1e3/O-.5)){y=N.timestamp,b=q;try{k(N)}catch{return}t.onFrame?.(),v||(v=!0,t.onFirstFrame?.())}},P=B=>new Promise(N=>setTimeout(N,B)),M=async()=>{try{for(;!r;){for(;!r&&(u.length>=m||o||t.paused());)await P(20);if(r)return;d||(d=f.samples(h));const B=await d.next();if(r){B.value?.close();return}if(B.done){d=null;continue}u.push(B.value)}}catch(B){r||t.onFatal(`\u89E3\u7801\u6CF5\u5F02\u5E38: ${B?.message??B}`)}};return(async()=>{try{l=new La({source:new qc(t.src),formats:mg});const B=await l.getPrimaryVideoTrack();if(!B)throw new Error("\u65E0\u89C6\u9891\u8F68");if(!await B.canDecode())throw new Error(`\u7F16\u7801\u4E0D\u53EF\u89E3\uFF08${B.codec}\uFF09`);const N=await B.computeDuration();if(h=await B.getFirstTimestamp(),p=Math.max(N-h,N>0?N:0),!isFinite(p)||p<=0)throw new Error("\u65F6\u957F\u5F02\u5E38");if(r){try{l.dispose()}catch{}return}f=new Bg(B);const O=await B.getDisplayWidth(),q=await B.getDisplayHeight();t.onDiag?.(`${B.codec} ${O}x${q} ${p.toFixed(2)}s \u2192 WebCodecs \u9010\u5E27\u8C03\u5EA6`),M(),i=requestAnimationFrame(S)}catch(B){r||t.onFatal(B?.message??String(B))}})(),{canvas:e,pause(){o||(o=!0,a=performance.now())},resume(){o&&(o=!1,s+=performance.now()-a)},destroy(){if(!r){r=!0,i&&cancelAnimationFrame(i),i=0,window.removeEventListener("resize",c);for(const B of u.splice(0))try{B.close()}catch{}d&&d.return(void 0).catch(()=>{});try{l?.dispose()}catch{}e.remove()}}}}function jg(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<16)throw new Error("\u6587\u4EF6\u592A\u5C0F\uFF0C\u4E0D\u662F scene.pkg");const n=e.getUint32(0,!0);if(n<4||n>16)throw new Error("\u9B54\u6570\u957F\u5EA6\u5F02\u5E38: "+n);const r=yf(t,4,n);if(!r.startsWith("PKGV"))throw new Error("\u4E0D\u662F scene.pkg\uFF0C\u9B54\u6570: "+r);const i=e.getUint32(4+n,!0);let s=4+n+4;const a=[];for(let c=0;c<i;c++){if(s+8>t.length)throw new Error("\u5165\u53E3\u8868\u8D8A\u754C @"+c);const u=e.getUint32(s,!0);if(s+=4,s+u+8>t.length)throw new Error("\u5165\u53E3 "+c+" \u8D8A\u754C");const l=Xg(t,s,u);s+=u;const f=e.getUint32(s,!0);s+=4;const d=e.getUint32(s,!0);s+=4,a.push({name:l,offset:f,size:d})}const o=s;return{magic:r,version:r.slice(4),count:i,entries:a,dataStart:o,fileSize:t.length,buf:t}}function nc(t,e){const n=t.entries.find(s=>s.name===e);if(n===void 0)return null;const r=t.dataStart+n.offset,i=r+n.size;if(r<0||i>t.fileSize)throw new Error("\u5165\u53E3 "+e+" \u8D8A\u754C");return t.buf.subarray(r,i)}function qg(t){let e=0;for(const n of t.entries)e=Math.max(e,n.offset+n.size);return{dataEnd:t.dataStart+e,fileSize:t.fileSize,ok:t.dataStart+e<=t.fileSize}}function yf(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}function Xg(t,e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t.subarray(e,e+n))}catch{return yf(t,e,n)}}const Gg=Object.freeze(Object.defineProperty({__proto__:null,getEntry:nc,parsePkg:jg,verifyLayout:qg},Symbol.toStringTag,{value:"Module"})),rc={0:"ARGB8888",1:"RGB888",2:"RGB565",4:"DXT5",6:"DXT3",7:"DXT1",8:"RG88",9:"R8",10:"RG1616f",11:"R16f",12:"BC7",13:"RGBa1010102",14:"RGBA16161616f",15:"RGB161616f"},lr={UNKNOWN:-1,JPEG:2,PNG:13,GIF:25,WEBP:35,MP4:35};function $g(t){const e=t.images[0];if(!e||e.length===0)throw new Error("\u65E0\u56FE\u50CF\u6570\u636E");const n=e[0];if(t.isVideo)return{width:n.width,height:n.height,video:n.data};if(t.freeImageFormat===lr.PNG)return{width:n.width,height:n.height,png:n.data};if(t.freeImageFormat!==lr.UNKNOWN)return{width:n.width,height:n.height,image:n.data,fif:t.freeImageFormat};const r=ic(t.format,n.data,n.width,n.height);return!t.frames?.list?.length&&(n.width!==t.width||n.height!==t.height)?{width:t.width,height:t.height,rgba:bf(r,n.width,n.height,t.width,t.height)}:{width:n.width,height:n.height,rgba:r}}function Qg(t){const e=t.images[0];if(!e||e.length===0)throw new Error("\u65E0\u56FE\u50CF\u6570\u636E");const n=[];for(const r of e){if(t.freeImageFormat!==lr.UNKNOWN){n.push({width:r.width,height:r.height,image:r.data,fif:t.freeImageFormat});continue}const i=ic(t.format,r.data,r.width,r.height);n.push({width:r.width,height:r.height,rgba:i})}return!t.frames?.list?.length&&n.length>0&&(n[0].width!==t.width||n[0].height!==t.height)&&n[0].rgba&&(n[0]={width:t.width,height:t.height,rgba:bf(n[0].rgba,n[0].width,n[0].height,t.width,t.height)}),n}function bf(t,e,n,r,i){const s=new Uint8Array(r*i*4);for(let a=0;a<i;a++)s.set(t.subarray(a*e*4,a*e*4+r*4),a*r*4);return s}function ic(t,e,n,r){switch(t){case 0:return Yg(e,n,r);case 1:return Kg(e,n,r);case 2:return Zg(e,n,r);case 4:return r0(e,n,r);case 6:return n0(e,n,r);case 7:return t0(e,n,r);case 8:return Jg(e,n,r);case 9:return e0(e,n,r);case 12:throw new Error("BC7 \u89E3\u7801\u6682\u672A\u5B9E\u73B0\uFF08format=12\uFF09");default:throw new Error("\u672A\u652F\u6301\u7684\u7EB9\u7406\u683C\u5F0F: "+(rc[t]||t))}}function Yg(t,e,n){return new Uint8Array(t.buffer,t.byteOffset,e*n*4).slice()}function Kg(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i*3],r[i*4+1]=t[i*3+1],r[i*4+2]=t[i*3+2],r[i*4+3]=255;return r}function Zg(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++){const s=t[i*2]|t[i*2+1]<<8,a=s>>11&31,o=s>>5&63,c=s&31;r[i*4]=a<<3|a>>2,r[i*4+1]=o<<2|o>>4,r[i*4+2]=c<<3|c>>2,r[i*4+3]=255}return r}function Jg(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i*2+1],r[i*4+1]=t[i*2+1],r[i*4+2]=t[i*2+1],r[i*4+3]=t[i*2];return r}function e0(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i],r[i*4+1]=t[i],r[i*4+2]=t[i],r[i*4+3]=255;return r}function t0(t,e,n){return sc(t,e,n,!0,0)}function n0(t,e,n){return sc(t,e,n,!1,3)}function r0(t,e,n){return sc(t,e,n,!1,5)}function sc(t,e,n,r,i){const s=new Uint8Array(e*n*4),a=r?8:16,o=new Uint8Array(16);let c=0;for(let u=0;u<n;u+=4)for(let l=0;l<e;l+=4){if(c+a>t.length)return s;o.set(t.subarray(c,c+a)),c+=a;const f=i0(o,r),d=s0(o,r),h=i===3?a0(o):i===5?o0(o):null;for(let p=0;p<4;p++)for(let m=0;m<4;m++){const g=l+m,w=u+p;if(g>=e||w>=n)continue;const y=p*4+m,b=(w*e+g)*4;s[b]=f[d[y]*4],s[b+1]=f[d[y]*4+1],s[b+2]=f[d[y]*4+2],s[b+3]=h!==null?h[y]:f[d[y]*4+3]}}return s}function wf(t,e){const n=t[e]|t[e+1]<<8,r=n>>11&31,i=n>>5&63,s=n&31;return[n,r<<3|r>>2,i<<2|i>>4,s<<3|s>>2]}function i0(t,e){const n=e?0:8,r=wf(t,n),i=wf(t,n+2),s=new Uint8Array(16);return s[0]=r[1],s[1]=r[2],s[2]=r[3],s[3]=255,s[4]=i[1],s[5]=i[2],s[6]=i[3],s[7]=255,e&&r[0]<=i[0]?(s[8]=r[1]+i[1]>>1,s[9]=r[2]+i[2]>>1,s[10]=r[3]+i[3]>>1,s[11]=255,s[12]=0,s[13]=0,s[14]=0,s[15]=0):(s[8]=Math.floor((2*r[1]+i[1])/3),s[9]=Math.floor((2*r[2]+i[2])/3),s[10]=Math.floor((2*r[3]+i[3])/3),s[11]=255,s[12]=Math.floor((r[1]+2*i[1])/3),s[13]=Math.floor((r[2]+2*i[2])/3),s[14]=Math.floor((r[3]+2*i[3])/3),s[15]=255),s}function s0(t,e){const n=e?4:12,r=new Uint8Array(16);for(let i=0;i<4;i++){const s=t[n+i];r[i*4]=s&3,r[i*4+1]=s>>2&3,r[i*4+2]=s>>4&3,r[i*4+3]=s>>6&3}return r}function a0(t){const e=new Uint8Array(16);for(let n=0;n<8;n++){const r=t[n],i=r&15,s=r&240;e[2*n]=i|i<<4,e[2*n+1]=s|s>>4}return e}function o0(t){const e=t[0],n=t[1],r=new Uint8Array(8);if(r[0]=e,r[1]=n,e<=n){for(let o=1;o<5;o++)r[1+o]=Math.floor(((5-o)*e+o*n)/5);r[6]=0,r[7]=255}else for(let o=1;o<7;o++)r[o+1]=Math.floor(((7-o)*e+o*n)/7);const i=new Uint8Array(16);let s=0;for(let o=0;o<2;o++){let c=0;for(let u=0;u<3;u++)c|=t[2+o*3+u]<<8*u;for(let u=0;u<8;u++)i[s++]=c>>3*u&7}const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=r[i[o]];return a}function vf(t,e){const n=new Uint8Array(e);let r=0,i=0;for(;r<t.length;){const s=t[r++];let a=s>>4;if(a===15){let l;do l=t[r++],a+=l;while(l===255)}for(let l=0;l<a;l++)n[i++]=t[r++];if(r>=t.length)break;const o=t[r]|t[r+1]<<8;r+=2;let c=4+(s&15);if((s&15)===15){let l;do l=t[r++],c+=l;while(l===255)}const u=i-o;for(let l=0;l<c;l++)n[i++]=n[u+l]}return n}function ot(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function kf(t,e){return ot(t,e)|0}const as=new DataView(new ArrayBuffer(4));function ur(t,e){return as.setUint8(0,t[e]),as.setUint8(1,t[e+1]),as.setUint8(2,t[e+2]),as.setUint8(3,t[e+3]),as.getFloat32(0,!0)}function c0(t){let e=0;const n=la(t,e,9);if(e+=9,n!=="TEXV0005\0")throw new Error("\u4E0D\u662F .tex \u6587\u4EF6: "+n);const r=la(t,e,9);if(e+=9,r!=="TEXI0001\0")throw new Error("\u672A\u77E5 TEXI \u5B50\u5BB9\u5668: "+r);const i=ot(t,e);e+=4;const s=ot(t,e);e+=4;const a=ot(t,e);e+=4;const o=ot(t,e);e+=4;const c=ot(t,e);e+=4;const u=ot(t,e);e+=4,e+=4;const l=la(t,e,9);e+=9;const f=ot(t,e);e+=4;let d=lr.UNKNOWN,h=0;if(l==="TEXB0004\0"){d=ot(t,e)|0,e+=4;const v=ot(t,e);e+=4,d===lr.UNKNOWN&&v===1&&(d=lr.MP4),h=v===1?4:3}else if(l==="TEXB0003\0")d=ot(t,e)|0,e+=4,h=3;else if(l==="TEXB0002\0")h=2;else if(l==="TEXB0001\0")h=1;else throw new Error("\u672A\u77E5 TEXB \u5BB9\u5668: "+l);const p=(s&32)!==0||d===lr.MP4,m=[];for(let v=0;v<f;v++){const k=ot(t,e);e+=4;const A=[];for(let T=0;T<k;T++){if(h===4){for(e+=8;e<t.length&&t[e]!==0;)e++;e+=1,e+=4}const S=ot(t,e);e+=4;const P=ot(t,e);e+=4;let M=0,B=0;h>=2&&(M=ot(t,e),e+=4,B=kf(t,e),e+=4);const N=kf(t,e);if(e+=4,p){A.push({width:S,height:P,compression:0,data:t.subarray(e)}),e=t.length;continue}M===0&&(B=N);const O=t.subarray(e,e+N);e+=N;let q=O;M===1&&(q=vf(O,B)),A.push({width:S,height:P,compression:M,data:q})}m.push(A)}const g=m[0]&&m[0][0],w=g?g.width:a,y=g?g.height:o;let b=null;if(e+13<=t.length){const v=la(t,e,9);if(v.indexOf("TEXS")===0){let k=e+9;const A=ot(t,k);k+=4;let T=0,S=0;v==="TEXS0003\0"&&(T=ot(t,k),k+=4,S=ot(t,k),k+=4);const P=t.length-k,M=A>0&&P>0&&P%A===0?P/A:0;if(A>0&&A<=4096&&M>=32){const B=[];for(let O=0;O<A;O++){const q=k+O*M;if(q+32>t.length)break;const H=ur(t,q+8),G=ur(t,q+12),Y=ur(t,q+16),J=ur(t,q+20),ne=ur(t,q+24),fe=ur(t,q+28);B.push({imageId:ur(t,q)|0,duration:ur(t,q+4),x:H,y:G,width:Math.hypot(Y,J)||T,height:Math.hypot(ne,fe)||S,uDir:[Y,J],vDir:[ne,fe],rotated:Math.abs(J)>.5||Math.abs(ne)>.5})}B.length===A&&B.every(O=>{if(!(O.width>0&&O.height>0))return!1;const q=[O.x,O.x+O.uDir[0],O.x+O.vDir[0],O.x+O.uDir[0]+O.vDir[0]],H=[O.y,O.y+O.uDir[1],O.y+O.vDir[1],O.y+O.uDir[1]+O.vDir[1]];return Math.min(...q)>=-1&&Math.max(...q)<=w+1&&Math.min(...H)>=-1&&Math.max(...H)<=y+1})&&(b={magic:v,frameWidth:T,frameHeight:S,atlasWidth:w,atlasHeight:y,list:B})}}}return{format:i,formatName:rc[i]||String(i),flags:s,textureWidth:a,textureHeight:o,width:c,height:u,freeImageFormat:d,containerMagic:l,containerVersion:h,isVideo:p,images:m,frames:b}}function la(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}const l0=Object.freeze(Object.defineProperty({__proto__:null,FIF:lr,TEXTURE_FORMATS:rc,decodeMip0:$g,decodeMips:Qg,decodePixels:ic,lz4Decompress:vf,parseTex:c0},Symbol.toStringTag,{value:"Module"}));function u0(t,e,n){const r=Math.max(0,Number(n)||0),i=Math.max(1,Number(t)||1),s=Math.max(1,Number(e)||1);return r*2>=Math.min(i,s)?0:r}function f0(t,e,n){const r=Math.max(1,e.boxW),i=Math.max(1,e.boxH),s=e.spacing||[0,0],a=Math.max(1,e.lineHeight||(e.pointsize||24)*1.25+s[1]),o=e.limitwidth&&e.maxwidth>0?e.maxwidth:1/0;function c(v){if(n(v)<=o)return[v];const k=[];let A="",T=-1;for(const S of v)if(A+=S,(S===" "||S===" ")&&(T=A.length),n(A)>o&&A.length>1)for(T>0?(k.push(A.slice(0,T-1)),A=A.slice(T)):(k.push(A.slice(0,-1)),A=S),T=-1;n(A)>o&&A.length>1;)k.push(A.slice(0,-1)),A=A.slice(-1);return A!==""&&k.push(A),k.length?k:[""]}let u=[];const l=String(t??"").split(`
3
- `);for(const v of l)u.push(...c(v));let f=!1;if(e.limitrows&&e.maxrows>0&&u.length>e.maxrows&&(u=u.slice(0,e.maxrows),f=!0,e.limituseellipsis)){let v=u[e.maxrows-1];for(;v.length>0&&n(v+"\u2026")>o;)v=v.slice(0,-1);u[e.maxrows-1]=v+"\u2026"}const d=u.map(v=>n(v)),h=u.length*a,p=e.halign||"center",m=e.valign||"center",g=r/2,w=i/2,y=m==="top"?w:m==="bottom"?w-h:(i-h)/2;return{lines:u.map((v,k)=>{const A=d[k],T=p==="left"?g:p==="right"?g-A:(r-A)/2;return{text:v,width:A,x:T,y:y+k*a}}),lineHeight:a,totalH:h,truncated:f,boxW:r,boxH:i}}function Af(t,e,n){let r=1/0,i=-1/0,s=1/0,a=-1/0;for(const o of t.lines||[])r=Math.min(r,o.x),i=Math.max(i,o.x+o.width),s=Math.min(s,o.y),a=Math.max(a,o.y+(t.lineHeight||0));return!t.lines||!t.lines.length?[0,0,0,0]:[Math.max(0,-r),Math.max(0,-s),Math.max(0,i-e),Math.max(0,a-n)]}function d0(t,e,n,r){const[i,s,a,o]=Af(t,e,n);return Math.max(r,i,s,a,o)}function h0(t,e,n){return t<=4&&e<=4&&!!n}function m0(t,e,n){const r=e.boxW,i=e.boxH,s=n.color||[1,1,1],a=n.alpha!==void 0?n.alpha:1,o=n.brightness!==void 0?n.brightness:1;t.font=n.font;try{t.letterSpacing=(n.spacing&&n.spacing[0]?n.spacing[0]:0)+"px"}catch{}if(t.textBaseline="middle",n.opaquebackground){const u=n.backgroundcolor||[0,0,0],l=n.backgroundbrightness!==void 0?n.backgroundbrightness:1;t.fillStyle=`rgba(${Math.round(u[0]*255*l)},${Math.round(u[1]*255*l)},${Math.round(u[2]*255*l)},${a})`,t.fillRect(0,0,r,i)}const c=(u,l,f)=>{t.fillStyle=f;for(const d of e.lines)t.fillText(d.text,d.x+u,d.y+e.lineHeight/2+l)};if(n.castshadow){const u=Math.max(1,(n.pointsize||24)/10);c(u,u,`rgba(0,0,0,${a*.75})`)}c(0,0,`rgba(${Math.round(s[0]*255*o)},${Math.round(s[1]*255*o)},${Math.round(s[2]*255*o)},${a})`)}const xf=/^add[A-Z]/;function Tf(){return{log:()=>{},warn:()=>{},error:()=>{},info:()=>{},debug:()=>{}}}function Sf(t){return new Proxy(t,{get(e,n,r){const i=Reflect.get(e,n,r);if(i==null&&typeof n=="string"&&n!=="then"){const s=()=>{};return e[n]=s,s}return i}})}function Ai(t,e){return()=>{}}function Pf(t,e){t.isScreensaver=!!e.isScreensaver,typeof e.isRunningInEditor=="boolean"&&(t.isRunningInEditor=oc(e.isRunningInEditor)),t.setInterval||(t.setInterval=e.setInterval||Ai),t.setTimeout||(t.setTimeout=e.setTimeout||Ai),t.clearTimeout||(t.clearTimeout=e.clearTimeout||(()=>{})),t.clearInterval||(t.clearInterval=e.clearInterval||(()=>{})),typeof e.openUserShortcut=="function"&&(t.openUserShortcut=e.openUserShortcut);const n=e.mediaControl||null;t.media={skipNext:()=>{if(n&&n.skipNext)return n.skipNext()},skipPrevious:()=>{if(n&&n.skipPrevious)return n.skipPrevious()},play:()=>{if(n&&n.play)return n.play()},pause:()=>{if(n&&n.pause)return n.pause()},playPause:()=>{if(n&&n.playPause)return n.playPause()},get snapshot(){return n&&n.snapshot?n.snapshot:null}};const r=e.windowTitle;Object.defineProperty(t,"windowTitle",{configurable:!0,enumerable:!0,get(){return r&&r.title?String(r.title):""}}),Object.defineProperty(t,"windowApp",{configurable:!0,enumerable:!0,get(){return r&&r.app?String(r.app):""}})}class Te{constructor(e,n,r){if(e!==null&&typeof e=="object")this.x=e.x!==void 0?e.x:e.width||0,this.y=n!==void 0?n:e.y!==void 0?e.y:e.height||0,this.z=r!==void 0?r:e.z||0;else if(n===void 0&&r===void 0){const i=Number(e)||0;this.x=i,this.y=i,this.z=i}else this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){const n=new Te(e);return new Te(this.x+n.x,this.y+n.y,this.z+n.z)}subtract(e){const n=new Te(e);return new Te(this.x-n.x,this.y-n.y,this.z-n.z)}multiply(e){return e&&typeof e=="object"?new Te(this.x*e.x,this.y*e.y,this.z*e.z):new Te(this.x*e,this.y*e,this.z*e)}divide(e){const n=(r,i)=>i===0?0:r/i;return e&&typeof e=="object"?new Te(n(this.x,e.x),n(this.y,e.y),n(this.z,e.z)):new Te(n(this.x,e),n(this.y,e),n(this.z,e))}copy(){return new Te(this.x,this.y,this.z)}mix(e,n){const r=new Te(e),i=Number(n),s=Number.isFinite(i)?i:0;return new Te(this.x+(r.x-this.x)*s,this.y+(r.y-this.y)*s,this.z+(r.z-this.z)*s)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSqr(){return this.x*this.x+this.y*this.y+this.z*this.z}normalize(){const e=this.length();return e===0?new Te(0,0,0):new Te(this.x/e,this.y/e,this.z/e)}dot(e){const n=new Te(e);return this.x*n.x+this.y*n.y+this.z*n.z}toString(){return this.x+" "+this.y+" "+this.z}}const _f=Te;function ac(t){if(t instanceof Te||!t||typeof t!="object"||Array.isArray(t)||!("x"in t)&&!("y"in t)&&!("z"in t)||Object.getPrototypeOf(t)===Te.prototype)return t;try{Object.setPrototypeOf(t,Te.prototype)}catch{}return t}function Ef(t){return t&&t.cursorWorldPosition?t:{cursorWorldPosition:new Te(0,0,0),cursorScreenPosition:new Te(0,0,0),cursorPosition:new Te(0,0,0),cursorPositionLast:new Te(0,0,0),cursorLeftDown:!1}}function p0(t,e,n){return new Te(t||0,e||0,n||0)}function g0(){const t={cursorWorldPosition:new Te(0,0,0),cursorScreenPosition:new Te(0,0,0),cursorPosition:new Te(0,0,0),cursorPositionLast:new Te(0,0,0),cursorLeftDown:!1};return t.update=function(e){return e&&(t.cursorWorldPosition.x=e.wx,t.cursorWorldPosition.y=e.originY!=null?e.originY:e.wy,t.cursorWorldPosition.z=0,t.cursorScreenPosition.x=e.screenX,t.cursorScreenPosition.y=e.screenY,t.cursorScreenPosition.z=0,t.cursorPosition.x=e.u,t.cursorPosition.y=e.v,t.cursorPosition.z=0,t.cursorPositionLast.x=e.lastU,t.cursorPositionLast.y=e.lastV,t.cursorPositionLast.z=0,t.cursorLeftDown=!!e.leftDown),t},t}const Cf={mix:(t,e,n)=>t+(e-t)*n,lerp:(t,e,n)=>t+(e-t)*n,clamp:(t,e,n)=>Math.min(n,Math.max(e,t)),saturate:t=>Math.min(1,Math.max(0,t)),smoothstep:(t,e,n)=>{const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)},smoothStep:(t,e,n)=>{const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)},random:(t,e)=>t===void 0?Math.random():t+Math.random()*((e===void 0?1:e)-t),randomInt:(t,e)=>Math.floor((t||0)+Math.random()*((e===void 0?1:e)+1-(t||0))),degrees:t=>t*180/Math.PI,radians:t=>t*Math.PI/180},If={hsv2rgb:t=>{const e=t&&typeof t=="object"?t:{x:0,y:0,z:0},n=((Number(e.x)||0)%1+1)%1,r=Math.min(1,Math.max(0,Number(e.y)||0)),i=Math.min(1,Math.max(0,Number(e.z)||0)),s=Math.floor(n*6),a=n*6-s,o=i*(1-r),c=i*(1-a*r),u=i*(1-(1-a)*r),f=[[i,u,o],[c,i,o],[o,i,u],[o,c,i],[u,o,i],[i,o,c]][s%6];return new Te(f[0],f[1],f[2])},rgb2hsv:t=>{const e=t&&typeof t=="object"?t:{x:0,y:0,z:0},n=Number(e.x)||0,r=Number(e.y)||0,i=Number(e.z)||0,s=Math.max(n,r,i),a=Math.min(n,r,i),o=s-a;let c=0;return o>0&&(s===n?c=(r-i)/o/6:s===r?c=(2+(i-n)/o)/6:c=(4+(n-r)/o)/6,c<0&&(c+=1)),new Te(c,s===0?0:o/s,s)}},Mf={add:(t,e)=>({x:(t.x||0)+(e.x||0),y:(t.y||0)+(e.y||0),z:(t.z||0)+(e.z||0)}),subtract:(t,e)=>({x:(t.x||0)-(e.x||0),y:(t.y||0)-(e.y||0),z:(t.z||0)-(e.z||0)}),scale:(t,e)=>({x:(t.x||0)*e,y:(t.y||0)*e,z:(t.z||0)*e}),length:t=>Math.hypot(t.x||0,t.y||0,t.z||0),dot:(t,e)=>(t.x||0)*(e.x||0)+(t.y||0)*(e.y||0)+(t.z||0)*(e.z||0),normalize:t=>{const e=Math.hypot(t.x||0,t.y||0,t.z||0)||1;return{x:(t.x||0)/e,y:(t.y||0)/e,z:(t.z||0)/e}},mix:(t,e,n)=>({x:(t.x||0)+((e.x||0)-(t.x||0))*n,y:(t.y||0)+((e.y||0)-(t.y||0))*n,z:(t.z||0)+((e.z||0)-(t.z||0))*n})},Bf=Object.freeze({PLAYBACK_STOPPED:0,PLAYBACK_PLAYING:1,PLAYBACK_PAUSED:2}),ua=["mediaPropertiesChanged","mediaThumbnailChanged","mediaPlaybackChanged","mediaTimelineChanged","mediaStatusChanged","mediaLyricsChanged"],y0=["scriptProperties","engine","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","thisLayer","thisScene","thisObject","localStorage","MediaPlaybackEvent"],b0=new RegExp(`(^[ \\t]*|;|\\})[ \\t]*(?:var|let|const)[ \\t]+(?=(?:${y0.join("|")})\\b)`,"gm"),w0={WEMath:!0,WEColor:!0,WEVector:!0};function Rf(t){return typeof t!="string"?t:t.replace(/([!=])==(\s*)(['"])(-?\d+)\3/g,"$1=$2$3$4$3")}function Ff(t){return Rf(t).replace(/\bimport\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]\s*;?/g,(e,n,r)=>{const i=String(r);return w0[i]?n===i?"":`var ${n} = ${i};`:`var ${n} = {};`}).replace(/(^[ \t]*|;|\})[ \t]*import\s+(?:[^;'"]+\s+from\s+)?['"][^'"]*['"];?[ \t]*/gm,"$1").replace(/(^[ \t]*|;|\})[ \t]*export[ \t]+(?=(?:async[ \t]+)?function\b|(?:var|let|const)\b)/gm,"$1").replace(b0,"$1")}function v0(t){if(typeof t=="boolean")return t;if(typeof t=="number"&&Number.isFinite(t))return t!==0}function Df(t){const e=Math.floor(Number(t));return Number.isFinite(e)&&e>=1?Math.min(64,e):64}function fa(t){return t!==null&&typeof t=="object"&&"value"in t?t.value:t}function oc(t){const e=!!t;return Object.assign(()=>e,{valueOf(){return e},toString(){return e?"true":"false"}})}function Nf(t,e,n,r){if(n!==null&&typeof n=="object"&&typeof n.user=="string"){const i=fa(n);let s,a=!1;Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get(){if(a)return s;const o=r?r[n.user]:void 0;return o!==void 0?o:i},set(o){s=o,a=!0}})}else t[e]=fa(n)}function Lf(t){const e=t||{width:1920,height:1080};return e.x!==void 0&&e.y!==void 0?e:{x:e.width,y:e.height,width:e.width,height:e.height}}function k0(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=Ff(t);if(r===t&&t.indexOf("update")<0)return null;const i={};if(e&&typeof e=="object")for(const[b,v]of Object.entries(e))Nf(i,b,v,n.userProperties);const s=new Proxy(()=>s,{apply(){return s},get(b,v){if(v==="finish")return()=>i;if(typeof v=="string"&&xf.test(v))return k=>(k&&typeof k=="object"&&typeof k.name=="string"&&!(k.name in i)&&(i[k.name]=fa(k.value)),s)}}),a={text:n.text!==void 0&&n.text!==null?String(n.text):"",font:n.font||"",pointsize:n.pointsize||24,color:(n.color||[1,1,1]).slice(),angles:(n.angles||[0,0,0]).slice(),scale:(n.scale||[1,1,1]).slice(),visible:n.visible!==!1,origin:cs(n.origin||[0,0,0])},o={registerAsset:b=>b,frametime:1/60,runtime:0,canvasSize:Lf(n.canvasSize),screenResolution:n.screenResolution||{x:1920,y:1080},timeOfDay:typeof n.timeOfDay=="number"?n.timeOfDay:0,userProperties:n.userProperties||{},AUDIO_RESOLUTION_16:16,AUDIO_RESOLUTION_32:32,AUDIO_RESOLUTION_64:64,setTimeout:n.setTimeout||Ai,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||Ai,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:oc(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};Pf(o,n);const c=n.audioViews;o.registerAudioBuffers=b=>{const v=Df(b);let k=c?c.get(v):void 0;return k||(k={left:new Float32Array(v),right:new Float32Array(v),average:new Float32Array(v)},c&&c.set(v,k)),k};const u={getLayer(b){const v=n.getLayerText?n.getLayerText(String(b)):void 0;return{text:v!=null?String(v):""}},createLayer(b){return{text:"",visible:!1,color:[0,0,0],alpha:1,pointsize:n.pointsize||24,font:n.font||"",origin:cs(n.origin||[0,0,0]),angles:[0,0,0],scale:[1,1,1]}},sortLayer:()=>{},getLayerIndex:()=>0},l=n.shared||{},f={console:Tf()},d=Ef(n.inputView);let h;try{h=new Function("scriptProperties","engine","thisLayer","thisScene","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","MediaPlaybackEvent",`"use strict";
1
+ function Nr(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function Wt(t,e){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++){let s=0;for(let a=0;a<4;a++)s+=t[a*4+i]*e[r*4+a];n[r*4+i]=s}return n}function Hi(t,e,n,r,i,s){const a=Nr();return a[0]=2/(e-t),a[5]=2/(r-n),a[10]=-2/(s-i),a[12]=-(e+t)/(e-t),a[13]=-(r+n)/(r-n),a[14]=-0/(s-i),a}function ui(t,e,n,r){return Wt(t,new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,e,n,r,1]))}function $o(t){const e=new Float32Array(16);for(let n=0;n<4;n++)for(let r=0;r<4;r++)e[r*4+n]=t[n*4+r];return e}function Lr(t,e,n,r){return Wt(t,new Float32Array([e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1]))}function xu(t,e){const n=Math.cos(e),r=Math.sin(e);return Wt(t,new Float32Array([n,r,0,0,-r,n,0,0,0,0,1,0,0,0,0,1]))}function ku(t,e){const n=Math.cos(e),r=Math.sin(e);return Wt(t,new Float32Array([1,0,0,0,0,n,r,0,0,-r,n,0,0,0,0,1]))}function Tu(t,e){const n=Math.cos(e),r=Math.sin(e);return Wt(t,new Float32Array([n,0,-r,0,0,1,0,0,r,0,n,0,0,0,0,1]))}function Su(t,e,n,r){const i=1/Math.tan(t*Math.PI/180/2),s=new Float32Array(16);return s[0]=i/(e||1),s[5]=i,s[10]=(r+n)/(n-r),s[11]=-1,s[14]=2*r*n/(n-r),s}function Ps(t,e){const n=t&&typeof t=="object"?t.value:t;return typeof n=="number"&&Number.isFinite(n)?n:e}function bp(t){const e=t&&t.general;if(!e)return!1;const n=e.orthogonalprojection;if(n&&typeof n=="object"){if(Object.keys(n).length>0)return!1}else if(n)return!1;return Ps(e.fov,0)>0}function wp(t,e){return e&&e.perspective&&t&&t.isSkybox&&e.eye?e.eye:t.origin}function vp(t,e,n){const r=_u([t[0]-e[0],t[1]-e[1],t[2]-e[2]]),i=_u(Eu(n,r)),s=Eu(r,i),a=new Float32Array([i[0],s[0],r[0],0,i[1],s[1],r[1],0,i[2],s[2],r[2],0,0,0,0,1]);return a[12]=-(i[0]*t[0]+i[1]*t[1]+i[2]*t[2]),a[13]=-(s[0]*t[0]+s[1]*t[1]+s[2]*t[2]),a[14]=-(r[0]*t[0]+r[1]*t[1]+r[2]*t[2]),a}function Ap(t,e,n,r){const i=t[3]*e+t[7]*n+t[11]*r+t[15];return[(t[0]*e+t[4]*n+t[8]*r+t[12])/i,(t[1]*e+t[5]*n+t[9]*r+t[13])/i,(t[2]*e+t[6]*n+t[10]*r+t[14])/i]}const xp=[[16,9],[16,10],[21,9],[32,9]];function kp(t,e,n,r,i){const s=t/e;if(!Number.isFinite(s)||s<=0||!(n>0)||!(r>0))return null;const a=.02,o=n/r;if(Math.abs(s-o)<=a*o)return{viewW:n,viewH:r};for(const[c,u]of xp){const l=c/u;if(Math.abs(s-l)>a*l)continue;const d=r,f=r*l;return f>n+1e-6?{viewW:n,viewH:n/l}:{viewW:f,viewH:d}}return null}function Go(t){let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const s of t||[]){if(!s||s.visible===!1||s.destroyed)continue;const a=Math.abs((s.size?.[0]??0)*(s.scale?.[0]??1)),o=Math.abs((s.size?.[1]??0)*(s.scale?.[1]??1));if(!(a>0)&&!(o>0))continue;const c=Number(s.angles?.[2]??0)||0,u=Math.abs(Math.cos(c)),l=Math.abs(Math.sin(c)),d=a*u+o*l,f=a*l+o*u,h=Number(s.origin?.[0]??0)||0,p=Number(s.origin?.[1]??0)||0;e=Math.min(e,h-d/2),r=Math.max(r,h+d/2),n=Math.min(n,p-f/2),i=Math.max(i,p+f/2)}return{minX:e,minY:n,maxX:r,maxY:i}}function Qo(t,e,n,r,i,s,a){const o=Pu(s),c=Pu(a);if(t==="cover"){const u=kp(r,i,e,n);if(u)return{offX:(e-u.viewW)*o,offY:(n-u.viewH)*c,viewW:u.viewW,viewH:u.viewH};const l=Math.max(r/e,i/n),d=r/l,f=i/l;return{offX:(e-d)*o,offY:(n-f)*c,viewW:d,viewH:f}}if(t==="contain"){const u=r/i;if(e/n>u){const h=e,p=e/u;return{offX:0,offY:(n-p)/2,viewW:h,viewH:p}}const d=n,f=n*u;return{offY:0,offX:(e-f)/2,viewW:f,viewH:d}}return{offX:0,offY:0,viewW:e,viewH:n}}function Tp(t,e,n,r,i,s){const a=t.general,o=t.camera,c=o&&o.eye?Yo(o.eye):[0,0,0],u=o&&o.center?Yo(o.center):[0,0,-1],l=o&&o.up?Yo(o.up):[0,1,0];if(bp(t)){const A=n>0?e/n:1.7777777777777777,b=Ps(a.fov,50),v=Math.max(Ps(a.nearz,.01),1e-4),x=Math.max(Ps(a.farz,1e4),v+1),P=vp(c,u,l),S=Su(b,A,v,x);return{view:P,projection:S,eye:c,center:u,projW:A,projH:1,offX:0,offY:0,viewW:A,viewH:1,perspective:!0}}const d=Nr(),f=a&&a.orthogonalprojection&&a.orthogonalprojection.width||e,h=a&&a.orthogonalprojection&&a.orthogonalprojection.height||n,p=Qo(r,f,h,e,n,i,s),m=t&&t.cameraTransforms?t.cameraTransforms.zoom:a&&a.zoom,g=m&&typeof m=="object"?m.value:m,y=Number(g);if(Number.isFinite(y)&&y>0&&Math.abs(y-1)>1e-6){const A=p.offX+p.viewW/2,b=p.offY+p.viewH/2,v=p.viewW/y,x=p.viewH/y;p.offX=A-v/2,p.offY=b-x/2,p.viewW=v,p.viewH=x}const w=Hi(p.offX,p.offX+p.viewW,p.offY+p.viewH,p.offY,-1e4,1e4);return{view:d,projection:w,eye:c,projW:f,projH:h,offX:p.offX,offY:p.offY,viewW:p.viewW,viewH:p.viewH,perspective:!1}}function Sp(t,e){if(!t||t.perspective||!(t.viewW>0)||!(t.viewH>0))return null;const n=Ps(e&&e.perspectiveoverridefov,0);let r,i;n>0?(r=n,i=t.viewH/2/Math.tan(r*Math.PI/180/2)):(i=1e3,r=2*Math.atan(t.viewH/2/i)*180/Math.PI);const s=t.offX+t.viewW/2,a=t.offY+t.viewH/2,o=[s,a,i],c=new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,-s,a,-i,1]),u=Su(r,t.viewW/t.viewH,1,i+2e4);return{viewProj:Wt(u,c),eye:o,fovY:r,dist:i}}function Pu(t){const e=Number(t);return Number.isFinite(e)?e<0?0:e>1?1:e:.5}function Yo(t){return String(t).trim().split(/\s+/).map(Number)}function _u(t){const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]}function Eu(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Ea(t){const e=Number(t);return Number.isFinite(e)?e*.5:0}const Pp=Object.freeze(["3233141951"]);function _p(t){const e=t&&t.parallaxFormula;if(e==="mirage"||e==="legacy")return e;const n=t&&t.workshopId!=null?String(t.workshopId):"";return n&&Pp.includes(n)?"mirage":"legacy"}function Ep(t,e){if(!e||!e.active||!t.parallaxDepth)return[0,0];const n=e.lx||0,r=e.ly||0;if(n===0&&r===0)return[0,0];const i=Ea(t.parallaxDepth[0]),s=Ea(t.parallaxDepth[1]);return[i*n,s*r]}function Mp(t,e){if(!e||!e.active)return[0,0];const n=t.parallaxDepthProp||t.parallaxDepth;if(!n)return[0,0];const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))return[0,0];if(r===0&&i===0)return[0,0];const s=t.parallaxAnchor||(t.origin?[t.origin[0],t.origin[1]]:null);if(!s)return[0,0];const a=Number(e.amount)||0,o=Number(e.cx)||0,c=Number(e.cy)||0,u=(s[0]-o+(Number(e.mx)||0))*r*a,l=(s[1]-c+(Number(e.my)||0))*i*a;return[u,-l]}function Ko(t,e){return!e||!e.active?[0,0]:e.mode==="mirage"?Mp(t,e):Ep(t,e)}const Cp=2,Mu=32;function Cu(t,e){const n=typeof location<"u"?location.search:"",r=new URLSearchParams(n).get(t);if(r===null||r==="")return null;if(r==="native"||r==="off"||r==="0")return 1;if(r==="auto")return null;const i=Number(r);return Number.isFinite(i)&&i>0?Math.min(1,i):null}function Ip(t,e){const n=Cu("resources");if(n!==null)return n;const r=e?.renderDpr??t.cfg?.renderDpr,i=Number(r);if(r==null||r===0||Number.isNaN(i)){const s=typeof window<"u"&&window.devicePixelRatio||1;return Math.max(.6,Math.min(1,s/Cp))}return i>=1.5?1:i>=.9?.8:.6}function Rp(t,e){const n=Cu("resourcesNormal");return n!==null?n:1}const Bp=1e6;function Iu(t,e,n=4){const r=Math.abs(Number(t)||0),i=Math.abs(Number(e)||0);return!(r>0)||!(i>0)?!0:r*i*(n>0?n:4)<Bp}function Fp(t,e,n){return t.startsWith("util/")||t.startsWith("_rt_")?1:/normal/i.test(t)?n:e}function Dp(t){const e=typeof location<"u"?location.search:"",n=new URLSearchParams(e).get("resources");return n==="native"||n==="off"||n==="0"}function Np(t,e,n,r){const i=Math.abs(Number(t?.[0]||0)*Number(e?.[0]??1)),s=Math.abs(Number(t?.[1]||0)*Number(e?.[1]??1));if(!(i>0)||!(s>0))return 0;const a=Math.abs(Math.cos(n||0)),o=Math.abs(Math.sin(n||0)),c=i*a+s*o,u=i*o+s*a,l=(r.canvasDeviceW||0)/Math.max(1,r.viewW||1),d=(r.canvasDeviceH||0)/Math.max(1,r.viewH||1),f=r.safety&&r.safety>0?r.safety:1;return Math.max(c*l,u*d)*f}function Lp(t,e,n){const r=Math.max(1,Math.round(e||0)),i=Math.max(1,Math.min(r,Math.round(t||0)||r));return n>0?Math.max(Mu,Math.min(r,Math.min(i,Math.round(n)))):i}function Up(t,e){return!t||e>=1?t:Math.max(Mu,Math.round(t*e))}function Op(t,e,n=0){if(!t||t.length<=1||!e)return 0;let r=-1;for(let s=0;s<t.length;s++)if(t[s]<=e){r=s;break}const i=Math.max(0,Number(n)||0);if(i>0){for(let s=Math.max(0,r);s<t.length;s++)if(t[s]<=e&&t[s]>=i)return s;for(let s=t.length-1;s>=0;s--)if(t[s]>=i)return s;return 0}return r<0?t.length-1:r}function zp(t,e){if(!(e<.999))return t;for(const n of t)n.x=Math.round(n.x*e),n.y=Math.round(n.y*e),n.width=Math.max(1,Math.round(n.width*e)),n.height=Math.max(1,Math.round(n.height*e));return t}function Hp(t){const e=t.length/4,n=Math.max(1,e/96|0);for(let r=0;r<e;r+=n)if(t[r*4+3]<250)return!1;return!0}const Vp=4096;function Vi(t,e){const n=window.devicePixelRatio||1,r=e?.renderDpr??t.cfg?.renderDpr;let i;r==null||r===0||Number.isNaN(Number(r))?i=n:i=Math.max(.25,Number(r));const s=Math.max(window.innerWidth||0,window.innerHeight||0,1),a=Vp/s;return Math.max(.25,Math.min(i,a))}function Ur(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function Zo(t){const e=Ur(t);return e==="contain"?{objectFit:"contain",background:"rgba(10,12,16,0.85)"}:e==="stretch"?{objectFit:"fill",background:"transparent"}:{objectFit:"cover",background:"transparent"}}function Jo(t,e){const n=t.userVolume;return typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.min(1,n)):(e??t.cfg)?.muted===!1?1:0}function Ru(t){const e=t.userVolume;if(typeof e!="number"||!Number.isFinite(e))return;const n=Math.max(0,Math.min(1,e));try{t.sceneAudio?.setVolume(n)}catch{}if(t.videoPairs?.length)for(const r of t.videoPairs)try{r.setVolume(n)}catch{}else t.video&&(t.video.volume=n,t.video.muted=n<=0);if(t.iframe)try{t.iframe.contentWindow.__weSetVolume?.(n)}catch{}}function Wp(t){return{cfg:{type:"canvas"},coverAlign:{x:.5,y:.5,tx:.5,ty:.5},frameMeter:{stamps:[],last:0,fps:0},disposers:[]}}(()=>{const t=e=>e.preventDefault();window.addEventListener("contextmenu",t,!0),document.addEventListener("contextmenu",t,!0),window.__blockContextMenu=e=>e.addEventListener("contextmenu",t,!0)})();function Or(t){if(t.iframe)try{t.iframe.contentWindow?.location.replace("about:blank")}catch{}if(t.wrap)t.wrap.innerHTML="";else if(t.iframe?.isConnected)try{t.iframe.remove()}catch{}t.raf!==void 0&&cancelAnimationFrame(t.raf),t.raf=void 0;for(const n of t.videoPairs??[])n.destroy();if(t.videoPairs=void 0,t.webcodecsPreferred=void 0,t.sceneCleanup)try{t.sceneCleanup()}catch{}t.sceneCleanup=void 0,t.sceneCtl=void 0,t.pointerCtl=void 0,t.mediaCtl=void 0;const e=t.wallpaperDisposers??[];t.wallpaperDisposers=[];for(const n of e)try{n()}catch{}t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0);for(const n of t.videoTextures??[])n.pause(),n.removeAttribute("src"),n.load(),n.remove();t.videoTextures=void 0;for(const n of t.objectUrls??[])try{URL.revokeObjectURL(n)}catch{}if(t.objectUrls=void 0,t.sceneAudio){for(const n of t.sceneAudio.audios)n.pause(),n.removeAttribute("src"),n.load();try{t.sceneAudio.dispose?.()}catch{}t.sceneAudio=void 0}if(t.video){t.video.pause(),t.video.removeAttribute("src");try{t.video.load()}catch{}t.video.remove()}t.video=void 0,t.img=void 0,t.iframe=void 0,t.canvas=void 0,t.ctx=void 0,t.info=void 0,Qp(),Fu(t)}function jp(t){try{Or(t)}catch{}t.peekRaf!==void 0&&(cancelAnimationFrame(t.peekRaf),t.peekRaf=void 0);for(const e of t.disposers.splice(0))try{e()}catch{}t.wrap?.remove(),t.wrap=void 0}const qp=new TextDecoder,jt=t=>qp.decode(t).replace(/^\uFEFF/,""),Bu=500;function zr(t,e){const n=t.frameMeter.stamps;n.push(e),t.frameMeter.last=e;const r=e-Bu;for(;n.length&&n[0]<r;)n.shift();const i=n.length>=2?n[n.length-1]-n[0]:0;t.frameMeter.fps=i>0?(n.length-1)*1e3/i:0}function Fu(t){t.frameMeter.stamps.length=0,t.frameMeter.last=0,t.frameMeter.fps=0}function Xp(t){return!t.frameMeter.last||t.paused?{fps:0,running:!1}:performance.now()-t.frameMeter.last>Math.max(Bu,400)?{fps:0,running:!1}:{fps:t.frameMeter.fps,running:!0}}class ys{static EPS_MS=.5;interval=0;nextAt=0;armed=!1;constructor(e){this.interval=ys.intervalFor(e)}static intervalFor(e){const n=Number(e);return n>0&&isFinite(n)?1e3/n:0}setFps(e){this.interval=ys.intervalFor(e)}shouldRender(e){const n=this.interval;return n<=0?!0:this.armed?e+ys.EPS_MS<this.nextAt?!1:(this.nextAt+=n,this.nextAt<e-n&&(this.nextAt=e+n),!0):(this.armed=!0,this.nextAt=e,!0)}reset(){this.armed=!1,this.nextAt=0}}function be(t,e,n){try{t.onDiagnostic?.(n,/fail|error|失败|ERROR/.test(n)?"error":"info")}catch{}try{const r=e.mediaBase?new URL(e.mediaBase,window.location.href).origin:"";if(r){const i=new Image;i.src=`${r}/diag?msg=${encodeURIComponent(`scene ${e.src??"?"}: ${n.slice(0,500)}`)}`}}catch{}}function ec(t){t.coverAlign.x=t.coverAlign.y=t.coverAlign.tx=t.coverAlign.ty=.5,$p(t)}function $p(t){const e=`${(t.coverAlign.x*100).toFixed(2)}% ${(t.coverAlign.y*100).toFixed(2)}%`,n=t.video??t.img;n&&n.isConnected&&(n.style.objectPosition=e)}const Gp=["__scene","__sceneLayers","__textures","__objScripts","__textWidgets","__mediaHooks","__mediaControl","__mediaStats","__mediaSet","__system","__liveSystem","__audioStats","__audioMute","__particleStats","__particleToggle","__pointerStats","__compositeStats","__compositeEnable"];function Qp(){const t=window;for(const e of Gp)e in t&&delete t[e]}function Du(t,e,n){const r=Vi(t,n),i=Math.max(1,Math.round((e.clientWidth||window.innerWidth||1)*r)),s=Math.max(1,Math.round((e.clientHeight||window.innerHeight||1)*r));return e.width===i&&e.height===s?!1:(e.width=i,e.height=s,!0)}const Yp=.5,Nu=.12,Kp=.125,Zp=.0625,Lu=64;function Uu(t,e){const n=U=>{const W=document.createElement("video");U&&(W.src=t),W.muted=e.muted,W.playsInline=!0,W.preload="metadata";const ie=e.renderDpr||0,we=Math.min(window.devicePixelRatio||1,ie<=0?window.devicePixelRatio||1:ie),Y=Math.max(1,Math.round((e.maxW||innerWidth)*we)),oe=Math.max(1,Math.round((e.maxH||innerHeight)*we));return W.width=Y,W.height=oe,W.loop=!0,W};let r=n(!0),i=n(!1),s=!1,a=1,o=e.muted;i.muted=!0;const c=()=>{s||(i.src=t,s=!0)};let u=!1,l=!1,d,f=-1,h=0,p=0,m=Nu,g=!1,y=0,w=0,A=0,b=0,v,x=-1,P=0,S=!1;const k=U=>{if(S||U!==r)return;if(!u||!g){_(),U.loop=!0,U.play().catch(()=>{}),O.onFallback?.();return}i.playbackRate=1;const W=r;l=!0,W.style.transition=`opacity ${Lu}ms linear`,W.style.opacity="0";let ie=!1;const we=()=>{ie||S||(ie=!0,l=!1,W.style.transition="",I(),W.style.opacity="1")};W.addEventListener("transitionend",we,{once:!0}),d=window.setTimeout(we,Lu+80)},_=()=>{u=!1,p=0,g=!1,l&&(l=!1,d&&(clearTimeout(d),d=void 0),r.style.transition="",r.style.opacity="1"),v&&(v.loop=!0,v=void 0),i.paused||i.pause(),i.playbackRate=1;try{i.currentTime=0}catch{}},I=()=>{const U=r;r=i,i=U,u=!1,p=0,g=!1,h=0,f=-1,A=0,b=0,w=performance.now()+Math.max(800,m*1e3+300),r.paused&&r.play().catch(()=>{}),r.playbackRate!==1&&(r.playbackRate=1),r.muted=o,r.volume=a,U.pause(),U.playbackRate=1;try{U.currentTime=0}catch{}U.muted=!0,U.loop=!0,x=-1,s=!0,O.onSwap?.(r)},B=(U,W)=>{const ie=performance.now();if(!(ie-b<1e3)){if(b=ie,A++,h=0,f=-1,A>=3){A=0;const we=W,Y=r;e.onRecover?.(`${U}\uFF1A\u91CD\u8F7D\u5A92\u4F53\u7BA1\u7EBF @${we.toFixed(2)}s`),x=-1,Y.addEventListener("loadedmetadata",()=>{if(!(S||Y!==r)){try{Y.currentTime=Math.max(0,Math.min(we,(Y.duration||we)-.05))}catch{}Y.play().catch(()=>{})}},{once:!0}),Y.src=t,Y.play().catch(()=>{});return}if(A===2){e.onRecover?.(`${U}\uFF1Aseek \u91CD\u542F\u89E3\u7801 @${W.toFixed(2)}s`);try{r.currentTime=Math.max(0,W-.001)}catch{}r.play().catch(()=>{});return}e.onRecover?.(`${U}\uFF1A\u8E22 play`),r.pause(),r.play().catch(()=>{})}},V=()=>{if(S)return;P=requestAnimationFrame(V);const U=r.duration;if(!isFinite(U)||U<=0)return;const W=r.currentTime;if(!document.hidden&&!l&&performance.now()>=w?r.paused&&!r.ended&&r.readyState>=1?(h++,h>30&&B("\u9759\u9ED8\u6682\u505C",W)):!r.paused&&r.readyState>=2?(f===W?(h++,h>30&&B("\u5047\u64AD\u653E",W)):(h=0,A=0),f=W):(h=0,f=-1):(h=0,f=-1),x>=0&&W<x-.05){const Y=u,oe=g;_(),x=W,Y&&!oe&&(m=Math.min(1,m*2)),Y||O.onFallback?.();return}x=W;const ie=U-W,we=Math.max(Yp,m+.5);if(ie>we+.5){u&&_();return}if(u){if(!g&&i.currentTime>.004){g=!0;const Y=performance.now()-y;m=Math.min(1,Math.max(Nu,Y/1e3*1.5+.15)),v!==r&&(r.loop=!1,v=r)}!l&&g&&(r.ended||p>0&&performance.now()-p>1500)&&k(r);return}if(ie<=we&&(c(),i.readyState>=2)){if(ie<=m){try{i.currentTime=0}catch{}i.playbackRate=m>.3?Zp:Kp,y=performance.now(),g=!1,i.play().catch(()=>{}),u=!0,p=performance.now()}else if(i.paused)try{i.currentTime=0}catch{}}};P=requestAnimationFrame(V),r.addEventListener("ended",()=>k(r)),i.addEventListener("ended",()=>k(i));const O={get active(){return r},get standby(){return i},onSwap:void 0,onFallback:void 0,setVolume(U){a=Math.max(0,Math.min(1,U)),o=U<=0,r.muted=o,r.volume=a,i.muted=!0,i.volume=a},pause(){_(),r.pause(),P&&cancelAnimationFrame(P),P=0},resume(){S||(r.play().catch(U=>{U&&U.name}),P||(P=requestAnimationFrame(V)))},destroy(){S=!0,P&&cancelAnimationFrame(P),P=0;for(const U of[r,i]){U.pause(),U.removeAttribute("src");try{U.load()}catch{}U.remove()}}};return O}function N(t){if(!t)throw new Error("Assertion failed.")}const tc=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},Yt=t=>t&&t[t.length-1],ke=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},cr=t=>{const e=ke(t);return(e&1)===0?-(e>>1):e+1>>1},lr=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),et=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Kt=new TextDecoder,nc=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),rc={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ur=nc(rc),ic={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},fr=nc(ic),sc={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},dr=nc(sc),ac=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,Ou={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Jp=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Ma{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const n=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),r=this.currentPromise;return this.currentPromise=n,this.pending++,await r,e}}const e0=/^[0-9a-fA-F]+$/,_s=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),t0=t=>{N(t.length%2===0);const e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.slice(n,n+2),16);return e},zu=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),Es=(t,e,n)=>{let r=0,i=t.length-1,s=-1;for(;r<=i;){const a=r+i>>1,o=n(t[a]);o===e?(s=a,i=a-1):o<e?r=a+1:i=a-1}return s},Ge=(t,e,n)=>{let r=0,i=t.length-1,s=-1;for(;r<=i;){const a=r+(i-r+1)/2|0;n(t[a])<=e?(s=a,r=a+1):i=a-1}return s},Hu=(t,e,n)=>{const r=Ge(t,n(e),n);t.splice(r+1,0,e)},Dt=()=>{let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}},oc=(t,e)=>{const n=t.indexOf(e);n!==-1&&t.splice(n,1)},Vu=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return t[n]},cc=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1},n0=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},r0=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},Ca=t=>{throw new Error(`Unexpected value: ${t}`)},Wu=(t,e,n)=>{const r=t.getUint8(e),i=t.getUint8(e+1),s=t.getUint8(e+2);return r<<16|i<<8|s},i0=(t,e,n,r)=>{n=n>>>0,n=n&16777215,t.setUint8(e,n>>>16&255),t.setUint8(e+1,n>>>8&255),t.setUint8(e+2,n&255)},Ms=(t,e,n)=>Math.max(e,Math.min(n,t)),qt="und",Cs=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},lc=(t,e)=>Math.round(t/e)*e,ju=(t,e)=>Math.round(t*e)/e,uc=(t,e)=>Math.floor(t/e)*e,s0=t=>{let e=0;for(;t;)e++,t>>=1;return e},fc=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},a0=/^[a-z]{3}$/,qu=t=>a0.test(t),Wi=1e6*(1+Number.EPSILON),Xu=(t,e)=>{const n={...t,...e};if(t.headers||e.headers){const r=t.headers?dc(t.headers):{},i=e.headers?dc(e.headers):{},s={...r};Object.entries(i).forEach(([a,o])=>{const c=Object.keys(s).find(u=>u.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),n.headers=s}return n},dc=t=>{if(t instanceof Headers){const e={};return t.forEach((n,r)=>{e[r]=n}),e}if(Array.isArray(t)){const e={};return t.forEach(([n,r])=>{e[n]=r}),e}return t},$u=async(t,e,n,r,i)=>{let s=0;for(;;)try{return await t(e,n)}catch(a){if(i())throw a;s++;const o=r(s,a,e);if(o===null)throw a;if(Be._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Ba(1e3*o),i())throw a}};class o0{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let hc=null;const mc=()=>hc!==null?hc:hc=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let pc=null;const c0=()=>pc!==null?pc:pc=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let gc=null;const yc=()=>gc!==null?gc:gc=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),l0=t=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${t} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${t} is not available in this environment.`,u0=(async()=>{})().constructor,le=t=>t instanceof u0||t instanceof Promise?!0:typeof t?.then=="function",ji=(t,e)=>t!==-1?t:e,bc=(t,e,n,r)=>t<=r&&n<=e,Gu=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n},f0=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0},wc=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ia=t=>typeof t=="number"&&!Number.isNaN(t),Hr=(t,e)=>{if(e.includes("://"))return e;if(t.includes("://")){const o=t.indexOf("?");o!==-1&&(t=t.slice(0,o))}let n;if(e.startsWith("/")){const o=t.indexOf("://");if(o===-1)n=e;else{const c=t.indexOf("/",o+3);c===-1?n=t+e:n=t.slice(0,c)+e}}else{const o=t.lastIndexOf("/");o===-1?n=e:n=t.slice(0,o+1)+e}let r="";const i=n.indexOf("://");if(i!==-1){const o=n.indexOf("/",i+3);o!==-1&&(r=n.slice(0,o),n=n.slice(o))}const s=n.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return r+a.join("/")},Is=(t,e)=>{let n=0;for(let r=0;r<t.length;r++)e(t[r])&&n++;return n},vc=(t,e)=>{let n=-1,r=1/0;for(let i=0;i<t.length;i++){const s=e(t[i]);s<r&&(r=s,n=i)}return n},Ra=t=>{N(Number.isInteger(t.num)),N(Number.isInteger(t.den)),N(t.den!==0);let e=Math.abs(t.num),n=Math.abs(t.den);for(;n!==0;){const i=e%n;e=n,n=i}const r=e||1;return{num:t.num/r,den:t.den/r}},Ac=(t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},Ba=t=>new Promise(e=>setTimeout(e,t));class xc{constructor(){this._listeners=new Map}on(e,n,r){this._listeners.has(e)||this._listeners.set(e,new Set);const i={fn:n,once:r?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){const[n,r]=e,i=this._listeners.get(n);if(i)for(const s of i){try{s.fn(r)}catch(a){console.error(a)}s.once&&i.delete(s)}}}var qn;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(qn||(qn={}));class Be{constructor(){}static get level(){return Be._level}static set level(e){if(e!==qn.Silent&&e!==qn.Errors&&e!==qn.Warnings&&e!==qn.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Be._level=e}static get _emitter(){return Be._emitterInstance??=new xc}static on(e,n,r){return Be._emitter.on(e,n,r)}static _error(...e){Be._emitter._emit("error",e),Be._level>=qn.Errors&&console.error(...e)}static _warn(...e){Be._emitter._emit("warn",e),Be._level>=qn.Warnings&&console.warn(...e)}static _info(...e){Be._emitter._emit("info",e),Be._level>=qn.Info&&console.info(...e)}}Be._level=qn.Info,Be._emitterInstance=null;class Fa{constructor(e,n){if(this.data=e,this.mimeType=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof n!="string")throw new TypeError("mimeType must be a string.")}}class d0{constructor(e,n,r,i){if(this.data=e,this.mimeType=n,this.name=r,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(n!==void 0&&typeof n!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}}const hr={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Qe{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),n=this.bytes[e]??0,r=7-(this.pos&7),i=(n&1<<r)>>r;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let n=0;for(let r=0;r<e;r++)n<<=1,n|=this.readBit();return n}writeBits(e,n){const r=this.pos+e;for(let i=this.pos;i<r;i++){const s=Math.floor(i/8);let a=this.bytes[s];const o=7-(i&7);a&=~(1<<o),a|=(n&1<<r-i-1)>>r-i-1<<o,this.bytes[s]=a}this.pos=r}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,n=this.bytes[e]??0;return this.pos+=8,n}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new Qe(this.bytes);return e.pos=this.pos,e}}const Rs=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],kc=[-1,1,2,3,4,5,6,8],Qu=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Qe(t),n=Tc(e),{frequencyIndex:r,sampleRate:i}=Sc(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=kc[s]);let o=n,c=!1,u=i;if(n===5||n===29)c=n===29,u=Sc(e).sampleRate,o=Tc(e),o===22&&e.skipBits(4);else for(;e.getBitsLeft()>15;){const l=e.pos;if(e.readBits(11)!==695){e.pos=l+1;continue}Tc(e)===5&&e.readBits(1)&&(u=Sc(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(c=!!e.readBits(1)));break}return a!==null&&a>1&&(c=!1),{objectType:n,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:u,outputNumberOfChannels:c&&a===1?2:a}},Tc=t=>{const e=t.readBits(5);return e===31?32+t.readBits(6):e},Sc=t=>{const e=t.readBits(4);return e===15?{frequencyIndex:e,sampleRate:t.readBits(24)}:{frequencyIndex:e,sampleRate:e<Rs.length?Rs[e]:null}};const Da=[48e3,44100,32e3],Yu=[24e3,22050,16e3];var Rt;(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(Rt||(Rt={}));var vt;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(vt||(vt={}));const Na=function*(t){let e=0,n=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(r===-1||r>=t.length-2)break;e=r;let i=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?i=4:t[e+1]===0&&t[e+2]===1&&(i=3),i===0){e++;continue}n!==-1&&e>n&&(yield{offset:n,length:e-n}),n=e+i,e=n}n!==-1&&n<t.length&&(yield{offset:n,length:t.length-n})},Ku=function*(t,e){let n=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;n+e<=t.length;){let i;e===1?i=r.getUint8(n):e===2?i=r.getUint16(n,!1):e===3?i=Wu(r,n):(N(e===4),i=r.getUint32(n,!1)),n+=e,yield{offset:n,length:i},n+=i}},Zu=(t,e)=>{if(e.description){const i=(lr(e.description)[4]&3)+1;return Ku(t,i)}else return Na(t)},La=t=>t&31,Ua=t=>{const e=[],n=t.length;for(let r=0;r<n;r++)r+2<n&&t[r]===0&&t[r+1]===0&&t[r+2]===3?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},Pc=new Uint8Array([0,0,0,1]),Ju=t=>{const e=t.reduce((i,s)=>i+Pc.byteLength+s.byteLength,0),n=new Uint8Array(e);let r=0;for(const i of t)n.set(Pc,r),r+=Pc.byteLength,n.set(i,r),r+=i.byteLength;return n},ef=(t,e)=>{const n=t.reduce((s,a)=>s+e+a.byteLength,0),r=new Uint8Array(n);let i=0;for(const s of t){const a=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:i0(a,i,s.byteLength);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,r.set(s,i),i+=s.byteLength}return r},h0=(t,e)=>{if(e.description){const i=(lr(e.description)[4]&3)+1;return ef(t,i)}else return Ju(t)},_c=t=>{try{const e=[],n=[],r=[];for(const o of Na(t)){const c=t.subarray(o.offset,o.offset+o.length),u=La(c[0]);u===Rt.SPS?e.push(c):u===Rt.PPS?n.push(c):u===Rt.SPS_EXT&&r.push(c)}if(e.length===0||n.length===0)return null;const i=e[0],s=Oa(i);N(s!==null);const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(e){return Be._error("Error building AVC Decoder Configuration Record:",e),null}},tf=t=>{try{const e=et(t);let n=0;const r=e.getUint8(n++),i=e.getUint8(n++),s=e.getUint8(n++),a=e.getUint8(n++),o=e.getUint8(n++)&3,c=e.getUint8(n++)&31,u=[];for(let h=0;h<c;h++){const p=e.getUint16(n,!1);n+=2,u.push(t.subarray(n,n+p)),n+=p}const l=e.getUint8(n++),d=[];for(let h=0;h<l;h++){const p=e.getUint16(n,!1);n+=2,d.push(t.subarray(n,n+p)),n+=p}const f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=t.length){const h=e.getUint8(n++)&3,p=e.getUint8(n++)&7,m=e.getUint8(n++)&7,g=e.getUint8(n++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const y=[];for(let w=0;w<g;w++){const A=e.getUint16(n,!1);n+=2,y.push(t.subarray(n,n+A)),n+=A}f.sequenceParameterSetExt=y}return f}catch(e){return Be._error("Error deserializing AVC Decoder Configuration Record:",e),null}},nf={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Oa=t=>{try{const e=new Qe(Ua(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const r=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();ke(e);let a=1,o=0,c=0,u=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(a=ke(e),a===3&&(u=e.readBits(1)),o=ke(e),c=ke(e),e.skipBits(1),e.readBits(1))){for(let B=0;B<(a!==3?8:12);B++)if(e.readBits(1)){const O=B<6?16:64;let U=8,W=8;for(let ie=0;ie<O;ie++){if(W!==0){const we=cr(e);W=(U+we+256)%256}U=W===0?U:W}}}ke(e);const l=ke(e);if(l===0)ke(e);else if(l===1){e.skipBits(1),cr(e),cr(e);const I=ke(e);for(let B=0;B<I;B++)cr(e)}ke(e),e.skipBits(1);const d=ke(e),f=ke(e),h=16*(d+1),p=16*(f+1);let m=h,g=p;const y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){const I=ke(e),B=ke(e),V=ke(e),O=ke(e);let U,W;if((u===0?a:0)===0)U=1,W=2-y;else{const we=a===3?1:2,Y=a===1?2:1;U=we,W=Y*(2-y)}m-=U*(I+B),g-=W*(V+O)}let A=2,b=2,v=2,x=0,P={num:1,den:1},S=null,k=null;if(e.readBits(1)){if(e.readBits(1)){const Y=e.readBits(8);if(Y===255)P={num:e.readBits(16),den:e.readBits(16)};else{const oe=nf[Y];oe&&(P=oe)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),x=e.readBits(1),e.readBits(1)&&(A=e.readBits(8),b=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&(ke(e),ke(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const W=e.readBits(1);W&&rf(e);const ie=e.readBits(1);ie&&rf(e),(W||ie)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),ke(e),ke(e),ke(e),ke(e),S=ke(e),k=ke(e))}if(S===null){N(k===null);const I=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&I)S=0,k=0;else{const B=d+1,V=f+1,O=(2-y)*V,U=wf.find(ie=>ie.level>=s)??Yt(wf),W=Math.min(Math.floor(U.maxDpbMbs/(B*O)),16);S=W,k=W}}return N(k!==null),{profileIdc:r,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:p,displayWidth:m,displayHeight:g,pixelAspectRatio:P,colourPrimaries:A,matrixCoefficients:v,transferCharacteristics:b,fullRangeFlag:x,numReorderFrames:S,maxDecFrameBuffering:k}}catch(e){return Be._error("Error parsing AVC SPS:",e),null}},rf=t=>{const e=ke(t);t.skipBits(4),t.skipBits(4);for(let n=0;n<=e;n++)ke(t),ke(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},m0=(t,e)=>{if(e.description){const i=(lr(e.description)[21]&3)+1;return ef(t,i)}else return Ju(t)},za=(t,e)=>{if(e.description){const i=(lr(e.description)[21]&3)+1;return Ku(t,i)}else return Na(t)},qi=t=>t>>1&63,Ec=t=>{try{const e=new Qe(Ua(t));e.skipBits(16),e.readBits(4);const n=e.readBits(3),r=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=p0(e,n);ke(e);const l=ke(e);let d=0;l===3&&(d=e.readBits(1));const f=ke(e),h=ke(e);let p=f,m=h;if(e.readBits(1)){const B=ke(e),V=ke(e),O=ke(e),U=ke(e);let W=1,ie=1;const we=d===0?l:0;we===1?(W=2,ie=2):we===2&&(W=2,ie=1),p-=(B+V)*W,m-=(O+U)*ie}const g=ke(e),y=ke(e);ke(e);const A=e.readBits(1)?0:n;let b=0;for(let B=A;B<=n;B++)ke(e),b=ke(e),ke(e);ke(e),ke(e),ke(e),ke(e),ke(e),ke(e),e.readBits(1)&&e.readBits(1)&&g0(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),ke(e),ke(e),e.skipBits(1));const v=ke(e);if(y0(e,v),e.readBits(1)){const B=ke(e);for(let V=0;V<B;V++)ke(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,P=2,S=2,k=0,_=0,I={num:1,den:1};if(e.readBits(1)){const B=w0(e,n);I=B.pixelAspectRatio,x=B.colourPrimaries,P=B.transferCharacteristics,S=B.matrixCoefficients,k=B.fullRangeFlag,_=B.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:I,colourPrimaries:x,transferCharacteristics:P,matrixCoefficients:S,fullRangeFlag:k,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:_}}catch(e){return Be._error("Error parsing HEVC SPS:",e),null}},Mc=t=>{try{const e=[],n=[],r=[],i=[];for(const u of Na(t)){const l=t.subarray(u.offset,u.offset+u.length),d=qi(l[0]);d===vt.VPS_NUT?e.push(l):d===vt.SPS_NUT?n.push(l):d===vt.PPS_NUT?r.push(l):(d===vt.PREFIX_SEI_NUT||d===vt.SUFFIX_SEI_NUT)&&i.push(l)}if(n.length===0||r.length===0)return null;const s=Ec(n[0]);if(!s)return null;let a=0;if(r.length>0){const u=r[0],l=new Qe(Ua(u));l.skipBits(16),ke(l),ke(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),ke(l),ke(l),cr(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&ke(l),cr(l),cr(l),l.skipBits(1),l.skipBits(1),l.skipBits(1),l.skipBits(1);const d=l.readBits(1),f=l.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:vt.VPS_NUT,nalUnits:e}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:vt.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:vt.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:qi(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return Be._error("Error building HEVC Decoder Configuration Record:",e),null}},p0=(t,e)=>{const n=t.readBits(2),r=t.readBits(1),i=t.readBits(5);let s=0;for(let l=0;l<32;l++)s=s<<1|t.readBits(1);const a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=t.readBits(8);const o=t.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(t.readBits(1)),u.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)c[l]&&t.skipBits(88),u[l]&&t.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},g0=t=>{for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBits(1))ke(t);else{const i=Math.min(64,1<<4+(e<<1));e>1&&cr(t);for(let s=0;s<i;s++)cr(t)}},y0=(t,e)=>{const n=[];for(let r=0;r<e;r++)n[r]=b0(t,r,e,n)},b0=(t,e,n,r)=>{let i=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===n){const c=ke(t);a=e-(c+1)}else a=e-1;t.readBits(1),ke(t);const o=r[a]??0;for(let c=0;c<=o;c++)t.readBits(1)||t.readBits(1);i=r[a]}else{const o=ke(t),c=ke(t);for(let u=0;u<o;u++)ke(t),t.readBits(1);for(let u=0;u<c;u++)ke(t),t.readBits(1);i=o+c}return i},w0=(t,e)=>{let n=2,r=2,i=2,s=0,a=0,o={num:1,den:1};if(t.readBits(1)){const c=t.readBits(8);if(c===255)o={num:t.readBits(16),den:t.readBits(16)};else{const u=nf[c];u&&(o=u)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(n=t.readBits(8),r=t.readBits(8),i=t.readBits(8))),t.readBits(1)&&(ke(t),ke(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(ke(t),ke(t),ke(t),ke(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&ke(t),t.readBits(1)&&v0(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=ke(t),ke(t),ke(t),ke(t),ke(t)),{pixelAspectRatio:o,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},v0=(t,e,n)=>{let r=!1,i=!1,s=!1;r=t.readBits(1)===1,i=t.readBits(1)===1,(r||i)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){const o=t.readBits(1)===1;let c=!0;o||(c=t.readBits(1)===1);let u=!1;c?ke(t):u=t.readBits(1)===1;let l=1;u||(l=ke(t)+1),r&&sf(t,l,s),i&&sf(t,l,s)}},sf=(t,e,n)=>{for(let r=0;r<e;r++)ke(t),ke(t),n&&(ke(t),ke(t)),t.readBits(1)},A0=t=>{try{const e=et(t);let n=0;const r=e.getUint8(n++),i=e.getUint8(n++),s=i>>6&3,a=i>>5&1,o=i&31,c=e.getUint32(n,!1);n+=4;const u=t.subarray(n,n+6);n+=6;const l=e.getUint8(n++),d=(e.getUint8(n++)&15)<<8|e.getUint8(n++),f=e.getUint8(n++)&3,h=e.getUint8(n++)&3,p=e.getUint8(n++)&7,m=e.getUint8(n++)&7,g=e.getUint16(n,!1);n+=2;const y=e.getUint8(n++),w=y>>6&3,A=y>>3&7,b=y>>2&1,v=y&3,x=e.getUint8(n++),P=[];for(let S=0;S<x;S++){const k=e.getUint8(n++),_=k>>7&1,I=k&63,B=e.getUint16(n,!1);n+=2;const V=[];for(let O=0;O<B;O++){const U=e.getUint16(n,!1);n+=2,V.push(t.subarray(n,n+U)),n+=U}P.push({arrayCompleteness:_,nalUnitType:I,nalUnits:V})}return{configurationVersion:r,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:g,constantFrameRate:w,numTemporalLayers:A,temporalIdNested:b,lengthSizeMinusOne:v,arrays:P}}catch(e){return Be._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Nt;(function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"})(Nt||(Nt={}));const x0=(t,e)=>{const n=new Set;let r=Nt.audAllowed;for(const s of za(t,e)){if(r===Nt.noMoreDataAllowed){n.add(s.offset);continue}const a=qi(t[s.offset]);if(r===Nt.eoBitstreamAllowed&&a!==37){n.add(s.offset);continue}let o=!1;a===35?r>Nt.audAllowed?o=!0:r=Nt.beforeFirstVcl:a<=31?r>Nt.afterFirstVcl?o=!0:r=Nt.afterFirstVcl:a===36?r!==Nt.afterFirstVcl?o=!0:r=Nt.eoBitstreamAllowed:a===37?r<Nt.afterFirstVcl?o=!0:r=Nt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?r>Nt.beforeFirstVcl?o=!0:r=Nt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&r<Nt.afterFirstVcl&&(o=!0),o&&n.add(s.offset)}if(n.size===0)return null;const i=[];for(const s of za(t,e))n.has(s.offset)||i.push(t.subarray(s.offset,s.offset+s.length));return m0(i,e)},k0={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},af=t=>{const e=new Qe(t);if(e.readBits(2)!==2)return null;const r=e.readBits(1),s=(e.readBits(1)<<1)+r;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);const l=e.readBits(3);let d=0,f=0;if(l!==7)if(f=e.readBits(1),s===1||s===3){const S=e.readBits(1),k=e.readBits(1);d=!S&&!k?3:S&&!k?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),p=e.readBits(16),m=h+1,g=p+1,y=m*g;let w=Yt($i).level;for(const P of $i)if(y<=P.maxPictureSize){w=P.level;break}const A=k0[l],b=A?.colourPrimaries??2,v=A?.transferCharacteristics??2,x=A?.matrixCoefficients??2;return{profile:s,level:w,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:b,transferCharacteristics:v,matrixCoefficients:x}},T0=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,of=function*(t){const e=new Qe(t),n=()=>{let r=0;for(let i=0;i<8;i++){const s=e.readAlignedByte();if(r+=(s&127)*2**(i*7),!(s&128))break;if(i===7&&s&128)return null}return r>2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){const o=n();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);N(e.pos%8===0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Cc=t=>{for(const{type:e,data:n}of of(t)){if(e!==1)continue;const r=new Qe(n),i=r.readBits(3);r.readBits(1);const s=r.readBits(1);let a=0,o=0,c=0;if(s)a=r.readBits(5);else{const k=r.readBits(1);let _=0;if(k){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let O=0;for(;O<32&&!r.readBits(1);)O++;O<32&&r.skipBits(O)}_=r.readBits(1),_&&(c=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}const I=r.readBits(1),B=r.readBits(5);for(let V=0;V<=B;V++){r.skipBits(12);const O=r.readBits(5);if(V===0&&(a=O),O>7){const U=r.readBits(1);V===0&&(o=U)}if(_&&r.readBits(1)){const W=c+1;r.skipBits(W),r.skipBits(W),r.skipBits(1)}I&&r.readBits(1)&&r.skipBits(4)}}const u=r.readBits(4),l=r.readBits(4),d=u+1;r.skipBits(d);const f=l+1;r.skipBits(f);let h=0;if(s?h=0:h=r.readBits(1),h&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const k=r.readBits(1);k&&(r.skipBits(1),r.skipBits(1));const _=r.readBits(1);let I=0;_?I=2:I=r.readBits(1),I>0&&(r.readBits(1)||r.skipBits(1)),k&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const p=r.readBits(1);let m=8;i===2&&p?m=r.readBits(1)?12:10:i<=2&&(m=p?10:8);let g=0;i!==1&&(g=r.readBits(1));let y=2,w=2,A=2;r.readBits(1)&&(y=r.readBits(8),w=r.readBits(8),A=r.readBits(8));let v=0,x=1,P=1,S=0;return g?v=r.readBits(1):y===1&&w===13&&A===0?(v=1,x=0,P=0):(v=r.readBits(1),i===0?(x=1,P=1):i===1?(x=0,P=0):m===12?(x=r.readBits(1),P=x?r.readBits(1):0):(x=1,P=0),x&&P&&(S=r.readBits(2))),{profile:i,level:a,tier:o,bitDepth:m,monochrome:g,chromaSubsamplingX:x,chromaSubsamplingY:P,chromaSamplePosition:S,videoFullRangeFlag:v,colourPrimaries:y,transferCharacteristics:w,matrixCoefficients:A}}return null},S0=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,cf=t=>{if(t.length<36)return null;const n=et(t);return n.getUint32(4)!==1768124518||n.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:n.getUint8(22),transferCharacteristics:n.getUint8(23),matrixCoefficients:n.getUint8(24)}},P0=t=>{const e=et(t),n=e.getUint8(9),r=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=t.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},_0=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],E0=t=>{const e=t[0]>>3,n=t[0]&3;let r;return n===0?r=1:n===1||n===2?r=2:r=t[1]&63,{durationInSamples:_0[e]*r}},M0=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const n=t.length,r=new Uint8Array(n);for(let d=0;d<n;d++)r[d]=t[n-1-d];const i=new Qe(r);let s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){const d=i.pos,f=i.readBits(8),h=i.readBits(16),p=i.readBits(16);if(f>63||h!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const u=c;i.pos=0,i.skipBits(s);const l=Array(u).fill(0);for(let d=u-1;d>=0;d--)i.skipBits(40),l[d]=i.readBits(1);return{modeBlockflags:l}},Ic=(t,e,n)=>{switch(t){case"avc":{for(const r of Zu(n,e)){const i=n[r.offset],s=La(i);if(s>=Rt.NON_IDR_SLICE&&s<=Rt.SLICE_DPC)return"delta";if(s===Rt.IDR)return"key";if(s===Rt.SEI&&!yc()){const a=n.subarray(r.offset,r.offset+r.length),o=Ua(a);let c=1;do{let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}if(u===6){const f=new Qe(o);f.pos=8*c;const h=ke(f),p=f.readBits(1);if(h===0&&p===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(const r of za(n,e)){const i=qi(n[r.offset]);if(i<vt.BLA_W_LP)return"delta";if(i<=vt.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(n[0]&1)===0?"key":"delta";case"vp9":{const r=new Qe(n);if(r.readBits(2)!==2)return null;const i=r.readBits(1);return(r.readBits(1)<<1)+i===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:i,data:s}of of(n))if(i===1){const a=new Qe(s);a.skipBits(4),r=!!a.readBits(1)}else if(i===3||i===6||i===7){if(r)return"key";const a=new Qe(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Ca(t),N(!1)}};var Xi;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Xi||(Xi={}));const Rc=(t,e)=>{const n=et(t);let r=0;const i=n.getUint32(r,!0);r+=4;const s=Kt.decode(t.subarray(r,r+i));r+=i,i>0&&(e.raw??={},e.raw.vendor??=s);const a=n.getUint32(r,!0);r+=4;for(let o=0;o<a;o++){const c=n.getUint32(r,!0);r+=4;const u=Kt.decode(t.subarray(r,r+c));r+=c;const l=u.indexOf("=");if(l===-1)continue;const d=u.slice(0,l).toUpperCase(),f=u.slice(l+1);switch(e.raw??={},e.raw[d]??=f,d){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{const h=f.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{const h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"DISCNUMBER":{const h=f.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{const h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DATE":{const h=new Date(f);Number.isNaN(h.getTime())||(e.date??=h)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{const h=Gu(f),p=et(h),m=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...h.subarray(8,8+g)),w=p.getUint32(8+g,!1),A=Kt.decode(h.subarray(12+g,12+g+w)),b=p.getUint32(g+w+28),v=h.subarray(g+w+32,g+w+32+b);e.images??=[],e.images.push({data:v,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:A||void 0})}break}}},Bc=[2,1,2,3,3,4,4,5],C0=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;const e=new Qe(t);e.skipBits(16),e.skipBits(16);const n=e.readBits(2);if(n===3)return null;const r=e.readBits(6),i=e.readBits(5);if(i>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(r/2);return{fscod:n,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},I0=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],R0=1536,lf=[1,2,3,6],B0=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;const e=new Qe(t);e.skipBits(16);const n=e.readBits(2);if(e.skipBits(3),n!==0&&n!==2)return null;const r=e.readBits(11),i=e.readBits(2);let s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;const l=lf[a];let d;return i<3?d=Da[i]/1e3:d=Yu[s]/1e3,{dataRate:Math.round((r+1)*d/(l*16)),substreams:[{fscod:i,fscod2:s,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},F0=t=>{if(t.length<2)return null;const e=new Qe(t),n=e.readBits(13),r=e.readBits(3),i=[];for(let s=0;s<=r&&!(Math.ceil(e.pos/8)+3>t.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),u=e.readBits(3),l=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let f=0;d>0?f=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:d,chanLoc:f})}return i.length===0?null:{dataRate:n,substreams:i}},uf=t=>{const e=t.substreams[0];return N(e),e.fscod<3?Da[e.fscod]:e.fscod2!==null&&e.fscod2<3?Yu[e.fscod2]:null},ff=t=>{const e=t.substreams[0];N(e);let n=Bc[e.acmod]+e.lfeon;if(e.numDepSub>0){const r=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(n+=r[i])}return n},D0=1683496997,Ha=18,Fc=10,N0=4096,df=32,hf=20,L0=8,U0=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],O0=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],z0=[16,16,20,20,0,24,24,0],Va=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],H0=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],V0=8,W0=44646,j0=[32e3,44100,48e3,0],q0=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],X0=[512,1024,2048,4096],mf=t=>{const e=gf(t),n=et(t);let r=e?Math.ceil(e.frameSize/4)*4:0,i=null;for(;r+4<=t.length&&n.getUint32(r)===D0;){const a=Wa(t.subarray(r));if(!a)break;i??=a,r+=a.frameSize}if(e)return{frameSize:i?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:i!==null};if(!i?.asset)return null;const{asset:s}=i;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},pf=t=>{const e=mf(t);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},gf=t=>{if(t.length<Ha||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;const e=new Qe(t);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==df-1)return null;const n=e.readBits(1),r=e.readBits(7)+1;if(r%L0!==0)return null;const i=e.readBits(14)+1;if(i<96)return null;const s=e.readBits(6);if(s>=Va.length)return null;const a=U0[e.readBits(4)];if(a===0)return null;const o=O0[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const c=e.readBits(2);if(c===3)return null;e.skipBits(1),n&&e.skipBits(16),e.skipBits(7);const u=z0[e.readBits(3)];if(u===0)return null;const l=c!==0;return{frameSize:i,sampleRate:a,numberOfChannels:Va[s]+(l?1:0),sampleCount:r*df,channelLayout:H0[s]|(l?V0:0),amode:s,lfePresent:l,bitRate:o,pcmResolution:u}},Wa=t=>{if(t.length<Fc||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;const e=new Qe(t);e.skipBits(32),e.skipBits(8);const n=e.readBits(2),r=e.readBits(1),i=8+4*r,s=16+4*r;e.skipBits(i);const a=e.readBits(s)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=j0[e.readBits(2)],u=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,d=e.readBits(3)+1,f=[];for(let y=0;y<l;y++)f.push(e.readBits(n+1));for(const y of f)e.skipBits(8*fc(y));if(e.readBits(1)){e.skipBits(2);const y=e.readBits(2)+1<<2,w=e.readBits(2)+1;e.skipBits(w*y)}for(let y=0;y<d;y++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,p=q0[e.readBits(4)],m=e.readBits(8)+1;let g=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const y=e.readBits(2)+1<<2;g=e.readBits(y)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(u*p/c),channelLayout:g,pcmResolution:h}}},$0=t=>{if(t.length<hf)return null;const e=et(t),n=e.getUint32(0);if(n===0)return null;const r=new Qe(t);r.seekToByte(13);const i=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return o!==0?c=G0(o):a<Va.length&&(c=Va[a]+s),{sampleRate:n,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:t[12],sampleCount:X0[i],channelLayout:o,numberOfChannels:c}},G0=t=>fc(t)+fc(t&W0);const yf=["avc","hevc","vp9","av1","vp8","prores"],ja=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Q0=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],bf=[...Q0,...ja],wf=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],$i=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],vf=".01.01.01.01.00",Af=".0.110.01.01.01.0",Dc=["ap4x","ap4h","apch","apcn","apcs","apco"],xf=["dtsc","dtsh","dtsl","dtse"],Nc=t=>{const{codec:e,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=t;if(e==="avc"){if(N(t.avcType!==null),i){const u=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${_s(u)}`}if(!n||n.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${_s(n.subarray(1,4))}`}else if(e==="hevc"){let u,l,d,f,h,p;if(s)u=s.generalProfileSpace,l=s.generalProfileIdc,d=zu(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const g=et(n),y=g.getUint8(1);u=y>>6&3,l=y&31,d=zu(g.getUint32(2)),f=y>>5&1,h=g.getUint8(12),p=[];for(let w=0;w<6;w++)p.push(g.getUint8(6+w))}let m="hev1.";for(m+=["","A","B","C"][u]+l,m+=".",m+=d.toString(16).toUpperCase(),m+=".",m+=f===0?"L":"H",m+=h;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(m+=".",m+=p.map(g=>g.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const w=t.width*t.height;let A=Yt($i).level;for(const b of $i)if(w<=b.maxPictureSize){A=b.level;break}return`vp09.00.${A.toString().padStart(2,"0")}.08`}const u=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),f=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),m=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0");let y=`vp09.${u}.${l}.${d}.${f}`;return y+=`.${h}.${p}.${m}.${g}`,y.endsWith(vf)&&(y=y.slice(0,-vf.length)),y}else if(e==="av1"){if(!o){const b=t.width*t.height;let v=Yt($i).level;for(const x of $i)if(b<=x.maxPictureSize){v=x.level;break}return`av01.0.${v.toString().padStart(2,"0")}M.08`}const u=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",f=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),m=r?.primaries?rc[r.primaries]:1,g=r?.transfer?ic[r.transfer]:1,y=r?.matrix?sc[r.matrix]:1,w=r?.fullRange?1:0;let A=`av01.${u}.${l}${d}.${f}`;return A+=`.${h}.${p.toString().padStart(3,"0")}`,A+=`.${m.toString().padStart(2,"0")}`,A+=`.${g.toString().padStart(2,"0")}`,A+=`.${y.toString().padStart(2,"0")}`,A+=`.${w}`,A.endsWith(Af)&&(A=A.slice(0,-Af.length)),A}else{if(e==="prores")return c??"apch";e!==null&&Ca(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},kf=t=>{switch(t.codec){case"avc":{let e=t.avcCodecInfo?.sequenceParameterSets[0];if(!e&&t.codecDescription&&(e=tf(t.codecDescription)?.sequenceParameterSets[0]),e){const n=Oa(e);if(n)return{primaries:ur[n.colourPrimaries],transfer:fr[n.transferCharacteristics],matrix:dr[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"hevc":{let e=t.hevcCodecInfo?.arrays.find(n=>n.nalUnitType===vt.SPS_NUT)?.nalUnits[0];if(!e&&t.codecDescription&&(e=A0(t.codecDescription)?.arrays.find(n=>n.nalUnitType===vt.SPS_NUT)?.nalUnits[0]),e){const n=Ec(e);if(n)return{primaries:ur[n.colourPrimaries],transfer:fr[n.transferCharacteristics],matrix:dr[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(t.vp9CodecInfo)return{primaries:ur[t.vp9CodecInfo.colourPrimaries],transfer:fr[t.vp9CodecInfo.transferCharacteristics],matrix:dr[t.vp9CodecInfo.matrixCoefficients],fullRange:!!t.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(t.av1CodecInfo)return{primaries:ur[t.av1CodecInfo.colourPrimaries],transfer:fr[t.av1CodecInfo.transferCharacteristics],matrix:dr[t.av1CodecInfo.matrixCoefficients],fullRange:!!t.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(t.proresCodecInfo)return{primaries:ur[t.proresCodecInfo.colourPrimaries],transfer:fr[t.proresCodecInfo.transferCharacteristics],matrix:dr[t.proresCodecInfo.matrixCoefficients],fullRange:t.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Lc=t=>{const{codec:e,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=t;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let s;return r.objectType!==null?s=r.objectType:s=Qu(n).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return i??"dtsc";if(e&&ja.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},qa=48e3,Tf=/^pcm-([usf])(\d+)(be)?$/,Y0=t=>{if(N(ja.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Tf.exec(t);N(e);let n;e[1]==="u"?n="unsigned":e[1]==="s"?n="signed":n="float";const r=Number(e[2])/8,i=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:s}},Bs=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":Dc.includes(t)?"prores":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"||t==="mp4a.40.34"?"mp3":t.startsWith("mp4a.40.")||t==="mp4a.67"?"aac":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":xf.includes(t)?"dts":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Tf.test(t)?t:t==="webvtt"?"webvtt":null;const fi=4,K0=[44100,48e3,32e3],Z0=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Sf=1483304551,Pf=1231971951,J0=(t,e,n,r,i)=>e===0?0:e===1?Math.floor(144*n/(r<<t))+i:e===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,eg=(t,e,n,r)=>e===0?0:e===1?144*n/(r<<t):e===2?144*n/r:12*n/r*4,_f=(t,e)=>t===3?e===3?21:36:e===3?13:21,Uc=(t,e)=>{const n=t>>>24,r=t>>>16&255,i=t>>>8&255,s=t&255;if(n!==255&&r!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(n!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;r&16?a=r&8?0:1:(a=1,o=1);const c=r>>3&3,u=r>>1&3,l=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,h=s>>6&3,p=s>>4&3,m=s>>3&1,g=s>>2&1,y=s&3,w=Z0[a*16*4+u*16+l];if(w===-1)return{header:null,bytesAdvanced:1};const A=w*1e3,b=K0[d]>>a+o,v=J0(a,u,A,b,f);if(e!==null&&e<v)return{header:null,bytesAdvanced:1};let x;return c===3?x=u===3?384:1152:u===3?x=384:u===2?x=1152:x=576,{header:{totalSize:v,mpegVersionId:c,lowSamplingFrequency:a,layer:u,bitrate:A,frequencyIndex:d,sampleRate:b,channel:h,modeExtension:p,copyright:m,original:g,emphasis:y,audioSamplesInFrame:x},bytesAdvanced:1}},Oc=t=>{let e=2130706432,n=0;for(;e!==0;)n>>=1,n|=t&e,e>>=8;return n};var Xa;(function(t){t[t.FrameCount=1]="FrameCount",t[t.FileSize=2]="FileSize",t[t.Toc=4]="Toc"})(Xa||(Xa={}));const Fs=t=>t===3?1:2;class mr{constructor(e){this.input=e}dispose(){}}const cn=new Uint8Array(0);class kt{constructor(e,n,r,i,s=-1,a,o){if(this.data=e,this.type=n,this.timestamp=r,this.duration=i,this.sequenceNumber=s,e===cn&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(n!=="key"&&n!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===cn}get microsecondTimestamp(){return Math.trunc(Wi*this.timestamp)}get microsecondDuration(){return Math.trunc(Wi*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,n){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new kt(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,n)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new kt(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const tg=t=>{let n=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const r=[...new Set(t.codecStrings)];n+=`; codecs="${r.join(", ")}"`}return n},Ef=t=>{const e=et(t);let n=0;const r=e.getUint8(n);n+=1,n+=3;const i=_s(t.subarray(n,n+16));n+=16;let s=null;if(r>0){const o=e.getUint32(n);if(n+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(_s(t.subarray(n,n+16))),n+=16}}const a=e.getUint32(n);return n+=4,{systemId:i,keyIds:s,data:t.slice(n,n+a)}},Mf=(t,e)=>t.systemId===e.systemId&&f0(t.data,e.data);const Gi=8,Ds=16,Vr=t=>{let e=ve(t);const n=mt(t,4);let r=8;e===1&&(e=un(t),r=16);const s=e-r;return s<0?null:{name:n,totalSize:e,headerSize:r,contentSize:s}},di=t=>bi(t)/65536,zc=t=>bi(t)/1073741824,Hc=t=>{let e=0;for(let n=0;n<4;n++){e<<=7;const r=Se(t);if(e|=r&127,(r&128)===0)break}return e},Xn=t=>{let e=At(t);return t.skip(2),e=Math.min(e,t.remainingLength),Kt.decode(Ee(t,e))},ng=t=>{const e=Vr(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;const n=ve(t);t.skip(4);const r=Ee(t,e.contentSize-8);switch(n){case 1:return Kt.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Fa(r,"image/jpeg");case 14:return new Fa(r,"image/png");case 27:return new Fa(r,"image/bmp");default:return r}};const $n=16,pr=new Uint32Array(256),Qi=new Uint32Array(256),Yi=new Uint32Array(256),Ki=new Uint32Array(256),Zi=new Uint32Array(256),Bt=new Uint32Array(256),Cf=new Uint32Array(10);let If=!1;const rg=()=>{const t=new Uint8Array(256),e=new Uint8Array(256),n=new Uint8Array(256);for(let s=0,a=1;s<256;s++)n[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const r=(s,a)=>s&&a?n[(e[s]+e[a])%255]:0;t[0]=99;for(let s=1;s<256;s++){const a=n[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,t[s]=o}for(let s=0;s<256;s++){const a=t[s],o=t.indexOf(s);pr[s]=a<<24|a<<16|a<<8|a,Bt[s]=o<<24|o<<16|o<<8|o;const c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),f=c<<24|u<<16|l<<8|d;Qi[s]=f,Yi[s]=f>>>8|f<<24,Ki[s]=f>>>16|f<<16,Zi[s]=f>>>24|f<<8}let i=1;for(let s=0;s<10;s++)Cf[s]=i<<24,i=i<<1^(i&128?283:0);If=!0};class Rf{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array($n/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array($n),this.out=new Uint8Array($n),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:n}){N(e.byteLength===16),N(n.byteLength===16),If||rg();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(n.buffer,n.byteOffset,n.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^pr[a>>>16&255]&4278190080^pr[a>>>8&255]&16711680^pr[a>>>0&255]&65280^pr[a>>>24&255]&255^Cf[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=Qi[pr[o>>>24&255]&255]^Yi[pr[o>>>16&255]&255]^Ki[pr[o>>>8&255]&255]^Zi[pr[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],n=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let u,l,d,f;for(let y=1;y<10;y++){const w=y*4;u=Qi[e>>>24]^Yi[i>>>16&255]^Ki[r>>>8&255]^Zi[n&255]^this.roundkey[w],l=Qi[n>>>24]^Yi[e>>>16&255]^Ki[i>>>8&255]^Zi[r&255]^this.roundkey[w+1],d=Qi[r>>>24]^Yi[n>>>16&255]^Ki[e>>>8&255]^Zi[i&255]^this.roundkey[w+2],f=Qi[i>>>24]^Yi[r>>>16&255]^Ki[n>>>8&255]^Zi[e&255]^this.roundkey[w+3],e=u,n=l,r=d,i=f}const h=Bt[e>>>24&255]&4278190080^Bt[i>>>16&255]&16711680^Bt[r>>>8&255]&65280^Bt[n>>>0&255]&255^this.roundkey[40],p=Bt[n>>>24&255]&4278190080^Bt[e>>>16&255]&16711680^Bt[i>>>8&255]&65280^Bt[r>>>0&255]&255^this.roundkey[41],m=Bt[r>>>24&255]&4278190080^Bt[n>>>16&255]&16711680^Bt[e>>>8&255]&65280^Bt[i>>>0&255]&255^this.roundkey[42],g=Bt[i>>>24&255]&4278190080^Bt[r>>>16&255]&16711680^Bt[n>>>8&255]&65280^Bt[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,g^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const ig=(t,e,n)=>{let r=!1,i=0;const s=2**16,a=16,o=new Rf;return new ReadableStream({pull:async c=>{r||(o.init(await e()),r=!0);const u=s+a;let l=t.requestSliceRange(i,0,u);if(le(l)&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");const d=l.length;if(d%16!==0)throw new Error("Invalid ciphertext.");const f=d===u?d-a:d,h=Ee(l,f),p=new Uint8Array(f);for(let m=0;m<f;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(f<d)c.enqueue(p),i+=f;else{const m=p[f-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const g=p.subarray(0,f-m);c.enqueue(g),c.close(),n()}},cancel:()=>{n()}})};class bu extends mr{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),n=await Promise.all(e.map(r=>r.getDecoderConfig().then(i=>i?.codec??null)));return tg({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:n.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,n=!1,r=!1;for(;;){let i=this.reader.requestSliceRange(e,Gi,Ds);if(le(i)&&(i=await i),!i)break;const s=e,a=Vr(i);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=mt(i,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(i.filePos,a.contentSize);if(le(o)&&(o=await o),!o)break;this.moovSlice=o,this.readContiguousBoxes(this.moovSlice);for(const c of this.tracks){const u=c.editListPreviousSegmentDurations/this.movieTimescale;c.editListOffset-=Math.round(u*c.timescale)}n=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,r=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),n=!1,r=!0;break}e=s+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),n){N(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);le(i)&&(i=await i),N(i);const s=ve(i),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Ds){let o=this.reader.requestSliceRange(a,Gi,Ds);if(le(o)&&(o=await o),o){const c=Vr(o);if(c&&c.name==="mfra"){let u=this.reader.requestSlice(o.filePos,c.contentSize);le(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}})()}async copyMetadataFromInitInput(e){const n=await e._getDemuxer();if(n.constructor!==bu)throw new Error("Init input must match the input's format.");await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(const r of n.tracks){const i={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking){if(N(i.info),i.info.type==="video"&&i.info.width!==-1){const s=i;i.trackBacking=new Ff(s),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){const s=i;i.trackBacking=new Df(s),this.tracks.push(i)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const n={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=n,e.sampleTableByteOffset===null)return n;N(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ja.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){N(e.info?.type==="audio");const s=Y0(e.info.codec),a=[],o=[];for(let c=0;c<n.sampleToChunk.length;c++){const u=n.sampleToChunk[c],l=n.sampleToChunk[c+1],d=(l?l.startChunkIndex:n.chunkOffsets.length)-u.startChunkIndex;for(let f=0;f<d;f++){const h=u.startSampleIndex+f*u.samplesPerChunk,p=h+u.samplesPerChunk,m=Ge(n.sampleTimingEntries,h,S=>S.startIndex),g=n.sampleTimingEntries[m],y=Ge(n.sampleTimingEntries,p,S=>S.startIndex),w=n.sampleTimingEntries[y],A=g.startDecodeTimestamp+(h-g.startIndex)*g.delta,v=w.startDecodeTimestamp+(p-w.startIndex)*w.delta-A,x=Yt(a);x&&x.delta===v?x.count++:a.push({startIndex:u.startChunkIndex+f,startDecodeTimestamp:A,count:1,delta:v});const P=u.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(P)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}n.sampleTimingEntries=a,n.sampleSizes=o}if(n.sampleCompositionTimeOffsets.length>0){n.presentationTimestamps=[];for(const s of n.sampleTimingEntries)for(let a=0;a<s.count;a++)n.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(const s of n.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){const o=s.startIndex+a,c=n.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}n.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),n.presentationTimestampIndexMap=Array(n.presentationTimestamps.length).fill(-1);for(let s=0;s<n.presentationTimestamps.length;s++)n.presentationTimestampIndexMap[n.presentationTimestamps[s].sampleIndex]=s}return n}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let n=this.reader.requestSliceRange(e,Gi,Ds);le(n)&&(n=await n),N(n);const r=Vr(n);N(r?.name==="moof");let i=this.reader.requestSlice(e,r.totalSize);le(i)&&(i=await i),N(i),this.traverseBox(i);const s=this.lastReadFragment;N(s&&s.moofOffset===e);for(const[,a]of s.trackData){const o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){const l=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(l)Wc(a,l.timestamp);else{const d=Ge(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];Wc(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const u=Ge(c,a.startTimestamp,l=>l.startTimestamp);if((u===-1||c[u].moofOffset!==s.moofOffset)&&c.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const l=await Uf(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,l.length);d++){const f=l[d];a.samples[d].encryption=f}}}return s}readContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-Gi&&this.traverseBox(e););}*iterateContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-Gi;){const r=e.filePos,i=Vr(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=r+i.totalSize}}traverseBox(e){const n=e.filePos,r=Vr(e);if(!r)return!1;const i=e.filePos,s=n+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mvhd":{const a=Se(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=ve(e),this.movieDurationInTimescale=un(e)):(e.skip(8),this.movieTimescale=ve(e),this.movieDurationInTimescale=ve(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...hr,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:qt,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,r.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new Ff(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new Df(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=Se(e),u=!!(vr(e)&1);if(a.disposition.default=u,o===0)e.skip(8),a.id=ve(e),e.skip(4),a.durationInMovieTimescale=ve(e);else if(o===1)e.skip(16),a.id=ve(e),e.skip(4),a.durationInMovieTimescale=un(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const l=[di(e),di(e),zc(e),di(e),di(e),zc(e),di(e),di(e),zc(e)],d=tc(lc(cg(l),90));N(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=Se(e);e.skip(3);let c=!1,u=0;const l=ve(e);for(let d=0;d<l;d++){const f=o===1?un(e):ve(e),h=o===1?Z1(e):bi(e),p=di(e);if(c){Be._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){u+=f;continue}if(p!==1){Be._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=h,c=!0}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=Se(e);e.skip(3),o===0?(e.skip(8),a.timescale=ve(e),a.durationInMediaTimescale=ve(e)):o===1&&(e.skip(16),a.timescale=ve(e),a.durationInMediaTimescale=un(e));let c=At(e);if(c>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;qu(a.languageCode)||(a.languageCode=qt)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=mt(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Ou},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=n,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=Se(e);e.skip(3);const c=ve(e);for(let u=0;u<c;u++){const l=e.filePos,d=Vr(e);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=At(e),a.info.height=At(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,l+d.totalSize-e.filePos));const h=f==="encv"?a.frmaCodecString:f;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":Dc.includes(f)?(a.info.codec="prores",a.info.proresFormat=f):h===null?Be._warn("Unknown encrypted video codec due to missing frma box."):Be._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);const h=At(e);e.skip(6);let p=At(e),m=At(e);e.skip(4);let g=ve(e)/65536,y=null;o===0&&h>0&&(h===1?(e.skip(4),m=8*ve(e),e.skip(8)):h===2&&(e.skip(4),g=Xd(e),p=ve(e),e.skip(4),m=ve(e),y=ve(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=g,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,l+d.totalSize-e.filePos));const w=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,w!=="mp4a")if(w==="opus")a.info.codec="opus",a.info.sampleRate=qa;else if(w==="flac")a.info.codec="flac";else if(w==="ulaw")a.info.codec="ulaw";else if(w==="alaw")a.info.codec="alaw";else if(w==="ac-3")a.info.codec="ac3";else if(w==="ec-3")a.info.codec="eac3";else if(xf.includes(w))a.info.codec="dts",a.info.dtsFormat=w;else if(w==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Be._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(w==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(Be._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(w==="raw ")a.info.codec="pcm-u8";else if(w==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(w==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(w==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(w==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(w==="ipcm"){const A=a.info.pcmSampleSize;a.info.pcmLittleEndian?A===16?a.info.codec="pcm-s16":A===24?a.info.codec="pcm-s24":A===32?a.info.codec="pcm-s32":(Be._warn(`Invalid ipcm sample size ${A}.`),a.info.codec=null):A===16?a.info.codec="pcm-s16be":A===24?a.info.codec="pcm-s24be":A===32?a.info.codec="pcm-s32be":(Be._warn(`Invalid ipcm sample size ${A}.`),a.info.codec=null)}else if(w==="fpcm"){const A=a.info.pcmSampleSize;a.info.pcmLittleEndian?A===32?a.info.codec="pcm-f32":A===64?a.info.codec="pcm-f64":(Be._warn(`Invalid fpcm sample size ${A}.`),a.info.codec=null):A===32?a.info.codec="pcm-f32be":A===64?a.info.codec="pcm-f64be":(Be._warn(`Invalid fpcm sample size ${A}.`),a.info.codec=null)}else if(w==="lpcm"&&y!==null){const A=m+7>>3,b=!!(y&1),v=!!(y&2),x=y&4?-1:0;m>0&&m<=64&&(b?m===32&&(a.info.codec=v?"pcm-f32be":"pcm-f32"):x&1<<A-1?A===1?a.info.codec="pcm-s8":A===2?a.info.codec=v?"pcm-s16be":"pcm-s16":A===3?a.info.codec=v?"pcm-s24be":"pcm-s24":A===4&&(a.info.codec=v?"pcm-s32be":"pcm-s32"):A===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&Be._warn("Unsupported PCM format.")}else w===null?Be._warn("Unknown encrypted audio codec due to missing frma box."):Be._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=l+d.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const c=mt(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=mt(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:Be._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=Se(e);e.skip(3),e.skip(1);const c=Se(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=Se(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=Se(e),a.encryptionInfo.defaultKid=_s(Ee(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const u=Se(e),l=new Uint8Array(16);l.set(Ee(e,u),0),a.encryptionInfo.defaultConstantIv=l}}break;case"avcC":{const a=this.currentTrack;if(!a||(N(a.info),r.contentSize===0))break;a.info.codecDescription=Ee(e,r.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(N(a.info),r.contentSize===0))break;a.info.codecDescription=Ee(e,r.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="video"),e.skip(4);const o=Se(e),c=Se(e),u=Se(e),l=u>>4,d=u>>1&7,f=u&1,h=Se(e),p=Se(e),m=Se(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="video"),e.skip(1);const o=Se(e),c=o>>5,u=o&31,l=Se(e),d=l>>7,f=l>>6&1,h=l>>5&1,p=l>>4&1,m=l>>3&1,g=l>>2&1,y=l&3,w=c===2&&f?h?12:10:f?10:8;e.skip(1);const A=Ee(e,r.contentSize-4),b=Cc(A);a.info.av1CodecInfo={profile:c,level:u,tier:d,bitDepth:w,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y,videoFullRangeFlag:b?.videoFullRangeFlag??0,colourPrimaries:b?.colourPrimaries??2,transferCharacteristics:b?.transferCharacteristics??2,matrixCoefficients:b?.matrixCoefficients??2}}break;case"colr":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="video");const o=mt(e,4);if(o!=="nclx"&&o!=="nclc")break;const c=At(e),u=At(e),l=At(e);let d;o==="nclx"&&(d=!!(Se(e)&128)),a.info.colorSpace={primaries:ur[c],transfer:fr[u],matrix:dr[l],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="video");const o=ve(e),c=ve(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"esds":{const a=this.currentTrack;if(!a||a.info?.type!=="audio")break;e.skip(4);const o=Se(e);N(o===3),Hc(e),e.skip(2);const c=Se(e),u=(c&128)!==0,l=(c&64)!==0,d=(c&32)!==0;if(u&&e.skip(2),l){const g=Se(e);e.skip(g)}d&&e.skip(2);const f=Se(e);N(f===4);const h=Hc(e),p=e.filePos,m=Se(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":m===169?a.info.codec="dts":Be._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),h>e.filePos-p){const g=Se(e);N(g===5);const y=Hc(e);if(a.info.codecDescription=Ee(e,y),a.info.codec==="aac"){const w=Qu(a.info.codecDescription);w.outputNumberOfChannels!==null&&(a.info.numberOfChannels=w.outputNumberOfChannels),w.outputSampleRate!==null&&(a.info.sampleRate=w.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(At(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio"),e.skip(4);const o=Se(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=Se(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio"),e.skip(1);const o=Se(e),c=At(e),u=ve(e),l=fl(e),d=Se(e);let f;d!==0?f=Ee(e,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),p=new DataView(h.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,u,!0),p.setInt16(16,l,!0),p.setUint8(18,d),h.set(f,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio"),e.skip(4);const o=127,c=128,u=e.filePos;for(;e.filePos<s;){const p=Se(e),m=vr(e);if((p&o)===Xi.STREAMINFO){e.skip(10);const y=ve(e),w=y>>>12,A=(y>>9&7)+1;a.info.sampleRate=w,a.info.numberOfChannels=A,e.skip(20)}else e.skip(m);if(p&c)break}const l=e.filePos;e.filePos=u;const d=Ee(e,l-u),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio");const o=Ee(e,3),c=new Qe(o),u=c.readBits(2);c.skipBits(8);const l=c.readBits(3),d=c.readBits(1);u<3&&(a.info.sampleRate=Da[u]),a.info.numberOfChannels=Bc[l]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio");const o=Ee(e,r.contentSize),c=F0(o);if(!c){Be._warn("Invalid dec3 box contents, ignoring.");break}const u=uf(c);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=ff(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;N(a.info?.type==="audio");const o=Ee(e,Math.min(r.contentSize,hf)),c=$0(o);if(!c){Be._warn("Invalid ddts box contents, ignoring.");break}a.info.sampleRate=c.sampleRate,c.numberOfChannels!==null&&(a.info.numberOfChannels=c.numberOfChannels)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e);let c=0,u=0;for(let l=0;l<o;l++){const d=ve(e),f=ve(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:u,count:d,delta:f}),c+=d,u+=d*f}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e);let c=0;for(let u=0;u<o;u++){const l=ve(e),d=bi(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:l,offset:d}),c+=l}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e),c=ve(e);if(o===0)for(let u=0;u<c;u++){const l=ve(e);a.sampleTable.sampleSizes.push(l)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);const o=Se(e),c=ve(e),u=Ee(e,Math.ceil(c*o/8)),l=new Qe(u);for(let d=0;d<c;d++){const f=l.readBits(o);a.sampleTable.sampleSizes.push(f)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];const o=ve(e);for(let c=0;c<o;c++){const u=ve(e)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e);for(let u=0;u<o;u++){const l=ve(e)-1,d=ve(e),f=ve(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:l,samplesPerChunk:d,sampleDescriptionIndex:f})}let c=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=c,u<a.sampleTable.sampleToChunk.length-1){const d=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;c+=d*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e);for(let c=0;c<o;c++){const u=ve(e);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=ve(e);for(let c=0;c<o;c++){const u=un(e);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mehd":{const a=Se(e);e.skip(3);const o=a===1?un(e):ve(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const a=ve(e),o=ve(e),c=ve(e),u=ve(e),l=ve(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:u,defaultSampleFlags:l})}break;case"tfra":{const a=Se(e);e.skip(3);const o=ve(e),c=this.tracks.find(w=>w.id===o);if(!c)break;const u=ve(e),l=(u&48)>>4,d=(u&12)>>2,f=u&3,h=[Se,At,vr,ve],p=h[l],m=h[d],g=h[f],y=ve(e);for(let w=0;w<y;w++){const A=a===1?un(e):ve(e),b=a===1?un(e):ve(e);p(e),m(e),g(e),c.fragmentLookupTable.push({timestamp:A,moofOffset:b})}c.fragmentLookupTable.sort((w,A)=>w.timestamp-A.timestamp);for(let w=0;w<c.fragmentLookupTable.length-1;w++){const A=c.fragmentLookupTable[w],b=c.fragmentLookupTable[w+1];A.timestamp===b.timestamp&&(c.fragmentLookupTable.splice(w+1,1),w--)}}break;case"moof":this.currentFragment={moofOffset:n,moofSize:r.totalSize,implicitBaseDataOffset:n,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(N(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((l,d)=>({presentationTimestamp:l.presentationTimestamp,sampleIndex:d})).sort((l,d)=>l.presentationTimestamp-d.presentationTimestamp);for(let l=0;l<a.presentationTimestamps.length;l++){const d=a.presentationTimestamps[l],f=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(a.firstKeyFrameTimestamp=f.presentationTimestamp),l<a.presentationTimestamps.length-1){const p=a.presentationTimestamps[l+1].presentationTimestamp-d.presentationTimestamp;f.duration=p}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[Yt(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:u}=this.currentTrack;N(u),u.startTimestamp!==null&&(Wc(a,u.startTimestamp),a.startTimestampIsFinal=!0),u.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=u.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=Ef(Ee(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{N(this.currentFragment),e.skip(1);const a=vr(e),o=!!(a&1),c=!!(a&2),u=!!(a&8),l=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),p=ve(e),m=this.tracks.find(y=>y.id===p);if(!m)break;const g=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=un(e):h&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=ve(e)),u&&(m.currentFragmentState.defaultSampleDuration=ve(e)),l&&(m.currentFragmentState.defaultSampleSize=ve(e)),d&&(m.currentFragmentState.defaultSampleFlags=ve(e)),f&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;N(a.currentFragmentState);const o=Se(e);e.skip(3);const c=o===0?ve(e):un(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;N(this.currentFragment),N(a.currentFragmentState);const o=Se(e),c=vr(e),u=!!(c&1),l=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),p=!!(c&2048),m=ve(e);let g=null;u&&(g=bi(e));let y=null;l&&(y=ve(e));let w;this.currentFragment.trackData.has(a.id)?(w=this.currentFragment.trackData.get(a.id),g!==null&&(w.currentOffset=a.currentFragmentState.baseDataOffset+g)):(w={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(g??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,w));for(let A=0;A<m;A++){let b;d?b=ve(e):(N(a.currentFragmentState.defaultSampleDuration!==null),b=a.currentFragmentState.defaultSampleDuration);let v;f?v=ve(e):(N(a.currentFragmentState.defaultSampleSize!==null),v=a.currentFragmentState.defaultSampleSize);let x;h?x=ve(e):(N(a.currentFragmentState.defaultSampleFlags!==null),x=a.currentFragmentState.defaultSampleFlags),A===0&&y!==null&&(x=y);let P=0;p&&(o===0?P=ve(e):P=bi(e));const S=!(x&65536);w.samples.push({presentationTimestamp:w.currentTimestamp+P,duration:b,byteOffset:w.currentOffset,byteSize:v,isKeyFrame:S,encryption:null}),w.currentOffset+=v,w.currentTimestamp+=b}this.currentFragment.implicitBaseDataOffset=w.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),vr(e)&1){const f=mt(e,4),h=ve(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const c=Se(e),u=ve(e);let l=null;c===0&&u>0&&(l=Ee(e,u));const d=Lf(a);d.defaultSampleInfoSize=c,d.sampleSizes=l,d.sampleCount=u}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=Se(e);if(vr(e)&1){const f=mt(e,4),h=ve(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const u=ve(e);if(u===0)break;u>1&&Be._warn("Multiple saio entries are not supported; using the first offset only.");let l=o===0?ve(e):Number(un(e));this.currentFragment&&(l+=this.currentFragment.moofOffset);const d=Lf(a);d.offset=l}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;N(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const u=!!(vr(e)&2),l=ve(e),d=a.encryptionInfo.defaultPerSampleIvSize;N(d!==null);for(let f=0;f<Math.min(l,o.samples.length);f++){const h=new Uint8Array(16);d>0?h.set(Ee(e,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(u){const g=At(e);p=[];for(let y=0;y<g;y++){const w=At(e),A=ve(e);p.push({clearLen:w,protectedLen:A})}}const m=o.samples[f];m.encryption={iv:h,subsamples:p}}}break;case"udta":{const a=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){const u=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=Xn(c):this.metadataTags.raw[o.name]??=Ee(c,o.contentSize),c.filePos=u}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=Kt.decode(Ee(c,o.contentSize)):this.metadataTags.title??=Xn(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Xn(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Xn(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Xn(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Xn(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Xn(c));break;case"\xA9day":if(!this.currentTrack){const u=new Date(Xn(c));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Xn(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Xn(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=ve(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const a=ve(e);for(let o=0;o<a;o++){const c=ve(e);e.skip(4);const u=Kt.decode(Ee(e,c-8));this.currentMetadataKeys.set(o+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:o,slice:c}of a){let u=o.name;const l=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(l)&&(u=this.currentMetadataKeys.get(l));const d=ng(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Fa?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=et(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=et(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}}class Bf{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,n=this.internalTrack.trackBacking.getType();let r=0;for(const i of e.tracks)if(i.trackBacking.getType()===n&&r++,i===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(N(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const n=await this.fetchPacketForSampleIndex(0,e);return n||!this.internalTrack.demuxer.isFragmented?n:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Cs(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,n){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Vc(i,r),a=await this.fetchPacketForSampleIndex(s,n);return!Nf(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=Ge(c.presentationTimestamps,r,f=>f.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,n)}async getNextPacket(e,n){const r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,n);const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}async getKeyPacket(e,n){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=sg(i,r),a=await this.fetchPacketForSampleIndex(s,n);return!Nf(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=cc(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,n)}async getNextKeyPacket(e,n){const r=this.packetToSampleIndex.get(e);if(r!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=og(s,r);return this.fetchPacketForSampleIndex(a,n)}const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,u)=>c.isKeyFrame&&u>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return N(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}async fetchPacketForSampleIndex(e,n){if(e===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ag(r,e);if(!i)return null;let s;if(n.metadataOnly)s=cn;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(le(u)&&(u=await u),!u)return null;if(s=Ee(u,i.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){const d=await Uf(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<d.length&&(l=d[e])}l??=Of(this.internalTrack.encryptionInfo),l&&(s=await zf(this.internalTrack,l,s,null))}}const a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new kt(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,n,r){if(n===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[n];N(s);let a;if(r.metadataOnly)a=cn;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(le(l)&&(l=await l),!l)return null;if(a=Ee(l,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??Of(this.internalTrack.encryptionInfo);d&&(a=await zf(this.internalTrack,d,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,u=new kt(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+n,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:n}),u}async performFragmentedLookup(e,n,r,i,s){const a=this.internalTrack.demuxer;let o=null,c=null,u=-1;if(e){const{sampleIndex:g,correctSampleFound:y}=n(e);if(y)return this.fetchPacketInFragment(e,g,s);g!==-1&&(c=e,u=g)}const l=Ge(this.internalTrack.fragmentLookupTable,r,g=>g.timestamp),d=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,f=Ge(this.internalTrack.fragmentPositionCache,r,g=>g.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){const A=o.trackData.get(this.internalTrack.id);if(A&&A.startTimestamp>i)break}let g=a.reader.requestSliceRange(m,Gi,Ds);if(le(g)&&(g=await g),!g)break;const y=m,w=Vr(g);if(!w)break;if(w.name==="moof"){o=await a.readFragment(y);const{sampleIndex:A,correctSampleFound:b}=n(o);if(b)return this.fetchPacketInFragment(o,A,s);A!==-1&&(c=o,u=A)}m=y+w.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const g=this.internalTrack.fragmentLookupTable[l-1];N(!g||g.timestamp<d.timestamp);const y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,n,y,i,s)}return c?this.fetchPacketInFragment(c,u,s):null}}class Ff extends Bf{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=n&&_c(n.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=n&&Mc(n.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!T0(this.internalTrack.info.vp9CodecInfo))){const n=await this.getFirstPacket({}),r=n&&af(n.data);r&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??r,videoFullRangeFlag:r.videoFullRangeFlag,colourPrimaries:r.colourPrimaries,transferCharacteristics:r.transferCharacteristics,matrixCoefficients:r.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!S0(this.internalTrack.info.av1CodecInfo))){const n=await this.getFirstPacket({}),r=n&&Cc(n.data);r&&(this.internalTrack.info.av1CodecInfo=r)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const n=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=n&&cf(n.data)}if(!ac(this.internalTrack.info.colorSpace)){const n=kf(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=n.primaries,this.internalTrack.info.colorSpace.transfer??=n.transfer,this.internalTrack.info.colorSpace.matrix??=n.matrix,this.internalTrack.info.colorSpace.fullRange??=n.fullRange}const e={codec:Nc(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}}class Df extends Bf{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&pf(e.data)}return{codec:Lc(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const Vc=(t,e)=>{if(t.presentationTimestamps){const n=Ge(t.presentationTimestamps,e,r=>r.presentationTimestamp);return n===-1?-1:t.presentationTimestamps[n].sampleIndex}else{const n=Ge(t.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(n===-1)return-1;const r=t.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},sg=(t,e)=>{if(!t.keySampleIndices)return Vc(t,e);if(t.presentationTimestamps){const n=Ge(t.presentationTimestamps,e,r=>r.presentationTimestamp);if(n===-1)return-1;for(let r=n;r>=0;r--){const i=t.presentationTimestamps[r].sampleIndex;if(Es(t.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{const n=Vc(t,e),r=Ge(t.keySampleIndices,n,i=>i);return t.keySampleIndices[r]??-1}},ag=(t,e)=>{const n=Ge(t.sampleTimingEntries,e,y=>y.startIndex),r=t.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=e)return null;let s=r.startDecodeTimestamp+(e-r.startIndex)*r.delta;const a=Ge(t.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=t.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],u=Ge(t.sampleToChunk,e,y=>y.startSampleIndex),l=t.sampleToChunk[u];N(l);const d=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),f=t.chunkOffsets[d],h=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk;let p=0,m=f;if(t.sampleSizes.length===1)m+=c*(e-h),p+=c*l.samplesPerChunk;else for(let y=h;y<h+l.samplesPerChunk;y++){const w=t.sampleSizes[y];y<e&&(m+=w),p+=w}let g=r.delta;if(t.presentationTimestamps){const y=t.presentationTimestampIndexMap[e];N(y!==void 0),y<t.presentationTimestamps.length-1&&(g=t.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:t.keySampleIndices?Es(t.keySampleIndices,e,y=>y)!==-1:!0}},og=(t,e)=>{if(!t.keySampleIndices)return e+1;const n=Ge(t.keySampleIndices,e,r=>r);return t.keySampleIndices[n+1]??-1},Wc=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(const n of t.samples)n.presentationTimestamp+=e;for(const n of t.presentationTimestamps)n.presentationTimestamp+=e},cg=t=>{const[e,n]=t,r=Math.atan2(n,e);return Number.isFinite(r)?r*(180/Math.PI):0},Nf=t=>t.sampleSizes.length===0,Lf=t=>t.currentFragmentState?t.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:t.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Uf=async(t,e,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{N(n.sampleSizes);for(let o=0;o<n.sampleCount;o++)r+=n.sampleSizes[o]}let i=t.requestSlice(n.offset,r);if(le(i)&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;N(s!==null);const a=[];for(let o=0;o<n.sampleCount;o++){const c=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[o],u=new Uint8Array(16);s>0?u.set(Ee(i,s),0):u.set(e.defaultConstantIv,0);let l=null;if(c>s){const d=At(i);l=[];for(let f=0;f<d;f++){const h=At(i),p=ve(i);l.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:l})}return n.resolved=a,a},Of=t=>t.defaultConstantIv?{iv:t.defaultConstantIv,subsamples:null}:null,zf=async(t,e,n,r)=>{N(t.encryptionInfo);const i=t.encryptionInfo;N(i.defaultKid!==null);const s=i.defaultKid;let a;const o=t.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!t.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const c=(async()=>{let u=t.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<u.length-1;d++)for(let f=d+1;f<u.length;f++)Mf(u[d],u[f])&&(u.splice(f,1),f--)}const l=await t.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof l=="string"&&l.length===32&&e0.test(l)||l instanceof Uint8Array&&l.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return l instanceof Uint8Array?l:t0(l)})();t.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?lg(a,i,e,n):ug(a,i,e,n)},lg=async(t,e,n,r)=>{const i=new Uint8Array(16);i.set(n.iv,0);const s=await crypto.subtle.importKey("raw",t,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!n.subsamples)return a(r);N(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=Hf(n.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const p of o)for(const m of p.perSubsample)c+=m.length;const u=new Uint8Array(c);let l=0;for(const p of o)for(const m of p.perSubsample)u.set(r.subarray(m.offset,m.offset+m.length),l),l+=m.length;const d=await a(u),f=new Uint8Array(r);let h=0;for(const p of o)for(const m of p.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},ug=(t,e,n,r)=>{const i=new Rf;i.init({key:t,iv:n.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(N(s!==null&&a!==null),!n.subsamples){const l=new Uint8Array(r),d=Math.floor(r.length/16);for(let f=0;f<d;f++){const h=f*16;i.in.set(r.subarray(h,h+16)),i.decrypt(),l.set(i.out,h)}return l}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),c=Hf(n.subsamples,s,a),u=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(const l of c){i.iv[0]=u.getUint32(0,!1),i.iv[1]=u.getUint32(4,!1),i.iv[2]=u.getUint32(8,!1),i.iv[3]=u.getUint32(12,!1);for(const d of l.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;i.in.set(r.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},Hf=(t,e,n)=>{const r=[],i=e!==0||n!==0;let s=0;for(const a of t){s+=a.clearLen;const o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,u=s;for(;c>0&&!(c<16*e);){const l=16*e;o.push({offset:u,length:l}),u+=l,c-=l;const d=Math.min(16*n,c);u+=d,c-=d}s+=a.protectedLen}r.push({perSubsample:o})}return r};var ce;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(ce||(ce={}));const fg=[ce.EBML,ce.Segment],Ns=[ce.SeekHead,ce.Info,ce.Cluster,ce.Tracks,ce.Cues,ce.Attachments,ce.Chapters,ce.Tags],$a=[...fg,...Ns],jc=8,bn=2,gr=2*jc,Vf=t=>{if(t.remainingLength<1)return null;const e=Se(t);if(t.skip(-1),e===0)return null;let n=1,r=128;for(;(e&r)===0;)n++,r>>=1;return t.remainingLength<n?null:n},Ls=t=>{if(t.remainingLength<1)return null;const e=Se(t);if(e===0)return null;let n=1,r=128;for(;(e&r)===0;)n++,r>>=1;if(t.remainingLength<n-1)return null;let i=e&r-1;for(let s=1;s<n;s++)i*=256,i+=Se(t);return i},He=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let n=0;for(let r=0;r<e;r++)n*=256,n+=Se(t);return n},dg=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let n=0n;for(let r=0;r<e;r++)n<<=8n,n+=BigInt(Se(t));return n},qc=t=>{const e=Vf(t);return e===null||t.remainingLength<e?null:He(t,e)},Wf=t=>{if(t.remainingLength<1)return null;if(Se(t)===255)return;t.skip(-1);const n=Ls(t);if(n===null)return null;if(n!==72057594037927940)return n},yr=t=>{N(t.remainingLength>=bn);const e=qc(t);if(e===null)return null;const n=Wf(t);return n===null?null:{id:e,size:n}},Ji=(t,e)=>{const n=Ee(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Us=(t,e)=>{const n=Ee(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return Kt.decode(n.subarray(0,r))},Xc=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ey(t):Xd(t)},$c=async(t,e,n,r)=>{const i=new Set(n);let s=e;for(;r===null||s<r;){let a=t.requestSliceRange(s,bn,gr);if(le(a)&&(a=await a),!a)break;const o=yr(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Wr(o.size),s=a.filePos+o.size}return{pos:r!==null&&r>s?r:s,found:!1}},jf=async(t,e,n,r)=>{const s=new Set(n);let a=e;for(;a<r;){let o=t.requestSliceRange(a,0,Math.min(65536,r-a));if(le(o)&&(o=await o),!o||o.length<jc)break;for(let c=0;c<o.length-jc;c++){o.filePos=a;const u=qc(o);if(u!==null&&s.has(u))return a;a++}}return null},Zt={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS"};function Wr(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const hg=t=>{let n=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){const r=[...new Set(t.codecStrings.filter(Boolean))];n+=`; codecs="${r.join(", ")}"`}return n};var br;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(br||(br={}));var Ga;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(Ga||(Ga={}));var Os;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Os||(Os={}));const Gc=[{id:ce.SeekHead,flag:"seekHeadSeen"},{id:ce.Info,flag:"infoSeen"},{id:ce.Tracks,flag:"tracksSeen"},{id:ce.Cues,flag:"cuesSeen"}],qf=10*2**20;class mg extends mr{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(n=>n.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),n=await Promise.all(e.map(r=>r.getDecoderConfig().then(i=>i?.codec??null)));return hg({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(r=>r.tracks.some(i=>i.info?.type==="audio")),codecStrings:n.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const n of this.segments)n.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(n),n.metadataTagsCollected=!0);let e={};for(const n of this.segments)e={...e,...n.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSliceRange(e,bn,gr);if(le(n)&&(n=await n),!n)break;const r=yr(n);if(!r)break;const i=r.id;let s=r.size;const a=n.filePos;if(i===ce.EBML){Wr(s);let o=this.reader.requestSlice(a,s);if(le(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===ce.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===ce.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await $c(this.reader,a,$a,this.reader.fileSize)).pos-a);const o=Yt(this.segments);o&&(o.elementEndPos=a+s)}Wr(s),e=a+s}})()}async readSegment(e,n){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:n===void 0?null:e+n,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(r,bn,gr);if(le(o)&&(o=await o),!o)break;const c=r,u=yr(o);if(!u||!Ns.includes(u.id)&&u.id!==ce.Void){const p=await jf(this.reader,c,Ns,Math.min(this.currentSegment.elementEndPos??1/0,c+qf));if(p){r=p;continue}else break}const{id:l,size:d}=u,f=o.filePos,h=Gc.findIndex(p=>p.id===l);if(h!==-1){const p=Gc[h].flag;this.currentSegment[p]=!0,Wr(d);let m=this.reader.requestSlice(f,d);le(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(l===ce.Tags||l===ce.Attachments){l===ce.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Wr(d);let p=this.reader.requestSlice(f,d);le(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(l===ce.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;r=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Gc.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,bn,gr);if(le(u)&&(u=await u),!u)continue;const l=yr(u);if(!l)continue;const{id:d,size:f}=l;if(d!==c.id)continue;Wr(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(u.filePos,f);le(h)&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,u)=>c.time-u.time);for(let c=0;c<o.cuePoints.length-1;c++){const u=o.cuePoints[c],l=o.cuePoints[c+1];u.time===l.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,n){if(n.lastReadCluster?.elementStartPos===e)return n.lastReadCluster;let r=this.reader.requestSliceRange(e,bn,gr);le(r)&&(r=await r),N(r);const i=e,s=yr(r);N(s);const a=s.id;N(a===ce.Cluster);let o=s.size;const c=r.filePos;o===void 0&&(o=(await $c(this.reader,c,$a,n.elementEndPos)).pos-c);let u=this.reader.requestSlice(c,o);le(u)&&(u=await u);const l={segment:n,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=l,u){const d=this.readContiguousElements(u,$a);l.elementEndPos=d}for(const[,d]of l.trackData){const f=d.track;N(d.blocks.length>0);let h=!1;for(let y=0;y<d.blocks.length;y++){const w=d.blocks[y];w.timestamp+=l.timestamp,h||=w.lacing!==br.None}d.presentationTimestamps=d.blocks.map((y,w)=>({timestamp:y.timestamp,blockIndex:w})).sort((y,w)=>y.timestamp-w.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){const w=d.presentationTimestamps[y],A=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&A.isKeyFrame&&(d.firstKeyFrameTimestamp=A.timestamp),y<d.presentationTimestamps.length-1){const b=d.presentationTimestamps[y+1];A.duration=b.timestamp-A.timestamp}else A.duration===0&&f.defaultDuration!=null&&A.lacing===br.None&&(A.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((y,w)=>({timestamp:y.timestamp,blockIndex:w})).sort((y,w)=>y.timestamp-w.timestamp));const p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[Yt(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;const g=Ge(f.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||f.clusterPositionCache[g].elementStartPos!==i)&&f.clusterPositionCache.splice(g+1,0,{elementStartPos:l.elementStartPos,startTimestamp:d.startTimestamp})}return n.lastReadCluster=l,l}getTrackDataInCluster(e,n){let r=e.trackData.get(n);if(!r){const i=e.segment.tracks.find(s=>s.id===n);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(n,r)}return r}expandLacedBlocks(e,n){for(let r=0;r<e.length;r++){const i=e[r];if(i.lacing===br.None)continue;i.decoded||(i.data=this.decodeBlockData(n,i.data),i.decoded=!0);const s=Nn.tempFromBytes(i.data),a=[],o=Se(s)+1;switch(i.lacing){case br.Xiph:{let u=0;for(let l=0;l<o-1;l++){let d=0;for(;s.bufferPos<s.length;){const f=Se(s);if(d+=f,f<255){a.push(d),u+=d;break}}}a.push(s.length-(s.bufferPos+u))}break;case br.FixedSize:{const u=s.length-1,l=Math.floor(u/o);for(let d=0;d<o;d++)a.push(l)}break;case br.Ebml:{const u=Ls(s);N(u!==null);let l=u;a.push(l);let d=l;for(let f=1;f<o-1;f++){const h=s.bufferPos,p=Ls(s);N(p!==null);const m=p,y=(1<<(s.bufferPos-h)*7-1)-1,w=m-y;l+=w,a.push(l),d+=l}a.push(s.length-(s.bufferPos+d))}break;default:N(!1)}N(a.length===o),e.splice(r,1);const c=i.duration||o*(n.defaultDuration??0);for(let u=0;u<o;u++){const l=a[u],d=Ee(s,l),f=i.timestamp+c*u/o,h=c/o;e.splice(r+u,0,{timestamp:f,duration:h,isKeyFrame:i.isKeyFrame,data:d,lacing:br.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const n of e.seekEntries){if(!(n.id===ce.Tags&&!e.tagsSeen)){if(!(n.id===ce.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+n.segmentPosition,bn,gr);if(le(r)&&(r=await r),!r)continue;const i=yr(r);if(!i||i.id!==n.id)continue;const{size:s}=i;Wr(s),N(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(r.filePos,s);le(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,n.id===ce.Tags?e.tagsSeen=!0:n.id===ce.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,n){for(;e.remainingLength>=bn;){const r=e.filePos;if(!this.traverseElement(e,n))return r}return e.filePos}traverseElement(e,n){const r=yr(e);if(!r||n&&n.includes(r.id))return!1;const{id:i,size:s}=r,a=e.filePos;switch(Wr(s),i){case ce.DocType:this.isWebM=Ji(e,s)==="webm";break;case ce.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case ce.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=He(e,s)}break;case ce.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=He(e,s)}break;case ce.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=He(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case ce.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Xc(e,s)}break;case ce.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...hr,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==Ga.Block||o.data.algorithm!==Os.HeaderStripping)&&(Be._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const l=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;l>0&&d>0&&(l>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*l/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/l))}if(this.currentTrack.codecId===Zt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Zt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===Zt.vp8)this.currentTrack.info.codec="vp8";else if(c===Zt.vp9)this.currentTrack.info.codec="vp9";else if(c===Zt.av1)this.currentTrack.info.codec="av1";else if(c===Zt.prores){const l=this.currentTrack.codecPrivate?Kt.decode(this.currentTrack.codecPrivate):"";Dc.includes(l)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=l)}const u=this.currentTrack;this.currentTrack.trackBacking=new pg(u),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Zt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Zt.mp3?this.currentTrack.info.codec="mp3":c===Zt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=qa):c===Zt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Zt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Zt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Zt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Zt.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const u=this.currentTrack;this.currentTrack.trackBacking=new gg(u),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case ce.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=He(e,s)}break;case ce.TrackType:{if(!this.currentTrack)break;const o=He(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Ou},alphaMode:!1,proresFormat:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case ce.FlagEnabled:{if(!this.currentTrack)break;He(e,s)||(this.currentTrack=null)}break;case ce.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!He(e,s)}break;case ce.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!He(e,s)}break;case ce.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!He(e,s)}break;case ce.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!He(e,s)}break;case ce.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!He(e,s)}break;case ce.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!He(e,s)}break;case ce.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Ji(e,s)}break;case ce.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=Ee(e,s)}break;case ce.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=He(e,s)}break;case ce.Name:{if(!this.currentTrack)break;this.currentTrack.name=Us(e,s)}break;case ce.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ji(e,s),qu(this.currentTrack.languageCode)||(this.currentTrack.languageCode=qt)}break;case ce.LanguageBCP47:{if(!this.currentTrack)break;const c=Ji(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=qt,this.currentTrack.hasLanguageBcp47=!0}break;case ce.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case ce.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=He(e,s)}break;case ce.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=He(e,s)}break;case ce.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=He(e,s)}break;case ce.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=He(e,s)}break;case ce.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=He(e,s)}break;case ce.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=He(e,s)===1}break;case ce.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case ce.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=He(e,s),c=dr[o];this.currentTrack.info.colorSpace.matrix=c}break;case ce.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=He(e,s);this.currentTrack.info.colorSpace.fullRange=o===1||o===2?o===2:void 0}break;case ce.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=He(e,s),c=fr[o];this.currentTrack.info.colorSpace.transfer=c}break;case ce.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=He(e,s),c=ur[o];this.currentTrack.info.colorSpace.primaries=c}break;case ce.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case ce.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Xc(e,s);try{this.currentTrack.info.rotation=tc(c)}catch{}}break;case ce.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case ce.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Xc(e,s)}break;case ce.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=He(e,s)}break;case ce.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=He(e,s)}break;case ce.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case ce.CueTime:this.currentCueTime=He(e,s);break;case ce.CueTrackPositions:{if(this.currentCueTime===null)break;N(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case ce.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=He(e,s)}break;case ce.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;N(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+He(e,s)}break;case ce.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=He(e,s)}break;case ce.SimpleBlock:{if(!this.currentCluster)break;const o=Ls(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=fl(e),l=Se(e),d=l>>1&3;let f=!!(l&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);const h=Ee(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:u,duration:0,isKeyFrame:f,data:h,lacing:d,decoded:!p,postProcessed:!1,mainAdditional:null})}break;case ce.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case ce.Block:{if(!this.currentCluster)break;const o=Ls(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=fl(e),d=Se(e)>>1&3,f=Ee(e,s-(e.filePos-a)),h=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:u,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!h,postProcessed:!1,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case ce.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case ce.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case ce.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Ee(e,s)}break;case ce.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=He(e,s)}break;case ce.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=He(e,s)}break;case ce.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case ce.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case ce.Targets:this.readContiguousElements(e.slice(a,s));break;case ce.TargetTypeValue:He(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case ce.TagTrackUID:case ce.TagEditionUID:case ce.TagChapterUID:case ce.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ce.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case ce.TagName:this.currentSimpleTagName=Us(e,s);break;case ce.TagString:{if(!this.currentSimpleTagName)break;const o=Us(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case ce.TagBinary:{if(!this.currentSimpleTagName)break;const o=Ee(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case ce.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new d0(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const c=this.currentAttachedFile.fileName;let u="unknown";if(c){const l=c.toLowerCase();l.startsWith("cover.")?u="coverFront":l.startsWith("back.")&&(u="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case ce.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=dg(e,s)}break;case ce.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Us(e,s)}break;case ce.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ji(e,s)}break;case ce.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=Ee(e,s)}break;case ce.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Us(e,s)}break;case ce.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case ce.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ga.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ce.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=He(e,s)}break;case ce.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=He(e,s)}break;case ce.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Os.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case ce.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=He(e,s)}break;case ce.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=Ee(e,s)}break;case ce.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,n){N(e.decodingInstructions.length>0);let r=n;for(const i of e.decodingInstructions)switch(N(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Os.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){const s=i.data.settings,a=new Uint8Array(s.length+r.length);a.set(s,0),a.set(r,s.length),r=a}break}break}return r}processTagValue(e,n){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=n,typeof n=="string")switch(e.toLowerCase()){case"title":r.title??=n;break;case"description":r.description??=n;break;case"artist":r.artist??=n;break;case"album":r.album??=n;break;case"album_artist":r.albumArtist??=n;break;case"genre":r.genre??=n;break;case"comment":r.comment??=n;break;case"lyrics":r.lyrics??=n;break;case"date":{const i=new Date(n);Number.isNaN(i.getTime())||(r.date??=i)}break;case"track_number":case"part_number":{const i=n.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(r.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{const i=n.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(r.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}break}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let n=null;for(const i of e.tracks){N(i.trackBacking);const s=await i.trackBacking.getFirstPacket({metadataOnly:!0});s&&(n=Math.min(n??1/0,s.timestamp))}let r=e.duration/e.timestampFactor;return r+=n??0,r}}class Xf{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,n=this.internalTrack.trackBacking.getType();let r=0;for(const i of e.segments)for(const s of i.tracks)if(s.trackBacking.getType()===n&&r++,s===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,n=>n.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Cs(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,n){const r=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=Ge(s.presentationTimestamps,r,u=>u.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,n)}async getNextPacket(e,n){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,i=>{if(i===r.cluster){const s=i.trackData.get(this.internalTrack.id);if(r.blockIndex+1<s.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async getKeyPacket(e,n){const r=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=cc(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,n)}async getNextKeyPacket(e,n){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,i=>{if(i===r.cluster){const a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return N(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async fetchPacketInCluster(e,n,r){if(n===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[n];if(N(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(s.data.length>=8&&s.data[4]===105&&s.data[5]===99&&s.data[6]===112&&s.data[7]===102)){const f=new Uint8Array(s.data.length+8);et(f).setUint32(0,f.length,!1),f[4]=105,f[5]=99,f[6]=112,f[7]=102,f.set(s.data,8),s.data=f}s.postProcessed=!0}const a=r.metadataOnly?cn:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,u={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?cn:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);const l=new kt(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+n,s.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:n}),l}async performClusterLookup(e,n,r,i,s){const{demuxer:a,segment:o}=this.internalTrack;let c=null,u=null,l=-1;if(e){const{blockIndex:y,correctBlockFound:w}=n(e);if(w)return this.fetchPacketInCluster(e,y,s);y!==-1&&(u=e,l=y)}const d=Ge(this.internalTrack.cuePoints,r,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=Ge(this.internalTrack.clusterPositionCache,r,y=>y.startTimestamp),p=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null;let g;for(e?m===null||e.elementStartPos>=m?(g=e.elementEndPos,c=e):g=m:g=m??o.clusterSeekStartPos;o.elementEndPos===null||g<=o.elementEndPos-bn;){if(c){const S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,bn,gr);if(le(y)&&(y=await y),!y)break;const w=g,A=yr(y);if(!A||!Ns.includes(A.id)&&A.id!==ce.Void){const S=await jf(a.reader,w,Ns,Math.min(o.elementEndPos??1/0,w+qf));if(S){g=S;continue}else break}const b=A.id;let v=A.size;const x=y.filePos;if(b===ce.Cluster){c=await a.readCluster(w,o),v=c.elementEndPos-x;const{blockIndex:S,correctBlockFound:k}=n(c);if(k)return this.fetchPacketInCluster(c,S,s);S!==-1&&(u=c,l=S)}v===void 0&&(N(b!==ce.Cluster),v=(await $c(a.reader,x,$a,o.elementEndPos)).pos-x);const P=x+v;if(o.elementEndPos===null){let S=a.reader.requestSliceRange(P,bn,gr);if(le(S)&&(S=await S),!S)break;if(qc(S)===ce.Segment){o.elementEndPos=P;break}}g=P}if(f&&(!u||u.elementStartPos<f.clusterPosition)){const y=this.internalTrack.cuePoints[d-1];N(!y||y.time<f.time);const w=y?.time??-1/0;return this.performClusterLookup(null,n,w,i,s)}return u?this.fetchPacketInCluster(u,l,s):null}}class pg extends Xf{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const r={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?_c(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Mc(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?af(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Cc(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?cf(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!ac(this.internalTrack.info.colorSpace)){const s=kf(r);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}const i={codec:Nc(r),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})():null}}class gg extends Xf{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&pf(e.data)}return{codec:Lc({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const Qc=async(t,e,n,r=null)=>{let s=e;for(;n===null||s<n;){const a=n!==null?Math.min(65536,n-s):65536;let o=t.requestSliceRange(s,fi,a);if(le(o)&&(o=await o),!o||o.length<fi)break;for(;o.remainingLength>=fi;){const c=o.filePos,u=ve(o),l=t.fileSize!==null?t.fileSize-s:null,d=Uc(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&Fs(d.header.channel)===Fs(r.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};class yg extends mr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new Ma,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new bg(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,wn);if(le(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=Ar(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Qc(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const n=e.header;this.lastLoadedPos=e.startPos+n.totalSize-1;const r=_f(n.mpegVersionId,n.channel);let i=this.reader.requestSlice(e.startPos+r,4);if(le(i)&&(i=await i),i){const o=ve(i);if(o===Sf||o===Pf){if(this.xingFrameHeader||(this.xingFrameHeader=n,this.xingFrameHeaderPos=e.startPos),!this.xingData){let u=this.reader.requestSlice(e.startPos+r+4,12);if(le(u)&&(u=await u),u){const l=Ee(u,12),d=et(l),f=d.getUint32(0,!1);this.xingData={frameCount:f&Xa.FrameCount?d.getUint32(4,!1):null,fileSize:f&Xa.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=n,this.firstFrameHeaderPos=e.startPos);const s=n.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:n.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=n.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let n=0,r=!1;for(;;){let i=this.reader.requestSlice(n,wn);if(le(i)&&(i=await i),!i)break;const s=Ar(i);if(!s)break;r=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(le(a)&&(a=await a),!a)break;eo(a,s,this.metadataTags),n=i.filePos+s.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Ja){let i=this.reader.requestSlice(this.reader.fileSize-Ja,Ja);le(i)&&(i=await i),N(i),mt(i,3)==="TAG"&&ty(i,this.metadataTags)}return this.metadataTags}finally{e()}}}class bg{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return N(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(N(e.firstFrameHeader!==null),N(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const n=eg(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),r=(e.reader.fileSize-e.firstFrameHeaderPos)/n;return Math.round(r)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return qt}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return N(this.demuxer.firstFrameHeader),Fs(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return N(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...hr}}async getDecoderConfig(){return N(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Fs(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,n){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=cn;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(le(s)&&(s=await s),!s)return null;i=Ee(s,r.dataSize)}return new kt(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=Es(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,n)}finally{r()}}async getPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Ge(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,n);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,n);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const $f=1399285583,wg=79764919,Gf=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let n=0;n<8;n++)e=e&2147483648?e<<1^wg:e<<1;Gf[t]=e>>>0&4294967295}const vg=t=>{const e=et(t),n=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let i=0;i<t.length;i++){const s=t[i];r=(r<<8^Gf[r>>>24^s])>>>0}return e.setUint32(22,n,!0),r},Ag=(t,e,n)=>{let r=0,i=null;if(t.length>0)if(e.codec==="vorbis"){N(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<s0(s-1))-1<<1,c=(t[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=n;const l=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[l],l===1){const d=(o|1)+1,f=t[0]&d?1:0;u=e.vorbisInfo.blocksizes[f]}r=u!==null?u+i>>2:0}else e.codec==="opus"&&(r=E0(t).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},xg=t=>{let e="audio/ogg";if(t.codecStrings){const n=[...new Set(t.codecStrings)];e+=`; codecs="${n.join(", ")}"`}return e};const hi=27,es=282,kg=es+65025,zs=t=>{const e=t.filePos;if(as(t)!==$f)return null;t.skip(1);const r=Se(t),i=J1(t),s=as(t),a=as(t),o=as(t),c=Se(t),u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=Se(t);const l=27+c,d=u.reduce((h,p)=>h+p,0),f=l+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+l,dataSize:d,headerType:r,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:u}},Tg=(t,e)=>{for(;t.filePos<e-3;){const n=as(t),r=n&255,i=n>>>8&255,s=n>>>16&255,a=n>>>24&255,o=79;if(!(r!==o&&i!==o&&s!==o&&a!==o)){if(t.skip(-4),n===$f)return!0;t.skip(1)}}return!1};class Sg extends mr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSliceRange(e,hi,es);if(le(n)&&(n=await n),!n)break;const r=zs(n);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const n of this.bitstreams){const r=await this.readPacket(n.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,n):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,n),n.codecInfo.codec!==null&&this.trackBackings.push(new Pg(n,this)))}})()}async readVorbisMetadata(e,n){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||(r=await this.findNextPacketStart(i),!r))return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(i.data.length);const c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),n.codecInfo.codec="vorbis",n.description=c,n.lastMetadataPacket=s;const u=et(e.data);n.numberOfChannels=u.getUint8(11),n.sampleRate=u.getUint32(12,!0);const l=u.getUint8(28);n.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:M0(s.data).modeBlockflags},Rc(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,n){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;n.codecInfo.codec="opus",n.description=e.data,n.lastMetadataPacket=i;const s=P0(e.data);n.numberOfChannels=s.outputChannelCount,n.sampleRate=qa,n.codecInfo.opusInfo={preSkip:s.preSkip},Rc(i.data.subarray(8),this.metadataTags)}async readPacket(e,n){N(n<e.lacingValues.length);let r=0;for(let d=0;d<n;d++)r+=e.lacingValues[d];let i=e,s=r,a=n;const o=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);le(d)&&(d=await d),N(d);const f=Ee(d,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(f.subarray(r,s));break}const p=i.lacingValues[a];if(s+=p,p<255){o.push(f.subarray(r,s));break e}a++}let h=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(h,hi,es);if(le(p)&&(p=await p),!p)return null;const m=zs(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;h=i.headerStartPos+i.totalSize}r=0,s=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;const u=new Uint8Array(c);let l=0;for(let d=0;d<o.length;d++){const f=o[d];u.set(f,l),l+=f.length}return{data:u,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(r,hi,es);if(le(i)&&(i=await i),!i)return null;const s=zs(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};r=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(n=>n.getDecoderConfig().then(r=>r?.codec??null)));return xg({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Pg{constructor(e,n){this.bitstream=e,this.demuxer=n,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Ma,this.internalSampleRate=e.codecInfo.codec==="opus"?qa:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(n=>n.bitstream===this.bitstream);return N(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return N(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return qt}getDisposition(){return{...hr,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(N(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,n,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:s}=Ag(e.data,this.bitstream.codecInfo,n.vorbisLastBlocksize),a=new kt(r.metadataOnly?cn:e.data,"key",Math.max(0,n.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:n.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:n.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){N(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(N(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const i=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,n){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const s=r.timestampInSamples+r.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:r.vorbisBlockSize},n)}async getPacket(e,n){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,n);const r=Cs(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(n);if(r<0)return null;N(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<a;){const w=s.headerStartPos,A=Math.floor((w+a)/2);let b=A;for(;;){const v=Math.min(b+kg,a-hi);let x=this.demuxer.reader.requestSlice(b,v-b);if(le(x)&&(x=await x),N(x),!Tg(x,v)){a=A+hi;continue e}let S=this.demuxer.reader.requestSliceRange(x.filePos,hi,es);le(S)&&(S=await S),N(S);const k=zs(S);N(k);let _=!1;if(k.serialNumber===this.bitstream.serialNumber)_=!0;else{let B=this.demuxer.reader.requestSlice(k.headerStartPos,k.totalSize);le(B)&&(B=await B),N(B);const V=Ee(B,k.totalSize);_=vg(V)===k.checksum}if(!_){b=k.headerStartPos+4;continue}if(_&&k.serialNumber!==this.bitstream.serialNumber){b=k.headerStartPos+k.totalSize;continue}if(k.granulePosition===-1){b=k.headerStartPos+k.totalSize;continue}this.granulePositionToTimestampInSamples(k.granulePosition)>r?a=k.headerStartPos:(s=k,o.push(k));continue e}}let c=i.startPage;for(const w of o){if(w.granulePosition===s.granulePosition)break;(!c||w.headerStartPos>c.headerStartPos)&&(c=w)}let u=c;const l=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){const w=u.headerStartPos+u.totalSize;let A=this.demuxer.reader.requestSliceRange(w,hi,es);le(A)&&(A=await A),N(A);const b=zs(A);N(b),u=b,u.serialNumber===this.bitstream.serialNumber&&l.push(u)}N(u.granulePosition!==-1);let d=null,f,h,p=u,m=0;if(u.headerStartPos===i.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{f=0,h=!1;for(let b=u.lacingValues.length-1;b>=0;b--)if(u.lacingValues[b]<255){d=b+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const w={data:cn,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(w)){const b=Yf(l,u,d);N(b);const v=Qf(l,b.page,b.segmentIndex);v&&(u=v.page,d=v.segmentIndex)}else for(;;){const b=Yf(l,u,d);if(!b)break;const v=Qf(l,b.page,b.segmentIndex);if(!v)break;if(u=v.page,d=v.segmentIndex,b.page.headerStartPos!==p.headerStartPos){p=b.page,m=b.segmentIndex;break}}}let g=null,y=null;for(;u!==null;){N(d!==null);const w=await this.demuxer.readPacket(u,d);if(!w)break;if(!(u.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},n);N(v);let x=this.encodedPacketToMetadata.get(v);if(N(x),!h&&w.endPage.headerStartPos===p.headerStartPos&&w.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(u.granulePosition),h=!0,v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f-x.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},n),N(v),x=this.encodedPacketToMetadata.get(v),N(x)):f+=x.durationInSamples,g=v,y=x,h&&(Math.max(f,0)>r||Math.max(x.timestampInSamples,0)===r))break}const b=await this.demuxer.findNextPacketStart(w);if(!b)break;u=b.startPage,d=b.startSegmentIndex}return g}async getPacketSequential(e,n){const r=await this.sequentialScanMutex.acquire();try{const i=Cs(e*this.internalSampleRate);e=i/this.internalSampleRate;const s=Ge(this.sequentialScanCache,i,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},n)}else a=await this.getFirstPacket(n);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,n);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const u=this.encodedPacketToMetadata.get(a);N(u),this.sequentialScanCache.length>0&&N(Yt(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const Qf=(t,e,n)=>{let r=e,i=n;e:for(;;){for(i--,i;i>=0;i--)if(r.lacingValues[i]<255){i++;break e}if(N(i===-1),!(r.headerType&1)){i=0;break}const a=Vu(t,o=>o.headerStartPos<r.headerStartPos);if(!a)return null;r=a,i=r.lacingValues.length}if(N(i!==-1),i===r.lacingValues.length){const s=t[t.indexOf(r)+1];N(s),r=s,i=0}return{page:r,segmentIndex:i}},Yf=(t,e,n)=>{if(n>0)return{page:e,segmentIndex:n-1};const r=Vu(t,i=>i.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Xt;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(Xt||(Xt={}));class _g extends mr{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);le(e)&&(e=await e),N(e);const n=mt(e,4),r=n!=="RIFX",i=n==="RF64",s=jr(e,r);let a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(mt(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,u=null,l=e.filePos;for(;a===null||l<a;){let f=this.reader.requestSlice(l,8);if(le(f)&&(f=await f),!f)break;const h=mt(f,4),p=jr(f,r),m=f.filePos;if(i&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,p,r);else if(h==="data"){if(u??=p,this.dataStart=f.filePos,this.dataSize=Math.min(u,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let g=this.reader.requestSlice(m,p);if(le(g)&&(g=await g),!g)break;const y=qd(g,r);u=qd(g,r),a=Math.min(y+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,p,r):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,p);l=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Eg(this))})()}async parseFmtChunk(e,n,r){let i=this.reader.requestSlice(e,n);if(le(i)&&(i=await i),!i)return;let s=Gs(i,r);const a=Gs(i,r),o=jr(i,r);i.skip(4);const c=Gs(i,r);let u;if(n===14?u=8:u=Gs(i,r),n>=18&&s!==357){const l=Gs(i,r),d=n-18;if(Math.min(d,l)>=22&&s===Xt.EXTENSIBLE){i.skip(6);const h=Ee(i,16);s=h[0]|h[1]<<8}}if((s===Xt.MULAW||s===Xt.ALAW)&&(u=8),s!==Xt.PCM&&s!==Xt.IEEE_FLOAT&&s!==Xt.ALAW&&s!==Xt.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===Xt.PCM&&![8,16,24,32].includes(u))throw new Error(`Unsupported WAVE PCM bit depth (${u}). Only 8, 16, 24, and 32 bits are supported.`);if(s===Xt.IEEE_FLOAT&&![32,64].includes(u))throw new Error(`Unsupported WAVE float bit depth (${u}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,n,r){let i=this.reader.requestSlice(e,n);if(le(i)&&(i=await i),!i)return;const s=mt(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+n-8;){i.filePos=a;const o=mt(i,4),c=jr(i,r),u=Ee(i,c);let l=0;for(let f=0;f<u.length&&u[f]!==0;f++)l++;const d=String.fromCharCode(...u.subarray(0,l));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{const f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,n){let r=this.reader.requestSlice(e,n);if(le(r)&&(r=await r),!r)return;const i=Ar(r);if(i){const s=n-wn;if(i.size=Math.min(i.size,s),i.size>0){const a=r.slice(e+wn,i.size);eo(a,i,this.metadataTags)}}}getCodec(){if(N(this.audioInfo),this.audioInfo.format===Xt.MULAW)return"ulaw";if(this.audioInfo.format===Xt.ALAW)return"alaw";if(this.audioInfo.format===Xt.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===Xt.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}N(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const ts=2048;class Eg{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(N(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return N(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return qt}getDisposition(){return{...hr}}async getPacketAtIndex(e,n){N(e>=0),N(this.demuxer.audioInfo);const r=e*ts*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(ts*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(le(c)&&(c=await c),!c)return null}let s;if(n.metadataOnly)s=cn;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);le(c)&&(c=await c),N(c),s=Ee(c,i)}const a=e*ts/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new kt(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,n){N(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ts,(this.demuxer.dataSize-1)/(ts*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const i=await this.getPacketAtIndex(r,n);if(i)return i;if(r===0)return null;N(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,n);for(;s;){const a=await this.getNextPacket(s,n);if(!a)break;s=a}return s}getNextPacket(e,n){N(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ts);return this.getPacketAtIndex(r+1,n)}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const Yc=7,ns=9,Hs=t=>{const e=t.filePos,n=Ee(t,9),r=new Qe(n);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const a=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);const u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return a===1?t.filePos-=2:f=r.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:f,startPos:e}};const Qa=1024;class Mg extends mr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Ma,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();N(this.firstFrameHeader),this.trackBackings=[new Cg(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,wn);if(le(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=Ar(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Yc,ns);if(le(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const n=Hs(e);if(!n){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&n.startPos+n.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=n);const r=Rs[n.samplingFrequencyIndex];N(r!==void 0);const i=Qa/r,s={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Qa,this.lastLoadedPos=n.startPos+n.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let n=0;for(;;){let r=this.reader.requestSlice(n,wn);if(le(r)&&(r=await r),!r)break;const i=Ar(r);if(!i)break;let s=this.reader.requestSlice(r.filePos,i.size);if(le(s)&&(s=await s),!s)break;eo(s,i,this.metadataTags),n=r.filePos+i.size}return this.metadataTags}finally{e()}}}class Cg{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Qa}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return qt}getCodec(){return"aac"}getInternalCodecId(){return N(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){N(this.demuxer.firstFrameHeader);const e=kc[this.demuxer.firstFrameHeader.channelConfiguration];return N(e!==void 0),e}getSampleRate(){N(this.demuxer.firstFrameHeader);const e=Rs[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return N(e!==void 0),e}getDisposition(){return{...hr}}async getDecoderConfig(){return N(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,n){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=cn;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(le(s)&&(s=await s),!s)return null;i=Ee(s,r.dataSize)}return new kt(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=Es(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,n)}finally{r()}}async getPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Ge(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,n);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,n);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const Ig=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,Rg=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Bg=t=>{let e=0;const n=new Qe(Ee(t,1));for(;n.readBits(1)===1;)e++;if(e===0)return n.readBits(7);const r=[],i=e-1,s=new Qe(Ee(t,i)),a=8-e-1;for(let c=0;c<a;c++)r.unshift(n.readBits(1));for(let c=0;c<i;c++)for(let u=0;u<8;u++){const l=s.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c|u<<l,0)},Fg=(t,e)=>{if(e==="uncommon-u16")return At(t)+1;if(e==="uncommon-u8")return Se(t)+1;if(typeof e=="number")return e;Ca(e),N(!1)},Dg=(t,e)=>e==="uncommon-u16"?At(t):e==="uncommon-u16-10"?At(t)*10:e==="uncommon-u8"?Se(t):typeof e=="number"?e:null,Ng=t=>{let n=0;for(const r of t){n^=r;for(let i=0;i<8;i++)(n&128)!==0?n=n<<1^7:n<<=1,n&=255}return n};class Lg extends mr{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Ma,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),N(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSlice(e,wn);if(le(n)&&(n=await n),!n){this.lastSampleLoaded=!0;return}const r=Ar(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);le(i)&&(i=await i),N(i),eo(i,r,this.metadataTags),e=n.filePos+r.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let n=this.reader.requestSlice(e,4);if(le(n)&&(n=await n),e+=4,n===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);N(n);const r=Se(n),i=vr(n),s=(r&128)!==0;switch(r&127){case Xi.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(le(o)&&(o=await o),N(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=Ee(o,34),u=new Qe(c),l=u.readBits(16),d=u.readBits(16),f=u.readBits(24),h=u.readBits(24),p=u.readBits(20),m=u.readBits(3)+1;u.readBits(5);const g=u.readBits(36);u.skipBits(128);const y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:g,minimumBlockSize:l,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:h,description:y},this.trackBacking=new Ug(this);break}case Xi.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);le(o)&&(o=await o),N(o),Rc(Ee(o,i),this.metadataTags);break}case Xi.PICTURE:{let o=this.reader.requestSlice(e,i);le(o)&&(o=await o),N(o);const c=ve(o),u=ve(o),l=Kt.decode(Ee(o,u)),d=ve(o),f=Kt.decode(Ee(o,d));o.skip(16);const h=ve(o),p=Ee(o,h);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:l,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}}if(e+=i,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:n}){N(this.audioInfo);const r=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,u=(this.audioInfo.maximumFrameSize||a)+i,l=await this.reader.requestSliceRange(e,i,u);if(!l)return null;const d=this.readFlacFrameHeader({slice:l,isFirstPacket:n});if(!d)return null;for(l.filePos=e+o;;){if(l.filePos>l.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:l.end-e,isLastFrame:!0};if(Se(l)===255){const h=l.filePos,p=Se(l),m=this.blockingBit===1?249:248;if(p!==m){l.filePos=h;continue}l.skip(-2);const g=l.filePos-e,y=this.readFlacFrameHeader({slice:l,isFirstPacket:!1});if(!y){l.filePos=h;continue}if(this.blockingBit===0){if(y.num-d.num!==1){l.filePos=h;continue}}else if(y.num-d.num!==d.blockSize){l.filePos=h;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:g,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:n}){const r=e.filePos,i=Ee(e,4),s=new Qe(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){N(n);const g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(N(!n),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(N(!n),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=Ig(s.readBits(4));if(!o)return null;N(this.audioInfo);const c=Rg(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const l=Bg(e),d=Fg(e,o),f=Dg(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const h=e.filePos-r,p=Se(e);e.skip(-h),e.skip(-1);const m=Ng(Ee(e,h));return p!==m?null:{num:l,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),N(this.lastLoadedPos!==null),N(this.audioInfo);const e=this.lastLoadedPos,n=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!n){this.lastSampleLoaded=!0;return}const r=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:n.blockSize,byteOffset:e,byteSize:n.size};if(this.lastLoadedPos=this.lastLoadedPos+n.size,this.loadedSamples.push(s),n.isLastFrame){this.lastSampleLoaded=!0;return}}}class Ug{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return qt}getTimeResolution(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return N(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...hr}}async getDecoderConfig(){return N(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,n){if(N(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Ge(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,n);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,n)}}finally{r()}}async getNextPacket(e,n){const r=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,n)}finally{r()}}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}async getPacketAtIndex(e,n){const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=cn;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(le(o)&&(o=await o),!o)return null;i=Ee(o,r.byteSize)}N(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,a=r.blockSize/this.demuxer.audioInfo.sampleRate;return new kt(i,"key",s,a,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const Mn=9e4,Kc=2**33,ln=188,Og=t=>{let e="video/MP2T";const n=[...new Set(t.filter(Boolean))];return n.length>0&&(e+=`; codecs="${n.join(", ")}"`),e};const Kf="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Zf=5,zg=1212435798,Hg=1212436562,Vg=1146376960,Wg=new Set([133,134,162]),Jf=new Set;class jg extends mr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{const e=ln+16+1;let n=this.reader.requestSlice(0,e);le(n)&&(n=await n),N(n);const r=Ee(n,e);if(r[0]===71&&r[ln]===71)this.packetOffset=0,this.packetStride=ln;else if(r[0]===71&&r[ln+16]===71)this.packetOffset=0,this.packetStride=ln+16;else if(r[4]===71&&r[4+ln+4]===71)this.packetOffset=4,this.packetStride=ln+4;else throw new Error("Unreachable.");const i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===u.pid)){s+=this.packetStride;continue}const l=await this.readSection(s,!0,!c);if(!l)break;const d=3,f=32;let h=!1;if(!c&&l.pid!==0&&!(l.payload[0]===0&&l.payload[1]===0&&l.payload[2]===1)){const g=new Qe(l.payload),y=g.readAlignedByte();g.skipBits(8*y),h=g.readBits(8)===2}if(l.pid===0&&!o){const m=new Qe(l.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);const y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>f;){const w=m.readBits(16);m.skipBits(3);const A=m.readBits(13);if(w!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=A}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((l.pid===a||h)&&!c){const m=new Qe(l.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);const y=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const w=m.readBits(10),A=m.pos+8*w;let b=!1;for(;m.pos<A;){const v=m.readBits(8),x=m.readBits(8),P=m.pos+8*x;if(v===Zf&&x>=4){const S=m.readBits(32);b||=S===zg||S===Hg}m.pos=P}for(m.pos=A;8*(y+d)-m.pos>f;){const v=m.readBits(8);m.skipBits(3);const x=m.readBits(13);m.skipBits(6);const P=m.readBits(10),S=m.pos+8*P;let k=!1,_=!1,I=!1;for(;m.pos<S;){const O=m.readBits(8),U=m.readBits(8),W=m.pos+8*U;if(O===106)k=!0;else if(O===122||O===204)_=!0;else if(O===123)I=!0;else if(O===Zf&&U>=4){const ie=m.readBits(32);I||=(ie&4294967040)===Vg}m.pos=W}let B=null;const V=b&&Wg.has(v)?130:v;switch(V){case 27:case 36:B={type:"video",codec:v===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let O;V===3||V===4?O="mp3":V===15?O="aac":V===129?O="ac3":V===135?O="eac3":O="dts",B={type:"audio",codec:O,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:_?B={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:k?B={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:I&&(B={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Jf.has(v)||(Be._warn(`Note: MPEG-TS streams with stream_type 0x${v.toString(16)} are not currently supported.`),Jf.add(v))}B&&this.elementaryStreams.push({demuxer:this,pid:x,streamType:v,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:B,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(g=>g.pid===l.pid);e:if(m&&!m.initialized){const g=rs(this,l,!0);if(!g)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=l,m.canBeTrustedWithKeyPackets=l.randomAccessIndicator===1,this.input._initInput){const A=(await this.input._initInput._getDemuxer()).elementaryStreams.find(b=>b.pid===l.pid&&b.info.codec===m.info.codec);if(A){m.info=A.info,m.initialized=!0;break e}}const y=new Vs(m,g);if(m.info.type==="video"){for(;;){const w=y;if(w.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=_c(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;const A=m.info.avcCodecInfo.sequenceParameterSets[0];N(A);const b=Oa(A);m.info.width=b.displayWidth,m.info.height=b.displayHeight;const v=b.pixelAspectRatio.num,x=b.pixelAspectRatio.den;v>0&&x>0&&(v>x?(m.info.squarePixelWidth=Math.round(m.info.width*v/x),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*x/v))),m.info.colorSpace={primaries:ur[b.colourPrimaries],transfer:fr[b.transferCharacteristics],matrix:dr[b.matrixCoefficients],fullRange:!!b.fullRangeFlag},m.info.reorderSize=b.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Mc(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const b=m.info.hevcCodecInfo.arrays.find(x=>x.nalUnitType===vt.SPS_NUT).nalUnits[0];N(b);const v=Ec(b);m.info.width=v.displayWidth,m.info.height=v.displayHeight,v.pixelAspectRatio.num>v.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*v.pixelAspectRatio.num/v.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*v.pixelAspectRatio.den/v.pixelAspectRatio.num)),m.info.colorSpace={primaries:ur[v.colourPrimaries],transfer:fr[v.transferCharacteristics],matrix:dr[v.matrixCoefficients],fullRange:!!v.fullRangeFlag},m.info.reorderSize=v.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Nc({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const w=Nn.tempFromBytes(y.suppliedPacket.data),A=Hs(w);if(!A)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:A.objectType},m.info.numberOfChannels=kc[A.channelConfiguration],m.info.sampleRate=Rs[A.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const w=ve(Nn.tempFromBytes(y.suppliedPacket.data)),A=Uc(w,y.suppliedPacket.data.byteLength);if(!A.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Fs(A.header.channel),m.info.sampleRate=A.header.sampleRate}else if(m.info.codec==="ac3"){const w=C0(y.suppliedPacket.data);if(!w)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(w.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Bc[w.acmod]+w.lfeon,m.info.sampleRate=Da[w.fscod]}else if(m.info.codec==="eac3"){const w=B0(y.suppliedPacket.data);if(!w)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const A=uf(w);if(A===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=ff(w),m.info.sampleRate=A}else if(m.info.codec==="dts"){const w=mf(y.suppliedPacket.data);if(!w)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=w.numberOfChannels,m.info.sampleRate=w.sampleRate,w.core&&(m.info.dtsFormat=w.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Lc({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo,dtsFormat:m.info.dtsFormat}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const u of this.elementaryStreams)u.initialized&&(u.info.type==="video"?this.trackBackingEntries.push(new qg(u)):this.trackBackingEntries.push(new Xg(u)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(n=>n.getDecoderConfig().then(r=>r?.codec??null)));return Og(e)}async readSection(e,n,r=!1){let i=e,s=e;const a=[];let o=0,c=null,u=!0,l=0;for(;;){const f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(c){if(f.pid!==c.pid){if(r)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}const h=!!(f.adaptationFieldControl&2),p=!!(f.adaptationFieldControl&1);let m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(l=f.body[1]>>6&1)),p&&(m===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(m)),o+=f.body.byteLength-m)),i=s,!n&&o>=64){u=!1;break}if(Es(this.sectionEndPositions,i,y=>y)!==-1){u=!1;break}}if(u){const f=Ge(this.sectionEndPositions,i,h=>h);this.sectionEndPositions.splice(f+1,0,i)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(f);let h=0;for(const p of a)d.set(p,h),h+=p.length}return{startPos:e,endPos:n?i:null,pid:c.pid,payload:d,randomAccessIndicator:l}}async readPacketHeader(e){let n=this.reader.requestSlice(e,4);if(le(n)&&(n=await n),!n)return null;if(Se(n)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=At(n),s=i>>14&1,a=i&8191,c=Se(n)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let n=this.reader.requestSlice(e,ln);if(le(n)&&(n=await n),!n)return null;const r=Ee(n,ln);if(r[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=(r[1]<<8)+r[2],a=s>>14&1,o=s&8191,u=r[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:u,body:r.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const i=60*Mn;this.timestampWrapInfo={reference:e-i,offset:e>=Kc-i?-Kc:Kc}}const{reference:n,offset:r}=this.timestampWrapInfo;return r<0&&e>=n||r>0&&e<n?e+r:e}}const mi=(t,e,n)=>{if(e.payload.byteLength<3)return null;const r=new Qe(e.payload);if(r.readBits(24)!==1)return null;const s=r.readBits(8);if(r.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;r.skipBits(8);const a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=t.normalizeTimestamp(o);else if(n)throw new Error(Kf);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}},rs=(t,e,n)=>{N(e.endPos!==null);const r=mi(t,e,n);if(!r)return null;const i=new Qe(e.payload);i.skipBits(32);const s=i.readBits(16),a=6;i.skipBits(16);const o=i.readBits(8),c=i.pos+8*o;i.pos=c;const u=c/8;N(Number.isInteger(u));const l=e.payload.subarray(u,s>0?a+s:e.payload.byteLength);return{...r,data:l}};class Ho{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,n=this.elementaryStream.info.type;let r=0;for(const i of e.trackBackingEntries)if(i.getType()===n&&r++,N(i instanceof Ho),i.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return qt}getDisposition(){return{...hr,primary:!1}}getTimeResolution(){return Mn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,n,r){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new kt(r.metadataOnly?cn:e.data,i,e.pts/Mn,Math.max(n/Mn,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const n=this.elementaryStream.firstSection;N(n);const r=rs(this.elementaryStream.demuxer,n,!0);N(r);const i=new Vs(this.elementaryStream,r),s=new Jc(this,i),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,n){let r=this.packetBuffers.get(e);if(r){const l=await r.readNext();if(!l)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(l.packet,l.duration,n);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}const i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,a=await s.readSection(i,!0);N(a);const o=rs(s,a,!0);N(o);const c=new Vs(this.elementaryStream,o);r=new Jc(this,c);const u=e.sequenceNumber;for(;;){const l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){const d=this.createEncodedPacket(l.packet,l.duration,n);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}async getNextKeyPacket(e,n){let r=e;for(;;){if(r=await this.getNextPacket(r,n),!r)return null;if(r.type==="key")return r}}getPacket(e,n){return this.doPacketLookup(e,!1,n)}getKeyPacket(e,n){return this.doPacketLookup(e,!0,n)}async doPacketLookup(e,n,r){const i=Cs(e*Mn),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,u=async(b,v,x)=>{let P=b;for(;P<v;){const S=await s.readPacketHeader(P);if(!S)return null;if(S.pid===c&&S.payloadUnitStartIndicator===1){const k=await s.readSection(P,x);if(!k)return null;const _=mi(s,k,!1);if(_&&_.pts!==null)return{pesPacketHeader:_,section:k}}P+=s.packetStride}return null},l=this.elementaryStream.firstSection;N(l);const d=mi(s,l,!0);if(N(d),i<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=Ge(h,i,b=>b.pts),m=p!==-1?h[p]:null;if(m&&i-m.pts<Mn/2)f=m.sectionStartPos;else{let b=0;if(a.fileSize!==null){const v=Math.ceil(a.fileSize/o);if(v>1){let x=0,P=v-1;for(b=x;x<=P;){const S=Math.floor((x+P)/2),k=uc(S*o,s.packetStride)+d.sectionStartPos,_=k+o,I=await u(k,_,!1);if(!I){P=S-1;continue}I.pesPacketHeader.pts<=i?(b=S,x=S+1):P=S-1}}}f=uc(b*o,s.packetStride)+d.sectionStartPos}let y=(await u(f,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);const w=this.getReorderSize(),A=async(b,v)=>{const x=await s.readSection(b,!0);N(x);const P=rs(s,x,!0);N(P);const S=new Vs(this.elementaryStream,P),k=new Jc(this,S);for(;!((Yt(k.presentationOrderPackets)?.pts??-1/0)>=i||!await k.readNextPacket()););const _=cc(k.presentationOrderPackets,v);if(_===-1)return null;const I=k.presentationOrderPackets[_],B=_===0?0:I.pts-k.presentationOrderPackets[_-1].pts;for(;k.decodeOrderPackets[0]!==I;)k.decodeOrderPackets.shift();k.lastDuration=B;const V=await k.readNext();N(V);const O=this.createEncodedPacket(V.packet,V.duration,r);return this.packetBuffers.set(O,k),this.packetSectionStarts.set(O,V.packet.sectionStartPos),O};if(!n||this.allPacketsAreKeyPackets()){e:for(;;){let b=y.sectionStartPos+s.packetStride;for(;;){const v=await s.readPacketHeader(b);if(!v)break e;if(v.pid===c&&v.payloadUnitStartIndicator===1){const x=await s.readSection(b,!1);if(x){const P=mi(s,x,!1);if(P&&P.pts!==null){if(P.pts>i)break e;y=P,Zc(this.elementaryStream,y);break}}}b+=s.packetStride}}e:for(let b=0;b<w+1;b++){let v=y.sectionStartPos-s.packetStride;for(;v>=s.packetOffset;){const x=await s.readPacketHeader(v);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){const P=await s.readSection(v,!1);if(P){const S=mi(s,P,!1);if(S&&S.pts!==null){y=S;break}}}v-=s.packetStride}}return A(y.sectionStartPos,b=>b.pts<=i)}else{let b=f,v=null;const x=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let P=null;const S=b<=d.sectionStartPos;let k,_=null;if(S)k=d,_=l;else{const V=await u(b,a.fileSize??1/0,x);k=V?.pesPacketHeader??null,_=V?.section??null}let I=!1,B=0;e:for(;k&&!(v!==null&&k.sectionStartPos>=v);){if(k.pts<=i){let O;if(this.elementaryStream.canBeTrustedWithKeyPackets)O=k.randomAccessIndicator===1;else{N(_);const U=rs(s,_,!0);N(U);const W=new Vs(this.elementaryStream,U);await W.markNextPacket(),O=W.suppliedPacket?.randomAccessIndicator===1}O&&(P=k)}if(k.pts>i&&(I=!0),I&&(B++,B>w))break;let V=k.sectionStartPos+s.packetStride;for(;;){const O=await s.readPacketHeader(V);if(!O)break e;if(O.pid===c&&O.payloadUnitStartIndicator===1){const U=await s.readSection(V,x);if(U){const W=mi(s,U,!1);if(W&&W.pts!==null){k=W,_=U,Zc(this.elementaryStream,k);break}}}V+=s.packetStride}}if(P){let V=P;if(B===0)e:for(let U=0;U<w;U++){let W=V.sectionStartPos-s.packetStride;for(;W>=s.packetOffset;){const ie=await s.readPacketHeader(W);if(!ie)break e;if(ie.pid===c&&ie.payloadUnitStartIndicator===1){const we=await s.readSection(W,x);if(we){const Y=mi(s,we,!1);if(Y&&Y.pts!==null){V=Y;break}}}W-=s.packetStride}}const O=await A(V.sectionStartPos,U=>U.pts<=i&&U.randomAccessIndicator===1);return N(O),O}if(S)return null;v=b,b=Math.max(uc(b-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class qg extends Ho{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return N(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Xg extends Ho{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return N(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Zc=(t,e)=>{const n=t.referencePesPackets,r=Ge(n,e.sectionStartPos,i=>i.sectionStartPos);if(r>=0){const i=n[r];if(e.pts<=i.pts)return!1;const s=t.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(r<n.length-1){const a=n[r+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return n.splice(r+1,0,e),!0};class Vs{constructor(e,n){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=n}ensureBuffered(e){const n=this.endPos-this.currentPos;return n>=e?e:this.bufferData(e-n).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return N(e),e}async bufferData(e){const n=this.endPos+e;for(;this.endPos<n;){let r;if(this.pesPackets.length===0)r=this.startingPesPacket;else{let i=Yt(this.pesPackets).sectionEndPos;for(N(i!==null);;){const s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(i,!0);if(!a)return;const o=rs(this.demuxer,a,!1);if(o){r=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(r),this.endPos+=r.data.byteLength}}readBytes(e){const n=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,i=r+e;if(this.currentPos+=e,i<=n.data.byteLength)return n.data.subarray(r,i);const s=new Uint8Array(e);s.set(n.data.subarray(r));let a=n.data.byteLength-r;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const n=this.currentPos-this.currentPesPacketPos;return this.currentPos++,n<e.data.byteLength?e.data[n]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const n=this.getCurrentPesPacket();this.currentPesPacketPos-=n.data.byteLength}else for(;;){const n=this.getCurrentPesPacket(),r=this.currentPesPacketPos+n.data.byteLength;if(e<r)break;this.currentPesPacketPos+=n.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){N(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const n=e.info.codec,r=1024;if(n!=="avc"&&n!=="hevc")throw new Error("Unhandled.");const i=n==="avc"?1:2;let s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(r);if(le(c)&&(c=await c),c===0)break;const u=this.currentPos,l=this.readBytes(c),d=l.byteLength;let f=0;for(;f<d;){const h=l.indexOf(0,f);if(h===-1||h>=d)break;f=h;const p=u+f;if(f+3>=d){this.seekTo(p);break}const m=l[f+1],g=l[f+2],y=l[f+3];let w=0;if(m===0&&g===0&&y===1?w=4:m===0&&g===1&&(w=3),w===0){f++;continue}const A=p;s??=A;const b=f+w,v=b+i,x=6;if(v+(n==="avc"?x:1)>d){this.seekTo(p);break}const S=l[b];let k,_,I;if(n==="avc")k=La(S),_=k===Rt.NON_IDR_SLICE||k===Rt.SLICE_DPA||k===Rt.IDR,I=k===Rt.SEI||k===Rt.SPS||k===Rt.PPS||k===Rt.AUD;else{if(k=qi(S),((S&1)<<5|l[b+1]>>3)>0){f+=w;continue}_=k<=vt.RASL_R||k>=vt.BLA_W_LP&&k<=21,I=k>=vt.VPS_NUT&&k<=37||k===vt.PREFIX_SEI_NUT||k>=41&&k<=44||k>=48&&k<=55}let B=!1;if(_){let V;if(n==="avc"){const O=l.subarray(v,v+x),U=ke(new Qe(O));V=!a||U<=o,o=U}else V=l[v]>>7===1;V&&(a?B=!0:a=!0)}else I&&a&&(B=!0);if(B){const V=A-s;return this.seekTo(s),this.supplyPacket(V,0)}f+=w}if(c<r)break}if(s!==null&&this.endPos>s){const c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{const n=e.info.codec,r=128;for(;;){let i=this.ensureBuffered(r);le(i)&&(i=await i);const s=this.currentPos;for(;this.currentPos-s<i;){const a=this.readU8();if(n==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(ns);if(le(c)&&(c=await c),c<ns)return;const u=this.readBytes(ns),l=Hs(Nn.tempFromBytes(u));if(l){this.seekTo(o);let d=this.ensureBuffered(l.frameLength);return le(d)&&(d=await d),this.supplyPacket(d,Math.round(Qa*Mn/e.info.sampleRate))}else this.seekTo(o+1)}else if(n==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(fi);if(le(c)&&(c=await c),c<fi)return;const u=this.readBytes(fi),l=et(u).getUint32(0),d=Uc(l,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);le(f)&&(f=await f);const h=d.header.audioSamplesInFrame*Mn/e.info.sampleRate;return this.supplyPacket(f,Math.round(h))}else this.seekTo(o+1)}else if(n==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(le(c)&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const l=u[4]>>6,d=u[4]&63;if(l===3||d>37){this.seekTo(o+1);continue}const f=I0[3*d+l];N(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),le(c)&&(c=await c);const h=Math.round(R0*Mn/e.info.sampleRate);return this.supplyPacket(c,h)}else if(n==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(le(c)&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const d=(((u[2]&7)<<8|u[3])+1)*2,h=u[4]>>6===3?3:u[4]>>4&3,p=lf[h];this.seekTo(o),c=this.ensureBuffered(d),le(c)&&(c=await c);const m=p*256,g=Math.round(m*Mn/e.info.sampleRate);return this.supplyPacket(c,g)}else if(n==="dts"){if(a!==127&&a!==100)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Ha);if(le(c)&&(c=await c),c<Ha)return;const u=this.readBytes(Ha),l=gf(u);let d=l?null:Wa(u);if(!l&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);const m=Math.min(d.frameSize,N0);let g=this.ensureBuffered(m);le(g)&&(g=await g),d=Wa(this.readBytes(g))??d}let f=l?l.frameSize:d.frameSize;if(l){let m=Math.ceil(l.frameSize/4)*4;for(;;){this.seekTo(o);const g=m+Fc;let y=this.ensureBuffered(g);if(le(y)&&(y=await y),y<g)break;this.seekTo(o+m);const w=Wa(this.readBytes(Fc));if(!w)break;m+=w.frameSize,f=m}}const h=l?.sampleCount??d.asset?.sampleCount;if(h===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(f),le(c)&&(c=await c);const p=Math.round(h*Mn/e.info.sampleRate);return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(i<r)break}}}supplyPacket(e,n){const r=this.getCurrentPesPacket();let i;if(this.lastSuppliedPesPacket===r)N(this.nextPts!==null),i=this.nextPts;else{if(r.pts===null)throw new Error(Kf);i=r.pts,Zc(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=i+n;const s=r.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const u=Ic(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Jc{constructor(e,n){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=n,this.reorderSize=e.getReorderSize(),N(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],n=this.presentationOrderPackets.indexOf(e);N(n!==-1);let r;for(n===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[n+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(N(e);;){const n=this.presentationOrderPackets.indexOf(e);if(n!==-1&&n<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let n=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[n].pts&&(n=i);const r=this.reorderBuffer[n];this.presentationOrderPackets.push(r),this.reorderBuffer.splice(n,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,n)=>e.pts-n.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const ed="application/vnd.apple.mpegurl",td="#EXT-X-STREAM-INF:",nd="#EXT-X-I-FRAME-STREAM-INF:",rd="#EXT-X-MEDIA:",el="#EXTINF:",id="#EXT-X-MAP:",sd="#EXT-X-KEY:",ad="#EXT-X-MEDIA-SEQUENCE:",od="#EXT-X-BYTERANGE:",cd="#EXT-X-PROGRAM-DATE-TIME:",$g="#EXT-X-DISCONTINUITY",ld="#EXT-X-TARGETDURATION:",Gg="#EXT-X-ENDLIST",ud="#EXT-X-PLAYLIST-TYPE:",Qg="#EXT-X-I-FRAMES-ONLY",fd=t=>t.length===0||t.startsWith("#")&&!t.startsWith("#EXT");class Ws{constructor(e){this._attributes={};let n="",r="",i=!1,s=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(n&&(this._attributes[n.trim().toLowerCase()]=r),n="",r="",i=!1):i?r+=o:n+=o}n&&(this._attributes[n.trim().toLowerCase()]=r)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const n=this.get(e);if(n===null)return null;const r=Number(n);return Number.isFinite(r)?r:null}merge(e){Object.assign(this._attributes,e._attributes)}}class Yg{constructor(e,n,r){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=n,this.trackDeclarations=r}async getDurationFromMetadata(e){const n=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return n?n.timestamp+n.duration:null}async getUnixTimeForTimestamp(e){let n=await this.getSegmentAt(e,{});if(n??=await this.getFirstSegment({}),!n||n.unixEpochTimestamp===null)return null;const r=e-n.timestamp;return n.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{const e=[];if(this.trackDeclarations){for(const n of this.trackDeclarations)if(n.type==="video"){const r=Is(e,i=>i.getType()==="video")+1;e.push(new hd(this,n,r))}else if(n.type==="audio"){const r=Is(e,i=>i.getType()==="audio")+1;e.push(new md(this,n,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const r=await this.getInputForSegment(this.firstSegment).getTracks();for(const i of r)if(i.type==="video"){const s=Is(e,a=>a.getType()==="video")+1;e.push(new hd(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){const s=Is(e,a=>a.getType()==="audio")+1;e.push(new md(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){const n=this.firstTimestampCache.get(e);if(n!==void 0)return n;const r=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,r),r}async getMediaOffset(e,n){const r=e.firstSegment??e;let i;if(this.firstSegmentFirstTimestamps.has(r))i=this.firstSegmentFirstTimestamps.get(r);else{const u=this.getInputForSegment(r);i=await this.getFirstTimestampForInput(u),this.firstSegmentFirstTimestamps.set(r,i)}if(r===e)return r.timestamp-i;const s=await this.getFirstTimestampForInput(n),a=e.timestamp-r.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?r.timestamp-i:e.timestamp-s}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class dd{constructor(e,n,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=n,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let e=this.segmentedInput.firstSegment,n=null;for(;e&&(n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number)??null,!n);)e=await this.segmentedInput.getNextSegment(e,{});if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),N(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,n,r){N(e.sequenceNumber>=0),N(this.segmentedInput.firstSegment);const i=await this.segmentedInput.getMediaOffset(n,r.input),s=n.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:ju(e.timestamp+i,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:n,track:r,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),N(this.firstInputTrack),N(this.firstSegment);let n=this.firstInputTrack,r=this.firstSegment;for(;;){if(n){const a=await n._backing.getFirstPacket(e);if(a)return this.createAdjustedPacket(a,r,n)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;n=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(a=>a.type===this.firstInputTrack.type&&a.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,n){return this._getNextInternal(e,n,!1)}getNextKeyPacket(e,n){return this._getNextInternal(e,n,!0)}async _getNextInternal(e,n,r){const i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");const s=r?await i.track._backing.getNextKeyPacket(i.sourcePacket,n):await i.track._backing.getNextPacket(i.sourcePacket,n);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:n.skipLiveWait});if(!o)return null;const l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===i.track.type&&f.number===i.track.number);if(!l){a=o;continue}const d=await l._backing.getFirstPacket(n);return d?this.createAdjustedPacket(d,o,l):null}}getPacket(e,n){return this._getPacketInternal(e,n,!1)}getKeyPacket(e,n){return this._getPacketInternal(e,n,!0)}async _getPacketInternal(e,n,r){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:n.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){const s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(i,s),u=e-c,l=r?await o._backing.getKeyPacket(u,n):await o._backing.getPacket(u,n);if(!l){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}return this.createAdjustedPacket(l,i,o)}return null}}class hd extends dd{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class md extends dd{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}wc();const pd=0,gd=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});class wr extends xc{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Lt;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,pd,gd),e=this._getFileSize(),N(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new Lt;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,n){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new i1(this,e,n)}_dispatchRead(e,n){this.onread?.(e,n),this._emit("read",{start:e,end:n})}ref(){return new tl(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class tl{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;N(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class is extends wr{constructor(e,n){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof n!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=n}_resolveRequest(e){const n=this.requestHandler(e),r=i=>{if(!(i instanceof wr||i instanceof tl))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=i instanceof wr?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return le(n)?n.then(r):r(n)}}const yd=(t,e)=>t.path===e.path;class Kg extends is{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,n,r,i){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof wr?o.ref():o;return this._root=c,this._rootRequest=null,c};le(s)?this._rootRequest=s.then(a):(a(s),N(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,n,r,i))}return this._root.source._read(e,n,r,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t.cancel().catch(()=>{})});const Zg=.5*2**20,Jg=(t,e,n)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return Be._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)},bd=new Set;class wu extends is{constructor(e,n={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.requestInit!==void 0&&(!n.requestInit||typeof n.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(n.getRetryDelay!==void 0&&typeof n.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(n.maxCacheSize!==void 0&&(!Ia(n.maxCacheSize)||n.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(n.parallelism!==void 0&&(!Number.isInteger(n.parallelism)||n.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(n.fetchFn!==void 0&&typeof n.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");const r=e instanceof Request?e.url:e instanceof URL?e.href:e;super(r,a=>new wu(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=n,this._getRetryDelay=n.getRetryDelay??Jg,this._requestInit={...n.requestInit};let i=null;if(n.requestInit?.headers){const a={...dc(n.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(i=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){const a=e.headers.get("Range");if(a!==null){i??=a;const o=new Request(e);o.headers.delete("Range"),this._url=o}}if(i!==null){const a=t1(i);a&&(this._offset=a.offset,this._length=a.length)}const s=2;this._orchestrator=new r1({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:n1.network,handleUnhandledError:n.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:Ms(e-this._offset,0,this._length??1/0)}_read(e,n,r,i){if(this._length!==null&&n>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+n):this._orchestrator.read(s+e,s+n,Math.max(s+r,s),s+Math.min(i,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return le(a)?a.then(o):o(a)}async _runWorker(e){for(;;){const n=new AbortController,r=await $u(this._options.fetchFn??fetch,this._url,Xu(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(this._orchestrator.fileSize===null&&(r.status===206||r.type==="basic"&&!r.headers.has("Content-Encoding"))){const s=r.headers.get("Content-Range");if(s){const o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=r.headers.get("Content-Length");if(a){const o=r.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(o+Number(a))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(r.status!==206){if(this._sequentialBacking){r.body.cancel();return}if(!this._usedForHls){const s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(bd.has(s.origin)||(Be._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),bd.add(s.origin)))}this._transitionToSequentialMode(r.body);return}const i=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;const u=this._getRetryDelay(1,c,this._url);if(u!==null){Be._error("Error while reading response stream. Attempting to resume.",c),await Ba(1e3*u);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_transitionToSequentialMode(e){let n=e.getReader(),r=0,i=0;const s=new ReadableStream({pull:async c=>{for(;;){let u;try{u=await n.read()}catch(d){if(this._disposed)throw d;const f=this._getRetryDelay(1,d,this._url);if(f===null)throw d;Be._error("Error while reading response stream. Attempting to resume.",d),await Ba(1e3*f);const h=await $u(this._options.fetchFn??fetch,this._url,Xu(this._requestInit,{headers:{Range:`bytes=${r}-`}}),this._getRetryDelay,()=>this._disposed);if(!h.ok)throw new Error(`Error fetching ${String(this._url)}: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=h.body.getReader(),i=h.status===206?0:r;continue}if(u.done){c.close();return}let l=u.value;if(i>0){const d=Math.min(i,l.length);i-=d,l=l.subarray(d)}if(l.length!==0){r+=l.length,c.enqueue(l);return}}},cancel:()=>n.cancel()}),a=new wd(s,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});a._endIndex=this._orchestrator.fileSize,a._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",a.on("read",({start:c,end:u})=>this._dispatchRead(c,u)),this._sequentialBacking=a;const o=new Set;for(const c of this._orchestrator.workers){for(const u of c.pendingSlices)o.add(u);c.aborted=!0,c.pendingSlices.length=0}for(const c of this._orchestrator.queuedReads)for(const u of c.pendingSlices)o.add(u);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const u=a._read(c.start,c.start+c.bytes.length);le(u)?u.then(l=>{l?(N(l.offset===c.start),c.resolve(l.bytes)):c.resolve(null)},l=>c.reject(l)):(N(u===null),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const e1=/^bytes=(\d+)-(\d*)$/,t1=t=>{const e=e1.exec(t.trim());if(!e)return null;const n=Number(e[1]),r=e[2]===""?null:Number(e[2]);return r!==null&&r<n?null:{offset:n,length:r!==null?r-n+1:null}};class wd extends wr{constructor(e,n={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(n.maxCacheSize!==void 0&&(!Ia(n.maxCacheSize)||n.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.",this._stream=e,this._maxCacheSize=n.maxCacheSize??32*2**20,this._handleUnhandledError=n.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,n){if(this._endIndex!==null&&n>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,n);const r=Ge(this._cache,e,l=>l.start),i=r!==-1?this._cache[r]:null;if(i&&i.start<=e&&n<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e;const a=new Uint8Array(n-e);if(r!==-1)for(let l=r;l<this._cache.length;l++){const d=this._cache[l];if(d.start>=n)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const h=Math.min(n,d.end);f<h&&(a.set(d.bytes.subarray(f-d.start,h-d.start),f-e),s=h)}if(s===n)return{bytes:a,view:et(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=Dt();return this._pendingSlices.push({start:e,end:n,bytes:a,resolve:c,reject:u}),this._targetIndex=Math.max(this._targetIndex,n),this._pulling||(this._pulling=!0,this._pull().catch(l=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(l)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(l);else throw l})),o}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:n}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const r=this._currentIndex,i=this._currentIndex+n.byteLength;this._dispatchRead(r,i);for(let s=0;s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(r,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(n.subarray(o-r,c-r),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:et(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:r,end:i,bytes:n,view:et(n),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=n.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Lt);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const n1={network:(t,e,n)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(const i of n){const a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(bc(t,e,a,i.targetPos)){const o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);e=Math.max(e,i.startPos+l)}}return e=Math.max(e,t+Zg),{start:t,end:e}}};class r1{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,n,r,i){N(!this.disposed);const s=this.options.prefetchProfile(e,n,this.workers),a=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,i);N(a<=e&&n<=o);let c=null;const u=Ge(this.cache,e,v=>v.start),l=u!==-1?this.cache[u]:null;l&&l.start<=e&&n<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});const d=Ge(this.cache,a,v=>v.start),f=c?null:new Uint8Array(n-e);let h=0,p=a;const m=[];if(d!==-1){for(let v=d;v<this.cache.length;v++){const x=this.cache[v];if(x.start>=o)break;if(x.end<=a)continue;const P=Math.max(a,x.start),S=Math.min(o,x.end);if(N(P<=S),p<P&&m.push({start:p,end:P}),p=S,f){const k=Math.max(e,x.start),_=Math.min(n,x.end);if(k<_){const I=k-e;f.set(x.bytes.subarray(k-x.start,_-x.start),I),I===h&&(h=_-e)}}x.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:et(f),offset:e}),m.length===0)return N(c),c;const{promise:g,resolve:y,reject:w}=Dt(),A=[];for(const v of m){const x=Math.max(e,v.start),P=Math.min(n,v.end);x===v.start&&P===v.end?A.push(v):x<P&&A.push({start:x,end:P})}const b=f&&{start:e,bytes:f,holes:A,resolve:y,reject:w};e:for(const v of m){for(const S of this.workers)if(this.checkHoleAgainstWorker(S,v,b?[b]:[])){this.checkQueuedReadsAgainstWorker(S);continue e}const x=v.end<o||this.fileSize!==null,P=this.createWorker(v.start,v.end,x);if(P)b&&(P.pendingSlices=[b]),this.runWorker(P);else{let S=Ge(this.queuedReads,v.start,_=>_.hole.start),k=S!==-1?this.queuedReads[S]:null;for(k&&v.start<=k.hole.end?(k.hole.end=Math.max(k.hole.end,v.end),k.strictTarget&&=x,b&&k.pendingSlices.push(b)):(S++,k={hole:{start:v.start,end:v.end},strictTarget:x,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(S,0,k));S+1<this.queuedReads.length;){const _=this.queuedReads[S+1];if(_.hole.start>k.hole.end)break;k.hole.end=Math.max(k.hole.end,_.hole.end),k.pendingSlices.push(..._.pendingSlices),k.strictTarget&&=_.strictTarget,k.age=Math.min(k.age,_.age),this.queuedReads.splice(S+1,1)}}}return c?g.catch(v=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(v);else throw v}):(N(f),c=g.then(v=>v&&{bytes:v,view:et(v),offset:e})),c}checkHoleAgainstWorker(e,n,r){if(bc(n.start-131072,n.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,n.end);for(let s=0;s<r.length;s++){const a=r[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let n=!1;for(let r=0;r<this.queuedReads.length;r++){const i=this.queuedReads[r];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(r,1),r--,n=!0;else if(n)break}}createWorker(e,n,r){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)N(a!==null),N(s.pendingSlices.length===0),this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(s);else return null}const i={startPos:e,currentPos:e,targetPos:n,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){N(!e.running),N(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(n=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(n)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(n);else throw n}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let n=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[n].age&&(n=s);const r=this.queuedReads[n],i=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);if(!i)return;this.queuedReads.splice(n,1),i.pendingSlices=r.pendingSlices,this.runWorker(i)}})}supplyWorkerData(e,n){N(!e.aborted);const r=e.currentPos,i=r+n.length;this.insertIntoCache({start:r,end:i,bytes:n,view:et(n),age:this.nextAge++}),e.currentPos+=n.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){const a=e.pendingSlices[s],o=Math.max(r,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(n.subarray(o-r,c-r),o-a.start);for(let u=0;u<a.holes.length;u++){const l=a.holes[u];r<=l.start&&i>l.start&&(l.start=i),l.end<=l.start&&(a.holes.splice(u,1),u--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const a=this.workers[s];e===a||a.running||bc(r,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a),s--)}}supplyFileSize(e){N(this.fileSize===null),this.fileSize=e;for(const n of this.workers){n.targetPos=Math.min(n.targetPos,e),n.strictTarget=!0;for(let r=0;r<n.pendingSlices.length;r++){const i=n.pendingSlices[r];for(const s of i.holes)if(s.end>e){i.resolve(null),n.pendingSlices.splice(r,1),r--;break}}}for(let n=0;n<this.queuedReads.length;n++){const r=this.queuedReads[n];if(r.hole.start>=e){for(const i of r.pendingSlices)i.resolve(null);this.queuedReads.splice(n,1),n--}else if(r.hole.end>e){r.hole.end=e,r.strictTarget=!0;for(let i=0;i<r.pendingSlices.length;i++){const s=r.pendingSlices[i];s.start>=e&&(s.resolve(null),r.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const n=this.workers.indexOf(e);N(n!==-1),e.running=!1,this.workers.splice(n,1),this.options.onIdleWorkerRemoved?.(e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const r of e.pendingSlices)r.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let n=Ge(this.cache,e.start,r=>r.start)+1;if(n>0){const r=this.cache[n-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=et(i),r.end=e.end,n--,e=r}else this.cache.splice(n,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(n,0,e),this.currentCacheSize+=e.bytes.length;for(let r=n+1;r<this.cache.length;r++){const i=this.cache[r];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(r,1),this.currentCacheSize-=i.bytes.length,r--;continue}const s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=et(s),e.end=i.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<i.age&&(r=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(const e of this.workers){for(const n of e.pendingSlices)n.reject(new Lt);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(const e of this.queuedReads)for(const n of e.pendingSlices)n.reject(new Lt);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class i1 extends wr{constructor(e,n,r){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=n,this._length=r??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:Ms(e-this._offset,0,this._length??1/0)}_read(e,n,r,i){if(this._length!==null&&n>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+n,this._offset+r,this._offset+i),a=o=>o?(o.offset-=this._offset,o):null;return le(s)?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var vd=function(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],n&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:n})}else n&&t.stack.push({async:!0});return e},Ad=(function(t){return function(e){function n(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,i=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&i===1)return i=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(a).then(s,function(o){return n(o),s()})}else i|=1}catch(o){n(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var r=new Error(n);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});const s1=/^0[xX][0-9a-fA-F]+$/,a1=/^data:.*;base64,/i;class xd extends Yg{constructor(e,n,r,i){super(e.input,n,r),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=n,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await Ba(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,n=Math.max(0,1e3*this.refreshInterval-e);return n<=50?0:n}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const A={stack:[],error:void 0,hasError:!1};try{const b=vd(A,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),x=await new Za(b.source).requestEntireFile();N(x),e=$d(x,x.length,{ignore:fd}),b.source instanceof is&&(this.rootPath=b.source.rootPath)}catch(b){A.error=b,A.hasError=!0}finally{Ad(A)}}const n=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1;let r=!1,i=0,s=null,a=null,o=null,c=0,u=null,l=null,d=null,f=null,h=null,p=null,m=!1,g=Yt(this.segments)??null;const y=A=>{const b=A.indexOf("@"),v=Number(b===-1?A:A.slice(0,b));if(!Number.isInteger(v)||v<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${A}'.`);let x=null;if(b!==-1&&(x=Number(A.slice(b+1)),!Number.isInteger(x)||x<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${A}'.`);return{length:v,offset:x}},w=A=>{c=A,g&&(N(g.sequenceNumber!==null),g.sequenceNumber<A&&(i=g.timestamp+g.duration,u=g.firstSegment,l=g.initSegment,h=g.lastProgramDateTimeSeconds,s=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+g.duration:null,g=null))};for(let A=0;A<e.length;A++){const b=e[A];if(!r){if(b!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");r=!0;continue}if(!b.startsWith("#")){if(!g){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let v=o;if(v&&v.method==="AES-128"&&!v.iv){const k=new Uint8Array($n),_=et(k);_.setUint32(8,Math.floor(c/2**32)),_.setUint32(12,c),v={...v,iv:k}}const P={path:Hr(this.rootPath,b),offset:f?.offset??0,length:f?.length??null},S={timestamp:i,unixEpochTimestamp:s,firstSegment:u,sequenceNumber:c,location:P,duration:a,encryption:v,initSegment:l,lastProgramDateTimeSeconds:h};u??=S,i+=a,s!==null&&(s+=a),this.segments.push(S)}a=null,f===null?d=null:f=null,w(c+1)}if(b.startsWith(el)){if(g){m=!0;continue}m||(h===null&&c>0&&p!==null&&(i=c*p),m=!0);const v=b.slice(el.length),x=v.indexOf(","),P=x===-1?v:v.slice(0,x),S=Number(P);if(!Number.isFinite(S)||S<0)throw new Error(`Invalid #EXTINF tag duration '${P}'.`);a=S}else if(b.startsWith(id)){const v=new Ws(b.slice(id.length)),x=v.get("uri");if(!x)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const P=v.get("byterange");let S=null;if(P!==null&&(S=y(P)),S&&S.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const _={path:Hr(this.rootPath,x),offset:S?.offset??0,length:S?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:i,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:_,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,f===null?d=null:f=null}else if(b.startsWith(sd)){const v=new Ws(b.slice(sd.length)),x=v.get("method");if(x==="NONE")o=null;else if(x==="AES-128"){const P=v.get("uri");if(!P)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let S=null;const k=v.get("iv");if(k){if(!s1.test(k))throw new Error(`Unsupported IV format '${k}'.`);let I=k.slice(2);I=I.padStart($n*2,"0"),S=new Uint8Array($n);for(let B=0;B<$n;B++){const V=-$n*2+B;S[B]=parseInt(I.slice(V,V+2),16)}}const _=v.get("keyformat")??"identity";if(_!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:Hr(this.rootPath,P),iv:S,keyFormat:_}}else if(x==="SAMPLE-AES"||x==="SAMPLE-AES-CTR"){const P=v.get("uri");if(!P)throw new Error(`Invalid #EXT-X-KEY: ${x} requires a URI attribute.`);if((v.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let k=null;if(a1.test(P)){const _=P.indexOf(","),I=Gu(P.slice(_+1));if(I.length>=8&&I[4]===112&&I[5]===115&&I[6]===115&&I[7]===104){const B=et(I).getUint32(0);k=Ef(I.subarray(8,Math.min(B,I.length)))}}o={method:x,psshBox:k}}else throw new Error(`Unsupported encryption method '${x}'. If you think this method should be supported, please raise an issue.`)}else if(b.startsWith(ad)){const v=b.slice(ad.length),x=Number(v);if(!Number.isInteger(x)||x<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${v}'.`);w(x)}else if(b.startsWith(od)){const v=y(b.slice(od.length));if(v.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");v.offset=d}f=v,d=v.offset+v.length}else if(b.startsWith(cd)){if(g)continue;const v=b.slice(cd.length),x=Date.parse(v);if(!Number.isFinite(x))continue;const P=x/1e3;if(h===P)continue;if(h===null&&this.segments.length>0){const S=Yt(this.segments),k=S.timestamp+S.duration,_=P-k;for(const I of this.segments)I.unixEpochTimestamp=I.timestamp+_,n&&(I.timestamp=I.unixEpochTimestamp)}h=P,s=P,n&&(i=P)}else if(b===$g)u=null;else if(b.startsWith(ld)){const v=b.slice(ld.length),x=Number(v);if(!Number.isFinite(x)||x<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${v}'.`);this.refreshInterval=x,p=x}else if(b===Gg){this.streamHasEnded=!0;break}else b.startsWith(ud)&&b.slice(ud.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!r)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,n){this.segments.length===0&&await this.runUpdateSegments();let r=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const i=Ge(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||r)return this.segments[i];const s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),n.skipLiveWait&&(r=!0)}}async getNextSegment(e,n){const r=this.segments.indexOf(e);N(r!==-1);const i=r+1;let s=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),n.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const n=this.segments.indexOf(e);return N(n!==-1),this.segments[n-1]??null}getInputForSegment(e){const n=e,r=this.inputCache.find(c=>c.segment===n);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(n.initSegment||n.firstSegment)&&(i=this.getInputForSegment(n.initSegment??n.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!n.encryption||!(n.encryption.method==="SAMPLE-AES"||n.encryption.method==="SAMPLE-AES-CTR")||!n.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let u=c.psshBoxes;const{psshBox:l}=n.encryption;return(l.keyIds===null||l.keyIds.includes(c.keyId))&&!u.some(d=>Mf(d,l))&&(u=[...u,l]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:u})})}},a=new Vo({source:new Kg(n.location.path,async c=>{N(c.isRoot);const u={...c,isRoot:!1};let l;const d=n.location.offset>0||n.location.length!==null;if(!n.encryption||n.encryption.method==="SAMPLE-AES"||n.encryption.method==="SAMPLE-AES-CTR"){if(l=await this.input._getSourceCached(u),d){const h=l.source.slice(n.location.offset,n.location.length??void 0).ref();l.free(),l=h}}else if(n.encryption.method==="AES-128"){const f=n.encryption;N(f.iv);let h=await this.input._getSourceCached(u);if(d){const y=h.source.slice(n.location.offset,n.location.length??void 0).ref();h.free(),h=y}const p=new Za(h.source),m=ig(p,async()=>{const g={stack:[],error:void 0,hasError:!1};try{const y=vd(g,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Y1),!1),A=await new Za(y.source).requestSlice(0,$n);if(!A)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Ee(A,$n),iv:f.iv}}catch(y){g.error=y,g.hasError=!0}finally{Ad(g)}},()=>{h.free()});l=new wd(m).ref()}else N(!1);return l}),formats:this.input._formats.filter(c=>!(c instanceof Cd)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((n.encryption?.method==="SAMPLE-AES"||n.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:n,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const c=vc(this.inputCache,u=>u.age);N(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class o1 extends mr{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{N(this.input._rootSource instanceof is);const e=await this.input._reader.requestEntireFile();N(e);const n=$d(e,e.length,{ignore:fd}),{rootPath:r}=this.input._rootSource,i=[],s=[];for(let d=1;d<n.length;d++){const f=n[d];if(f.startsWith(td)){const h=d,p=n[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const m=Hr(r,p),g=new Ws(f.slice(td.length));if(g.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:g,lineNumber:h,hasOnlyKeyPackets:!1})}else if(f.startsWith(nd)){const h=new Ws(f.slice(nd.length)),p=h.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const g=Hr(r,p);i.push({fullPath:g,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(rd)){const h=new Ws(f.slice(rd.length));if(h.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(h.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null;const y=h.get("uri");y!==null&&(g=Hr(r,y)),s.push({fullPath:g,attributes:h,lineNumber:d})}else if(f!==Qg){if(f.startsWith(el)){const h=new xd(this,r,null,n);this.segmentedInputs=[h],this.hasMasterPlaylist=!1,this.trackBackings=await h.getTrackBackings();return}}}const a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(i.map(async(d,f)=>{const h=[],p=d.attributes.get("codecs");let m;if(p)m=p.split(",").map(k=>k.trim());else{const _=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),I=await Promise.all(_.map(async B=>({track:B,codec:await B.getCodec()})));m=await Promise.all(I.filter(B=>B.codec!==null).map(B=>B.track.getDecoderConfig().then(V=>V.codec)))}const g=d.attributes.get("video"),y=d.attributes.get("audio"),w=m.some(k=>yf.includes(Bs(k))),A=m.some(k=>bf.includes(Bs(k)));if(g!==null&&!w){if(!a.includes(g))throw new Error(`Invalid M3U8 file; variant stream references video group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);const k=s.find(_=>{const I=_.attributes.get("group-id"),B=_.attributes.get("type");return I===g&&B.toLowerCase()==="video"});e:if(k){const _=k.attributes.get("uri");if(_===null)break e;const I=Hr(r,_),O=(await this.getSegmentedInputForPath(I).getTrackBackings()).find(W=>W.getType()==="video");if(!O||await O.getCodec()===null)break e;const U=await O.getDecoderConfig().then(W=>W?.codec??null);N(U!==null),m.push(U)}}if(y!==null&&!A){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);const k=s.find(_=>{const I=_.attributes.get("group-id"),B=_.attributes.get("type");return I===y&&B.toLowerCase()==="audio"});e:if(k){const _=k.attributes.get("uri");if(_===null)break e;const I=Hr(r,_),O=(await this.getSegmentedInputForPath(I).getTrackBackings()).find(W=>W.getType()==="audio");if(!O||await O.getCodec()===null)break e;const U=await O.getDecoderConfig().then(W=>W?.codec??null);N(U!==null),m.push(U)}}m=[...new Set(m)];let b=null,v=null;const x=d.attributes.getAsNumber("bandwidth");N(x!==null);const P=d.attributes.getAsNumber("average-bandwidth"),S=d.attributes.get("name");for(const k of m){const _=Bs(k);if(_!==null){if(yf.includes(_)){if(b!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=k;const I=d.attributes.get("video");if(I===null){const B=d.attributes.get("resolution");let V=null,O=null;if(B){const U=B.match(/^(\d+)x(\d+)$/);U&&(V=Number(U[1]),O=Number(U[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:qt,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(f),peakBitrate:x,averageBitrate:P,name:S,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:V,height:O}})}else{if(!a.includes(I))throw new Error(`Invalid M3U8 file; variant stream references video group "${I}" which is not defined in any #EXT-X-MEDIA tags.`);for(const B of s){const V=B.attributes.get("group-id"),O=B.attributes.get("type");if(V!==I||O.toLowerCase()!=="video")continue;const U=B.attributes.get("resolution")??d.attributes.get("resolution");let W=null,ie=null;if(U){const we=U.match(/^(\d+)x(\d+)$/);we&&(W=Number(we[1]),ie=Number(we[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:Ya(B.attributes),autoselect:Ya(B.attributes)||Pd(B.attributes),languageCode:_d(B.attributes.get("language")),lineNumber:B.lineNumber,fullPath:B.fullPath??d.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:B.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:W,height:ie}})}}}else if(bf.includes(_)){if(v!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");v=k;const I=d.attributes.get("audio");if(I===null){const B=d.attributes.get("channels"),V=B!==null?Number(B.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:qt,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:v,pairingMask:1n<<BigInt(f),peakBitrate:x,averageBitrate:P,name:S,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:V!==null&&Number.isInteger(V)&&V>0?V:null}})}else{if(!o.includes(I))throw new Error(`Invalid M3U8 file; variant stream references audio group "${I}" which is not defined in any #EXT-X-MEDIA tags.`);for(const B of s){const V=B.attributes.get("group-id"),O=B.attributes.get("type");if(V!==I||O.toLowerCase()!=="audio")continue;const U=B.attributes.get("channels")??d.attributes.get("channels"),W=U!==null?Number(U.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:Ya(B.attributes),autoselect:Ya(B.attributes)||Pd(B.attributes),languageCode:_d(B.attributes.get("language")),lineNumber:B.lineNumber,fullPath:B.fullPath??d.fullPath,fullCodecString:v,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:B.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:W!==null&&Number.isInteger(W)&&W>0?W:null}})}}}}}return h})),u=[],l=d=>{const f=u.find(h=>h.fullPath===d.fullPath&&h.info.type===d.info.type);f?(f.pairingMask|=d.pairingMask,f.default||=d.default,f.autoselect||=d.autoselect,f.lineNumber=Math.min(f.lineNumber,d.lineNumber),d.peakBitrate!==null&&(f.peakBitrate=Math.max(f.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(f.averageBitrate=Math.max(f.averageBitrate??-1/0,d.averageBitrate)),f.languageCode===qt&&(f.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(const d of c)for(const f of d)l(f);u.sort((d,f)=>d.lineNumber-f.lineNumber),this.trackBackings=[];for(const d of u)d.info.type==="video"?this.trackBackings.push(new Td(d)):this.trackBackings.push(new Sd(d));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),N(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let n=this.segmentedInputs.find(i=>i.path===e);if(n)return n;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),n=new xd(this,e,r,null),this.segmentedInputs.push(n),n}async getMetadataTags(){return{}}async getMimeType(){return ed}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class kd{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let n=null;const i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)n=i[0];else if(this instanceof Td){for(const s of i)if(await s.getCodec()===this.getCodec()){n=s;break}}else{N(this instanceof Sd);for(const s of i)if(await s.getCodec()===this.getCodec()){n=s;break}}if(!n)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=n})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...hr,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){N(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let n=0;for(const r of this.internalTrack.demuxer.internalTracks)if(r.info.type===e&&n++,r===this.internalTrack)break;return n}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,n)}async getKeyPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,n)}async getNextPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,n)}async getNextKeyPacket(e,n){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,n)}}class Td extends kd{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Bs(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class Sd extends kd{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Bs(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const Ya=t=>{const e=t.get("default");if(e===null)return!1;const n=e.toUpperCase();if(n==="YES")return!0;if(n==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Pd=t=>{const e=t.get("autoselect");if(e===null)return!1;const n=e.toUpperCase();if(n==="YES")return!0;if(n==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},_d=t=>{if(t===null)return qt;const e=t.split("-")[0];return e||qt};class Gn{constructor(){this._isIsobmff=!1}}class Ed extends Gn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let n=e._reader.requestSlice(0,12);if(le(n)&&(n=await n),!n)return null;n.skip(4);const r=mt(n,4);return r!=="ftyp"&&r!=="styp"?null:mt(n,4)}_createDemuxer(e){return new bu(e)}}class c1 extends Ed{async _canReadInput(e){const n=await this._getMajorBrand(e);if(n!==null)return n!=="qt ";let r=0;for(let i=0;i<10;i++){let s=e._reader.requestSlice(r,8);if(le(s)&&(s=await s),!s)return!1;let a=ve(s),o=8;if(a===1){let u=e._reader.requestSlice(r+8,8);if(le(u)&&(u=await u),!u)return!1;a=un(u),o=16}if(a<o)return!1;const c=mt(s,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")r+=a;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class l1 extends Ed{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Md extends Gn{async isSupportedEBMLOfDocType(e,n){let r=e._reader.requestSlice(0,gr);if(le(r)&&(r=await r),!r)return!1;const i=Vf(r);if(i===null||i<1||i>8||He(r,i)!==ce.EBML)return!1;const a=Wf(r);if(typeof a!="number")return!1;let o=e._reader.requestSlice(r.filePos,a);if(le(o)&&(o=await o),!o)return!1;const c=r.filePos;for(;o.filePos<=c+a-bn;){const u=yr(o);if(!u)break;const{id:l,size:d}=u,f=o.filePos;if(d===void 0)return!1;switch(l){case ce.EBMLVersion:if(He(o,d)!==1)return!1;break;case ce.EBMLReadVersion:if(He(o,d)!==1)return!1;break;case ce.DocType:if(Ji(o,d)!==n)return!1;break;case ce.DocTypeVersion:if(He(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new mg(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class u1 extends Md{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class f1 extends Gn{async _canReadInput(e){let n=0;for(;;){let d=e._reader.requestSlice(n,wn);if(le(d)&&(d=await d),!d)break;const f=Ar(d);if(!f)break;n=d.filePos+f.size}const r=await Qc(e._reader,n,n+4096);if(!r)return!1;const i=r.header,s=_f(i.mpegVersionId,i.channel);let a=e._reader.requestSlice(r.startPos+s,4);if(le(a)&&(a=await a),!a)return!1;const o=ve(a);if(o===Sf||o===Pf)return!0;n=r.startPos+r.header.totalSize;const u=await Qc(e._reader,n,n+fi);if(!u)return!1;const l=u.header;return!(i.channel!==l.channel||i.sampleRate!==l.sampleRate)}_createDemuxer(e){return new yg(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class d1 extends Gn{async _canReadInput(e){let n=e._reader.requestSlice(0,12);if(le(n)&&(n=await n),!n)return!1;const r=mt(n,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(n.skip(4),mt(n,4)==="WAVE")}_createDemuxer(e){return new _g(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class h1 extends Gn{async _canReadInput(e){let n=e._reader.requestSlice(0,4);return le(n)&&(n=await n),n?mt(n,4)==="OggS":!1}_createDemuxer(e){return new Sg(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class m1 extends Gn{async _canReadInput(e){let n=0;for(;;){let i=e._reader.requestSlice(n,wn);if(le(i)&&(i=await i),!i)break;const s=Ar(i);if(!s)break;n=i.filePos+s.size}let r=e._reader.requestSlice(n,4);return le(r)&&(r=await r),r?mt(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Lg(e)}}class p1 extends Gn{async _canReadInput(e){let n=0;for(;;){let a=e._reader.requestSlice(n,wn);if(le(a)&&(a=await a),!a)break;const o=Ar(a);if(!o)break;n=a.filePos+o.size}let r=e._reader.requestSliceRange(n,Yc,ns);if(le(r)&&(r=await r),!r)return!1;const i=Hs(r);if(!i||(n+=i.frameLength,r=e._reader.requestSliceRange(n,Yc,ns),le(r)&&(r=await r),!r))return!1;const s=Hs(r);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Mg(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class g1 extends Gn{async _canReadInput(e){const n=ln+16+1;let r=e._reader.requestSlice(0,n);if(le(r)&&(r=await r),!r)return!1;const i=Ee(r,n);return i[0]===71&&i[ln]===71||i[0]===71&&i[ln+16]===71?!0:i[4]===71&&i[4+ln+4]===71}_createDemuxer(e){return new jg(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Cd extends Gn{async _canReadInput(e){let n=e._reader.requestSlice(0,7);if(le(n)&&(n=await n),!n||!(mt(n,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof is))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new o1(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ed}}const y1=new c1,b1=new l1,w1=new Md,v1=new u1,A1=new f1,x1=new d1,k1=new h1,T1=new p1,S1=new m1,P1=new g1,_1=new Cd,E1=[_1,y1,b1,w1,v1,x1,k1,S1,A1,T1,P1],M1=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(t.isobmff!==void 0){if(!t.isobmff||typeof t.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(t.isobmff.resolveKeyId!==void 0&&typeof t.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(t.hls!==void 0){if(!t.hls||typeof t.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(t.hls.offsetTimestampsByDateTime!==void 0&&typeof t.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var C1=function(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],n&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:n})}else n&&t.stack.push({async:!0});return e},I1=(function(t){return function(e){function n(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,i=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&i===1)return i=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(a).then(s,function(o){return n(o),s()})}else i|=1}catch(o){n(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var r=new Error(n);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});wc();let Id=-1/0,Rd=-1/0,nl=null;typeof FinalizationRegistry<"u"&&(nl=new FinalizationRegistry(t=>{const e=performance.now();t.type==="video"?(e-Id>=1e3&&(Be._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Id=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Rd>=1e3&&(Be._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Rd=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class pi{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const rl=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],R1=new Set(rl);class Ln{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Wi*this.timestamp)}get microsecondDuration(){return Math.trunc(Wi*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,n){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.format===void 0||!R1.has(n.format))throw new TypeError("init.format must be one of: "+rl.join(", "));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(n.layout!==void 0){if(!Array.isArray(n.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const s of n.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(n.visibleRect!==void 0&&Ac(n.visibleRect,"init.visibleRect"),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0;const r=n.layout??D1(n.format,n.codedWidth,n.codedHeight);let i=n.colorSpace??null;i===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?i={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:i={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180===0?n.displayHeight:n.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=n._doNotCopy?lr(e):lr(e).slice(),this._layout=r,this.colorSpace=new il(i)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");n?.visibleRect!==void 0&&Ac(n.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=n?.timestamp??e.timestamp/1e6,this.duration=n?.duration??(e.duration??0)/1e6,this.colorSpace=new il(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(n.visibleRect!==void 0&&Ac(n.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new Ln(new VideoFrame(e,{timestamp:Math.trunc(n.timestamp*Wi),duration:Math.trunc((n.duration??0)*Wi)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw new TypeError("Could not determine dimensions.");const s=n.visibleRect??{left:0,top:0,width:r,height:i},a=new OffscreenCanvas(s.width,s.height),o=a.getContext("2d",{alpha:c0(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(e,-s.left,-s.top),this._data=a,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:s.width,height:s.height},this.squarePixelWidth=s.width,this.squarePixelHeight=s.height,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new il({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof pi){if(!n||typeof n!="object")throw new TypeError("init must be an object.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(n.timestamp))throw new TypeError("init.timestamp must be a number.");if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!rl.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=Ra({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),nl?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return N(this._data!==null),this._data instanceof pi?new Ln(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):qs(this._data)?new Ln(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(N(this._layout),new Ln(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new Ln(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(nl?.unregister(this),this._data instanceof pi?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):qs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ld(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return qs(this._data)?this._data.allocationSize(e):Ud(this,e).allocationSize}async copyTo(e,n={}){if(!Jp(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ld(n),this._closed)throw new Error("VideoSample is closed.");if((n.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(N(this._data!==null),qs(this._data))return this._data.copyTo(e,n);if(n.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(n.format))if(this._data instanceof pi){const u={stack:[],error:void 0,hasError:!1};try{const l=C1(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},n.colorSpace??"srgb"),!1);if(!(l instanceof Ln))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(l.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${l.format}' instead.`);return await l.copyTo(e,n)}catch(l){u.error=l,u.hasError=!0}finally{I1(u)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const u=this.toVideoFrame(),l=await u.copyTo(e,n);return u.close(),l}const r=Ud(this,n);N(this.format);const i=lr(e);if(i.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);const s=Ka(this.format);let a;if(this._data instanceof pi){let u=this._data.getDataPlanes();if(le(u)&&(u=await u),!Array.isArray(u)||u.some(l=>!(l.data instanceof Uint8Array)||!Number.isInteger(l.stride)||l.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=u}else if(this._data instanceof Uint8Array)N(this._layout),N(this._layout.length===s.length),a=this._layout.map((u,l)=>{const d=Math.ceil(this.codedHeight/s[l].heightDivisor);return{data:this._data.subarray(u.offset,u.offset+u.stride*d),stride:u.stride}});else{const l=this._data.getContext("2d");N(l);const d=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:lr(d.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let u=0;u<c;u++){const l=r.computedLayouts[u],d=a[u].stride,f=a[u].data;let h=l.sourceTop*d;h+=l.sourceLeftBytes;let p=l.destinationOffset;const m=l.sourceWidthBytes,g={offset:p,stride:l.destinationStride};for(let y=0;y<l.sourceHeight;y++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(p+m>i.byteLength)throw new Error("Destination buffer OOB write.");const w=f.subarray(h,h+m);i.set(w,p),h+=d,p+=l.destinationStride}o.push(g)}if(n.format!==void 0){const u=this.format.startsWith("RGB")!==n.format.startsWith("RGB"),l=this.format.includes("X")&&n.format.includes("A");if(u||l)for(let d=0;d<r.allocationSize;d+=4){if(u){const f=i[d],h=i[d+2];i[d]=h,i[d+2]=f}l&&(i[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(N(this._data!==null),this._data instanceof pi){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(le(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const n=e.reduce((a,o)=>a+o.data.byteLength,0),r=new Uint8Array(n);let i=0;const s=[];for(const a of e)r.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(r,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return qs(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(N(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,n,r,i,s,a,o,c,u){let l=0,d=0,f=this.displayWidth,h=this.displayHeight,p=0,m=0,g=this.displayWidth,y=this.displayHeight;if(a!==void 0?(l=n,d=r,f=i,h=s,p=a,m=o,c!==void 0?(g=c,y=u):(g=f,y=h)):(p=n,m=r,i!==void 0&&(g=i,y=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:f,sHeight:h}=this._rotateSourceRegion(l,d,f,h,this.rotation));const w=this.toCanvasImageSource();e.save();const A=p+g/2,b=m+y/2;e.translate(A,b),e.rotate(this.rotation*Math.PI/180);const v=this.rotation%180===0?1:g/y;e.scale(1/v,v),e.drawImage(w,l,d,f,h,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,n){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(n.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");n.crop!==void 0&&Nd(n.crop,"options.");const r=e.canvas.width,i=e.canvas.height,s=n.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=n.crop;c&&(c=Dd(c,a,o));let u,l,d,f;const{sx:h,sy:p,sWidth:m,sHeight:g}=this._rotateSourceRegion(n.crop?.left??0,n.crop?.top??0,n.crop?.width??a,n.crop?.height??o,s);if(n.fit==="fill")u=0,l=0,d=r,f=i;else{const[w,A]=n.crop?[n.crop.width,n.crop.height]:[a,o],b=n.fit==="contain"?Math.min(r/w,i/A):Math.max(r/w,i/A);d=w*b,f=A*b,u=(r-d)/2,l=(i-f)/2}e.save();const y=s%180===0?1:d/f;e.translate(r/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,p,m,g,u,l,d,f),e.restore()}_rotateSourceRegion(e,n,r,i,s){return s===90?[e,n,r,i]=[n,this.squarePixelHeight-e-r,i,r]:s===180?[e,n]=[this.squarePixelWidth-e-r,this.squarePixelHeight-n-i]:s===270&&([e,n,r,i]=[this.squarePixelWidth-n-i,e,i,r]),{sx:e,sy:n,sWidth:r,sHeight:i}}_drawWithFitAndMipmapping(e,n,r){const i=e.width,s=e.height,[a,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:a,u=r.crop?r.crop.height:o;let l=0;2*i<c&&2*s<u&&(l=Math.floor(Math.log2(Math.min(c/i,u/s))));const d=i*2**l,f=s*2**l,{canvas:h,context:p,isNew:m}=l>0?Fd(d,f):{canvas:e,context:n,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,f)):m||p.clearRect(0,0,d,f),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,crop:r.crop}),p.globalCompositeOperation="copy";for(let g=l;g>1;g--){const y=i*2**g,w=s*2**g;p.drawImage(h,0,0,y,w,0,0,y/2,w/2)}p.globalCompositeOperation="source-over",l>0&&(n.imageSmoothingQuality="high",n.globalCompositeOperation="copy",n.drawImage(h,0,0,2*i,2*s,0,0,i,s),n.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(N(this._data!==null),this._data instanceof pi||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Nd(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const n=tc(this.rotation+(e.rotate??0)),[r,i]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=Dd(s,r,i));const a=s?s.width:r,o=s?s.height:i,c=a/o;let u,l;e.width!==void 0&&e.height===void 0?(u=e.width,l=u/c):e.width===void 0&&e.height!==void 0?(l=e.height,u=l*c):e.width!==void 0&&e.height!==void 0?(u=e.width,l=e.height):(u=a,l=o),u=lc(u,e.roundDimensionsTo??1),l=lc(l,e.roundDimensionsTo??1);const d={width:u,height:l,fit:e.fit??"fill",rotation:n,crop:s??{left:0,top:0,width:r,height:i},alpha:e.alpha??"keep"};for(const m of B1){let g=m(this,d);if(le(g)&&(g=await g),g!==null)return g}const{canvas:f,context:h,isNew:p}=Fd(d.width,d.height);return this._drawWithFitAndMipmapping(f,h,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:p,fillBlack:d.alpha==="discard"}),new Ln(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const B1=[],F1=3,js=[];let Bd=0;const Fd=(t,e)=>{for(const i of js)if(i.canvas.width===t&&i.canvas.height===e)return i.age=Bd++,{canvas:i.canvas,context:i.context,isNew:!1};let n;if(typeof OffscreenCanvas<"u")n=new OffscreenCanvas(t,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");n=document.createElement("canvas"),n.width=t,n.height=e}const r=n.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return js.length>=F1&&js.splice(vc(js,i=>i.age),1),js.push({canvas:n,context:r,age:Bd++}),{canvas:n,context:r,isNew:!0}};class il{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const n=Object.keys(rc);if(e.primaries!=null&&!n.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${n.join(", ")}.`);const r=Object.keys(ic);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const i=Object.keys(sc);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const qs=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Dd=(t,e,n)=>{const r=Math.min(t.left,e),i=Math.min(t.top,n),s=Math.min(t.width,e-r),a=Math.min(t.height,n-i);return N(s>=0),N(a>=0),{left:r,top:i,width:s,height:a}},Nd=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ld=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},D1=(t,e,n)=>{const r=Ka(t),i=[];let s=0;for(const a of r){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(n/a.heightDivisor),u=o*a.sampleBytes,l=u*c;i.push({offset:s,stride:u}),s+=l}return i},Ka=t=>{const e=(n,r,i,s,a)=>{const o=[{sampleBytes:n,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:i,heightDivisor:s},{sampleBytes:r,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:n,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ca(t),N(!1)}},Ud=(t,e)=>{const n={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,i=N1(n,r,t.codedWidth,t.codedHeight,t.format),s=e.layout;let a;if(!e.format||e.format===t.format)a=t.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return U1(i,a,s)},N1=(t,e,n,r,i)=>{const s={...t};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>n)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!L1(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},L1=(t,e)=>{if(t===null)return!0;const n=Ka(t);for(let r=0;r<n.length;r++){const i=n[r],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},U1=(t,e,n)=>{const r=Ka(e),i=r.length;if(n!==void 0&&n.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0;const a=[],o=[];for(let c=0;c<i;c++){const u=r[c],l=u.sampleBytes,d=u.widthDivisor,f=u.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(t.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(t.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/d)*l,h.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/d)*l,n!==void 0){const g=n[c];if(g.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=g.offset,h.destinationStride=g.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let g=0;g<c;g++){const y=a[g];if(!(o[c]<=y.destinationOffset||o[g]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}};const Od=[],O1=[];const gi=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(t.skipLiveWait!==void 0&&typeof t.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ss=t=>{if(!Ia(t))throw new TypeError("timestamp must be a number.")},sl=(t,e,n)=>n.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;const i=await t.determinePacketType(r);return i&&(r.type=i),r}):e;class al{constructor(e){if(!(e instanceof ma))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(gi(e),this._track.input._disposed)throw new Lt;return sl(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){gi(e);const n=await this.getFirstPacket(e);return n?n.type==="key"?n:this.getNextKeyPacket(n,e):null}async getPacket(e,n={}){if(ss(e),gi(n),this._track.input._disposed)throw new Lt;return sl(this._track,this._track._backing.getPacket(e,n),n)}async getNextPacket(e,n={}){if(!(e instanceof kt))throw new TypeError("packet must be an EncodedPacket.");if(gi(n),this._track.input._disposed)throw new Lt;return sl(this._track,this._track._backing.getNextPacket(e,n),n)}async getKeyPacket(e,n={}){if(ss(e),gi(n),this._track.input._disposed)throw new Lt;if(!n.verifyKeyPackets)return this._track._backing.getKeyPacket(e,n);const r=await this._track._backing.getKeyPacket(e,n);return r&&(N(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),n):r)}async getNextKeyPacket(e,n={}){if(!(e instanceof kt))throw new TypeError("packet must be an EncodedPacket.");if(gi(n),this._track.input._disposed)throw new Lt;if(!n.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,n);const r=await this._track._backing.getNextKeyPacket(e,n);return r&&(N(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,n):r)}packets(e,n,r={}){if(e!==void 0&&!(e instanceof kt))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(n!==void 0&&!(n instanceof kt))throw new TypeError("endPacket must be an EncodedPacket.");if(gi(r),this._track.input._disposed)throw new Lt;const i=[];let{promise:s,resolve:a}=Dt(),{promise:o,resolve:c}=Dt(),u=!1,l=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let g=e??await this.getFirstPacket(r);for(;g&&!l&&!this._track.input._disposed&&!(n&&g.sequenceNumber>=n?.sequenceNumber);){if(i.length>p()){({promise:o,resolve:c}=Dt()),await o;continue}i.push(g),a(),{promise:s,resolve:a}=Dt(),g=await this.getNextPacket(g,r)}u=!0,a()})().catch(g=>{f||(d=g,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Lt;if(l)return{value:void 0,done:!0};if(f)throw d;if(i.length>0){const g=i.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return c(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return l=!0,c(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}class z1{constructor(e,n){this.onSample=e,this.onError=n}}class H1{mediaSamplesInRange(e=-1/0,n=1/0,r){ss(e),ss(n);const i=[];let s=!1,a=null,{promise:o,resolve:c}=Dt(),{promise:u,resolve:l}=Dt(),d=!1,f=!1,h=!1,p=null,m=null,g=!1;const y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(k=>{if(l(),k.timestamp>=n&&(f=!0),f){k.close();return}a&&(k.timestamp>e?(i.push(a),s=!0):a.close()),k.timestamp>=e&&(i.push(k),s=!0),a=s?null:k,i.length>0&&(c(),{promise:o,resolve:c}=Dt())},k=>{g||(m=k,g=!0,c())});const b=this._createPacketSink(),v=await b.getKeyPacket(e,y)??await b.getFirstKeyPacket(y);let x=v;const S=b.packets(v??void 0,void 0,y);for(await S.next();x&&!f&&!this._track.input._disposed;){const k=zd(i.length);if(i.length+p.getDecodeQueueSize()>k){({promise:u,resolve:l}=Dt()),await u;continue}p.decode(x);const _=await S.next();if(_.done)break;x=_.value}await S.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&i.push(a),d=!0,c()})().catch(b=>{g||(m=b,g=!0,c())}).finally(()=>{p?.close()});const w=this._track,A=()=>{a?.close();for(const b of i)b.close()};return{async next(){for(;;){if(w.input._disposed)throw h=!0,f=!0,A(),new Lt;if(h)return{value:void 0,done:!0};if(g)throw h=!0,f=!0,A(),m;if(i.length>0){const b=i.shift();return l(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,l(),c(),A(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,n){r0(e);const r=n0(e),i=[],s=[];let{promise:a,resolve:o}=Dt(),{promise:c,resolve:u}=Dt(),l=!1,d=!1,f=null,h=null,p=!1;const m=A=>{s.push(A),o(),{promise:a,resolve:o}=Dt()},g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(k=>{if(u(),d){k.close();return}let _=0;for(;i.length>0&&k.timestamp-i[0]>-1e-10;)_++,i.shift();if(_>0)for(let I=0;I<_;I++)m(I<_-1?k.clone():k);else k.close()},k=>{p||(h=k,p=!0,o())});const A=this._createPacketSink();let b=null,v=null,x=-1;const P=async()=>{N(v),N(f);let k=v;for(f.decode(k);k.sequenceNumber<x;){const _=zd(s.length);for(;s.length+f.getDecodeQueueSize()>_&&!d;)({promise:c,resolve:u}=Dt()),await c;if(d)break;const I=await A.getNextPacket(k,g);N(I),f.decode(I),k=I}x=-1},S=async()=>{N(f),await f.flush();for(let k=0;k<i.length;k++)m(null);i.length=0};for await(const k of r){if(ss(k),d||this._track.input._disposed)break;const _=await A.getPacket(k,g),I=_&&await A.getKeyPacket(k,g);if(!I){x!==-1&&(await P(),await S()),m(null),b=null;continue}b&&(I.sequenceNumber!==v.sequenceNumber||_.timestamp<b.timestamp)&&(await P(),await S()),i.push(_.timestamp),x=Math.max(_.sequenceNumber,x),b=_,v=I}!d&&!this._track.input._disposed&&(x!==-1&&await P(),await S()),l=!0,o()})().catch(A=>{p||(h=A,p=!0,o())}).finally(()=>{f?.close()});const y=this._track,w=()=>{for(const A of s)A?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,w(),new Lt;if(d)return{value:void 0,done:!0};if(p)throw d=!0,w(),h;if(s.length>0){const A=s.shift();return N(A!==void 0),u(),{value:A,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),w(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this}}}}const zd=t=>t===0?40:8;class V1 extends z1{constructor(e,n,r,i,s,a){super(e,n),this.codec=r,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new o0,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=Od.find(c=>c.supports(r,i));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof Ln))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoder.onError=c=>{n(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>n(c));else{const c=l=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();N(d!==void 0),this.mergeAlpha(l,d)}else this.colorQueue.push(l)};if(yc()){if(r==="avc"&&this.decoderConfig.description){const l=tf(lr(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const d=Oa(l.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}ac(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:l=>{try{c(l)}catch(d){this.onError(d)}},error:l=>{l.stack=u,this.onError(l)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(N(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(n=>this.onError(n)).finally(()=>this.customDecoderQueueSize--);else{if(N(this.decoder),mc()||Hu(this.inputTimestamps,e.timestamp,n=>n),yc()&&this.currentPacketIndex===0){if(this.codec==="avc"){const n=[];let r=!1;for(const s of Zu(e.data,this.decoderConfig)){const a=La(e.data[s.offset]);if(r||=a>=1&&a<=5,a===Rt.AUD){if(r)break;n.length=0}a>=20&&a<=31||n.push(e.data.subarray(s.offset,s.offset+s.length))}const i=h0(n,this.decoderConfig);e=new kt(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const n=x0(e.data,this.decoderConfig);n&&(e=new kt(n,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new W1),!this.alphaDecoder){const r=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();N(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();N(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{r(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const n=Ic(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=n==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(n??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const n of za(e,this.decoderConfig)){const r=qi(e[n.offset]);if(r===vt.RASL_N||r===vt.RASL_R)return!0}return!1}sampleHandler(e){if(mc()){if(this.sampleQueue.length>0&&e.timestamp>=Yt(this.sampleQueue).timestamp){for(const n of this.sampleQueue)this.finalizeAndEmitSample(n);this.sampleQueue.length=0}Hu(this.sampleQueue,e,n=>n.timestamp)}else{const n=this.inputTimestamps.shift();N(n!==void 0),e.setTimestamp(n),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,n){const r=Dt();this.mergeAlphaPromises.push(r.promise);const i={sample:null};this.finalSamples.push(i);try{if(!n)i.sample=new Ln(e);else{N(this.merger);const s=await this.merger.merge(e,n);i.sample=new Ln(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){oc(this.finalSamples,i),this.onError(s)}finally{oc(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(N(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),mc()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(N(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let ol=null;class W1{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,n){if(this.workers.length===0){if(!ol){const o=new Blob([`(${j1.toString()})()`],{type:"application/javascript"});ol=URL.createObjectURL(o)}const a=Ms(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(ol);c.addEventListener("message",u=>{const l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{const l=new Error(u.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}const r=this.nextRequestId++,i=Dt();this.pendingRequests.set(r,i);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:r,color:e,alpha:n},{transfer:[e,n]}),i.promise}close(){for(const n of this.workers)n.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const n of this.pendingRequests.values())n.reject(e);this.pendingRequests.clear()}}const j1=()=>{let t=null,e=null,n=Promise.resolve();self.addEventListener("message",c=>{const{id:u,color:l,alpha:d}=c.data;n=n.then(async()=>{try{const f=await r(l,d);self.postMessage({id:u,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:u,error:f.message})}finally{l.close(),d.close()}})});const r=async(c,u)=>{const l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=l.includes("P10"),h=l.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==f||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await i(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await s(c,u,l);if(l==="NV12")return await a(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},i=async(c,u,l)=>{const d=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,h=d*f,p=new Uint8Array(h*4);await c.copyTo(p);const m=await o(u,d,f,1);for(let w=0,A=3;w<h;w++,A+=4)p[A]=m[w];const y={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},s=async(c,u,l)=>{const d=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,h=l.includes("P10"),p=l.includes("P12"),m=h||p?2:1;let g,y;l.startsWith("I420")?(g=Math.ceil(d/2),y=Math.ceil(f/2)):l.startsWith("I422")?(g=Math.ceil(d/2),y=f):(g=d,y=f);const w=d*f,A=g*y,b=w*m,v=A*m,x=w*m,P=b+2*v+x,S=new Uint8Array(P);await c.copyTo(S);const k=await o(u,d,f,m),_=b+2*v;S.set(k,_);const B={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[S.buffer]};return new VideoFrame(S,B)},a=async(c,u)=>{const l=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,f=l*d,h=Math.ceil(l/2),p=Math.ceil(d/2),m=h*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);const y=new Uint8Array(f+2*m+f);y.set(e.subarray(0,f),0);const w=f,A=f+m,b=f;for(let P=0;P<m;P++)y[w+P]=e[b+P*2],y[A+P]=e[b+P*2+1];const v=await o(u,l,d,1);y.set(v,f+2*m);const x={format:"I420A",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,x)},o=async(c,u,l,d)=>{const f=c.allocationSize();(!t||t.byteLength!==f)&&(t=new Uint8Array(f)),await c.copyTo(t);const h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,m=u*l;for(let g=0;g<m;g++)t[g]=t[g*4+p];return t.subarray(0,m)}else return t.subarray(0,u*l*d)}},q1=t=>{if(!t||typeof t!="object")throw new TypeError("decoderOptions must be an object.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class X1 extends H1{constructor(e,n={}){if(!(e instanceof ll))throw new TypeError("videoTrack must be an InputVideoTrack.");q1(n),super(),this._track=e,this._decoderOptions=n}async _createDecoder(e,n){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(l0("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),i=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return N(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new V1(e,n,r,s,i,a)}_createPacketSink(){return new al(this._track)}async getSample(e,n={}){ss(e);for await(const r of this.mediaSamplesAtTimestamps([e],n))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,n,r={}){return this.mediaSamplesInRange(e,n,r)}samplesAtTimestamps(e,n={}){return this.mediaSamplesAtTimestamps(e,n)}}class ma{constructor(e,n){this.input=e,this._backing=n}isVideoTrack(){return this instanceof ll}isAudioTrack(){return this instanceof Hd}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return dt(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return dt(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return dt(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return dt(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return dt(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){const n=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),r=(n?.timestamp??0)+(n?.duration??0);return ju(r,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,n){const r=new al(this);let i=1/0,s=-1/0,a=0,o=0;for await(const c of r.packets(void 0,void 0,{metadataOnly:!0,...n})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof ma))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(yi({filter:n=>n.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(yi({filter:n=>n.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(yi({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(yi({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(yi({filter:n=>n.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=cl(e);const n=await this.input.getTracks();for(const r of n)if(this.canBePairedWith(r)&&(!e||await e(r)))return!0;return!1}hasPairableVideoTrack(e){return e&&=cl(e),this.hasPairableTrack(async n=>n.isVideoTrack()&&(!e||await e(n)))}hasPairableAudioTrack(e){return e&&=cl(e),this.hasPairableTrack(async n=>n.isAudioTrack()&&(!e||await e(n)))}}const dt=(t,e,n)=>{if(le(t))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return t},cl=t=>{if(t!==void 0&&typeof t!="function")throw new TypeError("predicate, when provided, must be a function.");return t?e=>{const n=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},r=t(e);return le(r)?r.then(n):n(r)}:void 0};class ll extends ma{constructor(e,n){super(e,n),this._pixelAspectRatioCache=null,this._backing=n}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return dt(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return dt(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return dt(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return dt(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return dt(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return dt(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ra({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ra({num:dt(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*dt(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:dt(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*dt(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){const i=dt(e,"displayWidth","getDisplayWidth");if(i!==null)return i}const r=dt(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return dt(r,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){const i=dt(e,"displayHeight","getDisplayHeight");if(i!==null)return i}const r=dt(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return dt(r,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const n=await this._backing.getCodec();return N(n!==null),Od.some(i=>i.supports(n,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return Be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof kt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const n=await this.getCodec();if(n===null)return null;const r=await this.getDecoderConfig();return N(r),Ic(n,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!Ia(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const n=await this.getTimeResolution(),r=e.targetPacketCount??256,i=new al(this),s=[];let a=-1/0,o=0;for await(const _ of i.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=r&&_.timestamp>=a)break;s.push(_.timestamp),a=Math.max(a,_.timestamp),o++}const c=new Float64Array(s.length);for(let _=0;_<s.length;_++)c[_]=Math.round(s[_]*n);c.sort();let u=1;for(let _=1;_<c.length;_++)c[_]!==c[u-1]&&(c[u++]=c[_]);if(u<2)return{underlyingFrameRate:null,bestGuessFrameRate:n,minFrameRate:n,maxFrameRate:n,averageFrameRate:n,medianFrameRate:n,frameRateIsConstant:!0,probedPacketCount:o};const l=c.subarray(0,u),d=$1(l,n),f=d??n,h=d!==null?n/d:null,p=new Map;let m=1/0,g=-1/0,y=0;for(let _=1;_<u;_++){const I=l[_]-l[_-1],B=h!==null?Math.max(1,Math.round(I/h)):I;p.set(B,(p.get(B)??0)+1),m=Math.min(m,B),g=Math.max(g,B),y+=B}const w=u-1,A=[...p.keys()].sort((_,I)=>_-I),b=w-1>>1,v=w>>1;let x=0,P=0,S=0;for(const _ of A)if(S+=p.get(_),x===0&&S>b&&(x=_),S>v){P=_;break}const k=(f/x+f/P)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:G1(k),minFrameRate:f/g,maxFrameRate:f/m,averageFrameRate:f*w/y,medianFrameRate:k,frameRateIsConstant:d!==null&&m===1&&g===1,probedPacketCount:o}}}class Hd extends ma{constructor(e,n){super(e,n),this._backing=n}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return dt(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return dt(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return dt(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const n=await this._backing.getCodec();return N(n!==null),O1.some(r=>r.supports(n,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return Be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof kt))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Vd=t=>-(t??-1/0),Xs=t=>-t,$s=t=>{if(typeof t!="object"||!t)throw new TypeError("query must be an object.");if(t.filter!==void 0&&typeof t.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(t.sortBy!==void 0&&typeof t.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:t.filter?e=>{const n=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},r=t.filter(e);return le(r)?r.then(n):n(r)}:void 0,sortBy:t.sortBy?e=>{const n=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},r=t.sortBy(e);return le(r)?r.then(n):n(r)}:void 0}},yi=(t,e)=>({filter:t?.filter||e?.filter?n=>{const r=t?.filter?.(n)??!0,i=s=>s===!1?!1:e?.filter?.(n)??!0;return le(r)?r.then(i):i(r)}:void 0,sortBy:t?.sortBy||e?.sortBy?n=>{const r=t?.sortBy?.(n)??[],i=e?.sortBy?.(n)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return le(r)||le(i)?Promise.all([r,i]).then(([a,o])=>s(a,o)):s(r,i)}:void 0}),ul=async(t,e)=>{let n=t;if(e?.filter){const a=t.map(c=>e.filter(c));if(a.some(c=>le(c))){const c=await Promise.all(a);n=t.filter((u,l)=>c[l])}else n=t.filter((c,u)=>a[u])}if(!e?.sortBy)return n;const r=n.map(a=>e.sortBy(a)),s=r.some(a=>le(a))?await Promise.all(r):r;return n.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;d<l;d++){const f=c[d]??0,h=u[d]??0;if(f!==h)return f-h}return 0}).map(a=>a.track)},$1=(t,e)=>{const i=1.000000001,s=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(t.length<2)return null;const o=new Float64Array(t.length-1);for(let P=1;P<t.length;P++){const S=t[P]-t[P-1];if(!(S>0))return null;o[P-1]=S}const c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let P=0;P<6;P++){let S=0,k=0;for(const I of o){const B=Math.max(1,Math.round(I/u));Math.abs(I-B*u)>=i||(S+=I,k+=B)}if(k===0)return null;const _=S/k;if(Math.abs(_-u)<=1e-12*Math.max(1,u)){u=_;break}u=_}let l=0,d=0,f=0;for(const P of o){const S=Math.max(1,Math.round(P/u));Math.abs(P-S*u)>=i||(l++,d+=P,f+=S)}if(l/o.length<.98)return null;u=d/f;const h=1/Math.min(f,s),p=Math.max(Number.EPSILON,u-h),m=u+h,g=e/m,y=e/p,w=e/u;let A=null,b=1/0;for(const P of a){if(P<g||P>y)continue;const S=Math.abs(P/w-1);S<b&&(A=P,b=S)}if(A===null){const P=Wd(p,m,1e6),S=Wd(g,y,1e6);if(S&&(!P||S.den<P.den||S.den===P.den&&S.num<=P.num))A=S.num/S.den;else if(P)A=e*P.den/P.num;else return null}const v=e/A;let x=0;for(const P of o){const S=Math.max(1,Math.round(P/v));Math.abs(P-S*v)<i&&x++}return x/o.length<.98?null:A},Wd=(t,e,n)=>{for(let r=1;r<=n;r++){const i=Math.floor(t*r)+1;if(i/r<e)return Ra({num:i,den:r})}return null},G1=t=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],n=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,i=.025;for(const o of e)if(Math.abs(o/t-1)<=r)return o;let s=t,a=1/0;for(const o of n){const c=Math.abs(o/t-1);c<=i&&c<a&&(s=o,a=c)}return s};wc();const Q1=1,Y1=2;class Vo extends xc{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(n=>!(n instanceof Gn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof wr||e.source instanceof tl))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof wr&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Vo))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&M1(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof wr?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){N(this._rootSource instanceof is);const n=await this._rootSource._resolveRequest(e);return this._emit("source",{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=Q1){const r=this._sourceCache.find(a=>a.cacheGroup===n&&yd(a.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const i=this._sourceCachePromises.find(a=>a.cacheGroup===n&&yd(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(Is(this._sourceCache,d=>d.cacheGroup===n&&d.sourceRef.source._refCount===1)>=4){const d=vc(this._sourceCache,h=>h.cacheGroup===n&&h.sourceRef.source._refCount===1?h.age:1/0);N(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),oc(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const u=this._sourceCachePromises.findIndex(d=>d.request===e);return N(u!==-1),this._sourceCachePromises.splice(u,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:n}})();return this._sourceCachePromises.push({request:e,cacheGroup:n,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Za(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new jd})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),N(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof jd)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const n=e.filter(s=>s!==null);if(n.length===0)return 0;const r=await Promise.all(n.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),i=Math.min(...r.map(s=>s?.timestamp??1/0));return i===1/0?0:i}async computeDuration(e,n){e??=await this.getTracks();const r=e.filter(s=>s!==null);if(r.length===0)return 0;const i=await Promise.all(r.map(s=>s.computeDuration(n)));return Math.max(...i)}async getDurationFromMetadata(e,n){e??=await this.getTracks();const r=e.filter(a=>a!==null),s=(await Promise.all(r.map(a=>a.getDurationFromMetadata(n)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=$s(e);const r=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return ul(r,e)}async getVideoTracks(e){e&&=$s(e);const r=(await this.getTracks()).filter(i=>i.isVideoTrack());return ul(r,e)}async getAudioTracks(e){e&&=$s(e);const r=(await this.getTracks()).filter(i=>i.isAudioTrack());return ul(r,e)}async getPrimaryVideoTrack(e){e&&=$s(e);const n=yi(e,{sortBy:async i=>[Xs((await i.getDisposition()).default),Xs(await i.hasPairableAudioTrack()),Xs(!await i.hasOnlyKeyPackets()),Vd(await i.getBitrate())]});return(await this.getVideoTracks(n))[0]??null}async getPrimaryAudioTrack(e){e&&=$s(e);const n=await this.getPrimaryVideoTrack(),r=yi(e,{sortBy:async s=>[Xs(!n||s.canBePairedWith(n)),Xs((await s.getDisposition()).default),Vd(await s.getBitrate())]});return(await this.getAudioTracks(r))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){const n=this._backingToTrack.get(e);if(n)return n;const i=e.getType()==="video"?new ll(this,e):new Hd(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class jd extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Lt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Za{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,n){if(this.source._disposed)throw new Lt;if(e<0||this.fileSizeNonStrict!==null&&e+n>this.fileSizeNonStrict)return null;if(n===0){const s=new Uint8Array(0);return new Nn(s,et(s),0,e,e)}const r=e+n,i=this.source._read(e,r,pd,gd);return le(i)?i.then(s=>s?new Nn(s.bytes,s.view,s.offset,e,r):null):i?new Nn(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new Lt;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ms(this.fileSizeNonStrict-e,n,r));{const i=this.requestSlice(e,r),s=a=>a||(N(this.fileSizeNonStrict!==null),this.requestSlice(e,Ms(this.fileSizeNonStrict-e,n,r)));return le(i)?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const n=[];let r=0;for(;;){if(n.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(r,0,e);if(le(a)&&(a=await a),!a||a.length===0)break;const o=Ee(a,a.length);n.push(o),r+=a.length}const i=new Uint8Array(r);let s=0;for(const a of n)i.set(a,s),s+=a.length;return new Nn(i,et(i),0,0,r)})()}}class Nn{constructor(e,n,r,i,s){this.bytes=e,this.view=n,this.offset=r,this.start=i,this.end=s,this.bufferPos=i-r}static tempFromBytes(e){return new Nn(e,et(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,n=this.end-e){if(e<this.start||e+n>this.end)throw new RangeError("Slicing outside of original slice.");return new Nn(this.bytes,this.view,this.offset,e,e+n)}}const Jt=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Ee=(t,e)=>{Jt(t,e);const n=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,n},Se=t=>(Jt(t,1),t.view.getUint8(t.bufferPos++)),Gs=(t,e)=>{Jt(t,2);const n=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,n},At=t=>{Jt(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},vr=t=>{Jt(t,3);const e=Wu(t.view,t.bufferPos);return t.bufferPos+=3,e},fl=t=>{Jt(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},jr=(t,e)=>{Jt(t,4);const n=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,n},ve=t=>{Jt(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},as=t=>{Jt(t,4);const e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},bi=t=>{Jt(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},K1=t=>{Jt(t,4);const e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},qd=(t,e)=>{let n,r;return e?(n=jr(t,!0),r=jr(t,!0)):(r=jr(t,!1),n=jr(t,!1)),r*4294967296+n},un=t=>{const e=ve(t),n=ve(t);return e*4294967296+n},Z1=t=>{const e=bi(t),n=ve(t);return e*4294967296+n},J1=t=>{const e=as(t);return K1(t)*4294967296+e},ey=t=>{Jt(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Xd=t=>{Jt(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},mt=(t,e)=>{Jt(t,e);let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t.bytes[t.bufferPos++]);return n},$d=(t,e,n)=>Kt.decode(Ee(t,e)).split(`
2
+ `).map(s=>s.trim()).filter(s=>s.length>0&&!n?.ignore?.(s));var wi;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(wi||(wi={}));var os;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(os||(os={}));const Ja=128,wn=10,cs=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],ty=(t,e)=>{const n=t.filePos;e.raw??={},e.raw.TAG??=Ee(t,Ja-3),t.filePos=n;const r=ls(t,30);r&&(e.title??=r);const i=ls(t,30);i&&(e.artist??=i);const s=ls(t,30);s&&(e.album??=s);const a=ls(t,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));const c=Ee(t,30);let u;if(c[28]===0&&c[29]!==0){const d=c[29];d>0&&(e.trackNumber??=d),t.skip(-30),u=ls(t,28),t.skip(2)}else t.skip(-30),u=ls(t,30);u&&(e.comment??=u);const l=Se(t);l<cs.length&&(e.genre??=cs[l])},ls=(t,e)=>{const n=Ee(t,e),r=ji(n.indexOf(0),n.length),i=n.subarray(0,r);let s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},Ar=t=>{const e=t.filePos,n=mt(t,3),r=Se(t),i=Se(t),s=Se(t),a=ve(t);if(n!=="ID3"||r===255||i===255||(a&2155905152)!==0)return t.filePos=e,null;let o=Oc(a);return s&wi.Footer&&(o+=wn),{majorVersion:r,revision:i,flags:s,size:o}},eo=(t,e,n)=>{if(![2,3,4].includes(e.majorVersion)){Be._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const r=e.flags&wi.Footer?e.size-wn:e.size,i=Ee(t,r),s=new ny(e,i);if(e.flags&wi.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&wi.ExtendedHeader){const a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const a=s.readId3V2Frame();if(!a)break;const o=s.pos,c=s.pos+a.size;let u=!1,l=!1,d=!1;if(e.majorVersion===3?(u=!!(a.flags&64),l=!!(a.flags&128)):e.majorVersion===4&&(u=!!(a.flags&4),l=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&wi.Unsynchronisation)),u){Be._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(l){Be._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(d&&s.ununsynchronizeRegion(s.pos,c),n.raw??={},a.id==="TXXX"){const f=n.raw.TXXX??={},h=s.readId3V2TextEncoding(),p=s.readId3V2Text(h,c),m=s.readId3V2Text(h,c);f[p]??=m}else a.id[0]==="T"?n.raw[a.id]??=s.readId3V2EncodingAndText(c):n.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":n.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":n.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":n.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":n.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":n.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(n.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(n.tracksTotal??=m)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(n.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(n.discsTotal??=m)}break;case"TCON":case"TCO":{const f=s.readId3V2EncodingAndText(c);let h=/^\((\d+)\)/.exec(f);if(h){const p=Number.parseInt(h[1]);if(cs[p]!==void 0){n.genre??=cs[p];break}}if(h=/^\d+$/.exec(f),h){const p=Number.parseInt(h[0]);if(cs[p]!==void 0){n.genre??=cs[p];break}}n.genre??=f}break;case"TDRC":case"TDAT":{const f=s.readId3V2EncodingAndText(c),h=new Date(f);Number.isNaN(h.getTime())||(n.date??=h)}break;case"TYER":case"TYE":{const f=s.readId3V2EncodingAndText(c),h=Number.parseInt(f,10);Number.isInteger(h)&&(n.date??=new Date(String(h)))}break;case"USLT":case"ULT":{const f=s.readU8();s.pos+=3,s.readId3V2Text(f,c),n.lyrics??=s.readId3V2Text(f,c)}break;case"COMM":case"COM":{const f=s.readU8();s.pos+=3,s.readId3V2Text(f,c),n.comment??=s.readId3V2Text(f,c)}break;case"APIC":case"PIC":{const f=s.readId3V2TextEncoding();let h;if(e.majorVersion===2){const y=s.readAscii(3);h=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(f,c);const p=s.readU8(),m=s.readId3V2Text(f,c).trimEnd(),g=c-s.pos;if(g>=0){const y=s.readBytes(g);n.images||(n.images=[]),n.images.push({data:y,mimeType:h,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}};class ny{constructor(e,n){this.header=e,this.bytes=n,this.pos=0,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let n=0;n<this.bytes.length;n++){const r=this.bytes[n];e.push(r),r===255&&n!==this.bytes.length-1&&this.bytes[n]===0&&n++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,n){const r=[];for(let a=e;a<n;a++){const o=this.bytes[a];r.push(o),o===255&&a!==n-1&&this.bytes[a+1]===0&&a++}const i=this.bytes.subarray(0,e),s=this.bytes.subarray(n);this.bytes=new Uint8Array(i.length+r.length+s.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(s,i.length+r.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){const n=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,n}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),n=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+n}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,n}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const n=this.readU24();return{id:e,size:n,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const n=this.readU32();let r=this.header.majorVersion===4?Oc(n):n;const i=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!a(r)){const o=this.header.majorVersion===4?n:Oc(n);a(o)&&(r=o)}return this.pos=s,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,n){const r=this.pos,i=this.readBytes(n-this.pos);switch(e){case os.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){const o=i[a];if(o===0){this.pos=r+a+1;break}s+=String.fromCharCode(o)}return s}case os.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){const s=new TextDecoder("utf-16le"),a=ji(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){const s=new TextDecoder("utf-16be"),a=ji(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{const s=ji(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Kt.decode(i.subarray(0,s))}case os.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=ji(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=r+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case os.UTF_8:{const s=ji(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Kt.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const n=this.readId3V2TextEncoding();return this.readId3V2Text(n,e)}}function Gd(){return typeof VideoDecoder=="function"&&typeof VideoFrame=="function"}const Qd=6,Yd=16;function ry(t){const e=document.createElement("canvas");e.style.cssText=t.cssText,t.container.appendChild(e);const n=e.getContext("2d",{alpha:!1});if(!n)return e.remove(),queueMicrotask(()=>t.onFatal("2d \u4E0A\u4E0B\u6587\u521B\u5EFA\u5931\u8D25")),{canvas:e,pause(){},resume(){},destroy(){}};n.imageSmoothingEnabled=!0,n.imageSmoothingQuality="high";let r=!1,i=0,s=performance.now(),a=0,o=!1;const c=()=>{const I=t.renderDpr||0,B=Math.min(window.devicePixelRatio||1,I<=0?window.devicePixelRatio||1:I),V=Math.max(1,Math.round((t.container.clientWidth||window.innerWidth)*B)),O=Math.max(1,Math.round((t.container.clientHeight||window.innerHeight)*B));e.width!==V&&(e.width=V),e.height!==O&&(e.height=O)};c(),window.addEventListener("resize",c);const u=[];let l=null,d=null,f=null,h=0,p=0,m=Qd,g=0,y=!1,w=-1,A=0,b=!1;const v=I=>{const B=e.width,V=e.height,O=I.displayWidth,U=I.displayHeight;if(B<=0||V<=0||O<=0||U<=0)return;const W=t.fit();if(W==="stretch"){I.draw(n,0,0,B,V);return}const ie=W==="cover"?Math.max(B/O,V/U):Math.min(B/O,V/U),we=Math.round(O*ie),Y=Math.round(U*ie),oe=Math.round((B-we)/2),he=Math.round((V-Y)/2);W==="contain"&&(n.fillStyle="#000",n.fillRect(0,0,B,V)),I.draw(n,oe,he,we,Y)},x=()=>h+(performance.now()-s)/1e3%p,P=()=>{g++,m<Yd&&g%30===1&&(m=Math.min(Yd,m+2),!y&&m>=Qd+4&&(y=!0,t.onDiag?.(`\u5FAA\u73AF\u70B9\u89E3\u7801\u7A7A\u7A97\uFF0C\u524D\u77BB\u52A0\u6DF1\u81F3 ${m} \u5E27`)))},S=()=>{if(r||(i=requestAnimationFrame(S),o||t.paused()||p<=0))return;const I=x();for(;u.length>0;){const U=u[0],W=u[1];if(U.timestamp-I>p/2){U.close(),u.shift();continue}if(W&&W.timestamp<=I+1e-4){U.close(),u.shift();continue}break}const B=u[0];if(!B){P();return}if(B.timestamp>I+1e-4||B.timestamp===w)return;const V=t.fps(),O=performance.now();if(!(V>0&&O-A<1e3/V-.5)){w=B.timestamp,A=O;try{v(B)}catch{return}t.onFrame?.(),b||(b=!0,t.onFirstFrame?.())}},k=I=>new Promise(B=>setTimeout(B,I)),_=async()=>{try{for(;!r;){for(;!r&&(u.length>=m||o||t.paused());)await k(20);if(r)return;f||(f=d.samples(h));const I=await f.next();if(r){I.value?.close();return}if(I.done){f=null;continue}u.push(I.value)}}catch(I){r||t.onFatal(`\u89E3\u7801\u6CF5\u5F02\u5E38: ${I?.message??I}`)}};return(async()=>{try{l=new Vo({source:new wu(t.src),formats:E1});const I=await l.getPrimaryVideoTrack();if(!I)throw new Error("\u65E0\u89C6\u9891\u8F68");if(!await I.canDecode())throw new Error(`\u7F16\u7801\u4E0D\u53EF\u89E3\uFF08${I.codec}\uFF09`);const B=await I.computeDuration();if(h=await I.getFirstTimestamp(),p=Math.max(B-h,B>0?B:0),!isFinite(p)||p<=0)throw new Error("\u65F6\u957F\u5F02\u5E38");if(r){try{l.dispose()}catch{}return}d=new X1(I);const V=await I.getDisplayWidth(),O=await I.getDisplayHeight();t.onDiag?.(`${I.codec} ${V}x${O} ${p.toFixed(2)}s \u2192 WebCodecs \u9010\u5E27\u8C03\u5EA6`),_(),i=requestAnimationFrame(S)}catch(I){r||t.onFatal(I?.message??String(I))}})(),{canvas:e,pause(){o||(o=!0,a=performance.now())},resume(){o&&(o=!1,s+=performance.now()-a)},destroy(){if(!r){r=!0,i&&cancelAnimationFrame(i),i=0,window.removeEventListener("resize",c);for(const I of u.splice(0))try{I.close()}catch{}f&&f.return(void 0).catch(()=>{});try{l?.dispose()}catch{}e.remove()}}}}function iy(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<16)throw new Error("\u6587\u4EF6\u592A\u5C0F\uFF0C\u4E0D\u662F scene.pkg");const n=e.getUint32(0,!0);if(n<4||n>16)throw new Error("\u9B54\u6570\u957F\u5EA6\u5F02\u5E38: "+n);const r=Kd(t,4,n);if(!r.startsWith("PKGV"))throw new Error("\u4E0D\u662F scene.pkg\uFF0C\u9B54\u6570: "+r);const i=e.getUint32(4+n,!0);let s=4+n+4;const a=[];for(let c=0;c<i;c++){if(s+8>t.length)throw new Error("\u5165\u53E3\u8868\u8D8A\u754C @"+c);const u=e.getUint32(s,!0);if(s+=4,s+u+8>t.length)throw new Error("\u5165\u53E3 "+c+" \u8D8A\u754C");const l=ay(t,s,u);s+=u;const d=e.getUint32(s,!0);s+=4;const f=e.getUint32(s,!0);s+=4,a.push({name:l,offset:d,size:f})}const o=s;return{magic:r,version:r.slice(4),count:i,entries:a,dataStart:o,fileSize:t.length,buf:t}}function dl(t,e){const n=t.entries.find(s=>s.name===e);if(n===void 0)return null;const r=t.dataStart+n.offset,i=r+n.size;if(r<0||i>t.fileSize)throw new Error("\u5165\u53E3 "+e+" \u8D8A\u754C");return t.buf.subarray(r,i)}function sy(t){let e=0;for(const n of t.entries)e=Math.max(e,n.offset+n.size);return{dataEnd:t.dataStart+e,fileSize:t.fileSize,ok:t.dataStart+e<=t.fileSize}}function Kd(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}function ay(t,e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t.subarray(e,e+n))}catch{return Kd(t,e,n)}}const oy=Object.freeze(Object.defineProperty({__proto__:null,getEntry:dl,parsePkg:iy,verifyLayout:sy},Symbol.toStringTag,{value:"Module"})),to={0:"ARGB8888",1:"RGB888",2:"RGB565",4:"DXT5",6:"DXT3",7:"DXT1",8:"RG88",9:"R8",10:"RG1616f",11:"R16f",12:"BC7",13:"RGBa1010102",14:"RGBA16161616f",15:"RGB161616f"},$t={UNKNOWN:-1,JPEG:2,PNG:13,GIF:25,WEBP:35,MP4:35};function cy(t){const e=t.images[0];if(!e||e.length===0)throw new Error("\u65E0\u56FE\u50CF\u6570\u636E");const n=e[0];if(t.isVideo)return{width:n.width,height:n.height,video:n.data};if(t.freeImageFormat===$t.PNG)return{width:n.width,height:n.height,png:n.data};if(t.freeImageFormat!==$t.UNKNOWN)return{width:n.width,height:n.height,image:n.data,fif:t.freeImageFormat};const r=no(t.format,n.data,n.width,n.height);return!t.frames?.list?.length&&(n.width!==t.width||n.height!==t.height)?{width:t.width,height:t.height,rgba:hl(r,n.width,n.height,t.width,t.height)}:{width:n.width,height:n.height,rgba:r}}function ly(t,e){const n=t.images[0];if(!n||n.length===0)throw new Error("\u65E0\u56FE\u50CF\u6570\u636E");const r=Math.max(0,Math.min(n.length-1,Math.floor(e)||0)),i=n[r];if(t.isVideo)return{width:i.width,height:i.height,video:i.data,level:r};if(t.freeImageFormat===$t.PNG)return{width:i.width,height:i.height,png:i.data,level:r};if(t.freeImageFormat!==$t.UNKNOWN)return{width:i.width,height:i.height,image:i.data,fif:t.freeImageFormat,level:r};const s=no(t.format,i.data,i.width,i.height);if(!t.frames?.list?.length){const a=Math.min(i.width,Math.max(1,Math.round((t.width||i.width)/2**r))),o=Math.min(i.height,Math.max(1,Math.round((t.height||i.height)/2**r)));if(i.width!==a||i.height!==o)return{width:a,height:o,rgba:hl(s,i.width,i.height,a,o),level:r}}return{width:i.width,height:i.height,rgba:s,level:r}}function uy(t){const e=t.images[0];if(!e||e.length===0)throw new Error("\u65E0\u56FE\u50CF\u6570\u636E");const n=[];for(const r of e){if(t.freeImageFormat!==$t.UNKNOWN){n.push({width:r.width,height:r.height,image:r.data,fif:t.freeImageFormat});continue}const i=no(t.format,r.data,r.width,r.height);n.push({width:r.width,height:r.height,rgba:i})}return!t.frames?.list?.length&&n.length>0&&(n[0].width!==t.width||n[0].height!==t.height)&&n[0].rgba&&(n[0]={width:t.width,height:t.height,rgba:hl(n[0].rgba,n[0].width,n[0].height,t.width,t.height)}),n}function hl(t,e,n,r,i){const s=new Uint8Array(r*i*4);for(let a=0;a<i;a++)s.set(t.subarray(a*e*4,a*e*4+r*4),a*r*4);return s}function no(t,e,n,r){switch(t){case 0:return fy(e,n,r);case 1:return dy(e,n,r);case 2:return hy(e,n,r);case 4:return by(e,n,r);case 6:return yy(e,n,r);case 7:return gy(e,n,r);case 8:return my(e,n,r);case 9:return py(e,n,r);case 12:throw new Error("BC7 \u89E3\u7801\u6682\u672A\u5B9E\u73B0\uFF08format=12\uFF09");default:throw new Error("\u672A\u652F\u6301\u7684\u7EB9\u7406\u683C\u5F0F: "+(to[t]||t))}}function fy(t,e,n){return new Uint8Array(t.buffer,t.byteOffset,e*n*4).slice()}function dy(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i*3],r[i*4+1]=t[i*3+1],r[i*4+2]=t[i*3+2],r[i*4+3]=255;return r}function hy(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++){const s=t[i*2]|t[i*2+1]<<8,a=s>>11&31,o=s>>5&63,c=s&31;r[i*4]=a<<3|a>>2,r[i*4+1]=o<<2|o>>4,r[i*4+2]=c<<3|c>>2,r[i*4+3]=255}return r}function my(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i*2+1],r[i*4+1]=t[i*2+1],r[i*4+2]=t[i*2+1],r[i*4+3]=t[i*2];return r}function py(t,e,n){const r=new Uint8Array(e*n*4);for(let i=0;i<e*n;i++)r[i*4]=t[i],r[i*4+1]=t[i],r[i*4+2]=t[i],r[i*4+3]=255;return r}function gy(t,e,n){return ml(t,e,n,!0,0)}function yy(t,e,n){return ml(t,e,n,!1,3)}function by(t,e,n){return ml(t,e,n,!1,5)}function ml(t,e,n,r,i){const s=new Uint8Array(e*n*4),a=r?8:16,o=new Uint8Array(16);let c=0;for(let u=0;u<n;u+=4)for(let l=0;l<e;l+=4){if(c+a>t.length)return s;o.set(t.subarray(c,c+a)),c+=a;const d=wy(o,r),f=vy(o,r),h=i===3?Ay(o):i===5?xy(o):null;for(let p=0;p<4;p++)for(let m=0;m<4;m++){const g=l+m,y=u+p;if(g>=e||y>=n)continue;const w=p*4+m,A=(y*e+g)*4;s[A]=d[f[w]*4],s[A+1]=d[f[w]*4+1],s[A+2]=d[f[w]*4+2],s[A+3]=h!==null?h[w]:d[f[w]*4+3]}}return s}function Zd(t,e){const n=t[e]|t[e+1]<<8,r=n>>11&31,i=n>>5&63,s=n&31;return[n,r<<3|r>>2,i<<2|i>>4,s<<3|s>>2]}function wy(t,e){const n=e?0:8,r=Zd(t,n),i=Zd(t,n+2),s=new Uint8Array(16);return s[0]=r[1],s[1]=r[2],s[2]=r[3],s[3]=255,s[4]=i[1],s[5]=i[2],s[6]=i[3],s[7]=255,e&&r[0]<=i[0]?(s[8]=r[1]+i[1]>>1,s[9]=r[2]+i[2]>>1,s[10]=r[3]+i[3]>>1,s[11]=255,s[12]=0,s[13]=0,s[14]=0,s[15]=0):(s[8]=Math.floor((2*r[1]+i[1])/3),s[9]=Math.floor((2*r[2]+i[2])/3),s[10]=Math.floor((2*r[3]+i[3])/3),s[11]=255,s[12]=Math.floor((r[1]+2*i[1])/3),s[13]=Math.floor((r[2]+2*i[2])/3),s[14]=Math.floor((r[3]+2*i[3])/3),s[15]=255),s}function vy(t,e){const n=e?4:12,r=new Uint8Array(16);for(let i=0;i<4;i++){const s=t[n+i];r[i*4]=s&3,r[i*4+1]=s>>2&3,r[i*4+2]=s>>4&3,r[i*4+3]=s>>6&3}return r}function Ay(t){const e=new Uint8Array(16);for(let n=0;n<8;n++){const r=t[n],i=r&15,s=r&240;e[2*n]=i|i<<4,e[2*n+1]=s|s>>4}return e}function xy(t){const e=t[0],n=t[1],r=new Uint8Array(8);if(r[0]=e,r[1]=n,e<=n){for(let o=1;o<5;o++)r[1+o]=Math.floor(((5-o)*e+o*n)/5);r[6]=0,r[7]=255}else for(let o=1;o<7;o++)r[o+1]=Math.floor(((7-o)*e+o*n)/7);const i=new Uint8Array(16);let s=0;for(let o=0;o<2;o++){let c=0;for(let u=0;u<3;u++)c|=t[2+o*3+u]<<8*u;for(let u=0;u<8;u++)i[s++]=c>>3*u&7}const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=r[i[o]];return a}function ky(t,e,n,r,i){const s=Math.ceil(e/4),a=Math.ceil(n/4),o=Math.ceil(r/4);if(s===a)return t.subarray(0,a*o*i);const c=new Uint8Array(a*o*i);for(let u=0;u<o;u++){const l=u*s*i;c.set(t.subarray(l,l+a*i),u*a*i)}return c}function Jd(t,e){const n=new Uint8Array(e);let r=0,i=0;for(;r<t.length;){const s=t[r++];let a=s>>4;if(a===15){let l;do l=t[r++],a+=l;while(l===255)}for(let l=0;l<a;l++)n[i++]=t[r++];if(r>=t.length)break;const o=t[r]|t[r+1]<<8;r+=2;let c=4+(s&15);if((s&15)===15){let l;do l=t[r++],c+=l;while(l===255)}const u=i-o;for(let l=0;l<c;l++)n[i++]=n[u+l]}return n}function tt(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function ro(t,e){return tt(t,e)|0}const Qs=new DataView(new ArrayBuffer(4));function qr(t,e){return Qs.setUint8(0,t[e]),Qs.setUint8(1,t[e+1]),Qs.setUint8(2,t[e+2]),Qs.setUint8(3,t[e+3]),Qs.getFloat32(0,!0)}const Ty={[$t.PNG]:[137,80,78,71],[$t.JPEG]:[255,216,255],[$t.GIF]:[71,73,70],[$t.WEBP]:[82,73,70,70]};function Sy(t){let e=0;const n=Ys(t,e,9);if(e+=9,n==="TEXV0004\0")return Py(t);if(n!=="TEXV0005\0")throw new Error("\u4E0D\u662F .tex \u6587\u4EF6: "+n);const r=Ys(t,e,9);if(e+=9,r!=="TEXI0001\0")throw new Error("\u672A\u77E5 TEXI \u5B50\u5BB9\u5668: "+r);const i=tt(t,e);e+=4;const s=tt(t,e);e+=4;const a=tt(t,e);e+=4;const o=tt(t,e);e+=4;let c=46;for(let v=34;v<=64;v++){const x=Ys(t,v,9);if(x==="TEXB0001\0"||x==="TEXB0002\0"||x==="TEXB0003\0"||x==="TEXB0004\0"){c=v;break}}const u=tt(t,c-12),l=tt(t,c-8);e=c;const d=Ys(t,e,9);e+=9;const f=tt(t,e);e+=4;let h=$t.UNKNOWN,p=0;if(d==="TEXB0004\0"){h=tt(t,e)|0,e+=4;const v=tt(t,e);e+=4,h===$t.UNKNOWN&&v===1&&(h=$t.MP4),p=v===1?4:3}else if(d==="TEXB0003\0")h=tt(t,e)|0,e+=4,p=3;else if(d==="TEXB0002\0")p=2;else if(d==="TEXB0001\0")p=1;else throw new Error("\u672A\u77E5 TEXB \u5BB9\u5668: "+d);const m=(s&32)!==0||h===$t.MP4,g=[];for(let v=0;v<f;v++){const x=tt(t,e);e+=4;const P=[];for(let S=0;S<x;S++){if(p===4){for(e+=8;e<t.length&&t[e]!==0;)e++;e+=1,e+=4}const k=tt(t,e);e+=4;const _=tt(t,e);e+=4;let I=0;if(s&64&&p>=2&&!m){const ie=tt(t,e),we=ro(t,e+8),Y=tt(t,e+4),oe=ro(t,e+12),he=Ce=>{if(!(oe>=0)||Ce+oe>t.length)return!1;const Le=Ty[h];return Le?Le.every((Ne,De)=>t[Ce+De]===Ne):!0},Ae=ie<=1&&we>=0&&e+12+we<=t.length,Pe=Y<=1&&he(e+16);!Ae&&Pe&&(I=4)}e+=I;let B=0,V=0;p>=2&&(B=tt(t,e),e+=4,V=ro(t,e),e+=4);const O=ro(t,e);if(e+=4,m){P.push({width:k,height:_,compression:0,data:t.subarray(e)}),e=t.length;continue}B===0&&(V=O);const U=t.subarray(e,e+O);e+=O;let W=U;B===1&&(W=Jd(U,V)),P.push({width:k,height:_,compression:B,data:W})}g.push(P)}const y=g[0]&&g[0][0],w=y?y.width:a,A=y?y.height:o;let b=null;if(e+13<=t.length){const v=Ys(t,e,9);if(v.indexOf("TEXS")===0){let x=e+9;const P=tt(t,x);x+=4;let S=0,k=0;v==="TEXS0003\0"&&(S=tt(t,x),x+=4,k=tt(t,x),x+=4);const _=t.length-x,I=P>0&&_>0&&_%P===0?_/P:0;if(P>0&&P<=4096&&I>=32){const B=[];for(let O=0;O<P;O++){const U=x+O*I;if(U+32>t.length)break;const W=qr(t,U+8),ie=qr(t,U+12),we=qr(t,U+16),Y=qr(t,U+20),oe=qr(t,U+24),he=qr(t,U+28),Ae=Math.hypot(we,Y),Pe=Math.hypot(oe,he);B.push({imageId:qr(t,U)|0,duration:qr(t,U+4),x:W,y:ie,width:(Ae>1e-30?Ae:0)||S,height:(Pe>1e-30?Pe:0)||k,uDir:[we,Y],vDir:[oe,he],rotated:Math.abs(Y)>.5||Math.abs(oe)>.5})}B.length===P&&B.every(O=>{if(!(O.width>0&&O.height>0))return!1;const U=[O.x,O.x+O.uDir[0],O.x+O.vDir[0],O.x+O.uDir[0]+O.vDir[0]],W=[O.y,O.y+O.uDir[1],O.y+O.vDir[1],O.y+O.uDir[1]+O.vDir[1]];return Math.min(...U)>=-1&&Math.max(...U)<=w+1&&Math.min(...W)>=-1&&Math.max(...W)<=A+1})&&(b={magic:v,frameWidth:S,frameHeight:k,atlasWidth:w,atlasHeight:A,list:B})}}}return{format:i,formatName:to[i]||String(i),flags:s,textureWidth:a,textureHeight:o,width:u,height:l,freeImageFormat:h,containerMagic:d,containerVersion:p,isVideo:m,images:g,frames:b}}function Py(t){let e=9;const n=tt(t,e);e+=4;const r=tt(t,e);e+=4;const i=tt(t,e);e+=4;const s=tt(t,e);e+=4;const a=tt(t,e);e+=4;const o=tt(t,e);e+=4;const c=tt(t,e);e+=4;const u=[];for(let l=0;l<c;l++){if(e+12>t.length)throw new Error("TEXV0004 mip \u8BB0\u5F55\u8D8A\u754C @"+l);const d=tt(t,e);e+=4;const f=tt(t,e);e+=4;const h=tt(t,e);if(e+=4,e+h>t.length)throw new Error("TEXV0004 \u8F7D\u8377\u8D8A\u754C @"+l);u.push([{width:d,height:f,compression:0,data:t.subarray(e,e+h)}]),e+=h}return{format:n,formatName:to[n]||String(n),flags:r,textureWidth:i,textureHeight:s,width:a,height:o,freeImageFormat:$t.UNKNOWN,containerMagic:"TEXV0004",containerVersion:0,isVideo:!1,images:u,frames:null}}function Ys(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}const _y=Object.freeze(Object.defineProperty({__proto__:null,FIF:$t,TEXTURE_FORMATS:to,cropBlocks:ky,decodeMip0:cy,decodeMipLevel:ly,decodeMips:uy,decodePixels:no,lz4Decompress:Jd,parseTex:Sy},Symbol.toStringTag,{value:"Module"})),Xr=0,pl=1;function gl(t,e){const n=new Map,r=eh(t)||Ey(n),i=eh(e)||null,s=o=>o===pl&&i?i:r,a={LOCATION_SCREEN:Xr,LOCATION_GLOBAL:pl,getItem(o,c=Xr){return s(c).get(String(o))},setItem(o,c,u=Xr){s(u).set(String(o),String(c))},delete(o,c=Xr){s(c).remove(String(o))},removeItem(o,c=Xr){s(c).remove(String(o))},clear(o=Xr){s(o).clear()},key(o,c=Xr){const u=s(c).keys();return o>=0&&o<u.length?u[o]:null}};return a.get=a.getItem,a.set=a.setItem,a.remove=a.delete,Object.defineProperties(a,{length:{enumerable:!1,get(){return r.keys().length}}}),a}function eh(t){return!t||typeof t!="object"?null:typeof t.get=="function"&&typeof t.set=="function"&&typeof t.remove=="function"&&typeof t.keys=="function"&&typeof t.clear=="function"?t:null}function Ey(t){return{get:e=>t.has(e)?t.get(e):null,set:(e,n)=>{t.set(e,String(n))},remove:e=>{t.delete(e)},keys:()=>Array.from(t.keys()),clear:()=>{t.clear()}}}function My(t,e,n){const r=Math.max(0,Number(n)||0),i=Math.max(1,Number(t)||1),s=Math.max(1,Number(e)||1);return r*2>=Math.min(i,s)?0:r}function Cy(t,e,n){const r=Math.max(1,e.boxW),i=Math.max(1,e.boxH),s=e.spacing||[0,0],a=Math.max(1,e.lineHeight||(e.pointsize||24)*1.25+s[1]),o=e.limitwidth&&e.maxwidth>0?e.maxwidth:1/0;function c(b){if(n(b)<=o)return[b];const v=[];let x="",P=-1;for(const S of b)if(x+=S,(S===" "||S===" ")&&(P=x.length),n(x)>o&&x.length>1)for(P>0?(v.push(x.slice(0,P-1)),x=x.slice(P)):(v.push(x.slice(0,-1)),x=S),P=-1;n(x)>o&&x.length>1;)v.push(x.slice(0,-1)),x=x.slice(-1);return x!==""&&v.push(x),v.length?v:[""]}let u=[];const l=String(t??"").split(`
3
+ `);for(const b of l)u.push(...c(b));let d=!1;if(e.limitrows&&e.maxrows>0&&u.length>e.maxrows&&(u=u.slice(0,e.maxrows),d=!0,e.limituseellipsis)){let b=u[e.maxrows-1];for(;b.length>0&&n(b+"\u2026")>o;)b=b.slice(0,-1);u[e.maxrows-1]=b+"\u2026"}const f=u.map(b=>n(b)),h=u.length*a,p=e.halign||"center",m=e.valign||"center",g=r/2,y=i/2,w=m==="top"?y:m==="bottom"?y-h:(i-h)/2;return{lines:u.map((b,v)=>{const x=f[v],P=p==="left"?g:p==="right"?g-x:(r-x)/2;return{text:b,width:x,x:P,y:w+v*a}}),lineHeight:a,totalH:h,truncated:d,boxW:r,boxH:i}}function th(t,e,n){let r=1/0,i=-1/0,s=1/0,a=-1/0;for(const o of t.lines||[])r=Math.min(r,o.x),i=Math.max(i,o.x+o.width),s=Math.min(s,o.y),a=Math.max(a,o.y+(t.lineHeight||0));return!t.lines||!t.lines.length?[0,0,0,0]:[Math.max(0,-r),Math.max(0,-s),Math.max(0,i-e),Math.max(0,a-n)]}function Iy(t,e,n,r){const[i,s,a,o]=th(t,e,n);return Math.max(r,i,s,a,o)}function Ry(t,e,n){return t<=4&&e<=4&&!!n}function By(t,e,n){const r=e.boxW,i=e.boxH,s=n.color||[1,1,1],a=n.alpha!==void 0?n.alpha:1,o=n.brightness!==void 0?n.brightness:1;t.font=n.font;try{t.letterSpacing=(n.spacing&&n.spacing[0]?n.spacing[0]:0)+"px"}catch{}if(t.textBaseline="middle",n.opaquebackground){const u=n.backgroundcolor||[0,0,0],l=n.backgroundbrightness!==void 0?n.backgroundbrightness:1;t.fillStyle=`rgba(${Math.round(u[0]*255*l)},${Math.round(u[1]*255*l)},${Math.round(u[2]*255*l)},${a})`,t.fillRect(0,0,r,i)}const c=(u,l,d)=>{t.fillStyle=d;for(const f of e.lines)t.fillText(f.text,f.x+u,f.y+e.lineHeight/2+l)};if(n.castshadow){const u=Math.max(1,(n.pointsize||24)/10);c(u,u,`rgba(0,0,0,${a*.75})`)}c(0,0,`rgba(${Math.round(s[0]*255*o)},${Math.round(s[1]*255*o)},${Math.round(s[2]*255*o)},${a})`)}const nh=/^add[A-Z]/;function rh(){return{log:()=>{},warn:()=>{},error:()=>{},info:()=>{},debug:()=>{}}}function ih(t){return new Proxy(t,{get(e,n,r){const i=Reflect.get(e,n,r);if(i==null&&typeof n=="string"&&n!=="then"){const s=()=>{};return e[n]=s,s}return i}})}function us(t,e){return()=>{}}function sh(t,e){t.isScreensaver=!!e.isScreensaver,typeof e.isRunningInEditor=="boolean"&&(t.isRunningInEditor=bl(e.isRunningInEditor)),t.setInterval||(t.setInterval=e.setInterval||us),t.setTimeout||(t.setTimeout=e.setTimeout||us),t.clearTimeout||(t.clearTimeout=e.clearTimeout||(()=>{})),t.clearInterval||(t.clearInterval=e.clearInterval||(()=>{})),typeof e.openUserShortcut=="function"&&(t.openUserShortcut=e.openUserShortcut);const n=e.mediaControl||null;t.media={skipNext:()=>{if(n&&n.skipNext)return n.skipNext()},skipPrevious:()=>{if(n&&n.skipPrevious)return n.skipPrevious()},play:()=>{if(n&&n.play)return n.play()},pause:()=>{if(n&&n.pause)return n.pause()},playPause:()=>{if(n&&n.playPause)return n.playPause()},get snapshot(){return n&&n.snapshot?n.snapshot:null}};const r=e.windowTitle;Object.defineProperty(t,"windowTitle",{configurable:!0,enumerable:!0,get(){return r&&r.title?String(r.title):""}}),Object.defineProperty(t,"windowApp",{configurable:!0,enumerable:!0,get(){return r&&r.app?String(r.app):""}})}class Ue{constructor(e,n,r){if(e!==null&&typeof e=="object")this.x=e.x!==void 0?e.x:e.width||0,this.y=e.y!==void 0?e.y:e.height||0,this.z=(n!==void 0?n:r!==void 0?r:e.z)||0;else if(n===void 0&&r===void 0){const i=Number(e)||0;this.x=i,this.y=i,this.z=i}else this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){const n=new Ue(e);return new Ue(this.x+n.x,this.y+n.y,this.z+n.z)}subtract(e){const n=new Ue(e);return new Ue(this.x-n.x,this.y-n.y,this.z-n.z)}multiply(e){return e&&typeof e=="object"?new Ue(this.x*e.x,this.y*e.y,this.z*e.z):new Ue(this.x*e,this.y*e,this.z*e)}divide(e){const n=(r,i)=>i===0?0:r/i;return e&&typeof e=="object"?new Ue(n(this.x,e.x),n(this.y,e.y),n(this.z,e.z)):new Ue(n(this.x,e),n(this.y,e),n(this.z,e))}copy(){return new Ue(this.x,this.y,this.z)}mix(e,n){const r=new Ue(e),i=Number(n),s=Number.isFinite(i)?i:0;return new Ue(this.x+(r.x-this.x)*s,this.y+(r.y-this.y)*s,this.z+(r.z-this.z)*s)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSqr(){return this.x*this.x+this.y*this.y+this.z*this.z}normalize(){const e=this.length();return e===0?new Ue(0,0,0):new Ue(this.x/e,this.y/e,this.z/e)}dot(e){const n=new Ue(e);return this.x*n.x+this.y*n.y+this.z*n.z}toString(){return this.x+" "+this.y+" "+this.z}}const ah=Ue;function yl(t){if(t instanceof Ue||!t||typeof t!="object"||Array.isArray(t)||!("x"in t)&&!("y"in t)&&!("z"in t)||Object.getPrototypeOf(t)===Ue.prototype)return t;try{Object.setPrototypeOf(t,Ue.prototype)}catch{}return t}function oh(t){return t&&t.cursorWorldPosition?t:{cursorWorldPosition:new Ue(0,0,0),cursorScreenPosition:new Ue(0,0,0),cursorPosition:new Ue(0,0,0),cursorPositionLast:new Ue(0,0,0),cursorLeftDown:!1}}function Fy(t,e,n){return new Ue(t||0,e||0,n||0)}function Dy(){const t={cursorWorldPosition:new Ue(0,0,0),cursorScreenPosition:new Ue(0,0,0),cursorPosition:new Ue(0,0,0),cursorPositionLast:new Ue(0,0,0),cursorLeftDown:!1};return t.update=function(e){return e&&(t.cursorWorldPosition.x=e.wx,t.cursorWorldPosition.y=e.originY!=null?e.originY:e.wy,t.cursorWorldPosition.z=0,t.cursorScreenPosition.x=e.screenX,t.cursorScreenPosition.y=e.screenY,t.cursorScreenPosition.z=0,t.cursorPosition.x=e.u,t.cursorPosition.y=e.v,t.cursorPosition.z=0,t.cursorPositionLast.x=e.lastU,t.cursorPositionLast.y=e.lastV,t.cursorPositionLast.z=0,t.cursorLeftDown=!!e.leftDown),t},t}const ch={mix:(t,e,n)=>t+(e-t)*n,lerp:(t,e,n)=>t+(e-t)*n,clamp:(t,e,n)=>Math.min(n,Math.max(e,t)),saturate:t=>Math.min(1,Math.max(0,t)),smoothstep:(t,e,n)=>{const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)},smoothStep:(t,e,n)=>{const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)},random:(t,e)=>t===void 0?Math.random():t+Math.random()*((e===void 0?1:e)-t),randomInt:(t,e)=>Math.floor((t||0)+Math.random()*((e===void 0?1:e)+1-(t||0))),degrees:t=>t*180/Math.PI,radians:t=>t*Math.PI/180},lh={hsv2rgb:t=>{const e=t&&typeof t=="object"?t:{x:0,y:0,z:0},n=((Number(e.x)||0)%1+1)%1,r=Math.min(1,Math.max(0,Number(e.y)||0)),i=Math.min(1,Math.max(0,Number(e.z)||0)),s=Math.floor(n*6),a=n*6-s,o=i*(1-r),c=i*(1-a*r),u=i*(1-(1-a)*r),d=[[i,u,o],[c,i,o],[o,i,u],[o,c,i],[u,o,i],[i,o,c]][s%6];return new Ue(d[0],d[1],d[2])},rgb2hsv:t=>{const e=t&&typeof t=="object"?t:{x:0,y:0,z:0},n=Number(e.x)||0,r=Number(e.y)||0,i=Number(e.z)||0,s=Math.max(n,r,i),a=Math.min(n,r,i),o=s-a;let c=0;return o>0&&(s===n?c=(r-i)/o/6:s===r?c=(2+(i-n)/o)/6:c=(4+(n-r)/o)/6,c<0&&(c+=1)),new Ue(c,s===0?0:o/s,s)}},uh={add:(t,e)=>({x:(t.x||0)+(e.x||0),y:(t.y||0)+(e.y||0),z:(t.z||0)+(e.z||0)}),subtract:(t,e)=>({x:(t.x||0)-(e.x||0),y:(t.y||0)-(e.y||0),z:(t.z||0)-(e.z||0)}),scale:(t,e)=>({x:(t.x||0)*e,y:(t.y||0)*e,z:(t.z||0)*e}),length:t=>Math.hypot(t.x||0,t.y||0,t.z||0),dot:(t,e)=>(t.x||0)*(e.x||0)+(t.y||0)*(e.y||0)+(t.z||0)*(e.z||0),normalize:t=>{const e=Math.hypot(t.x||0,t.y||0,t.z||0)||1;return{x:(t.x||0)/e,y:(t.y||0)/e,z:(t.z||0)/e}},mix:(t,e,n)=>({x:(t.x||0)+((e.x||0)-(t.x||0))*n,y:(t.y||0)+((e.y||0)-(t.y||0))*n,z:(t.z||0)+((e.z||0)-(t.z||0))*n})},fh=Object.freeze({PLAYBACK_STOPPED:0,PLAYBACK_PLAYING:1,PLAYBACK_PAUSED:2}),io=["mediaPropertiesChanged","mediaThumbnailChanged","mediaPlaybackChanged","mediaTimelineChanged","mediaStatusChanged","mediaLyricsChanged"],Ny=["scriptProperties","engine","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","thisLayer","thisScene","thisObject","localStorage","MediaPlaybackEvent"],Ly=new RegExp(`(^[ \\t]*|;|\\})[ \\t]*(?:var|let|const)[ \\t]+(?=(?:${Ny.join("|")})\\b)`,"gm"),Uy={WEMath:!0,WEColor:!0,WEVector:!0};function dh(t){return typeof t!="string"?t:t.replace(/([!=])==(\s*)(['"])(-?\d+)\3/g,"$1=$2$3$4$3")}function hh(t){return dh(t).replace(/\bimport\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]\s*;?/g,(e,n,r)=>{const i=String(r);return Uy[i]?n===i?"":`var ${n} = ${i};`:`var ${n} = {};`}).replace(/(^[ \t]*|;|\})[ \t]*import\s+(?:[^;'"]+\s+from\s+)?['"][^'"]*['"];?[ \t]*/gm,"$1").replace(/(^[ \t]*|;|\})[ \t]*export[ \t]+(?=(?:async[ \t]+)?function\b|(?:var|let|const)\b)/gm,"$1").replace(Ly,"$1")}function Oy(t){if(typeof t=="boolean")return t;if(typeof t=="number"&&Number.isFinite(t))return t!==0}function mh(t){const e=Math.floor(Number(t));return Number.isFinite(e)&&e>=1?Math.min(64,e):64}function so(t){return t!==null&&typeof t=="object"&&"value"in t?t.value:t}function bl(t){const e=!!t;return Object.assign(()=>e,{valueOf(){return e},toString(){return e?"true":"false"}})}function ph(t,e,n,r){if(n!==null&&typeof n=="object"&&typeof n.user=="string"){const i=so(n);let s,a=!1;Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get(){if(a)return s;const o=r?r[n.user]:void 0;return o!==void 0?o:i},set(o){s=o,a=!0}})}else t[e]=so(n)}function gh(t){const e=t||{width:1920,height:1080};if(typeof e.divide=="function"&&e.x!==void 0)return e;const n=new Ue(e.x!==void 0?e.x:e.width||0,e.y!==void 0?e.y:e.height||0,0);return n.width=n.x,n.height=n.y,n}function zy(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=hh(t);if(r===t&&t.indexOf("update")<0&&t.indexOf("resizeScreen")<0)return null;const i={};if(e&&typeof e=="object")for(const[b,v]of Object.entries(e))ph(i,b,v,n.userProperties);const s=new Proxy(()=>s,{apply(){return s},get(b,v){if(v==="finish")return()=>i;if(typeof v=="string"&&nh.test(v))return x=>(x&&typeof x=="object"&&typeof x.name=="string"&&!(x.name in i)&&(i[x.name]=so(x.value)),s)}}),a={text:n.text!==void 0&&n.text!==null?String(n.text):"",font:n.font||"",pointsize:n.pointsize||24,color:(n.color||[1,1,1]).slice(),angles:(n.angles||[0,0,0]).slice(),scale:(n.scale||[1,1,1]).slice(),visible:n.visible!==!1,origin:vi(n.origin||[0,0,0])},o={registerAsset:b=>b,frametime:1/60,runtime:0,canvasSize:gh(n.canvasSize),screenResolution:n.screenResolution||{x:1920,y:1080},timeOfDay:typeof n.timeOfDay=="number"?n.timeOfDay:0,userProperties:n.userProperties||{},AUDIO_RESOLUTION_16:16,AUDIO_RESOLUTION_32:32,AUDIO_RESOLUTION_64:64,setTimeout:n.setTimeout||us,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||us,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:bl(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};sh(o,n);const c=n.audioViews;o.registerAudioBuffers=b=>{const v=mh(b);let x=c?c.get(v):void 0;return x||(x={left:new Float32Array(v),right:new Float32Array(v),average:new Float32Array(v)},c&&c.set(v,x)),x};const u={getLayer(b){const v=n.getLayerText?n.getLayerText(String(b)):void 0;return{text:v!=null?String(v):""}},createLayer(b){return{text:"",visible:!1,color:[0,0,0],alpha:1,pointsize:n.pointsize||24,font:n.font||"",origin:vi(n.origin||[0,0,0]),angles:[0,0,0],scale:[1,1,1]}},sortLayer:()=>{},getLayerIndex:()=>0},l=n.shared||{},d={console:rh()},f=oh(n.inputView);let h;try{h=new Function("scriptProperties","engine","thisLayer","thisScene","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","MediaPlaybackEvent","localStorage",`"use strict";
4
4
  `+r+`
5
- ;return {update: typeof update === "function" ? update : null,init: typeof init === "function" ? init : null,applyUserProperties: typeof applyUserProperties === "function" ? applyUserProperties : null,cursorClick: typeof cursorClick === "function" ? cursorClick : null,cursorEnter: typeof cursorEnter === "function" ? cursorEnter : null,cursorLeave: typeof cursorLeave === "function" ? cursorLeave : null,cursorDown: typeof cursorDown === "function" ? cursorDown : null,cursorUp: typeof cursorUp === "function" ? cursorUp : null,cursorMove: typeof cursorMove === "function" ? cursorMove : null,`+ua.map(v=>`${v}: typeof ${v} === "function" ? ${v} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,dummy_: 0};')(i,Sf(o),a,u,Cf,If,Mf,s,l,f.console,void 0,f,f,f,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Te,_f,d,Bf)}catch(b){return n.onError&&n.onError(b,"parse"),null}const p=!!(h&&ua.some(b=>h[b])),m=!!(h&&typeof h.applyUserProperties=="function"),g=!!(h&&typeof h.animationEvent=="function");if(!h||!h.update&&!p&&!m&&!g)return null;const w=(()=>{if(!h.update)return!1;const b=Function.prototype.toString.call(h.update),v=b.indexOf("{");if(v<0)return!1;const A=(/\(([^)]*)\)/.exec(b.slice(0,v))?.[1]||"").split(",").map(S=>S.trim().split(/[=\s]/)[0]).filter(Boolean);if(!A.length)return!1;let T=b.slice(v+1,b.lastIndexOf("}"));T=T.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g,'""').replace(/([A-Za-z_$][\w$]*)\s*:/g,(S,P)=>A.includes(P)?" :":S);for(const S of A)T=T.replace(new RegExp(`\\b${S}\\s*(\\+\\+|--|=(?!=)|\\+=|-=|\\*=|\\/=)`,"g")," "),T=T.replace(new RegExp(`return\\s+${S}\\s*;?`,"g")," ");return A.some(S=>new RegExp(`\\b${S}\\b`).test(T))})();h.update&&w&&(a.text="");const y={engine:o,thisLayer:a,scriptProperties:i,hasUpdate:!!h.update,hasCursorHook:!!(h.cursorClick||h.cursorEnter||h.cursorLeave||h.cursorDown||h.cursorUp||h.cursorMove),hasMediaHook:p,hasApplyHook:m,hasAnimEventHook:g,errCount:0,disabled:!1,init(b){if(h.init)try{return h.init(b)}catch(v){y.errCount++,n.onError&&n.onError(v,"init")}},applyUserProperties(b){if(h.applyUserProperties)try{h.applyUserProperties(b||{})}catch(v){y.errCount++,n.onError&&n.onError(v,"applyUserProperties")}},callUpdateRaw(b){if(!(!h.update||y.disabled))try{return h.update(b)}catch(v){y.errCount++,n.onError&&n.onError(v,"update"),y.errCount>=3&&(y.disabled=!0);return}},callUpdate(b){if(!h.update||y.disabled)return null;const v=a.text;let k;try{k=h.update(v)}catch(A){return y.errCount++,n.onError&&n.onError(A,"update"),y.errCount>=3&&(y.disabled=!0),null}return typeof k=="string"?(a.text=k,k):typeof k=="boolean"?null:k!=null?(a.text=String(k),a.text):a.text!==v?a.text:null},callCursor(b,v){if(y.disabled)return;const k=h[b];if(typeof k=="function")try{return k(v)}catch(A){y.errCount++,n.onError&&n.onError(A,b),y.errCount>=3&&(y.disabled=!0);return}},callMedia(b,v){if(y.disabled)return;const k=h[b];if(typeof k=="function")try{return k(v)}catch(A){y.errCount++,n.onError&&n.onError(A,b),y.errCount>=3&&(y.disabled=!0);return}},callAnimationEvent(b,v){if(!y.disabled&&typeof h.animationEvent=="function")try{return h.animationEvent(b,v)}catch(k){y.errCount++,n.onError&&n.onError(k,"animationEvent"),y.errCount>=3&&(y.disabled=!0);return}},updateIsWriteback:w};return y}function os(){const t={play:()=>t,pause:()=>t,stop:()=>t,setFrame:()=>t,setRate:()=>t,setBlend:()=>t,setVisible:()=>t,isPlaying:Object.assign(()=>!1,{valueOf:()=>!1,toString:()=>"false"}),get frame(){return 0},get frameCount(){return 0},get rate(){return 1}};return t}function A0(t){if(!t)return os();if(t.textureAnimation)return t.textureAnimation.api;const e={frame:null,playing:!0,rate:1},n={play:()=>(e.playing=!0,n),pause:()=>(e.playing=!1,n),stop:()=>(e.playing=!1,n),setFrame:r=>{const i=Number(r);return e.frame=Number.isFinite(i)?i:0,n},setRate:r=>{const i=Number(r);return Number.isFinite(i)&&(e.rate=i),n},setBlend:()=>n,setVisible:r=>(t.visible=!!r,n),isPlaying:Object.assign(()=>e.playing,{valueOf:()=>e.playing,toString:()=>String(e.playing)}),get frame(){return e.frame===null?0:e.frame},get frameCount(){return t.spriteFrameCount||0},get rate(){return e.rate}};return e.api=n,t.textureAnimation=e,n}function x0(t){if(t&&t.videoTextureApi)return t.videoTextureApi;const e=()=>t&&t.videoCtl||null,n={get duration(){const r=e(),i=r&&typeof r.duration=="function"?r.duration():0;return Number.isFinite(i)?i:0},get rate(){const r=e(),i=r&&typeof r.getRate=="function"?r.getRate():1;return Number.isFinite(i)&&i>0?i:1},set rate(r){const i=e(),s=Number(r);i&&typeof i.setRate=="function"&&Number.isFinite(s)&&i.setRate(s)},get loop(){const r=e();return r&&typeof r.getLoop=="function"?!!r.getLoop():!0},set loop(r){const i=e();i&&typeof i.setLoop=="function"&&i.setLoop(!!r)},play:()=>{const r=e();r&&r.play&&r.play()},pause:()=>{const r=e();r&&r.pause&&r.pause()},stop:()=>{const r=e();r&&r.stop&&r.stop()},isPlaying:Object.assign(()=>{const r=e();return!!(r&&typeof r.isPlaying=="function"&&r.isPlaying())},{valueOf(){const r=e();return!!(r&&typeof r.isPlaying=="function"&&r.isPlaying())},toString(){const r=e();return String(!!(r&&typeof r.isPlaying=="function"&&r.isPlaying()))}}),getCurrentTime:()=>{const r=e(),i=r&&typeof r.getCurrentTime=="function"?r.getCurrentTime():0;return Number.isFinite(i)?i:0},setCurrentTime:r=>{const i=e(),s=Number(r);i&&typeof i.setCurrentTime=="function"&&Number.isFinite(s)&&i.setCurrentTime(s)},addEndedCallback:r=>{const i=e();typeof r=="function"&&i&&typeof i.addEndedCallback=="function"&&i.addEndedCallback(r)}};return t&&(t.videoTextureApi=n),n}function T0(){const t=new Map,e=r=>t.has(String(r))?t.get(String(r)):null,n=(r,i)=>{t.set(String(r),String(i))};return{getItem:e,setItem:n,get:e,set:n,removeItem:r=>{t.delete(String(r))},remove:r=>{t.delete(String(r))},clear:()=>{t.clear()},key:r=>Array.from(t.keys())[r]??null,get length(){return t.size}}}function S0(t,e){const n=t&&t.puppet,r=n&&n.bones||null,i=r?r.length:0,s=t&&t.origin||[0,0,0],a=t&&t.scale||[1,1,1],o=a[0]||1,c=a[1]||1,u=(p,m)=>[s[0]+p*o,s[1]-m*c],l=(p,m)=>[(p-s[0])/o,-(m-s[1])/c],f=p=>{const m=e.get(p);if(m)return[m[0],m[1],m[2]];const g=r[p].matrix;return[g[12],g[13],g[14]]},d=p=>{let m=0,g=0,w=p;for(let y=0;w>=0&&w<i&&y<64;y++){const b=f(w);m+=b[0],g+=b[1],w=r[w].parent}return u(m,g)},h=p=>{const m={translation(g){if(g===void 0){const k=d(p);return new Te(k[0],k[1],0)}const w=fr(g);let y=0,b=0;if(r[p].parent>=0){const k=d(r[p].parent),A=l(k[0],k[1]);y=A[0],b=A[1]}const v=l(w[0],w[1]);return e.set(p,[v[0]-y,v[1]-b,0]),m},rotation(){return m},scale(){return m}};return m};return{getBoneCount:()=>i,getBoneTransform:p=>{const m=Math.floor(Number(p));if(!r||!(m>=0)||m>=i){const g={translation(w){return w===void 0?new Te(0,0,0):g},rotation(){return g},scale(){return g}};return g}return h(m)},setBoneTransform:(p,m)=>{const g=Math.floor(Number(p));!r||!(g>=0)||g>=i},applyBonePhysicsImpulse:()=>{}}}function cc(t){return{get visible(){return t?!!t.visible:!1},set visible(e){t&&(t.visible=!!e)},get name(){return t&&t.name||""},getMaterial:()=>null}}function Uf(t,e){if(t==null)return null;const n=r=>{if(!r)return null;if(e&&typeof e.getSceneLayer=="function"){const i=e.getSceneLayer(String(r));if(i)return i}return e&&e.layer&&e.layer.name===r?e.layer:null};if(typeof t=="object"){const r=Number(t.id);if(r>0&&e&&typeof e.enumerateSceneLayers=="function"){const i=e.enumerateSceneLayers();for(const s of i)if(s&&s.id===r)return s}return n(t.name)}return n(String(t))}function P0(t,e){t&&(t.visibleSelf=!1,t.visible=!1,t.destroyed=!0,e&&typeof e.recomputeVisibility=="function"&&e.recomputeVisibility())}function Of(t,e){if(typeof t!="string"||!t||/\/workshop\//.test(t))return t;const n=e!=null&&e!==""?String(e):"";if(!n)return t;const r=t.match(/^(models|materials|shaders|particles|effects)\/(.+)$/);return r?`${r[1]}/workshop/${n}/${r[2]}`:t}function _0(t){if(typeof t!="string")return null;const e=t.match(/export\s+let\s+__workshopId\s*=\s*['"](\d+)['"]/);return e?e[1]:null}function E0(t){const e=n=>da(n||null,t);return{getLayer(n){if(t.getSceneLayer){const r=t.getSceneLayer(String(n));if(r&&!r.destroyed)return e(r)}return e(null)},createLayer(n){if(typeof t.createSceneLayer!="function")return e(null);let r=n;if(typeof n=="string"){const s=typeof t.getWorkshopId=="function"?t.getWorkshopId():t.workshopId;r=Of(n,s)}const i=t.createSceneLayer(r);return e(i||null)},destroyLayer(n){P0(Uf(n,t),t)},sortLayer:()=>{},getLayerIndex(n){const r=typeof t.enumerateSceneLayers=="function"?t.enumerateSceneLayers():[],i=n&&typeof n=="object"?n.name:String(n||""),s=r.findIndex(a=>a&&a.name===i);return s<0?0:s},enumerateLayers(){const n=typeof t.enumerateSceneLayers=="function"?t.enumerateSceneLayers():[],r=[];for(const i of n)i&&!i.destroyed&&r.push(e(i));return r},getAnimation(n){if(typeof t.getSceneAnimation=="function"){const r=t.getSceneAnimation(n);if(r)return r}return os()},getCameraTransforms(){const n=t.cameraTransforms||{zoom:1};return{zoom:typeof n.zoom=="number"?n.zoom:1,center:n.center||null,eye:n.eye||null,parallaxAmount:typeof n.parallaxAmount=="number"?n.parallaxAmount:0}},setCameraTransforms(n){const r=t.cameraTransforms;!r||!n||typeof n!="object"||(typeof n.zoom=="number"&&Number.isFinite(n.zoom)&&n.zoom>0&&(r.zoom=n.zoom),n.center!==void 0&&(r.center=n.center),n.eye!==void 0&&(r.eye=n.eye),typeof n.parallaxAmount=="number"&&(r.parallaxAmount=n.parallaxAmount))},getInitialLayerConfig(n){return typeof t.getInitialLayerConfig=="function"?t.getInitialLayerConfig(n):Uf(n,t)||null}}}function da(t,e){const n=a=>cs(Array.isArray(a)?a:[0,0,0]),r=e&&typeof e.getBoneOverrides=="function"&&t?e.getBoneOverrides(t):null,i={origin:n(t?t.origin:[0,0,0]),scale:n(t?t.scale:[1,1,1]),angles:M0(t),size:n(t?t.size:[0,0,0]),color:n(t?t.color:[1,1,1])},s={get name(){return t&&t.name||""},get id(){return t&&t.id||0},get visible(){const a=e&&e.targetEffect;return a?!!a.visible:t?t.visibleSelf!==void 0?!!t.visibleSelf:!!t.visible:!1},set visible(a){const o=e&&e.targetEffect;if(o){o.visible=!!a;return}t&&(t.visibleSelf=!!a,typeof e.recomputeVisibility=="function"?e.recomputeVisibility():t.visible=!!a)},get alpha(){return t&&typeof t.alpha=="number"?t.alpha:1},set alpha(a){t&&(t.alpha=Number(a)||0)},get brightness(){return t&&typeof t.brightness=="number"?t.brightness:1},set brightness(a){t&&(t.brightness=Number(a)||0)},get text(){return t&&t.text!==void 0?String(t.text):""},set text(a){t&&typeof a!="boolean"&&(t.text=a==null?"":String(a))},get pointsize(){return t&&t.textPointsize||24},set pointsize(a){t&&(t.textPointsize=Number(a)||24)},get font(){return t&&t.textFont||""},set font(a){t&&(t.textFont=String(a||""))},get alignment(){return t&&t.alignment||"center"},set alignment(a){if(!t)return;const o=String(a||"center").toLowerCase();t.alignment=o==="centre"?"center":o},...t&&t.puppet&&r?S0(t,r):{getBoneCount:()=>0,getBoneTransform:()=>{const a={translation(o){return o===void 0?new Te(0,0,0):a},rotation(){return a},scale(){return a}};return a},setBoneTransform:()=>{},applyBonePhysicsImpulse:()=>{}},getParent:()=>{if(!t||t.parentId==null)return null;const a=e&&typeof e.getSceneLayerById=="function"?e.getSceneLayerById(t.parentId):null;return!a||a.destroyed?null:da(a,e)},getChildren:()=>{const a=t&&t.childIds||[];if(!a.length)return[];const o=e&&typeof e.getSceneLayerById=="function"?e.getSceneLayerById:null;if(!o)return[];const c=[];for(const u of a){const l=o(u);l&&!l.destroyed&&c.push(da(l,e))}return c},getAnimation:a=>{const o=t&&t.animations,c=t&&t.animationList||[];if(a==null||a===""){if(typeof e.getAnimationForProperty=="function"){const u=e.getAnimationForProperty();if(u)return u}return c[0]||os()}return o&&o[a]?o[a]:typeof a=="number"&&c[a]?c[a]:typeof a=="string"&&/^\d+$/.test(a)&&c[Number(a)]?c[Number(a)]:os()},getAnimationLayer:a=>{const o=t&&t.animations,c=t&&t.animationList||[];return o&&o[a]?o[a]:typeof a=="number"&&c[a]?c[a]:typeof a=="string"&&/^\d+$/.test(a)&&c[Number(a)]?c[Number(a)]:os()},getAnimationLayerCount:()=>(t&&t.animationList||[]).length,getTextureAnimation:()=>A0(t),play:()=>{t&&t.soundCtl&&t.soundCtl.play&&t.soundCtl.play(),t&&t.videoCtl&&t.videoCtl.play&&t.videoCtl.play()},pause:()=>{t&&t.soundCtl&&t.soundCtl.pause&&t.soundCtl.pause(),t&&t.videoCtl&&t.videoCtl.pause&&t.videoCtl.pause()},stop:()=>{t&&t.soundCtl&&t.soundCtl.stop&&t.soundCtl.stop(),t&&t.videoCtl&&t.videoCtl.stop&&t.videoCtl.stop()},isPlaying:Object.assign(()=>{const a=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),o=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return!!(a||o)},{valueOf(){const a=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),o=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return!!(a||o)},toString(){const a=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),o=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return String(!!(a||o))}}),get volume(){if(t&&t.soundCtl&&typeof t.soundCtl.getVolume=="function")return t.soundCtl.getVolume();const a=t&&t.soundprops&&t.soundprops.volume;return typeof a=="number"?a:1},set volume(a){const o=Number(a);if(!Number.isFinite(o)||!t)return;const c=Math.max(0,Math.min(1,o));t.soundprops&&(t.soundprops.volume=c),t.soundCtl&&typeof t.soundCtl.setVolume=="function"&&t.soundCtl.setVolume(c)},getVideoTexture:()=>x0(t),getTransformMatrix:()=>{const a=t&&t.origin||[0,0,0],o=new Float32Array(16);return o[0]=1,o[5]=1,o[10]=1,o[15]=1,o[12]=a[0]||0,o[13]=a[1]||0,o[14]=a[2]||0,{m:o}},getEffect:a=>{const o=t&&t.effects||null;if(!o||o.length===0)return cc(null);if(typeof a=="number"||typeof a=="string"&&/^\d+$/.test(a))return cc(o[Number(a)]||null);const c=String(a);return cc(o.find(u=>u&&u.name===c)||null)}};Object.defineProperty(s,"angles",{enumerable:!0,get(){return i.angles},set(a){if(t&&Array.isArray(t.angles)){const o=zf(a);t.angles[0]=o[0],t.angles[1]=o[1],t.angles[2]=o[2]}}});for(const a of["origin","scale","size","color"])Object.defineProperty(s,a,{enumerable:!0,get(){const o=t&&Array.isArray(t[a])?t[a]:null;return cs(o||[0,0,0])},set(o){const c=fr(o);i[a].x=c[0],i[a].y=c[1],i[a].z=c[2],t&&Array.isArray(t[a])&&a!=="size"&&(t[a][0]=c[0],t[a][1]=c[1],t[a][2]=c[2])}});return s}function C0(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=Ff(t),i={};if(e&&typeof e=="object")for(const[A,T]of Object.entries(e))Nf(i,A,T,n.userProperties);const s=new Proxy(()=>s,{apply(){return s},get(A,T){if(T==="finish")return()=>i;if(typeof T=="string"&&xf.test(T))return S=>(S&&typeof S=="object"&&typeof S.name=="string"&&!(S.name in i)&&(i[S.name]=fa(S.value)),s)}}),a={registerAsset:A=>A,frametime:1/60,runtime:0,canvasSize:Lf(n.canvasSize),screenResolution:n.screenResolution||{x:1920,y:1080},timeOfDay:typeof n.timeOfDay=="number"?n.timeOfDay:0,userProperties:n.userProperties||{},AUDIO_RESOLUTION_16:16,AUDIO_RESOLUTION_32:32,AUDIO_RESOLUTION_64:64,setTimeout:n.setTimeout||Ai,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||Ai,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:oc(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};Pf(a,n);const o=n.audioViews;a.registerAudioBuffers=A=>{const T=Df(A);let S=o?o.get(T):void 0;return S||(S={left:new Float32Array(T),right:new Float32Array(T),average:new Float32Array(T)},o&&o.set(T,S)),S};const c=n.shared||{},u={console:Tf()},l=Ef(n.inputView),f=n.layer||null,d=n.workshopId!=null?n.workshopId:_0(t),h=da(f,n),p=E0({...n,workshopId:d,getWorkshopId:()=>d});let m;try{m=new Function("scriptProperties","engine","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","thisLayer","thisScene","thisObject","localStorage","MediaPlaybackEvent",`"use strict";
5
+ ;return {update: typeof update === "function" ? update : null,init: typeof init === "function" ? init : null,applyUserProperties: typeof applyUserProperties === "function" ? applyUserProperties : null,cursorClick: typeof cursorClick === "function" ? cursorClick : null,cursorEnter: typeof cursorEnter === "function" ? cursorEnter : null,cursorLeave: typeof cursorLeave === "function" ? cursorLeave : null,cursorDown: typeof cursorDown === "function" ? cursorDown : null,cursorUp: typeof cursorUp === "function" ? cursorUp : null,cursorMove: typeof cursorMove === "function" ? cursorMove : null,`+io.map(v=>`${v}: typeof ${v} === "function" ? ${v} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,resizeScreen: typeof resizeScreen === "function" ? resizeScreen : null,dummy_: 0};')(i,ih(o),a,u,ch,lh,uh,s,l,d.console,void 0,d,d,d,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ue,ah,f,fh,n.storage||gl())}catch(b){return n.onError&&n.onError(b,"parse"),null}const p=!!(h&&io.some(b=>h[b])),m=!!(h&&typeof h.applyUserProperties=="function"),g=!!(h&&typeof h.animationEvent=="function"),y=!!(h&&typeof h.resizeScreen=="function");if(!h||!h.update&&!p&&!m&&!g&&!y)return null;const w=(()=>{if(!h.update)return!1;const b=Function.prototype.toString.call(h.update),v=b.indexOf("{");if(v<0)return!1;const P=(/\(([^)]*)\)/.exec(b.slice(0,v))?.[1]||"").split(",").map(k=>k.trim().split(/[=\s]/)[0]).filter(Boolean);if(!P.length)return!1;let S=b.slice(v+1,b.lastIndexOf("}"));S=S.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g,'""').replace(/([A-Za-z_$][\w$]*)\s*:/g,(k,_)=>P.includes(_)?" :":k);for(const k of P)S=S.replace(new RegExp(`\\b${k}\\s*(\\+\\+|--|=(?!=)|\\+=|-=|\\*=|\\/=)`,"g")," "),S=S.replace(new RegExp(`return\\s+${k}\\s*;?`,"g")," ");return P.some(k=>new RegExp(`\\b${k}\\b`).test(S))})();h.update&&w&&(a.text="");const A={engine:o,thisLayer:a,scriptProperties:i,hasUpdate:!!h.update,hasCursorHook:!!(h.cursorClick||h.cursorEnter||h.cursorLeave||h.cursorDown||h.cursorUp||h.cursorMove),hasMediaHook:p,hasApplyHook:m,hasAnimEventHook:g,hasResizeHook:y,errCount:0,disabled:!1,init(b){if(h.init)try{return h.init(b)}catch(v){A.errCount++,n.onError&&n.onError(v,"init")}},applyUserProperties(b){if(h.applyUserProperties)try{h.applyUserProperties(b||{})}catch(v){A.errCount++,n.onError&&n.onError(v,"applyUserProperties")}},callUpdateRaw(b){if(!(!h.update||A.disabled))try{return h.update(b)}catch(v){A.errCount++,n.onError&&n.onError(v,"update"),A.errCount>=3&&(A.disabled=!0);return}},callUpdate(b){if(!h.update||A.disabled)return null;const v=a.text;let x;try{x=h.update(v)}catch(P){return A.errCount++,n.onError&&n.onError(P,"update"),A.errCount>=3&&(A.disabled=!0),null}return typeof x=="string"?(a.text=x,x):typeof x=="boolean"?null:x!=null?(a.text=String(x),a.text):a.text!==v?a.text:null},callCursor(b,v){if(A.disabled)return;const x=h[b];if(typeof x=="function")try{return x(v)}catch(P){A.errCount++,n.onError&&n.onError(P,b),A.errCount>=3&&(A.disabled=!0);return}},callMedia(b,v){if(A.disabled)return;const x=h[b];if(typeof x=="function")try{return x(v)}catch(P){A.errCount++,n.onError&&n.onError(P,b),A.errCount>=3&&(A.disabled=!0);return}},callAnimationEvent(b,v){if(!A.disabled&&typeof h.animationEvent=="function")try{return h.animationEvent(b,v)}catch(x){A.errCount++,n.onError&&n.onError(x,"animationEvent"),A.errCount>=3&&(A.disabled=!0);return}},callResize(b,v){if(A.disabled||typeof h.resizeScreen!="function")return;const x=Number(b)||0,P=Number(v)||0;o.screenResolution={x,y:P};const S={x,y:P,width:x,height:P};try{const k=h.resizeScreen(S);return typeof k=="string"&&(a.text=k),k}catch(k){A.errCount++,n.onError&&n.onError(k,"resizeScreen"),A.errCount>=3&&(A.disabled=!0);return}},updateIsWriteback:w};return A}function Ks(){const t={play:()=>t,pause:()=>t,stop:()=>t,setFrame:()=>t,setRate:()=>t,setBlend:()=>t,setVisible:()=>t,isPlaying:Object.assign(()=>!1,{valueOf:()=>!1,toString:()=>"false"}),get frame(){return 0},get frameCount(){return 0},get rate(){return 1}};return t}function Hy(t){if(!t)return Ks();if(t.textureAnimation)return t.textureAnimation.api;const e={frame:null,playing:!0,rate:1},n={play:()=>(e.playing=!0,n),pause:()=>(e.playing=!1,n),stop:()=>(e.playing=!1,n),setFrame:r=>{const i=Number(r);return e.frame=Number.isFinite(i)?i:0,n},setRate:r=>{const i=Number(r);return Number.isFinite(i)&&(e.rate=i),n},setBlend:()=>n,setVisible:r=>(t.visible=!!r,n),isPlaying:Object.assign(()=>e.playing,{valueOf:()=>e.playing,toString:()=>String(e.playing)}),get frame(){return e.frame===null?0:e.frame},get frameCount(){return t.spriteFrameCount||0},get rate(){return e.rate}};return e.api=n,t.textureAnimation=e,n}function Vy(t){if(t&&t.videoTextureApi)return t.videoTextureApi;const e=()=>t&&t.videoCtl||null,n={get duration(){const r=e(),i=r&&typeof r.duration=="function"?r.duration():0;return Number.isFinite(i)?i:0},get rate(){const r=e(),i=r&&typeof r.getRate=="function"?r.getRate():1;return Number.isFinite(i)&&i>0?i:1},set rate(r){const i=e(),s=Number(r);i&&typeof i.setRate=="function"&&Number.isFinite(s)&&i.setRate(s)},get loop(){const r=e();return r&&typeof r.getLoop=="function"?!!r.getLoop():!0},set loop(r){const i=e();i&&typeof i.setLoop=="function"&&i.setLoop(!!r)},play:()=>{const r=e();r&&r.play&&r.play()},pause:()=>{const r=e();r&&r.pause&&r.pause()},stop:()=>{const r=e();r&&r.stop&&r.stop()},isPlaying:Object.assign(()=>{const r=e();return!!(r&&typeof r.isPlaying=="function"&&r.isPlaying())},{valueOf(){const r=e();return!!(r&&typeof r.isPlaying=="function"&&r.isPlaying())},toString(){const r=e();return String(!!(r&&typeof r.isPlaying=="function"&&r.isPlaying()))}}),getCurrentTime:()=>{const r=e(),i=r&&typeof r.getCurrentTime=="function"?r.getCurrentTime():0;return Number.isFinite(i)?i:0},setCurrentTime:r=>{const i=e(),s=Number(r);i&&typeof i.setCurrentTime=="function"&&Number.isFinite(s)&&i.setCurrentTime(s)},addEndedCallback:r=>{const i=e();typeof r=="function"&&i&&typeof i.addEndedCallback=="function"&&i.addEndedCallback(r)}};return t&&(t.videoTextureApi=n),n}function Wy(t,e){const n=t&&t.puppet,r=n&&n.bones||null,i=r?r.length:0,s=t&&t.origin||[0,0,0],a=t&&t.scale||[1,1,1],o=a[0]||1,c=a[1]||1,u=(p,m)=>[s[0]+p*o,s[1]-m*c],l=(p,m)=>[(p-s[0])/o,-(m-s[1])/c],d=p=>{const m=e.get(p);if(m)return[m[0],m[1],m[2]];const g=r[p].matrix;return[g[12],g[13],g[14]]},f=p=>{let m=0,g=0,y=p;for(let w=0;y>=0&&y<i&&w<64;w++){const A=d(y);m+=A[0],g+=A[1],y=r[y].parent}return u(m,g)},h=p=>{const m={translation(g){if(g===void 0){const v=f(p);return new Ue(v[0],v[1],0)}const y=xr(g);let w=0,A=0;if(r[p].parent>=0){const v=f(r[p].parent),x=l(v[0],v[1]);w=x[0],A=x[1]}const b=l(y[0],y[1]);return e.set(p,[b[0]-w,b[1]-A,0]),m},rotation(){return m},scale(){return m}};return m};return{getBoneCount:()=>i,getBoneTransform:p=>{const m=Math.floor(Number(p));if(!r||!(m>=0)||m>=i){const g={translation(y){return y===void 0?new Ue(0,0,0):g},rotation(){return g},scale(){return g}};return g}return h(m)},setBoneTransform:(p,m)=>{const g=Math.floor(Number(p));!r||!(g>=0)||g>=i},applyBonePhysicsImpulse:()=>{}}}function wl(t){return{get visible(){return t?!!t.visible:!1},set visible(e){t&&(t.visible=!!e)},get name(){return t&&t.name||""},getMaterial:()=>null}}function yh(t,e){if(t==null)return null;const n=r=>{if(!r)return null;if(e&&typeof e.getSceneLayer=="function"){const i=e.getSceneLayer(String(r));if(i)return i}return e&&e.layer&&e.layer.name===r?e.layer:null};if(typeof t=="object"){const r=Number(t.id);if(r>0&&e&&typeof e.enumerateSceneLayers=="function"){const i=e.enumerateSceneLayers();for(const s of i)if(s&&s.id===r)return s}return n(t.name)}return n(String(t))}function jy(t,e){t&&(t.visibleSelf=!1,t.visible=!1,t.destroyed=!0,e&&typeof e.recomputeVisibility=="function"&&e.recomputeVisibility())}function bh(t,e){if(typeof t!="string"||!t||/\/workshop\//.test(t))return t;const n=e!=null&&e!==""?String(e):"";if(!n)return t;const r=t.match(/^(models|materials|shaders|particles|effects)\/(.+)$/);return r?`${r[1]}/workshop/${n}/${r[2]}`:t}function qy(t){if(typeof t!="string")return null;const e=t.match(/export\s+let\s+__workshopId\s*=\s*['"](\d+)['"]/);return e?e[1]:null}function Xy(t){const e=n=>ao(n||null,t);return{getLayer(n){if(t.getSceneLayer){const r=t.getSceneLayer(String(n));if(r&&!r.destroyed)return e(r)}return e(null)},createLayer(n){if(typeof t.createSceneLayer!="function")return e(null);let r=n;if(typeof n=="string"){const s=typeof t.getWorkshopId=="function"?t.getWorkshopId():t.workshopId;r=bh(n,s)}const i=t.createSceneLayer(r);return e(i||null)},destroyLayer(n){jy(yh(n,t),t)},sortLayer:()=>{},getLayerIndex(n){const r=typeof t.enumerateSceneLayers=="function"?t.enumerateSceneLayers():[],i=n&&typeof n=="object"?n.name:String(n||""),s=r.findIndex(a=>a&&a.name===i);return s<0?0:s},enumerateLayers(){const n=typeof t.enumerateSceneLayers=="function"?t.enumerateSceneLayers():[],r=[];for(const i of n)i&&!i.destroyed&&r.push(e(i));return r},getAnimation(n){if(typeof t.getSceneAnimation=="function"){const r=t.getSceneAnimation(n);if(r)return r}return Ks()},getCameraTransforms(){const n=t.cameraTransforms||{zoom:1};return{zoom:typeof n.zoom=="number"?n.zoom:1,center:n.center||null,eye:n.eye||null,parallaxAmount:typeof n.parallaxAmount=="number"?n.parallaxAmount:0}},setCameraTransforms(n){const r=t.cameraTransforms;!r||!n||typeof n!="object"||(typeof n.zoom=="number"&&Number.isFinite(n.zoom)&&n.zoom>0&&(r.zoom=n.zoom),n.center!==void 0&&(r.center=n.center),n.eye!==void 0&&(r.eye=n.eye),typeof n.parallaxAmount=="number"&&(r.parallaxAmount=n.parallaxAmount))},getInitialLayerConfig(n){return typeof t.getInitialLayerConfig=="function"?t.getInitialLayerConfig(n):yh(n,t)||null}}}function ao(t,e){const n=o=>vi(Array.isArray(o)?o:[0,0,0]),r=e&&typeof e.getBoneOverrides=="function"&&t?e.getBoneOverrides(t):null,i={origin:n(t?t.origin:[0,0,0]),scale:n(t?t.scale:[1,1,1]),angles:Qy(t,e),size:n(t?t.size:[0,0,0]),color:n(t?t.color:[1,1,1])},s={get name(){return t&&t.name||""},get id(){return t&&t.id||0},get originalOrigin(){const o=t&&(t.originalOrigin||t.localOrigin)||[0,0,0];return vi(o)},get visible(){const o=e&&e.targetEffect;return o?!!o.visible:t?t.visibleSelf!==void 0?!!t.visibleSelf:!!t.visible:!1},set visible(o){const c=e&&e.targetEffect;if(c){c.visible=!!o;return}t&&(t.visibleSelf=!!o,typeof e.recomputeVisibility=="function"?e.recomputeVisibility():t.visible=!!o)},get alpha(){return t&&typeof t.alpha=="number"?t.alpha:1},set alpha(o){t&&(t.alpha=Number(o)||0)},get perspective(){return!!(t&&t.perspective)},set perspective(o){t&&(t.perspective=!!o)},get brightness(){return t&&typeof t.brightness=="number"?t.brightness:1},set brightness(o){t&&(t.brightness=Number(o)||0)},get text(){return t&&t.text!==void 0?String(t.text):""},set text(o){t&&typeof o!="boolean"&&(t.text=o==null?"":String(o))},get pointsize(){return t&&t.textPointsize||24},set pointsize(o){t&&(t.textPointsize=Number(o)||24)},get font(){return t&&t.textFont||""},set font(o){t&&(t.textFont=String(o||""))},get alignment(){return t&&t.alignment||"center"},set alignment(o){if(!t)return;const c=String(o||"center").toLowerCase();t.alignment=c==="centre"?"center":c},...t&&t.puppet&&r?Wy(t,r):{getBoneCount:()=>0,getBoneTransform:()=>{const o={translation(c){return c===void 0?new Ue(0,0,0):o},rotation(){return o},scale(){return o}};return o},setBoneTransform:()=>{},applyBonePhysicsImpulse:()=>{}},getParent:()=>{if(!t||t.parentId==null)return null;const o=e&&typeof e.getSceneLayerById=="function"?e.getSceneLayerById(t.parentId):null;return!o||o.destroyed?null:ao(o,e)},getChildren:()=>{const o=t&&t.childIds||[];if(!o.length)return[];const c=e&&typeof e.getSceneLayerById=="function"?e.getSceneLayerById:null;if(!c)return[];const u=[];for(const l of o){const d=c(l);d&&!d.destroyed&&u.push(ao(d,e))}return u},getAnimation:o=>{const c=t&&t.animations,u=t&&t.animationList||[];if(o==null||o===""){if(typeof e.getAnimationForProperty=="function"){const l=e.getAnimationForProperty();if(l)return l}return u[0]||Ks()}return c&&c[o]?c[o]:typeof o=="number"&&u[o]?u[o]:typeof o=="string"&&/^\d+$/.test(o)&&u[Number(o)]?u[Number(o)]:Ks()},getAnimationLayer:o=>{const c=t&&t.animationLayers||[];let u=null;if(typeof o=="number"?u=c[o]||null:typeof o=="string"&&/^\d+$/.test(o)?u=c[Number(o)]||null:typeof o=="string"&&(u=c.find(f=>f&&f.name===o)||null),u)return{play:()=>u.play?.(),pause:()=>u.pause?.(),stop:()=>u.stop?.(),isPlaying:()=>u.playing!==!1&&!u.paused,get visible(){return u.visible!==!1},set visible(f){u.visible=!!f},get rate(){return u.rate??1},set rate(f){u.rate=Number(f)||1},get name(){return u.name||""}};const l=t&&t.animations,d=t&&t.animationList||[];return l&&l[o]?l[o]:typeof o=="number"&&d[o]?d[o]:typeof o=="string"&&/^\d+$/.test(o)&&d[Number(o)]?d[Number(o)]:Ks()},getAnimationLayerCount:()=>(t&&t.animationLayers||[]).length||(t&&t.animationList||[]).length,getTextureAnimation:()=>Hy(t),play:()=>{t&&t.soundCtl&&t.soundCtl.play&&t.soundCtl.play(),t&&t.videoCtl&&t.videoCtl.play&&t.videoCtl.play()},pause:()=>{t&&t.soundCtl&&t.soundCtl.pause&&t.soundCtl.pause(),t&&t.videoCtl&&t.videoCtl.pause&&t.videoCtl.pause()},stop:()=>{t&&t.soundCtl&&t.soundCtl.stop&&t.soundCtl.stop(),t&&t.videoCtl&&t.videoCtl.stop&&t.videoCtl.stop()},isPlaying:Object.assign(()=>{const o=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),c=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return!!(o||c)},{valueOf(){const o=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),c=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return!!(o||c)},toString(){const o=t&&t.soundCtl&&typeof t.soundCtl.isPlaying=="function"&&t.soundCtl.isPlaying(),c=t&&t.videoCtl&&typeof t.videoCtl.isPlaying=="function"&&t.videoCtl.isPlaying();return String(!!(o||c))}}),get volume(){if(t&&t.soundCtl&&typeof t.soundCtl.getVolume=="function")return t.soundCtl.getVolume();const o=t&&t.soundprops&&t.soundprops.volume;return typeof o=="number"?o:1},set volume(o){const c=Number(o);if(!Number.isFinite(c)||!t)return;const u=Math.max(0,Math.min(1,c));t.soundprops&&(t.soundprops.volume=u),t.soundCtl&&typeof t.soundCtl.setVolume=="function"&&t.soundCtl.setVolume(u)},getVideoTexture:()=>Vy(t),getTransformMatrix:()=>{const o=t&&t.origin||[0,0,0],c=new Float32Array(16);return c[0]=1,c[5]=1,c[10]=1,c[15]=1,c[12]=o[0]||0,c[13]=o[1]||0,c[14]=o[2]||0,{m:c}},getEffect:o=>{const c=t&&t.effects||null;if(!c||c.length===0)return wl(null);if(typeof o=="number"||typeof o=="string"&&/^\d+$/.test(o))return wl(c[Number(o)]||null);const u=String(o);return wl(c.find(l=>l&&l.name===u)||null)},getMaterial(o){const c=t&&Array.isArray(t.effects)?t.effects:null;let u=null;if(c){const l=[];for(const f of c)for(const h of f.materialPasses||[])l.push(h);const d=l[Number(o)];d&&(d.constantshadervalues=d.constantshadervalues||{},u=d.constantshadervalues)}return u||(u=t&&t.__dummyMaterialBags?.[Number(o)]||null),u||(u={},t&&((t.__dummyMaterialBags||={})[Number(o)]=u)),u}};Object.defineProperty(s,"angles",{enumerable:!0,get(){return i.angles},set(o){if(t&&Array.isArray(t.angles)){const c=wh(o);Array.isArray(t.localAngles)&&(t.localAngles[0]=c[0],t.localAngles[1]=c[1],t.localAngles[2]=c[2]),t.parentId===void 0||t.parentId===null?(t.angles[0]=c[0],t.angles[1]=c[1],t.angles[2]=c[2]):e&&typeof e.markTransformDirty=="function"&&e.markTransformDirty(t)}}});const a={origin:"localOrigin",scale:"localScale"};for(const o of["origin","scale","size","color"])Object.defineProperty(s,o,{enumerable:!0,get(){const c=a[o],u=o==="scale"?[1,1,1]:[0,0,0],l=t&&c&&Array.isArray(t[c])?t[c]:t&&Array.isArray(t[o])?t[o]:null;return vi(l||u)},set(c){const u=xr(c);i[o].x=u[0],i[o].y=u[1],i[o].z=u[2];const l=a[o];if(t)if(l){Array.isArray(t[l])&&(t[l][0]=u[0],t[l][1]=u[1],t[l][2]=u[2]);const d=t.parentId===void 0||t.parentId===null;d&&Array.isArray(t[o])?(t[o][0]=u[0],t[o][1]=u[1],t[o][2]=u[2]):!d&&typeof e.markTransformDirty=="function"&&e.markTransformDirty(t)}else Array.isArray(t[o])&&o!=="size"&&(t[o][0]=u[0],t[o][1]=u[1],t[o][2]=u[2])}});return s}function $y(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=hh(t),i={};if(e&&typeof e=="object")for(const[S,k]of Object.entries(e))ph(i,S,k,n.userProperties);const s=new Proxy(()=>s,{apply(){return s},get(S,k){if(k==="finish")return()=>i;if(typeof k=="string"&&nh.test(k))return _=>(_&&typeof _=="object"&&typeof _.name=="string"&&!(_.name in i)&&(i[_.name]=so(_.value)),s)}}),a={registerAsset:S=>S,frametime:1/60,runtime:0,canvasSize:gh(n.canvasSize),screenResolution:n.screenResolution||{x:1920,y:1080},timeOfDay:typeof n.timeOfDay=="number"?n.timeOfDay:0,userProperties:n.userProperties||{},AUDIO_RESOLUTION_16:16,AUDIO_RESOLUTION_32:32,AUDIO_RESOLUTION_64:64,setTimeout:n.setTimeout||us,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||us,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:bl(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};sh(a,n);const o=n.audioViews;a.registerAudioBuffers=S=>{const k=mh(S);let _=o?o.get(k):void 0;return _||(_={left:new Float32Array(k),right:new Float32Array(k),average:new Float32Array(k)},o&&o.set(k,_)),_};const c=n.shared||{},u={console:rh()},l=oh(n.inputView),d=n.layer||null,f=n.workshopId!=null?n.workshopId:qy(t),h=ao(d,n),p=Xy({...n,workshopId:f,getWorkshopId:()=>f});let m;try{m=new Function("scriptProperties","engine","WEMath","WEColor","WEVector","createScriptProperties","shared","console","process","globalThis","self","window","document","require","module","exports","fetch","XMLHttpRequest","Worker","importScripts","location","navigator","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","performance","Function","Vec3","Vec2","input","thisLayer","thisScene","thisObject","localStorage","MediaPlaybackEvent",`"use strict";
6
6
  `+r+`
7
- ;return {update: typeof update === "function" ? update : null,init: typeof init === "function" ? init : null,applyUserProperties: typeof applyUserProperties === "function" ? applyUserProperties : null,cursorClick: typeof cursorClick === "function" ? cursorClick : null,cursorEnter: typeof cursorEnter === "function" ? cursorEnter : null,cursorLeave: typeof cursorLeave === "function" ? cursorLeave : null,cursorDown: typeof cursorDown === "function" ? cursorDown : null,cursorUp: typeof cursorUp === "function" ? cursorUp : null,cursorMove: typeof cursorMove === "function" ? cursorMove : null,`+ua.map(T=>`${T}: typeof ${T} === "function" ? ${T} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,dummy_: 0};')(i,Sf(a),Cf,If,Mf,s,c,u.console,void 0,u,u,u,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Te,_f,l,h,p,h,T0(),Bf)}catch(A){return n.onError&&n.onError(A,"parse"),null}const g=!!(m&&(m.cursorClick||m.cursorEnter||m.cursorLeave||m.cursorDown||m.cursorUp||m.cursorMove)),w=!!(m&&ua.some(A=>m[A])),y=!!(m&&typeof m.applyUserProperties=="function"),b=/\bengine\s*\.\s*(runtime|frametime)\b/.test(r),v=!!(m&&typeof m.animationEvent=="function");if(!m||!m.update&&!g&&!w&&!y&&!b&&!v)return null;const k={engine:a,scriptProperties:i,hasUpdate:!!m.update,hasCursorHook:g,hasApplyHook:y,errCount:0,disabled:!1,init(A){if(m.init)try{return m.init(ac(A))}catch(T){k.errCount++,n.onError&&n.onError(T,"init")}},applyUserProperties(A){if(m.applyUserProperties)try{m.applyUserProperties(A||{})}catch(T){k.errCount++,n.onError&&n.onError(T,"applyUserProperties")}},callUpdate(A){if(k.disabled||!m.update)return;let T;try{T=m.update(ac(A))}catch(S){k.errCount++,n.onError&&n.onError(S,"update"),k.errCount>=3&&(k.disabled=!0);return}return T},hasCursorHook:g,callCursor(A,T){if(k.disabled)return;const S=m[A];if(typeof S=="function")try{return S(T)}catch(P){k.errCount++,n.onError&&n.onError(P,A),k.errCount>=3&&(k.disabled=!0);return}},hasMediaHook:w,callMedia(A,T){if(k.disabled)return;const S=m[A];if(typeof S=="function")try{return S(T)}catch(P){k.errCount++,n.onError&&n.onError(P,A),k.errCount>=3&&(k.disabled=!0);return}},hasMediaHook:w,hasAnimEventHook:v,callAnimationEvent(A,T){if(!k.disabled&&typeof m.animationEvent=="function")try{return m.animationEvent(A,ac(T))}catch(S){k.errCount++,n.onError&&n.onError(S,"animationEvent"),k.errCount>=3&&(k.disabled=!0);return}}};return k}function cs(t){const e=Array.isArray(t)?t:[0,0,0],n={x:e[0]||0,y:e[1]||0,z:e[2]||0},r={get x(){return n.x},set x(i){n.x=Number(i)||0},get y(){return n.y},set y(i){n.y=Number(i)||0},get z(){return n.z},set z(i){n.z=Number(i)||0},add(i){const s=fr(i);return n.x+=s[0],n.y+=s[1],n.z+=s[2],r},subtract(i){const s=fr(i);return cs([n.x-s[0],n.y-s[1],n.z-s[2]])},multiply(i){if(i&&typeof i=="object"){const s=fr(i);n.x*=s[0],n.y*=s[1],n.z*=s[2]}else{const s=Number(i)||0;n.x*=s,n.y*=s,n.z*=s}return r},copy(){return new Te(n.x,n.y,n.z)},length(){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)},lengthSqr(){return n.x*n.x+n.y*n.y+n.z*n.z},toArray(){return[n.x,n.y,n.z]}};return r}function fr(t){if(Array.isArray(t))return[t[0]||0,t[1]||0,t[2]||0];if(t&&typeof t=="object")return[t.x||0,t.y||0,t.z||0];const e=Number(t)||0;return[e,e,e]}const ha=Math.PI/180,ma=180/Math.PI;function I0(t){const e=Array.isArray(t)?t:[0,0,0];return{x:(e[0]||0)*ma,y:(e[1]||0)*ma,z:(e[2]||0)*ma}}function zf(t){const e=fr(t);return[e[0]*ha,e[1]*ha,e[2]*ha]}function M0(t){const e={x:0,y:1,z:2},n={add(r){const i=fr(r);return n.x+=i[0],n.y+=i[1],n.z+=i[2],n},subtract(r){const i=fr(r);return n.x-=i[0],n.y-=i[1],n.z-=i[2],n},multiply(r){return n.x*=r,n.y*=r,n.z*=r,n},toArray(){return[n.x,n.y,n.z]}};for(const r of["x","y","z"])Object.defineProperty(n,r,{enumerable:!0,get(){return!t||!Array.isArray(t.angles)?0:(t.angles[e[r]]||0)*ma},set(i){!t||!Array.isArray(t.angles)||(t.angles[e[r]]=(Number(i)||0)*ha)}});return n}function B0(t,e){return Math.min(256,Math.ceil(Math.max(1,Number(t)||1)*2+8))}function R0(t){for(const e of t&&t.effects?t.effects:[]){if(e&&e.visible===!1)continue;if(String(e&&(e.file||e.name)||"").includes("tint"))return!0;for(const r of e&&e.passes||[])for(const i of r&&r.textures||[])if(i&&String(i).toLowerCase().includes("mask"))return!0}return!1}const F0=Object.freeze(Object.defineProperty({__proto__:null,Vec3:Te,createInputView:g0,drawTextLayer:m0,effectiveTextPadding:u0,evalObjectScript:C0,evalTextScript:k0,foldVisibleReturn:v0,inkOverflow:Af,layoutText:f0,makeCursorEventVec:p0,radToScriptAngles:I0,resolveWorkshopAssetPath:Of,rewriteComboStringEq:Rf,scriptAnglesToRad:zf,shouldGrowMediaPlaceholder:h0,textCanvasMargin:B0,textCanvasMarginGrow:d0,textLayerHasTintMask:R0},Symbol.toStringTag,{value:"Module"}));function Hf(t){if(t instanceof Te)return t;if(Array.isArray(t))return new Te(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0);const e=String(t??"").trim().split(/\s+/).map(Number);return new Te(e[0]||0,e[1]||0,e[2]||0)}function Vf(t,e){if(!t||typeof e!="string")return null;const n=t[e];return n&&typeof n=="object"?n:null}function lc(t){return typeof t=="string"?t:t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}function D0(t,e){return pa(t)&&pa(e)?Number(t)===Number(e):String(t)===String(e)}function uc(t){if(typeof t=="boolean")return"bool";if(typeof t=="number")return Number.isFinite(t)?"num":"other";if(typeof t=="string"){const e=t.trim().split(/\s+/);return e.length>0&&e[0]!==""&&e.every(n=>Number.isFinite(Number(n)))?"num":"text"}return"other"}function N0(t){switch(t.type){case"bool":return"bool";case"slider":return"num";case"color":return"num";case"textinput":return"text";default:return uc(t.value)}}function Wf(t,e){if(t===null||typeof t!="object")return t;if(t.user&&typeof t.user=="object"&&typeof t.user.name=="string"){const r=Vf(e,t.user.name);if(!r||r.value===void 0||r.value===null)return t.value;const i=r.type==="combo"?fc(r.value,r.options):r.value;return D0(i,t.user.condition)}if(typeof t.user!="string")return t;const n=Vf(e,t.user);if(!n||n.value===void 0||n.value===null)return t.value;if(n.userOverridden)return n.value;if(t.value!==null&&typeof t.value=="object")return t.value;if(t.value===void 0)return n.value;if(uc(t.value)==="bool"&&n.type==="slider"){const r=Number(n.value);return Number.isFinite(r)?r!==0:t.value}return uc(t.value)===N0(n)?n.value:t.value}function Hr(t,e,n){if(n>32||t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let r=0;r<t.length;r++)t[r]=Hr(t[r],e,n+1);return t}if(lc(t.user)){let r=Wf(t,e);for(let i=0;i<8&&r!==null&&typeof r=="object"&&lc(r.user);i++)r=Wf(r,e);return t.value=Hr(r,e,n+1),t}for(const r of Object.keys(t))t[r]=Hr(t[r],e,n+1);return t}function L0(t){return t?Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"value"in e?e.value:e):typeof t=="object"?Object.values(t):[]:[]}function pa(t){return typeof t=="number"?Number.isInteger(t):typeof t=="string"&&/^-?\d+$/.test(t.trim())}function fc(t,e){const n=L0(e);return!(n.length>0?n.every(pa):pa(t))||typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&/^-?\d+$/.test(t.trim())?Number(t):t}function U0(t){const e={};if(!t||typeof t!="object")return e;for(const[n,r]of Object.entries(t))!r||typeof r!="object"||!("value"in r)||(e[n]=r.type==="combo"?fc(r.value,r.options):r.type==="color"?Hf(r.value):r.value);return e}function Tn(t){return t&&typeof t=="object"?lc(t.user):null}function O0(t,e,n){const r={};if(!n||typeof n!="object")return r;const i=t&&typeof t=="object"?t:{},s=e&&typeof e=="object"?e:{};for(const[a,o]of Object.entries(n)){const c=o&&typeof o=="object"&&"value"in o?o.value:o,u=i[a];if(u&&typeof u=="object"){u.value=c,u.userOverridden=!0;const l=u.type==="combo"?fc(u.value,u.options):u.value,f=u.type==="color"?Hf(l):l;s[a]=f,r[a]=f}else s[a]=c,r[a]=c}return r}function xi(t){typeof t=="object"&&t!==null&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return e.length===1?[e[0]||0,e[0]||0,e[0]||0]:[e[0]||0,e[1]||0,e[2]||0]}function ls(t){typeof t=="object"&&t!==null&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return e.length===1?[e[0]||0,e[0]||0]:[e[0]||0,e[1]||0]}function ga(t){return t==null?[1,1,1]:typeof t=="string"?xi(t):typeof t=="object"&&t!==null?xi(t.value):[1,1,1]}function jt(t,e=!1){if(t==null)return e;if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="object"&&t!==null){const n=t.value;return typeof n=="number"?n!==0:!!n}return e}function Kt(t,e){if(typeof t=="number")return t;if(t!==null&&typeof t=="object"){const n=Number(t.value);return Number.isFinite(n)?n:e}return e}function dc(t){return t?!t.image&&!t.model&&!t.particle&&t.text==null&&!t.size:!1}function hc(t,e,n){const r=n?t.scale:[1,1,1],i=(t.angles[2]||0)*Math.PI/180,s=Math.cos(i),a=Math.sin(i),o=e.origin[0]*r[0],c=e.origin[1]*r[1];return{origin:[t.origin[0]+o*s-c*a,t.origin[1]+o*a+c*s,t.origin[2]+(e.origin[2]||0)],scale:[r[0]*e.scale[0],r[1]*e.scale[1],r[2]*e.scale[2]],angles:[e.angles[0],e.angles[1],(t.angles[2]||0)+e.angles[2]]}}function z0(t,e){const n=e&&e.general&&e.general.properties||{},r=t.objects||[];Hr(r,n,0),Hr(t.general||{},n,0);const i=new Map;for(const g of r)g.id!==void 0&&i.set(g.id,g);const s=r.map(g=>({id:g.id,parent:g.parent,origin:xi(g.origin||"0 0 0"),scale:xi(g.scale||"1 1 1"),angles:xi(g.angles||"0 0 0")})),a=s.map(g=>({origin:g.origin.slice(),scale:g.scale.slice(),angles:g.angles.slice()}));for(let g=0;g<8;g++){let w=!1;for(const y of s){if(y.parent===void 0||y.parent===null||!i.get(y.parent))continue;const v=s.findIndex(B=>B.id===y.parent);if(v<0)continue;const k=s[v];if(k.parent!==void 0&&k.parent!==null)continue;const A=r[v],T=A.scale,P=!(T!==null&&typeof T=="object"&&(typeof T.script=="string"||T.user!==void 0)&&dc(A)),M=hc(k,y,P);y.origin=M.origin,y.scale=M.scale,y.angles=M.angles,y.parent=null,w=!0}if(!w)break}const o=r.map(g=>jt(g.visible,!0)),c=new Map;r.forEach((g,w)=>{g.id!==void 0&&c.set(g.id,w)});const u=new Map,l=new Map;for(const g of r)if(g.parent!==void 0&&g.parent!==null){u.set(g.parent,(u.get(g.parent)||0)+1);const w=g.id!==void 0?g.id:null;if(w!==null){const y=l.get(g.parent);y?y.push(w):l.set(g.parent,[w])}}const f=r.map(()=>!0);for(let g=0;g<r.length;g++){let w=o[g],y=r[g].parent;for(let b=0;w&&y!==void 0&&y!==null&&b<64;b++){const v=c.get(y);if(v===void 0)break;o[v]||(w=!1),y=r[v].parent}f[g]=w}const d=r.map((g,w)=>{const y=s[w],b=typeof g.image=="string"&&(g.image.indexOf("models/util/projectlayer")===0||g.image.indexOf("models/util/fullscreenlayer")===0);let v=ls(g.size||"0 0"),k=y.origin;if(b){const A=(t.general||{}).orthogonalprojection,T=A&&Number(A.width),S=A&&Number(A.height);T>0&&S>0&&(v=[T,S],k=[T/2,S/2,y.origin[2]||0])}return{id:g.id!==void 0?g.id:w,name:g.name||"",visible:f[w],visibleSelf:o[w],srcObject:g,image:typeof g.image=="string"?g.image:null,model:typeof g.model=="string"?g.model:null,isSkybox:typeof g.name=="string"&&g.name.indexOf("\u5929\u7A7A\u76D2")>=0,particle:typeof g.particle=="string"?g.particle:null,instanceoverride:g.instanceoverride||null,particleOverrideAnimations:(()=>{const A=g.instanceoverride;if(!A||typeof A!="object")return null;const T={};for(const[S,P]of Object.entries(A))P&&typeof P=="object"&&P.animation&&typeof P.animation=="object"&&P.animation.options&&(T[S]={animation:P.animation,value:P.value});return Object.keys(T).length?T:null})(),sound:Array.isArray(g.sound)?g.sound.filter(A=>typeof A=="string"):[],soundprops:{volume:Kt(g.volume,1),playbackmode:g.playbackmode||"single",startsilent:jt(g.startsilent,!1),maxtime:Kt(g.maxtime,0),mintime:Kt(g.mintime,0),spatialization:jt(g.spatialization,!1),muteineditor:jt(g.muteineditor,!1)},text:typeof g.text=="string"?g.text:g.text&&typeof g.text=="object"?g.text.value:null,textScript:g.text&&typeof g.text=="object"&&g.text.script||null,textScriptProps:g.text&&typeof g.text=="object"&&g.text.scriptproperties||null,component:typeof g.component=="string"?g.component:null,isText:g.text!==void 0&&g.text!==null,textFont:typeof g.font=="string"?g.font:null,textPointsize:Kt(g.pointsize,24)||24,textColor:ga(g.color),textAnchor:typeof g.anchor=="string"&&g.anchor!=="none"?g.anchor:"center",textMaxwidth:Kt(g.maxwidth,0),textMaxrows:Kt(g.maxrows,0),textLimitwidth:jt(g.limitwidth,!1),textLimitrows:jt(g.limitrows,!1),textLimituseellipsis:jt(g.limituseellipsis,!1),textHAlign:g.horizontalalign||"center",textVAlign:g.verticalalign||"center",textSpacing:g.spacing?ls(g.spacing):[0,0],textPadding:(()=>{const A=g.padding;if(typeof A=="number")return A;const T=String(A??"").trim().split(/\s+/).map(Number).filter(S=>Number.isFinite(S));return T.length?T.reduce((S,P)=>S+P,0)/T.length:0})(),textOpaquebackground:jt(g.opaquebackground,!1),textBackgroundcolor:ga(g.backgroundcolor),textBackgroundbrightness:Kt(g.backgroundbrightness,1),textCastshadow:jt(g.castshadow,!1),isSound:!!(g.sound&&g.sound.length),isComponent:!!g.component,objectScripts:(()=>{const A={};for(const T of["scale","origin","color","alpha","brightness","angles","visible"]){const S=g[T];S&&typeof S=="object"&&typeof S.script=="string"&&S.script&&(A[T]={script:S.script,scriptproperties:S.scriptproperties||null,value:S.value})}return Object.keys(A).length?A:null})(),objectAnimations:(()=>{const A={};for(const T of["scale","origin","color","alpha","brightness","angles","visible","volume","maxwidth","zoom"]){const S=g[T];S&&typeof S=="object"&&S.animation&&typeof S.animation=="object"&&S.animation.options&&(A[T]={animation:S.animation,value:S.value})}return Object.keys(A).length?A:null})(),animationLayers:(g.animationlayers||[]).filter(A=>A&&typeof A.animation=="number").map(A=>({animation:A.animation,visible:jt(A.visible,!0),additive:jt(A.additive,!1),blend:Kt(A.blend,1),rate:Kt(A.rate,1)})),solid:(()=>{if(typeof g.particle=="string")return!1;const A=typeof g.image=="string"?g.image:"";return A.indexOf("models/util/composelayer")===0?!1:A.indexOf("models/util/solidlayer")===0?!0:g.solid?!A||A.indexOf("models/util/")===0:!1})(),isContainer:typeof g.image=="string"&&g.image.indexOf("models/util/composelayer")===0,hasChildren:(u.get(g.id!==void 0?g.id:w)||0)>0,childIds:l.get(g.id!==void 0?g.id:w)||null,parentId:g.parent!==void 0&&g.parent!==null?g.parent:null,attachment:typeof g.attachment=="string"&&g.attachment!==""?g.attachment:null,passthrough:!!(g.config&&g.config.passthrough===!0),isPostProcess:b,origin:k,scale:y.scale,angles:y.angles,localOrigin:a[w].origin,localScale:a[w].scale,localAngles:a[w].angles,renderInert:dc(g),scaleRuntimeBound:g.scale!==null&&typeof g.scale=="object"&&(typeof g.scale.script=="string"||g.scale.user!==void 0),size:v,alignment:g.alignment||"center",color:ga(g.color),alpha:Kt(g.alpha,1),brightness:Kt(g.brightness,1),copybackground:!!g.copybackground,colorBlendMode:g.colorBlendMode||0,parallaxDepth:g.parallaxDepth!==void 0?ls(g.parallaxDepth):null,effects:(g.effects||[]).map(A=>({file:A.file||"",name:typeof A.name=="string"?A.name:"",visible:jt(A.visible,!0),visibleScript:A.visible&&typeof A.visible=="object"&&typeof A.visible.script=="string"&&A.visible.script?{script:A.visible.script,scriptproperties:A.visible.scriptproperties||null,value:!!A.visible.value}:null,passes:(A.passes||[]).map(T=>{const S=T.textures||[],P=T.usertextures;let M=S;if(Array.isArray(P))for(let B=0;B<P.length;B++){const N=P[B],O=N&&typeof N=="object"&&typeof N.name=="string"?N.name:typeof N=="string"?N:null;O&&(M===S&&(M=S.slice()),M[B]=O)}return{combos:T.combos||{},constantshadervalues:T.constantshadervalues||{},textures:M}})}))}}),h=t.general||{},p=(()=>{const g={};for(const[w,y]of Object.entries(h))y&&typeof y=="object"&&typeof y.script=="string"&&y.script&&(g[w]={script:y.script,scriptproperties:y.scriptproperties||null,value:y.value});return Object.keys(g).length?g:null})(),m=(()=>{const g={};for(const[w,y]of Object.entries(h))y&&typeof y=="object"&&y.animation&&typeof y.animation=="object"&&y.animation.options&&(g[w]={animation:y.animation,value:y.value});return Object.keys(g).length?g:null})();{const g=new Map;for(const w of d)w.id!==void 0&&g.set(w.id,w);for(let w=0;w<8;w++){let y=!1;for(const b of d){if(b.parallaxDepth||b.parentId==null)continue;const v=g.get(b.parentId);!v||!v.parallaxDepth||v.image||v.particle||v.model||(b.parallaxDepth=v.parallaxDepth.slice(),y=!0)}if(!y)break}}return{camera:t.camera||null,general:h,generalScripts:p,generalAnimations:m,layers:d,properties:n}}function H0(t){if(!Array.isArray(t))return;const e=new Map;for(const n of t)n&&n.id!==void 0&&n.id!==null&&e.set(n.id,n);for(const n of t){if(!n)continue;if(n.destroyed){n.visible=!1;continue}let r=n.visibleSelf!==!1,i=n.parentId;for(let s=0;r&&i!=null&&s<64;s++){const a=e.get(i);if(!a)break;(a.visibleSelf===!1||a.destroyed)&&(r=!1),i=a.parentId}n.visible=r}}function V0(t,e){!t||!e||typeof e!="object"||t.isContainer||e.solidlayer===!0&&(t.solid=!0)}function W0(t){return!t||typeof t.material!="string"?null:{materialPath:t.material,autosize:!!t.autosize,cropoffset:t.cropoffset?ls(t.cropoffset):null}}function j0(t,e){if(!t||t.length===0)return;const n=new Map;for(const s of t)s&&s.id!==void 0&&s.id!==null&&n.set(s.id,s);const r=s=>{let a=0,o=s.parentId;for(let c=0;o!=null&&c<64;c++){const u=n.get(o);if(!u)break;a++,o=u.parentId}return a},i=[];for(const s of t)!s||!s.localOrigin||s.isPostProcess||e&&!e.has(s.id)||i.push(s);i.sort((s,a)=>r(s)-r(a));for(const s of i){const a=s.parentId!==void 0&&s.parentId!==null?n.get(s.parentId):null;let o;if(!a)o={origin:s.localOrigin.slice(),scale:s.localScale.slice(),angles:s.localAngles.slice()};else{const u=!(a.scaleRuntimeBound&&a.renderInert);o=hc({origin:a.origin,scale:a.scale,angles:a.angles},{origin:s.localOrigin,scale:s.localScale,angles:s.localAngles},u)}const c=s.attachBindDelta;c&&(o.origin[0]+=c[0],o.origin[1]+=c[1]),s.origin[0]=o.origin[0],s.origin[1]=o.origin[1],s.origin[2]=o.origin[2],s.scale[0]=o.scale[0],s.scale[1]=o.scale[1],s.scale[2]=o.scale[2],s.angles[0]=o.angles[0],s.angles[1]=o.angles[1],s.angles[2]=o.angles[2],s.attachBase&&(s.attachBase[0]=o.origin[0],s.attachBase[1]=o.origin[1])}}function q0(t,e){const n=new Set;if(!t||t.length===0)return n;const r=new Map;for(const o of t){if(!o||o.parentId===void 0||o.parentId===null)continue;const c=r.get(o.parentId);c?c.push(o):r.set(o.parentId,[o])}const i=["origin","scale","angles"],s=[];for(const o of t){if(!o||o.id===void 0||o.id===null)continue;const c=o.objectScripts||null,u=o.objectAnimations||null;i.some(f=>c&&c[f]||u&&u[f])&&s.push(o)}if(e)for(const o of e)o&&o.id!==void 0&&o.id!==null&&s.push(o);const a=s.slice();for(let o=0;a.length>0&&o<1e5;o++){const c=a.pop();if(!c||c.id===void 0||c.id===null||n.has(c.id))continue;n.add(c.id);const u=r.get(c.id);if(u)for(const l of u)a.push(l)}return n}const X0=Object.freeze(Object.defineProperty({__proto__:null,applySolidFromModel:V0,collectTransformDirty:q0,composeChildTransform:hc,isRenderInert:dc,parseBool:jt,parseColor:ga,parseNum:Kt,parseScene:z0,parseVec2:ls,parseVec3:xi,recomposeWorld:j0,recomputeLayerVisibility:H0,resolveMaterial:W0},Symbol.toStringTag,{value:"Module"}));function G0(t,e,n){const r=nc(t,e.file);if(r===null)return;let i;try{i=JSON.parse(n(r))}catch{return}e.fbos=i.fbos||[],e.materialPasses=(i.passes||[]).map(s=>{if(!s.material)return{shader:null,copyCommand:!0,target:s.target||null,source:s.source||null,binds:s.bind||[],blending:"normal",textures:[],combos:{},constants:{}};const a=nc(t,s.material);if(a===null)return{shader:null,copyCommand:!1,target:s.target||null,binds:s.bind||[],blending:"normal",textures:[],combos:{},constants:{}};const o=JSON.parse(n(a)),c=o.passes&&o.passes[0]||{};return{shader:c.shader||null,copyCommand:!1,target:s.target||null,binds:s.bind||[],blending:c.blending||"normal",textures:c.textures||[],combos:c.combos||{},constants:c.constantshadervalues||{}}})}const $0={"models/util/solidlayer.json":{material:"materials/util/solidlayer.json"},"models/util/composelayer.json":{material:"materials/util/solidlayer.json"},"models/util/fullscreenlayer.json":{material:"materials/util/solidlayer.json"},"models/util/projectlayer.json":{material:"materials/util/solidlayer.json"}};function jf(t){if(!t||typeof t!="string")return!0;const e=t.toLowerCase();return e==="generic"||e==="sprite"||e==="flat"||e.startsWith("genericimage")}function Q0(t,e){return!t||!e||!e.shader||jf(e.shader)||(t.effects=t.effects||[],t.effects.some(n=>n.layerMaterial))?!1:(t.effects.unshift({file:"",name:"_layerMaterial",visible:!0,layerMaterial:!0,passes:[{combos:e.combos||{},constantshadervalues:e.constantshadervalues||{},textures:e.textures||[]}],materialPasses:[{shader:e.shader,copyCommand:!1,target:null,binds:[],blending:e.blending||"normal",textures:e.textures||[],combos:e.combos||{},constants:e.constantshadervalues||{}}],fbos:[]}),!0)}const Y0={"materials/util/solidlayer.json":{passes:[{shader:"flat",blending:"translucent",cullmode:"nocull",depthtest:"disabled",depthwrite:"disabled",textures:[],combos:{}}]}},K0=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_MATERIALS:Y0,BUILTIN_MODELS:$0,attachLayerMaterialEffect:Q0,isBuiltinAlbedoShader:jf,resolveEffectChain:G0},Symbol.toStringTag,{value:"Module"}));function Z0(t){const e=new Map,n=new Map,r=/^[ \t]*#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]*)\))?[ \t]*(.*)$/gm;let i;for(;(i=r.exec(t))!==null;){const s=a=>a.replace(/\/\/.*$/,"").replace(/\/\*[\s\S]*?\*\//g,"").trim();i[2]!==void 0?n.set(i[1],{args:i[2].split(",").map(a=>a.trim()).filter(Boolean),body:s(i[3])}):e.set(i[1],s(i[3]))}return{defs:e,fns:n}}function J0(t,e,n,r){const i=[];let s=0;for(;s<t.length;){const a=t.indexOf(e,s);if(a===-1){i.push(t.slice(s));break}i.push(t.slice(s,a));let c=a+e.length;for(;c<t.length&&/\s/.test(t[c]);)c++;if(t[c]!=="("){i.push(t.slice(a,c)),s=c;continue}let u=0,l=c;for(;l<t.length;l++)if(t[l]==="(")u++;else if(t[l]===")"&&(u--,u===0))break;if(l>=t.length){i.push(t.slice(a));break}const f=t.slice(c+1,l),d=Gn(f);let h=n.body;n.args.forEach((p,m)=>{const g=d[m]!==void 0?d[m].trim():"";h=us(h,p,g)}),r>0&&(h=qf(h,r-1)),i.push("("+h+")"),s=l+1}return i.join("")}function us(t,e,n){return t.replace(new RegExp("\\b"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","g"),n)}function Gn(t){const e=[];let n=0,r="";for(let i=0;i<t.length;i++){const s=t[i];s==="("?n++:s===")"&&n--,s===","&&n===0?(e.push(r),r=""):r+=s}return r.trim()!==""&&e.push(r),e}function qf(t,e){for(let n=0;n<12;n++){const{defs:r,fns:i}=Z0(t);if(r.size===0&&i.size===0)break;const s=t.split(`
8
- `),a=new Map;for(let u=0;u<s.length;u++){const l=/^[ \t]*#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)/.exec(s[u]);l&&!a.has(l[1])&&a.set(l[1],u)}const o=new Map;{const u="(?:float|int|bool|vec[234]|ivec[234]|bvec[234]|mat[234])";for(const l of r.keys()){const f=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp("^\\s*(?:const\\s+|uniform\\s+|varying\\s+|in\\s+|out\\s+|attribute\\s+)*"+u+"\\s+"+f+"\\s*[=;]");for(let h=0;h<s.length;h++)if(d.test(s[h])){o.set(l,h);break}}}let c=!1;for(let u=0;u<s.length;u++){const l=s[u];if(/^[ \t]*#/.test(l))continue;let f=l;for(const[d,h]of r){const p=a.get(d);if(p!==void 0&&u<p||o.get(d)===u)continue;new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b").test(f)&&(f=us(f,d,h),c=!0)}for(const[d,h]of i){const p=a.get(d);p!==void 0&&u<p||f.includes(d)&&(f=J0(f,d,h,e),c=!0)}s[u]=f}if(t=s.join(`
9
- `),!c)break}return t}function Xf(t,e,n){const r=h=>e[h]!==void 0?String(e[h]):n.has(h)?"("+n.get(h)+")":"0";let i=t.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g,h=>r(h)),s=0;function a(){for(;s<i.length&&/\s/.test(i[s]);)s++}function o(){let h=c();for(a();i.startsWith("||",s);){s+=2;const p=c();h=h||p,a()}return h}function c(){let h=u();for(a();i.startsWith("&&",s);){s+=2;const p=u();h=h&&p,a()}return h}function u(){let h=l();for(a();i.startsWith("==",s)||i.startsWith("!=",s);){const p=i[s]==="="?"==":"!=";s+=2;const m=l();h=p==="=="?h===m:h!==m,a()}return h}function l(){let h=f();for(a();/^[<>]/.test(i[s]||"");){let p=i[s];i[s+1]==="="&&(p+="=",s++),s++;const m=f();p==="<"?h=h<m:p===">"?h=h>m:p==="<="?h=h<=m:h=h>=m,a()}return h}function f(){return a(),i[s]==="!"?(s++,!f()):d()}function d(){if(a(),i[s]==="("){s++;const p=o();return a(),s++,p}const h=/^-?\d+(\.\d+)?/.exec(i.slice(s));return h?(s+=h[0].length,Number(h[0])):!1}return o()}function Gf(t){let e="",n=0;const r=t.length;for(;n<r;){const i=t[n],s=t[n+1];if(i==="/"&&s==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)t[n]===`
7
+ ;return {update: typeof update === "function" ? update : null,init: typeof init === "function" ? init : null,applyUserProperties: typeof applyUserProperties === "function" ? applyUserProperties : null,cursorClick: typeof cursorClick === "function" ? cursorClick : null,cursorEnter: typeof cursorEnter === "function" ? cursorEnter : null,cursorLeave: typeof cursorLeave === "function" ? cursorLeave : null,cursorDown: typeof cursorDown === "function" ? cursorDown : null,cursorUp: typeof cursorUp === "function" ? cursorUp : null,cursorMove: typeof cursorMove === "function" ? cursorMove : null,`+io.map(k=>`${k}: typeof ${k} === "function" ? ${k} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,resizeScreen: typeof resizeScreen === "function" ? resizeScreen : null,dummy_: 0};')(i,ih(a),ch,lh,uh,s,c,u.console,void 0,u,u,u,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ue,ah,l,h,p,h,n.storage||gl(),fh)}catch(S){return n.onError&&n.onError(S,"parse"),null}const g=!!(m&&(m.cursorClick||m.cursorEnter||m.cursorLeave||m.cursorDown||m.cursorUp||m.cursorMove)),y=!!(m&&io.some(S=>m[S])),w=!!(m&&typeof m.applyUserProperties=="function"),A=/\bengine\s*\.\s*(runtime|frametime)\b/.test(r),b=!!(m&&typeof m.animationEvent=="function"),v=!!(m&&typeof m.resizeScreen=="function"),x=!!(m&&typeof m.init=="function");if(!m||!m.update&&!g&&!y&&!w&&!A&&!b&&!v&&!x)return null;const P={engine:a,scriptProperties:i,hasUpdate:!!m.update,hasCursorHook:g,hasApplyHook:w,errCount:0,disabled:!1,init(S){if(m.init)try{return m.init(yl(S))}catch(k){P.errCount++,n.onError&&n.onError(k,"init")}},applyUserProperties(S){if(m.applyUserProperties)try{m.applyUserProperties(S||{})}catch(k){P.errCount++,n.onError&&n.onError(k,"applyUserProperties")}},callUpdate(S){if(P.disabled||!m.update)return;let k;try{k=m.update(yl(S))}catch(_){P.errCount++,n.onError&&n.onError(_,"update"),P.errCount>=3&&(P.disabled=!0);return}return k},hasCursorHook:g,callCursor(S,k){if(P.disabled)return;const _=m[S];if(typeof _=="function")try{return _(k)}catch(I){P.errCount++,n.onError&&n.onError(I,S),P.errCount>=3&&(P.disabled=!0);return}},hasMediaHook:y,callMedia(S,k){if(P.disabled)return;const _=m[S];if(typeof _=="function")try{return _(k)}catch(I){P.errCount++,n.onError&&n.onError(I,S),P.errCount>=3&&(P.disabled=!0);return}},hasMediaHook:y,hasAnimEventHook:b,callAnimationEvent(S,k){if(!P.disabled&&typeof m.animationEvent=="function")try{return m.animationEvent(S,yl(k))}catch(_){P.errCount++,n.onError&&n.onError(_,"animationEvent"),P.errCount>=3&&(P.disabled=!0);return}},hasResizeHook:v,callResize(S,k){if(P.disabled||typeof m.resizeScreen!="function")return;const _=Number(S)||0,I=Number(k)||0;a.screenResolution={x:_,y:I};const B={x:_,y:I,width:_,height:I};try{return m.resizeScreen(B)}catch(V){P.errCount++,n.onError&&n.onError(V,"resizeScreen"),P.errCount>=3&&(P.disabled=!0);return}}};return P}function vi(t){const e=Array.isArray(t)?t:[0,0,0],n={x:e[0]||0,y:e[1]||0,z:e[2]||0},r={get x(){return n.x},set x(i){n.x=Number(i)||0},get y(){return n.y},set y(i){n.y=Number(i)||0},get z(){return n.z},set z(i){n.z=Number(i)||0},add(i){const s=xr(i);return n.x+=s[0],n.y+=s[1],n.z+=s[2],r},subtract(i){const s=xr(i);return vi([n.x-s[0],n.y-s[1],n.z-s[2]])},divide(i){const s=xr(i),a=(o,c)=>c===0?0:o/c;return vi([a(n.x,s[0]),a(n.y,s[1]),a(n.z,s[2])])},multiply(i){if(i&&typeof i=="object"){const s=xr(i);n.x*=s[0],n.y*=s[1],n.z*=s[2]}else{const s=Number(i)||0;n.x*=s,n.y*=s,n.z*=s}return r},copy(){return new Ue(n.x,n.y,n.z)},length(){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)},lengthSqr(){return n.x*n.x+n.y*n.y+n.z*n.z},toArray(){return[n.x,n.y,n.z]}};return r}function xr(t){if(Array.isArray(t))return[t[0]||0,t[1]||0,t[2]||0];if(t&&typeof t=="object")return[t.x||0,t.y||0,t.z||0];const e=Number(t)||0;return[e,e,e]}const oo=Math.PI/180,co=180/Math.PI;function Gy(t){const e=Array.isArray(t)?t:[0,0,0];return{x:(e[0]||0)*co,y:(e[1]||0)*co,z:(e[2]||0)*co}}function wh(t){const e=xr(t);return[e[0]*oo,e[1]*oo,e[2]*oo]}function Qy(t,e){const n={x:0,y:1,z:2},r=(s,a)=>{if(!t||!Array.isArray(t.angles))return;Array.isArray(t.localAngles)&&(t.localAngles[s]=a),t.parentId===void 0||t.parentId===null?t.angles[s]=a:e&&typeof e.markTransformDirty=="function"&&e.markTransformDirty(t)},i={add(s){const a=xr(s);return i.x+=a[0],i.y+=a[1],i.z+=a[2],i},subtract(s){const a=xr(s);return i.x-=a[0],i.y-=a[1],i.z-=a[2],i},multiply(s){return i.x*=s,i.y*=s,i.z*=s,i},toArray(){return[i.x,i.y,i.z]}};for(const s of["x","y","z"])Object.defineProperty(i,s,{enumerable:!0,get(){const a=t&&Array.isArray(t.localAngles)?t.localAngles:t&&Array.isArray(t.angles)?t.angles:null;return a?(a[n[s]]||0)*co:0},set(a){r(n[s],(Number(a)||0)*oo)}});return i}function Yy(t,e){return Math.min(256,Math.ceil(Math.max(1,Number(t)||1)*2+8))}function Ky(t){for(const e of t&&t.effects?t.effects:[]){if(e&&e.visible===!1)continue;if(String(e&&(e.file||e.name)||"").includes("tint"))return!0;for(const r of e&&e.passes||[])for(const i of r&&r.textures||[])if(i&&String(i).toLowerCase().includes("mask"))return!0}return!1}const Zy=Object.freeze(Object.defineProperty({__proto__:null,LOCATION_GLOBAL:pl,LOCATION_SCREEN:Xr,Vec3:Ue,createInputView:Dy,drawTextLayer:By,effectiveTextPadding:My,evalObjectScript:$y,evalTextScript:zy,foldVisibleReturn:Oy,inkOverflow:th,layoutText:Cy,makeCursorEventVec:Fy,makeSandboxStorage:gl,radToScriptAngles:Gy,resolveWorkshopAssetPath:bh,rewriteComboStringEq:dh,scriptAnglesToRad:wh,shouldGrowMediaPlaceholder:Ry,textCanvasMargin:Yy,textCanvasMarginGrow:Iy,textLayerHasTintMask:Ky},Symbol.toStringTag,{value:"Module"}));function vh(t){if(t instanceof Ue)return t;if(Array.isArray(t))return new Ue(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0);const e=String(t??"").trim().split(/\s+/).map(Number);return new Ue(e[0]||0,e[1]||0,e[2]||0)}function Ah(t,e){if(!t||typeof e!="string")return null;const n=t[e];return n&&typeof n=="object"?n:null}function vl(t){return typeof t=="string"?t:t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}function Jy(t,e){return lo(t)&&lo(e)?Number(t)===Number(e):String(t)===String(e)}function Al(t){if(typeof t=="boolean")return"bool";if(typeof t=="number")return Number.isFinite(t)?"num":"other";if(typeof t=="string"){const e=t.trim().split(/\s+/);return e.length>0&&e[0]!==""&&e.every(n=>Number.isFinite(Number(n)))?"num":"text"}return"other"}function eb(t){switch(t.type){case"bool":return"bool";case"slider":return"num";case"color":return"num";case"textinput":return"text";default:return Al(t.value)}}function xh(t,e){if(t===null||typeof t!="object")return t;if(t.user&&typeof t.user=="object"&&typeof t.user.name=="string"){const r=Ah(e,t.user.name);if(!r||r.value===void 0||r.value===null)return t.value;const i=r.type==="combo"?xl(r.value,r.options):r.value;return Jy(i,t.user.condition)}if(typeof t.user!="string")return t;const n=Ah(e,t.user);if(!n||n.value===void 0||n.value===null)return t.value;if(n.userOverridden)return n.value;if(t.value!==null&&typeof t.value=="object")return t.value;if(t.value===void 0)return n.value;if(Al(t.value)==="bool"&&n.type==="slider"){const r=Number(n.value);return Number.isFinite(r)?r!==0:t.value}return Al(t.value)===eb(n)?n.value:t.value}function Ai(t,e,n){if(n>32||t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let r=0;r<t.length;r++)t[r]=Ai(t[r],e,n+1);return t}if(vl(t.user)){let r=xh(t,e);for(let i=0;i<8&&r!==null&&typeof r=="object"&&vl(r.user);i++)r=xh(r,e);return t.value=Ai(r,e,n+1),t}for(const r of Object.keys(t))t[r]=Ai(t[r],e,n+1);return t}function tb(t){return t?Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"value"in e?e.value:e):typeof t=="object"?Object.values(t):[]:[]}function lo(t){return typeof t=="number"?Number.isInteger(t):typeof t=="string"&&/^-?\d+$/.test(t.trim())}function xl(t,e){const n=tb(e);return!(n.length>0?n.every(lo):lo(t))||typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&/^-?\d+$/.test(t.trim())?Number(t):t}function nb(t){const e={};if(!t||typeof t!="object")return e;for(const[n,r]of Object.entries(t))!r||typeof r!="object"||!("value"in r)||(e[n]=r.type==="combo"?xl(r.value,r.options):r.type==="color"?vh(r.value):r.value);return e}function Qn(t){return t&&typeof t=="object"?vl(t.user):null}function rb(t,e,n){const r={};if(!n||typeof n!="object")return r;const i=t&&typeof t=="object"?t:{},s=e&&typeof e=="object"?e:{};for(const[a,o]of Object.entries(n)){const c=o&&typeof o=="object"&&"value"in o?o.value:o,u=i[a];if(u&&typeof u=="object"){u.value=c,u.userOverridden=!0;const l=u.type==="combo"?xl(u.value,u.options):u.value,d=u.type==="color"?vh(l):l;s[a]=d,r[a]=d}else s[a]=c,r[a]=c}return r}function fs(t){typeof t=="object"&&t!==null&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return e.length===1?[e[0]||0,e[0]||0,e[0]||0]:[e[0]||0,e[1]||0,e[2]||0]}function ds(t){typeof t=="object"&&t!==null&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return e.length===1?[e[0]||0,e[0]||0]:[e[0]||0,e[1]||0]}function uo(t){return t==null?[1,1,1]:typeof t=="string"?fs(t):typeof t=="object"&&t!==null?fs(t.value):[1,1,1]}function fn(t,e=!1){if(t==null)return e;if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="object"&&t!==null){const n=t.value;return typeof n=="number"?n!==0:!!n}return e}function vn(t,e){if(typeof t=="number")return t;if(t!==null&&typeof t=="object"){const n=Number(t.value);return Number.isFinite(n)?n:e}return e}function kh(t){return t?!t.image&&!t.model&&!t.particle&&t.text==null&&!t.size:!1}function kl(t,e,n){const r=n?t.scale:[1,1,1],i=t.angles[2]||0,s=Math.cos(i),a=Math.sin(i),o=e.origin[0]*r[0],c=e.origin[1]*r[1];return{origin:[t.origin[0]+o*s-c*a,t.origin[1]+o*a+c*s,t.origin[2]+(e.origin[2]||0)],scale:[r[0]*e.scale[0],r[1]*e.scale[1],r[2]*e.scale[2]],angles:[e.angles[0],e.angles[1],(t.angles[2]||0)+e.angles[2]]}}function ib(t,e){const n=e&&e.general&&e.general.properties||{},r=t.objects||[];Ai(r,n,0),Ai(t.general||{},n,0);const i=new Map;for(const g of r)g.id!==void 0&&i.set(g.id,g);const s=r.map(g=>({id:g.id,parent:g.parent,origin:fs(g.origin||"0 0 0"),scale:fs(g.scale||"1 1 1"),angles:fs(g.angles||"0 0 0")})),a=s.map(g=>({origin:g.origin.slice(),scale:g.scale.slice(),angles:g.angles.slice()}));for(let g=0;g<8;g++){let y=!1;for(const w of s){if(w.parent===void 0||w.parent===null||!i.get(w.parent))continue;const b=s.findIndex(P=>P.id===w.parent);if(b<0)continue;const v=s[b];if(v.parent!==void 0&&v.parent!==null)continue;const x=kl(v,w,!0);w.origin=x.origin,w.scale=x.scale,w.angles=x.angles,w.parent=null,y=!0}if(!y)break}const o=r.map(g=>fn(g.visible,!0)),c=new Map;r.forEach((g,y)=>{g.id!==void 0&&c.set(g.id,y)});const u=new Map,l=new Map;for(const g of r)if(g.parent!==void 0&&g.parent!==null){u.set(g.parent,(u.get(g.parent)||0)+1);const y=g.id!==void 0?g.id:null;if(y!==null){const w=l.get(g.parent);w?w.push(y):l.set(g.parent,[y])}}const d=r.map(()=>!0);for(let g=0;g<r.length;g++){let y=o[g],w=r[g].parent;for(let A=0;y&&w!==void 0&&w!==null&&A<64;A++){const b=c.get(w);if(b===void 0)break;o[b]||(y=!1),w=r[b].parent}d[g]=y}const f=r.map((g,y)=>{const w=s[y],A=typeof g.image=="string"&&(g.image.indexOf("models/util/projectlayer")===0||g.image.indexOf("models/util/fullscreenlayer")===0);let b=ds(g.size||"0 0"),v=w.origin;if(A){const x=(t.general||{}).orthogonalprojection,P=x&&Number(x.width),S=x&&Number(x.height);P>0&&S>0&&(b=[P,S],v=[P/2,S/2,w.origin[2]||0])}return{id:g.id!==void 0?g.id:y,name:g.name||"",visible:d[y],visibleSelf:o[y],srcObject:g,image:typeof g.image=="string"?g.image:null,model:typeof g.model=="string"?g.model:null,isSkybox:typeof g.name=="string"&&g.name.indexOf("\u5929\u7A7A\u76D2")>=0,particle:typeof g.particle=="string"?g.particle:null,instanceoverride:g.instanceoverride||null,particleOverrideAnimations:(()=>{const x=g.instanceoverride;if(!x||typeof x!="object")return null;const P={};for(const[S,k]of Object.entries(x))k&&typeof k=="object"&&k.animation&&typeof k.animation=="object"&&k.animation.options&&(P[S]={animation:k.animation,value:k.value});return Object.keys(P).length?P:null})(),particleOverrideScripts:(()=>{const x=g.instanceoverride;if(!x||typeof x!="object")return null;const P={};for(const[S,k]of Object.entries(x))k&&typeof k=="object"&&typeof k.script=="string"&&k.script&&(P[S]={script:k.script,scriptproperties:k.scriptproperties||null,value:k.value});return Object.keys(P).length?P:null})(),sound:Array.isArray(g.sound)?g.sound.filter(x=>typeof x=="string"):[],soundprops:{volume:vn(g.volume,1),playbackmode:g.playbackmode||"single",startsilent:fn(g.startsilent,!1),maxtime:vn(g.maxtime,0),mintime:vn(g.mintime,0),spatialization:fn(g.spatialization,!1),muteineditor:fn(g.muteineditor,!1)},text:typeof g.text=="string"?g.text:g.text&&typeof g.text=="object"?g.text.value:null,textScript:g.text&&typeof g.text=="object"&&g.text.script||null,textScriptProps:g.text&&typeof g.text=="object"&&g.text.scriptproperties||null,component:typeof g.component=="string"?g.component:null,isText:g.text!==void 0&&g.text!==null,textFont:typeof g.font=="string"?g.font:null,textPointsize:vn(g.pointsize,24)||24,textColor:uo(g.color),textAnchor:typeof g.anchor=="string"&&g.anchor!=="none"?g.anchor:"center",textMaxwidth:vn(g.maxwidth,0),textMaxrows:vn(g.maxrows,0),textLimitwidth:fn(g.limitwidth,!1),textLimitrows:fn(g.limitrows,!1),textLimituseellipsis:fn(g.limituseellipsis,!1),textHAlign:g.horizontalalign||"center",textVAlign:g.verticalalign||"center",textSpacing:g.spacing?ds(g.spacing):[0,0],textPadding:(()=>{const x=g.padding;if(typeof x=="number")return x;const P=String(x??"").trim().split(/\s+/).map(Number).filter(S=>Number.isFinite(S));return P.length?P.reduce((S,k)=>S+k,0)/P.length:0})(),textOpaquebackground:fn(g.opaquebackground,!1),textBackgroundcolor:uo(g.backgroundcolor),textBackgroundbrightness:vn(g.backgroundbrightness,1),textCastshadow:fn(g.castshadow,!1),isSound:!!(g.sound&&g.sound.length),isComponent:!!g.component,objectScripts:(()=>{const x={};for(const P of["scale","origin","color","alpha","brightness","angles","visible","maxwidth","pointsize","volume","intensity","exponent"]){const S=g[P];S&&typeof S=="object"&&typeof S.script=="string"&&S.script&&(x[P]={script:S.script,scriptproperties:S.scriptproperties||null,value:S.value})}return Object.keys(x).length?x:null})(),objectAnimations:(()=>{const x={};for(const P of["scale","origin","color","alpha","brightness","angles","visible","volume","maxwidth","zoom"]){const S=g[P];S&&typeof S=="object"&&S.animation&&typeof S.animation=="object"&&S.animation.options&&(x[P]={animation:S.animation,value:S.value})}return Object.keys(x).length?x:null})(),animationLayers:(g.animationlayers||[]).filter(x=>x&&typeof x.animation=="number").map(x=>({animation:x.animation,name:typeof x.name=="string"?x.name:"",visibleScript:x.visible&&typeof x.visible=="object"&&typeof x.visible.script=="string"&&x.visible.script?{script:x.visible.script,scriptproperties:x.visible.scriptproperties||null,value:x.visible.value}:null,visible:fn(x.visible,!0),additive:fn(x.additive,!1),blend:vn(x.blend,1),rate:vn(x.rate,1),playing:!0,paused:!1,play(){this.playing=!0,this.paused=!1},pause(){this.paused=!0},stop(){this.playing=!1,this.paused=!1}})),solid:(()=>{if(typeof g.particle=="string")return!1;const x=typeof g.image=="string"?g.image:"";return x.indexOf("models/util/composelayer")===0?!1:x.indexOf("models/util/solidlayer")===0?!0:g.solid?!x||x.indexOf("models/util/")===0:!1})(),isContainer:typeof g.image=="string"&&g.image.indexOf("models/util/composelayer")===0,hasChildren:(u.get(g.id!==void 0?g.id:y)||0)>0,childIds:l.get(g.id!==void 0?g.id:y)||null,parentId:g.parent!==void 0&&g.parent!==null?g.parent:null,attachment:typeof g.attachment=="string"&&g.attachment!==""?g.attachment:null,passthrough:!!(g.config&&g.config.passthrough===!0),isPostProcess:A,origin:v,scale:w.scale,angles:w.angles,localOrigin:a[y].origin,localScale:a[y].scale,localAngles:a[y].angles,originalOrigin:a[y].origin.slice(),renderInert:kh(g),scaleRuntimeBound:g.scale!==null&&typeof g.scale=="object"&&(typeof g.scale.script=="string"||g.scale.user!==void 0),size:b,alignment:g.alignment||"center",color:uo(g.color),alpha:vn(g.alpha,1),brightness:vn(g.brightness,1),copybackground:!!g.copybackground,colorBlendMode:g.colorBlendMode||0,perspective:g.perspective===!0?!0:void 0,parallaxDepth:g.parallaxDepth!==void 0?ds(g.parallaxDepth):null,parallaxDepthOwn:g.parallaxDepth!==void 0?ds(g.parallaxDepth):null,disablePropagation:g.disablepropagation===!0,effects:(g.effects||[]).map(x=>({file:x.file||"",name:typeof x.name=="string"?x.name:"",visible:fn(x.visible,!0),visibleScript:x.visible&&typeof x.visible=="object"&&typeof x.visible.script=="string"&&x.visible.script?{script:x.visible.script,scriptproperties:x.visible.scriptproperties||null,value:!!x.visible.value}:null,passes:(x.passes||[]).map(P=>{const S=P.textures||[],k=P.usertextures;let _=S,I=null;if(Array.isArray(k))for(let B=0;B<k.length;B++){const V=k[B],O=V&&typeof V=="object"&&typeof V.name=="string"?V.name:typeof V=="string"?V:null;O&&(_===S&&(_=S.slice()),S[B]!==void 0&&S[B]!==null&&S[B]!==O&&(I||(I=[]),I[B]=S[B]),_[B]=O)}return{combos:P.combos||{},constantshadervalues:P.constantshadervalues||{},textures:_,textureFallbacks:I}})}))}}),h=t.general||{},p=(()=>{const g={};for(const[y,w]of Object.entries(h))w&&typeof w=="object"&&typeof w.script=="string"&&w.script&&(g[y]={script:w.script,scriptproperties:w.scriptproperties||null,value:w.value});return Object.keys(g).length?g:null})(),m=(()=>{const g={};for(const[y,w]of Object.entries(h))w&&typeof w=="object"&&w.animation&&typeof w.animation=="object"&&w.animation.options&&(g[y]={animation:w.animation,value:w.value});return Object.keys(g).length?g:null})();{const g=new Map;for(const y of f)y.id!==void 0&&g.set(y.id,y);for(let y=0;y<8;y++){let w=!1;for(const A of f){if(A.parallaxDepth||A.parentId==null)continue;const b=g.get(A.parentId);!b||!b.parallaxDepth||b.image||b.particle||b.model||(A.parallaxDepth=b.parallaxDepth.slice(),w=!0)}if(!w)break}}{const g=new Map;for(const y of f)y.id!==void 0&&g.set(y.id,y);for(const y of f){let w=y;for(let b=y.parentId!=null?g.get(y.parentId):null;b&&b.disablePropagation!==!0;b=b.parentId!=null?g.get(b.parentId):null)w=b;y.parallaxNodeId=w===y?null:w.id,y.parallaxAnchor=[w.origin?w.origin[0]:0,w.origin?w.origin[1]:0];const A=w.parallaxDepthOwn;y.parallaxDepthProp=A?A.slice():[0,0]}}return{camera:t.camera||null,general:h,generalScripts:p,generalAnimations:m,layers:f,properties:n}}function sb(t){if(!Array.isArray(t))return;const e=new Map;for(const n of t)n&&n.id!==void 0&&n.id!==null&&e.set(n.id,n);for(const n of t){if(!n)continue;if(n.destroyed){n.visible=!1;continue}let r=n.visibleSelf!==!1,i=n.parentId;for(let s=0;r&&i!=null&&s<64;s++){const a=e.get(i);if(!a)break;(a.visibleSelf===!1||a.destroyed)&&(r=!1),i=a.parentId}n.visible=r}}function ab(t,e){!t||!e||typeof e!="object"||t.isContainer||e.solidlayer===!0&&(t.solid=!0)}function ob(t){return!t||typeof t.material!="string"?null:{materialPath:t.material,autosize:!!t.autosize,cropoffset:t.cropoffset?ds(t.cropoffset):null}}function cb(t,e){if(!t||t.length===0)return;const n=new Map;for(const s of t)s&&s.id!==void 0&&s.id!==null&&n.set(s.id,s);const r=s=>{let a=0,o=s.parentId;for(let c=0;o!=null&&c<64;c++){const u=n.get(o);if(!u)break;a++,o=u.parentId}return a},i=[];for(const s of t)!s||!s.localOrigin||s.isPostProcess||e&&!e.has(s.id)||i.push(s);i.sort((s,a)=>r(s)-r(a));for(const s of i){const a=s.parentId!==void 0&&s.parentId!==null?n.get(s.parentId):null;let o;a?o=kl({origin:a.origin,scale:a.scale,angles:a.angles},{origin:s.localOrigin,scale:s.localScale,angles:s.localAngles},!0):o={origin:s.localOrigin.slice(),scale:s.localScale.slice(),angles:s.localAngles.slice()};const c=s.attachBindDelta;c&&(o.origin[0]+=c[0],o.origin[1]+=c[1]),s.origin[0]=o.origin[0],s.origin[1]=o.origin[1],s.origin[2]=o.origin[2],s.scale[0]=o.scale[0],s.scale[1]=o.scale[1],s.scale[2]=o.scale[2],s.angles[0]=o.angles[0],s.angles[1]=o.angles[1],s.angles[2]=o.angles[2],s.attachBase&&(s.attachBase[0]=o.origin[0],s.attachBase[1]=o.origin[1])}if(n.size)for(const s of t){if(s.parallaxNodeId==null||e&&!e.has(s.parallaxNodeId))continue;const a=n.get(s.parallaxNodeId);a&&s.parallaxAnchor&&(s.parallaxAnchor[0]=a.origin[0],s.parallaxAnchor[1]=a.origin[1])}}function lb(t,e){const n=new Set;if(!t||t.length===0)return n;const r=new Map;for(const o of t){if(!o||o.parentId===void 0||o.parentId===null)continue;const c=r.get(o.parentId);c?c.push(o):r.set(o.parentId,[o])}const i=["origin","scale","angles"],s=[];for(const o of t){if(!o||o.id===void 0||o.id===null)continue;const c=o.objectScripts||null,u=o.objectAnimations||null;i.some(d=>c&&c[d]||u&&u[d])&&s.push(o)}if(e)for(const o of e)o&&o.id!==void 0&&o.id!==null&&s.push(o);const a=s.slice();for(let o=0;a.length>0&&o<1e5;o++){const c=a.pop();if(!c||c.id===void 0||c.id===null||n.has(c.id))continue;n.add(c.id);const u=r.get(c.id);if(u)for(const l of u)a.push(l)}return n}const ub=Object.freeze(Object.defineProperty({__proto__:null,applySolidFromModel:ab,collectTransformDirty:lb,composeChildTransform:kl,isRenderInert:kh,parseBool:fn,parseColor:uo,parseNum:vn,parseScene:ib,parseVec2:ds,parseVec3:fs,recomposeWorld:cb,recomputeLayerVisibility:sb,resolveMaterial:ob},Symbol.toStringTag,{value:"Module"}));function fb(t,e,n){const r=dl(t,e.file);if(r===null)return;let i;try{i=JSON.parse(n(r))}catch{return}e.fbos=i.fbos||[],e.materialPasses=(i.passes||[]).map(s=>{if(!s.material)return{shader:null,copyCommand:!0,target:s.target||null,source:s.source||null,binds:s.bind||[],blending:"normal",textures:[],combos:{},constants:{}};const a=dl(t,s.material);if(a===null)return{shader:null,copyCommand:!1,target:s.target||null,binds:s.bind||[],blending:"normal",textures:[],combos:{},constants:{}};const o=JSON.parse(n(a)),c=o.passes&&o.passes[0]||{};return{shader:c.shader||null,copyCommand:!1,target:s.target||null,binds:s.bind||[],blending:c.blending||"normal",textures:c.textures||[],combos:c.combos||{},constants:c.constantshadervalues||{}}})}const db={"models/util/solidlayer.json":{material:"materials/util/solidlayer.json"},"models/util/composelayer.json":{material:"materials/util/solidlayer.json"},"models/util/fullscreenlayer.json":{material:"materials/util/solidlayer.json"},"models/util/projectlayer.json":{material:"materials/util/solidlayer.json"}};function Th(t){if(!t||typeof t!="string")return!0;const e=t.toLowerCase();return e==="generic"||e==="sprite"||e==="flat"||e.startsWith("genericimage")}function hb(t,e){return!t||!e||!e.shader||Th(e.shader)||(t.effects=t.effects||[],t.effects.some(n=>n.layerMaterial))?!1:(t.effects.unshift({file:"",name:"_layerMaterial",visible:!0,layerMaterial:!0,passes:[{combos:e.combos||{},constantshadervalues:e.constantshadervalues||{},textures:e.textures||[]}],materialPasses:[{shader:e.shader,copyCommand:!1,target:null,binds:[],blending:e.blending||"normal",textures:e.textures||[],combos:e.combos||{},constants:e.constantshadervalues||{}}],fbos:[]}),!0)}const mb={"materials/util/solidlayer.json":{passes:[{shader:"flat",blending:"translucent",cullmode:"nocull",depthtest:"disabled",depthwrite:"disabled",textures:[],combos:{}}]}},pb=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_MATERIALS:mb,BUILTIN_MODELS:db,attachLayerMaterialEffect:hb,isBuiltinAlbedoShader:Th,resolveEffectChain:fb},Symbol.toStringTag,{value:"Module"}));function gb(t){const e=new Map,n=new Map,r=/^[ \t]*#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]*)\))?[ \t]*(.*)$/gm;let i;for(;(i=r.exec(t))!==null;){const s=a=>a.replace(/\/\/.*$/,"").replace(/\/\*[\s\S]*?\*\//g,"").trim();i[2]!==void 0?n.set(i[1],{args:i[2].split(",").map(a=>a.trim()).filter(Boolean),body:s(i[3])}):e.set(i[1],s(i[3]))}return{defs:e,fns:n}}function yb(t,e,n,r){const i=[];let s=0;for(;s<t.length;){const a=t.indexOf(e,s);if(a===-1){i.push(t.slice(s));break}i.push(t.slice(s,a));let c=a+e.length;for(;c<t.length&&/\s/.test(t[c]);)c++;if(t[c]!=="("){i.push(t.slice(a,c)),s=c;continue}let u=0,l=c;for(;l<t.length;l++)if(t[l]==="(")u++;else if(t[l]===")"&&(u--,u===0))break;if(l>=t.length){i.push(t.slice(a));break}const d=t.slice(c+1,l),f=kr(d);let h=n.body;n.args.forEach((p,m)=>{const g=f[m]!==void 0?f[m].trim():"";h=Zs(h,p,g)}),r>0&&(h=Sh(h,r-1)),i.push("("+h+")"),s=l+1}return i.join("")}function Zs(t,e,n){return t.replace(new RegExp("\\b"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","g"),n)}function kr(t){const e=[];let n=0,r="";for(let i=0;i<t.length;i++){const s=t[i];s==="("?n++:s===")"&&n--,s===","&&n===0?(e.push(r),r=""):r+=s}return r.trim()!==""&&e.push(r),e}function Sh(t,e){for(let n=0;n<12;n++){const{defs:r,fns:i}=gb(t);if(r.size===0&&i.size===0)break;const s=t.split(`
8
+ `),a=new Map;for(let u=0;u<s.length;u++){const l=/^[ \t]*#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)/.exec(s[u]);l&&!a.has(l[1])&&a.set(l[1],u)}const o=new Map;{const u="(?:float|int|bool|vec[234]|ivec[234]|bvec[234]|mat[234])";for(const l of r.keys()){const d=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),f=new RegExp("^\\s*(?:const\\s+|uniform\\s+|varying\\s+|in\\s+|out\\s+|attribute\\s+)*"+u+"\\s+"+d+"\\s*[=;]");for(let h=0;h<s.length;h++)if(f.test(s[h])){o.set(l,h);break}}}let c=!1;for(let u=0;u<s.length;u++){const l=s[u];if(/^[ \t]*#/.test(l))continue;let d=l;for(const[f,h]of r){const p=a.get(f);if(p!==void 0&&u<p||o.get(f)===u)continue;new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b").test(d)&&(d=Zs(d,f,h),c=!0)}for(const[f,h]of i){const p=a.get(f);p!==void 0&&u<p||d.includes(f)&&(d=yb(d,f,h,e),c=!0)}s[u]=d}if(t=s.join(`
9
+ `),!c)break}return t}function Ph(t,e,n){const r=h=>e[h]!==void 0?String(e[h]):n.has(h)?"("+n.get(h)+")":"0";let i=t.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g,h=>r(h)),s=0;function a(){for(;s<i.length&&/\s/.test(i[s]);)s++}function o(){let h=c();for(a();i.startsWith("||",s);){s+=2;const p=c();h=h||p,a()}return h}function c(){let h=u();for(a();i.startsWith("&&",s);){s+=2;const p=u();h=h&&p,a()}return h}function u(){let h=l();for(a();i.startsWith("==",s)||i.startsWith("!=",s);){const p=i[s]==="="?"==":"!=";s+=2;const m=l();h=p==="=="?h===m:h!==m,a()}return h}function l(){let h=d();for(a();/^[<>]/.test(i[s]||"");){let p=i[s];i[s+1]==="="&&(p+="=",s++),s++;const m=d();p==="<"?h=h<m:p===">"?h=h>m:p==="<="?h=h<=m:h=h>=m,a()}return h}function d(){return a(),i[s]==="!"?(s++,!d()):f()}function f(){if(a(),i[s]==="("){s++;const p=o();return a(),s++,p}const h=/^-?\d+(\.\d+)?/.exec(i.slice(s));return h?(s+=h[0].length,Number(h[0])):!1}return o()}function _h(t){let e="",n=0;const r=t.length;for(;n<r;){const i=t[n],s=t[n+1];if(i==="/"&&s==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)t[n]===`
10
10
  `&&(e+=`
11
11
  `),n++;n+=2;continue}if(i==="/"&&s==="/"){for(;n<r&&t[n]!==`
12
- `;)n++;continue}e+=i,n++}return e}function $f(t,e,n,r){const i=t.split(`
13
- `),s=[],a=[],o=new Map;for(let c=0;c<i.length;c++){const u=i[c],l=u.trim();if(l.startsWith("#include")){if(fs(a)){const f=/^#include[ \t]+"([^"]+)"|^#include[ \t]+<([^>]+)>/.exec(l),d=f&&(f[1]||f[2]),h=d&&n?n(d):null;h!=null?s.push($f(Gf(h),e,n)):s.push("// [include \u7F3A\u5931: "+d+"]")}continue}if(l.startsWith("#define")){if(fs(a)){s.push(u);const f=/^#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)(?:\([^)]*\))?[ \t]*(.*)$/.exec(l);f&&o.set(f[1],f[2].trim())}continue}if(l.startsWith("#undef")){fs(a)&&s.push(u);continue}if(l.startsWith("#ifdef")||l.startsWith("#ifndef")||l.startsWith("#if")){const f=fs(a);let d=!1;if(l.startsWith("#ifdef")){const h=l.slice(6).trim().split(/\s+/)[0];d=e[h]!==void 0||o.has(h)}else if(l.startsWith("#ifndef")){const h=l.slice(7).trim().split(/\s+/)[0];d=!(e[h]!==void 0||o.has(h))}else try{d=!!Xf(l.slice(3).trim(),e,o)}catch{d=!1}a.push({parent:f,hit:d,done:d});continue}if(l.startsWith("#else")){if(a.length>0){const f=a[a.length-1];f.hit=!f.done,f.done=!0}continue}if(l.startsWith("#elif")){if(a.length>0){const f=a[a.length-1];if(f.done)f.hit=!1;else{let d=!1;try{d=!!Xf(l.slice(5).trim(),e,o)}catch{d=!1}f.hit=d,f.done=d}}continue}if(l.startsWith("#endif")){a.length>0&&a.pop();continue}l.startsWith("#")||fs(a)&&s.push(u)}return s.join(`
14
- `)}function fs(t){return t.every(e=>e.parent&&e.hit)}function ya(t,e,n,r){let i=0;for(let s=e;s<t.length;s++)if(t[s]===n)i++;else if(t[s]===r&&(i--,i===0))return s;return-1}function Qf(t,e){return ya(t,e,"(",")")}const ey=new Set(["void","bool","int","uint","float","double","vec2","vec3","vec4","bvec2","bvec3","bvec4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4"]);function ty(t,e){let n=e-1;for(;n>=0&&/[ \t]/.test(t[n]);)n--;if(n<0||n===e-1)return!1;let r=n+1;for(;n>=0&&/[A-Za-z0-9_]/.test(t[n]);)n--;const i=t.slice(n+1,r);return ey.has(i)}function Yf(t){const e=new Set;let n;const r=/\b(?:const\s+)?int\s+([A-Za-z_]\w*)\s*[=;)\u0003]/g;for(;(n=r.exec(t))!==null;)e.add(n[1]);return e}function dt(t,e,n){let r="",i=0;for(;i<t.length;){const s=t.indexOf(e,i);if(s===-1){r+=t.slice(i);break}if(s>0&&/[A-Za-z0-9_]/.test(t[s-1])){r+=t.slice(i,s+1),i=s+1;continue}const a=s+e.length;if(a<t.length&&/[A-Za-z0-9_]/.test(t[a])){r+=t.slice(i,a),i=a;continue}if(ty(t,s)){r+=t.slice(i,a),i=a;continue}r+=t.slice(i,s);let o=s+e.length;for(;o<t.length&&/\s/.test(t[o]);)o++;if(t[o]!=="("){r+=t.slice(s,o),i=o;continue}const c=Qf(t,o);if(c===-1){r+=t.slice(s);break}const u=t.slice(o+1,c);r+=n(u,s),i=c+1}return r}function Kf(t,e,n,r,i){const s=t;t=Gf(t);const a={},o=/\[COMBO\][^\n]*?"combo"\s*:\s*"([^"]+)"[^\n]*?"default"\s*:\s*(-?\d+)/g;let c;if(typeof i=="string"&&i){const y=new RegExp(o.source,"g");let b;for(;(b=y.exec(i))!==null;)a[b[1]]=Number(b[2])}for(;(c=o.exec(s))!==null;)a[c[1]]=Number(c[2]);const u={GLSL:1,...a,...n||{}};let l=$f(t,u,r);l=qf(l,20),l=l.replace(/^[ \t]*#define[^\n]*\n?/gm,"");{const y=new Set,b=/\[COMBO\][^\n]*"combo"\s*:\s*"([^"]+)"/g;let v;for(;(v=b.exec(s))!==null;)y.add(v[1]);for(const k of Object.keys(u))y.add(k);y.delete("GLSL");for(const k of y){const A=u[k]!==void 0?u[k]:0;l=us(l,k,String(A))}}l=us(l,"sample","smp"),l=l.replace(/(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)[fh]\b/g,"$1"),l=l.replace(/\bfloat4x4\b/g,"mat4").replace(/\bfloat3x3\b/g,"mat3").replace(/\bfloat2x2\b/g,"mat2").replace(/\bfloat4\b/g,"vec4").replace(/\bfloat3\b/g,"vec3").replace(/\bfloat2\b/g,"vec2").replace(/\bhalf4\b/g,"vec4").replace(/\bhalf3\b/g,"vec3").replace(/\bhalf2\b/g,"vec2").replace(/\bhalf\b/g,"float"),l=l.replace(/\btexSample2DLod\b/g,"textureLod").replace(/\btexSample2D\b/g,"texture"),l=dt(l,"saturate",y=>"clamp("+y+", 0.0, 1.0)"),l=dt(l,"CAST4",y=>"vec4("+y+")"),l=dt(l,"CAST3",y=>"vec3("+y+")"),l=dt(l,"CAST2",y=>"vec2("+y+")"),l=l.replace(/\b(max|min)\(\s*(-?\d+(?:\.\d+)?)\s*,\s*([A-Za-z_]\w*\.(rgb|xyz|rg|xy|r|x))\s*\)/g,(y,b,v,k,A)=>{const T=A.length;return b+"(vec"+T+"("+v+"), "+k+")"}),l=l.replace(/(\.([xyzwrgba]{2,4})\s*=\s*)(max|min)\(\s*(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\s*,\s*([^;]+?)\s*\)\s*;/g,(y,b,v,k,A,T)=>/\.[xyzwrgba]{2,4}\b|\bvec[234]\s*\(/.test(T)?`${b}${k}(vec${v.length}(${A}), ${T});`:y),l=l.replace(/(^|[^\w)\]])([+-])([+-])(?=[\d.])/g,(y,b,v,k)=>b+(v===k?"+":"-"));const f=[];l=l.replace(/\b\d+(?:\.\d+)?[eE][+-]?\d+\b/g,y=>(f.push(y),""+"".repeat(f.length)+""));const d=[];l=l.replace(/\bfor\s*\(\s*int\s+([A-Za-z_]\w*)([^)]*)\)/g,(y,b,v)=>(d.push(v+")"),`for (int ${b}${"".repeat(d.length)}`));for(let y=0;y<8;y++){const b=l;l=l.replace(/(^|[^\w.])(\d+)\s*([*/])\s*([A-Za-z_][A-Za-z0-9_]*)/g,"$1$2.0 $3 $4"),l=l.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(\d+\.\d+)\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(^|[^\w.])(\d+)\s*([*/])\s*(\d+\.\d+)/g,"$1$2.0 $3 $4"),l=l.replace(/(\.\d+)\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/([A-Za-z_]\w*\.(?:xyzw|xyz|xy|zw|rgba|rgb|rg|x|y|z|w|r|g|b|a))\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(^|[^\w.])(\d+)\s*([+-])\s*(\d+\.\d+)/g,"$1$2.0 $3 $4"),l=l.replace(/(^|[^\w.])(\d+)\s*([+-])\s*([A-Za-z_]\w*\.(?:xyzw|xyz|xy|zw|rgba|rgb|rg|x|y|z|w|r|g|b|a))/g,"$1$2.0 $3 $4"),l=l.replace(/(^|[^\w.])(\d+)\s*([*/+-])\s*(\()/g,(v,k,A,T,S,P,M)=>{let B=0,N=P+v.length-1;for(;N<M.length;N++){const q=M[N];if(q==="(")B++;else if(q===")"){if(B--,B===0){N++;break}}else if(B===0&&(q===";"||q===","||q===`
15
- `))break}for(;N<M.length;N++){const q=M[N];if(q===";"||q===","||q===`
16
- `||q===")")break}const O=M.slice(P,N);return/\d\.\d/.test(O)?`${k}${A}.0 ${T} ${S}`:v});{const v=new Set,k=/\b(?:uniform\s+)?(?:highp|mediump|lowp\s+)?(?:float|vec2|vec3|vec4|mat2|mat3|mat4)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let A;for(;(A=k.exec(l))!==null;)v.add(A[1]);if(v.size>0){const T=Array.from(v).sort((S,P)=>P.length-S.length).join("|");l=l.replace(new RegExp("(^|[^\\w.])(\\d+)\\s*([+-])\\s*("+T+")(?![A-Za-z0-9_])","g"),"$1$2.0 $3 $4"),l=l.replace(new RegExp("\\b("+T+")\\s*([+-])\\s*(\\d+)(?![\\d.])","g"),"$1 $2 $3.0")}}if(l===b)break}{const y=["smoothstep","step","mix","clamp","max","min","pow","mod","atan","sqrt","inversesqrt","exp","log","exp2","log2","abs","sign","floor","ceil","fract","length","distance","dot","reflect","refract","faceforward","normalize","cross"],b=/\b(ApplyBlending|ApplyComposite|BlendTransparency)\s*\(/;for(const v of y)l=dt(l,v,k=>{const T=Gn(k).map(S=>{if(b.test(S))return S;const P=[];let M=S.replace(/\[[^\]]*\]/g,B=>(P.push(B),"\0"+(P.length-1)+"\0")).replace(/\b(?:ivec[234]|uvec[234]|int|uint)\s*\([^()]*\)/g,B=>(P.push(B),"\0"+(P.length-1)+"\0"));return M=M.replace(/(?<![A-Za-z0-9_.\u0000])(\d+)(?![.\d])(?![A-Za-z_])/g,"$1.0"),M.replace(/\u0000(\d+)\u0000/g,(B,N)=>P[Number(N)])});return v+"("+T.join(",")+")"});l=dt(l,"pow",v=>{const k=Gn(v);if(k.length!==2)return"pow("+v+")";const A=k[0].trim(),T=k[1].trim(),S=/\.(xyzw|rgba|xyz|rgb|xy|rg|zw)\s*$/.exec(A),M=S?{xyzw:4,rgba:4,xyz:3,rgb:3,xy:2,rg:2,zw:2}[S[1]]:0,B=/\bvec[234]\s*\(/.test(T)||/\.(xyzw|rgba|xyz|rgb|xy|rg|zw)\b/.test(T);return M>=2&&!B?"pow("+A+", vec"+M+"("+T+"))":"pow("+A+", "+T+")"})}l=l.replace(/([)\]])\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/\)\s*([+-])\s*(\d+)(?![\d.])/g,") $1 $2.0"),l=l.replace(/(^|[^\w.])(\d+)(?![.\d])\s*([+-])\s*((?:step|smoothstep|mix|mod|fract|abs|sin|cos|tan|atan|sqrt|pow|inversesqrt|floor|ceil|sign|length|normalize|distance|dot|cross|exp|log|exp2|log2|clamp|min|max)\s*\()/g,"$1$2.0 $3 $4");{const y=new Set,b=/\b(?:vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)/g;let v;for(;(v=b.exec(l))!==null;)y.add(v[1]);if(y.size>0){const k=Array.from(y).sort((A,T)=>T.length-A.length).join("|");l=l.replace(new RegExp("\\b("+k+")\\s*([+-])\\s*(\\d+)(?![\\d.])","g"),"$1 $2 $3.0")}}{const y=new Set,b=/\b(?:int|uint)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let v;for(;(v=b.exec(l))!==null;)y.add(v[1]);l=l.replace(/\buint\b/g,"int"),l=l.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\s*%\s*(\d+)(?![\d.])/g,(k,A,T)=>y.has(A)?k:"mod("+A+", "+T+".0)"),l=l.replace(/\bint\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*mod\(([^;]*)\);/g,"int $1 = int(mod($2));")}l=l.replace(/\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^;()\n,]+);/g,(y,b,v,k)=>{const A=k.trim();return/^(vec[234]|mat[234]|int\b|float\b)/.test(A)?y:b+" "+v+" = "+b+"("+A+");"});for(const y of["mix","clamp","step","smoothstep","min","max","mod","pow"])l=dt(l,y,b=>y+"("+b.replace(/(?<![A-Za-z0-9_.])(\d+)(?![.\d])/g,"$1.0")+")");l=dt(l,"clamp",y=>{const b=Gn(y);if(b.length!==3)return"clamp("+y+")";const v=b[0].trim(),k=b[1].trim(),A=T=>/^-?\d+\.?\d*$/.test(T);return A(v)&&A(k)&&Number(v)===0&&Number(k)===1?"clamp("+b[2].trim()+", "+v+", "+k+")":"clamp("+y+")"}),l=l.replace(/(\.\d+)\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/([)\]])\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=dt(l,"smoothstep",y=>{const b=Gn(y);return b.length===3&&b[1].trim()==="0.0"&&b[0].trim()!=="0.0"?"(1.0 - smoothstep(0.0, "+b[0].trim()+", "+b[2].trim()+"))":"smoothstep("+y+")"});{const y=new Map,b=/\b(?:uniform|varying|attribute|in|out)?\s*\b(vec([234]))\s+([A-Za-z_]\w*)/g;let v;for(;(v=b.exec(l))!==null;)y.set(v[3],Number(v[2]));if(y.size>0){const k={2:"xy",3:"xyz",4:"xyzw"};l=l.replace(/(^|[;{}\n]\s*)([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*)\s*;/g,(A,T,S,P)=>{const M=y.get(S),B=y.get(P);return!M||!B||M>=B?A:T+S+" = "+P+"."+k[M]+";"})}{const k=new Set;{const S=/\b(?:uniform|varying|attribute|in|out|const)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let P;for(;(P=S.exec(l))!==null;)k.add(P[1])}const A=S=>{const P=S.trim();{const N=/^vec([234])\s*\(/.exec(P);if(N){let O=0;for(let q=P.indexOf("(");q<P.length;q++)if(P[q]==="(")O++;else if(P[q]===")"&&(O--,O===0))return q===P.length-1?Number(N[1]):0;return 0}}if(/^texture(?:Lod)?\s*\(/.test(P)){let N=0;for(let O=P.indexOf("(");O<P.length;O++)if(P[O]==="(")N++;else if(P[O]===")"&&(N--,N===0))return O===P.length-1?4:0;return 0}const M=/^([A-Za-z_]\w*)(?:\.([xyzwrgba]{2,4}))?\s*[*/]\s*([^*/]+)$/.exec(P);if(!M)return 0;const B=M[3];return/\bvec[234]\s*\(|\.[xyzwrgba]{2,4}\b/.test(B)?0:M[2]?M[2].length:k.has(M[1])?0:y.get(M[1])||0};l=l.replace(/(^|[;{}\n]\s*)float\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(S,P,M,B)=>A(B)<2?S:`${P}float ${M} = (${B.trim()}).x;`);const T={2:"xy",3:"xyz"};l=l.replace(/(^|[;{}\n]\s*)vec([23])\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(S,P,M,B,N)=>{const O=Number(M);return A(N)<=O?S:`${P}vec${M} ${B} = (${N.trim()}).${T[O]};`})}if(y.size>0){const k=new Set,A=/\b(?:uniform|varying|attribute|in|out)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let T;for(;(T=A.exec(l))!==null;)k.add(T[1]);const S="pow|saturate|clamp|smoothstep|step|abs|floor|ceil|fract|frac|sin|cos|tan|asin|acos|atan|sqrt|length|distance|dot|exp|log|sign|fmod|mod|min|max|mix|lerp",P=/^(?:length|distance|dot)$/,M=N=>{const O=N.match(new RegExp("^(?:"+S+")\\s*\\("));if(!O)return!1;let q=0;const H=O[0].length-1;let G=-1;for(let ne=H;ne<N.length;ne++)if(N[ne]==="(")q++;else if(N[ne]===")"&&(q--,q===0)){G=ne;break}if(G!==N.length-1)return!1;const Y=O[0].replace(/\s*\($/,"");if(P.test(Y))return!0;const J=N.slice(H+1,G);if(/\bvec[234]\s*\(/.test(J)||/\.[xyzwrgba]{2,4}\b/.test(J))return!1;for(const ne of y.keys()){const fe=ne.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp("(?<!\\.)\\b"+fe+"\\b(?!\\s*\\.[xyzwrgba]\\b)").test(J))return!1}return!0},B=new Set;if(l=l.replace(/(^|[;{}\n]\s*)([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(N,O,q,H)=>{const G=y.get(q);if(!G||k.has(q))return N;const Y=H.trim();if(new RegExp("^vec"+G+"\\s*\\(").test(Y)||y.has(Y))return N;const J=/^-?\d+(?:\.\d+)?(?:e[-+]?\d+)?$/i.test(Y),ne=k.has(Y);return!J&&!ne&&!M(Y)?N:(B.add(q),O+q+" = vec"+G+"("+Y+");")}),B.size>0){const N=[...B].sort((O,q)=>q.length-O.length).join("|");l=l.replace(new RegExp(`\\b([A-Za-z_]\\w*)\\s*([*/])\\s*(${N})\\b`,"g"),(O,q,H,G)=>y.has(q)?O:`${q} ${H} ${G}.x`),l=l.replace(new RegExp(`\\b(${N})\\s*([*/])\\s*([A-Za-z_]\\w*)\\b`,"g"),(O,q,H,G)=>y.has(G)?O:`${q}.x ${H} ${G}`)}}}l=l.replace(/(\.[xyzwrgba]{1,4}\s*=\s*)(-?\d+)\s*;/g,"$1$2.0;"),l=l.replace(/\b(float|vec2|vec3|vec4)\s+([A-Za-z_]\w*)\s*=\s*(-?\d+)\s*;/g,(y,b,v,k)=>b==="float"?`${b} ${v} = ${k}.0;`:`${b} ${v} = ${b}(${k}.0);`);{const y=new Set,b=/\b(?:uniform|varying|attribute|in|out)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let v;for(;(v=b.exec(l))!==null;)y.add(v[1]);if(y.size>0){const k=[...y].sort((A,T)=>T.length-A.length).join("|");l=l.replace(new RegExp(`\\b(${k})\\s*=\\s*(-?\\d+)\\s*;`,"g"),"$1 = $2.0;"),l=l.replace(new RegExp(`\\b(${k})\\s*([-+*/]=)\\s*(-?\\d+)\\s*;`,"g"),"$1 $2 $3.0;")}}l=l.replace(/(\.[xyzwrgba]{1,4}\s*[-+*/]=\s*)(-?\d+)\s*;/g,"$1$2.0;");const h="step|smoothstep|saturate|clamp|mix|lerp|frac|fract|abs|floor|ceil|min|max|pow|sqrt|length|dot|distance";l=l.replace(new RegExp(`\\bint\\s+([A-Za-z_]\\w*)\\s*=\\s*((?:${h})\\s*\\()`,"g"),"float $1 = $2"),l=l.replace(/\bfloat\s+([A-Za-z_]\w*)\s*=\s*(int\s*\([^;]*\))\s*;/g,"float $1 = float($2);");{const y=Yf(l);y.size>0&&(l=l.replace(/\b(const\s+)?float\s+([A-Za-z_]\w*)\s*=\s*([^;{}]+);/g,(b,v,k,A)=>{const T=A.trim();if(/\./.test(T)||/[A-Za-z_]\w*\s*\(/.test(T))return b;const S=T.match(/[A-Za-z_]\w*/g);return!S||!S.length||!S.every(P=>y.has(P))?b:`${v||""}float ${k} = float(${T});`}))}{const y=Yf(l),b=new Set;let v;const k=/\b(?:const\s+|uniform\s+|varying\s+|in\s+|out\s+)*float\s+([A-Za-z_]\w*)/g;for(;(v=k.exec(l))!==null;)b.add(v[1]);for(const A of[...y])b.has(A)&&(y.delete(A),b.delete(A));if(y.size>0&&b.size>0){const A=[...y].sort((S,P)=>P.length-S.length).join("|"),T=[...b].sort((S,P)=>P.length-S.length).join("|");l=l.replace(new RegExp(`\\b(${A})\\s*([*/+-])\\s*(${T})\\b`,"g"),(S,P,M,B)=>`float(${P}) ${M} ${B}`),l=l.replace(new RegExp(`\\b(${T})\\s*([*/+-])\\s*(${A})\\b`,"g"),(S,P,M,B)=>`${P} ${M} float(${B})`)}}{const y=new Set,b=/\bbool\s+([A-Za-z_]\w*)\s*=/g;let v;for(;(v=b.exec(l))!==null;)y.add(v[1]);if(y.size>0){const k=[...y].join("|");l=l.replace(new RegExp(`([-+*/]=\\s*)(${k})\\b`,"g"),(A,T,S)=>`${T}float(${S})`)}}{const y=/\(\s*([^()&|]+?)\s*(<=|>=|<|>|==|!=)\s*([^()&|]+?)\s*\)/g;l=l.replace(new RegExp(y.source+"\\s*([*/])","g"),(b,v,k,A,T)=>`float(${v.trim()} ${k} ${A.trim()}) ${T}`),l=l.replace(new RegExp("([-+*/]=\\s*)"+y.source,"g"),(b,v,k,A,T)=>`${v}float(${k.trim()} ${A} ${T.trim()})`)}{const y=new Set;for(const b of l.matchAll(/\b(?:uniform\s+)?(?:highp|mediump|lowp\s+)?float\s+([A-Za-z_]\w*)\s*\[/g))y.add(b[1]);if(y.size){const b=[...y].sort((S,P)=>P.length-S.length).join("|"),v=new RegExp("\\b("+b+")\\s*\\[","g");let k="",A=0,T;for(;T=v.exec(l);){const S=T.index+T[0].length-1,P=ya(l,S,"[","]");if(P<0)break;let M=P+1;for(;M<l.length&&/[ \t]/.test(l[M]);)M++;if(l[M]!=="["){const H=l.slice(S+1,P).trim(),G=/\d\.\d/.test(H)||/^[A-Za-z_]\w*$/.test(H)&&new RegExp("\\bfloat\\s+"+H.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b").test(l),Y=/^\s*int\s*\(/.test(H)||/^-?\d+$/.test(H);if(G&&!Y){k+=l.slice(A,T.index),k+=T[1]+"[int("+H+")]",A=P+1,v.lastIndex=A;continue}v.lastIndex=P+1;continue}const B=ya(l,M,"[","]");if(B<0)break;const N=l.slice(S+1,P),O=l.slice(M+1,B);k+=l.slice(A,T.index),k+=T[1]+"[int(("+N+")) * 4 + int(("+O+"))]",A=B+1,v.lastIndex=A}l=k+l.slice(A)}}l=dt(l,"mix",(y,b)=>{const v=Gn(y);if(v.length!==3)return"mix("+y+")";const k=M=>{const B=M.trim(),N=/\.([xyzwrgba]{1,4})\s*$/.exec(B);if(N)return N[1].length;const O=/^vec([234])\s*\(/.exec(B);if(O)return Number(O[1]);if(!/^[A-Za-z_]\w*$/.test(B))return 0;const q=new RegExp("\\b(vec([234])|float)\\s+"+B+"\\b","g");let H=0,G;for(;(G=q.exec(l))!==null&&G.index<b;)H=G[1].startsWith("vec")?Number(G[2]):1;return H},A=v[0].trim(),T=v[1].trim(),S=k(A),P=k(T);if(S>=2&&P>=2&&S!==P){const M=Math.min(S,P),B=M===2?".xy":M===3?".xyz":"";return B?"mix("+(S>M?A+B:A)+", "+(P>M?T+B:T)+", "+v[2].trim()+")":"mix("+y+")"}return"mix("+y+")"});{const y=/\b(vec([234]))\s+([A-Za-z_]\w*)\s*\(/g;let b="",v=0,k;for(;k=y.exec(l);){const A=Qf(l,k.index+k[0].length-1);if(A<0)break;let T=A+1;for(;T<l.length&&/\s/.test(l[T]);)T++;if(l[T]!=="{")continue;const S=ya(l,T,"{","}");if(S<0)break;const P=Number(k[2]);if(P>=4){y.lastIndex=S;continue}let M=l.slice(T+1,S);const B=new Map;for(const O of l.slice(0,k.index).matchAll(/\buniform\s+(?:highp|mediump|lowp\s+)?(vec([234]))\s+([A-Za-z_]\w*)/g))B.set(O[3],Number(O[2]));for(const O of M.matchAll(/\b(vec([234]))\s+([A-Za-z_]\w*)/g))B.set(O[3],Number(O[2]));const N=P===2?"xy":"xyz";M=M.replace(/\breturn\s+([A-Za-z_]\w*)\s*;/g,(O,q)=>{const H=B.get(q);return H&&H>P?"return "+q+"."+N+";":O}),b+=l.slice(v,T+1)+M,v=S,y.lastIndex=S}l=b+l.slice(v)}const p=new Set,m=/\b(?:uniform\s+)?(?:mat4|mat3|mat2|float4x4)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let g;for(;(g=m.exec(l))!==null;)p.add(g[1]);if(l=dt(l,"mul",y=>{const b=Gn(y);if(b.length!==2)return"mul("+y+")";const v=b[0].trim(),k=b[1].trim(),A=T=>p.has(T.split(/[\[.\s]/)[0])||/^mat[234]\(/.test(T);return A(v)&&A(k)?"(transpose("+k+") * transpose("+v+"))":A(k)?"(transpose("+k+") * "+v+")":"("+v+" * "+k+")"}),l=l.replace(/\blerp\b/g,"mix").replace(/\bfrac\b/g,"fract"),l=dt(l,"atan2",y=>"atan("+y+")"),l=dt(l,"fmod",y=>{const b=Gn(y);if(b.length!==2)return"mod("+y+")";const v=b[0].trim(),k=b[1].trim();return"(("+v+") - ("+k+") * trunc(("+v+") / ("+k+")))"}),l=dt(l,"ddx",y=>"dFdx("+y+")"),l=dt(l,"ddy",y=>"dFdy("+y+")"),l=dt(l,"CAST3X3",y=>"mat3("+y+")"),e==="vert")l=l.replace(/\battribute\b/g,"in").replace(/\bvarying\b/g,"out");else{if(l=l.replace(/\bvarying\b/g,"in").replace(/\battribute\b/g,"in"),typeof i=="string"&&i){const v=new Map,k=/^\s*(?:varying|out)\s+(?:highp|mediump|lowp\s+)?(vec[234]|float)\s+([A-Za-z_]\w*)\s*;/gm;let A;for(;(A=k.exec(i))!==null;)v.set(A[2],A[1]);const T={float:1,vec2:2,vec3:3,vec4:4},S=new Map;if(l=l.replace(/^(\s*in\s+(?:highp|mediump|lowp\s+)?)(vec[234]|float)(\s+)([A-Za-z_]\w*)(\s*;)/gm,(P,M,B,N,O,q)=>{const H=v.get(O);return!H||T[H]<=T[B]?P:(S.set(O,T[B]),M+H+N+O+q)}),S.size>0){const P={1:"x",2:"xy",3:"xyz"};for(const[M,B]of S){const N=P[B];N&&(l=l.split(`
17
- `).map(O=>/^\s*in\s/.test(O)?O:O.replace(new RegExp("\\b"+M+"\\b(?!\\s*[.\\w])","g"),M+"."+N)).join(`
18
- `))}}l=l.replace(/^(\s*in\s+(?:highp|mediump|lowp\s+)?)(vec[234]|float)(\s+)([A-Za-z_]\w*)(\s*;)/gm,(P,M,B,N,O,q)=>{const H=v.get(O);if(!H||T[H]>=T[B])return P;const G="xyzw",Y="rgba";return new RegExp("\\b"+O+"\\s*\\.\\s*["+G+Y+"]*["+G.slice(T[H])+Y.slice(T[H])+"]").test(l)?P:M+H+N+O+q})}{const v=new Map,k=/^\s*in\s+(?:highp|mediump|lowp\s+)?(vec[34])\s+([A-Za-z_]\w*)\s*;/gm;let A;for(;(A=k.exec(l))!==null;)v.set(A[2],Number(A[1].slice(3)));const T=new Map(v),S=/\b(vec[34])\s+([A-Za-z_]\w*)\s*[=;]/g;for(;(A=S.exec(l))!==null;)T.has(A[2])||T.set(A[2],Number(A[1].slice(3)));if(T.size>0){const P=M=>{const B=M.trim();if(!B)return M;const N=/^([A-Za-z_]\w*)$/.exec(B);if(N&&T.has(N[1]))return N[1]+".xy";const O=/^([A-Za-z_]\w*)(\s*[+\-].+)$/.exec(B);return O&&T.has(O[1])?"("+O[1]+".xy"+O[2]+")":M};for(const M of["textureLod","texture"])l=dt(l,M,B=>{const N=Gn(B);return N.length>=2&&(N[1]=P(N[1])),M+"("+N.join(", ")+")"})}v.size>0&&(l=l.split(`
19
- `).map(P=>{if(!/\bvec2\s+[A-Za-z_]\w*\s*=/.test(P))return P;let M=P;for(const B of v.keys())M=M.replace(new RegExp("\\b"+B+"\\b(?!\\s*[.\\w])","g"),B+".xy");return M}).join(`
20
- `))}const y=new Set,b=new Set;{const v=/^\s*in\s+(?:highp|mediump|lowp\s+)?(vec[234]|float)\s+([A-Za-z_]\w*)\s*;/gm;let k;for(;(k=v.exec(l))!==null;)b.add(k[2])}for(const v of b)new RegExp("\\b"+v+"\\b\\s*(?:\\.[xyzwrgba]{1,4})?\\s*(?:[-+*/]?=(?!=)|\\+\\+|--)").test(l)&&y.add(v);if(y.size>0){const v=l.search(/\bvoid\s+main\s*\([^)]*\)\s*\{/);if(v!==-1){const k=l.indexOf("{",v),A=l.slice(0,k+1);let T=l.slice(k+1);const S=[];for(const P of y){if(new RegExp("(?:^|[;{}\\n])\\s*(?:highp|mediump|lowp\\s+)?(?:vec[234]|float|int|bool)\\s+"+P+"\\s*[=;]").test(T))continue;const B=new RegExp("^\\s*in\\s+(?:highp|mediump|lowp\\s+)?(vec[234]|float)\\s+"+P+"\\s*;","m").exec(l),N=B?B[1]:"vec4";S.push(" "+N+" "+P+"_rw = "+P+";"),T=us(T,P,P+"_rw")}S.length>0&&(T=`
21
- `+S.map(P=>P.replace(/= (\w+)_rw;/,"= $1;")).join(`
12
+ `;)n++;continue}e+=i,n++}return e}function Eh(t,e,n,r){const i=t.split(`
13
+ `),s=[],a=[],o=new Map;for(let c=0;c<i.length;c++){const u=i[c],l=u.trim();if(l.startsWith("#include")){if(Js(a)){const d=/^#include[ \t]+"([^"]+)"|^#include[ \t]+<([^>]+)>/.exec(l),f=d&&(d[1]||d[2]),h=f&&n?n(f):null;h!=null?s.push(Eh(_h(h),e,n)):s.push("// [include \u7F3A\u5931: "+f+"]")}continue}if(l.startsWith("#define")){if(Js(a)){s.push(u);const d=/^#define[ \t]+([A-Za-z_][A-Za-z0-9_]*)(?:\([^)]*\))?[ \t]*(.*)$/.exec(l);d&&o.set(d[1],d[2].trim())}continue}if(l.startsWith("#undef")){Js(a)&&s.push(u);continue}if(l.startsWith("#ifdef")||l.startsWith("#ifndef")||l.startsWith("#if")){const d=Js(a);let f=!1;if(l.startsWith("#ifdef")){const h=l.slice(6).trim().split(/\s+/)[0];f=e[h]!==void 0||o.has(h)}else if(l.startsWith("#ifndef")){const h=l.slice(7).trim().split(/\s+/)[0];f=!(e[h]!==void 0||o.has(h))}else try{f=!!Ph(l.slice(3).trim(),e,o)}catch{f=!1}a.push({parent:d,hit:f,done:f});continue}if(l.startsWith("#else")){if(a.length>0){const d=a[a.length-1];d.hit=!d.done,d.done=!0}continue}if(l.startsWith("#elif")){if(a.length>0){const d=a[a.length-1];if(d.done)d.hit=!1;else{let f=!1;try{f=!!Ph(l.slice(5).trim(),e,o)}catch{f=!1}d.hit=f,d.done=f}}continue}if(l.startsWith("#endif")){a.length>0&&a.pop();continue}l.startsWith("#")||Js(a)&&s.push(u)}return s.join(`
14
+ `)}function Js(t){return t.every(e=>e.parent&&e.hit)}function fo(t,e,n,r){let i=0;for(let s=e;s<t.length;s++)if(t[s]===n)i++;else if(t[s]===r&&(i--,i===0))return s;return-1}function Mh(t,e){return fo(t,e,"(",")")}const bb=new Set(["void","bool","int","uint","float","double","vec2","vec3","vec4","bvec2","bvec3","bvec4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4"]);function wb(t,e){let n=e-1;for(;n>=0&&/[ \t]/.test(t[n]);)n--;if(n<0||n===e-1)return!1;let r=n+1;for(;n>=0&&/[A-Za-z0-9_]/.test(t[n]);)n--;const i=t.slice(n+1,r);return bb.has(i)}function Ch(t){const e=new Set;let n;const r=/\b(?:const\s+)?int\s+([A-Za-z_]\w*)\s*[=;)\u0003]/g;for(;(n=r.exec(t))!==null;)e.add(n[1]);return e}function vb(t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(r==="("||r==="["){e++;continue}if(r===")"||r==="]"){e--;continue}if(e===0){if(r==="?"||r==="#")return!1;if((r==="&"||r==="|")&&t[n+1]===r)return!0;if(r==="<"||r===">"){if(t[n+1]===r){n++;continue}return!0}if(r==="="&&t[n+1]==="="||r==="!"&&t[n+1]==="=")return!0}}return!1}function Ab(t,e){const n=a=>{if(/[{}]/.test(a))return a;const o=/^(\s*)([A-Za-z_]\w*(?:\.\s*[A-Za-z_]\w*)*)\s*([-+*/]=)([\s\S]+)$/.exec(a);if(!o)return a;const[,c,u,l,d]=o,f=d.trim();return!f||e.has(u.split(".")[0])||!vb(f)?a:c+u+" "+l+" float("+f+")"};let r="",i=0,s=0;for(let a=0;a<t.length;a++){const o=t[a];o==="("||o==="["?s++:o===")"||o==="]"?s--:o===";"&&s===0&&(r+=n(t.slice(i,a))+";",i=a+1)}return r+n(t.slice(i))}function Ft(t,e,n){let r="",i=0;for(;i<t.length;){const s=t.indexOf(e,i);if(s===-1){r+=t.slice(i);break}if(s>0&&/[A-Za-z0-9_]/.test(t[s-1])){r+=t.slice(i,s+1),i=s+1;continue}const a=s+e.length;if(a<t.length&&/[A-Za-z0-9_]/.test(t[a])){r+=t.slice(i,a),i=a;continue}if(wb(t,s)){r+=t.slice(i,a),i=a;continue}r+=t.slice(i,s);let o=s+e.length;for(;o<t.length&&/\s/.test(t[o]);)o++;if(t[o]!=="("){r+=t.slice(s,o),i=o;continue}const c=Mh(t,o);if(c===-1){r+=t.slice(s);break}const u=t.slice(o+1,c);r+=n(u,s),i=c+1}return r}function Ih(t,e,n,r,i){const s=t;t=_h(t);const a={},o=/\[COMBO\][^\n]*?"combo"\s*:\s*"([^"]+)"[^\n]*?"default"\s*:\s*(-?\d+)/g;let c;if(typeof i=="string"&&i){const w=new RegExp(o.source,"g");let A;for(;(A=w.exec(i))!==null;)a[A[1]]=Number(A[2])}for(;(c=o.exec(s))!==null;)a[c[1]]=Number(c[2]);const u={GLSL:1,...a,...n||{}};{const w=["mod","mix","clamp","min","max","step","smoothstep","fract","abs","floor","ceil","sign","pow","exp","exp2","log","log2","sqrt","inversesqrt","sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","dot","cross","normalize","length","distance","reflect","refract","round","trunc","modf","degrees","radians"],A="(?:void|float|int|uint|bool|half|double|vec[234]|ivec[234]|bvec[234]|mat[234]|mat[234]x[234])";for(const b of w){if(!new RegExp("(^|[;}\\n])[ \\t]*(?:(?:static|const|inline)[ \\t]+)*"+A+"[ \\t]+"+b+"[ \\t]*\\(","m").test(t))continue;const x="we_fn_"+b;new RegExp("\\b"+x+"\\b").test(t)||(t=t.replace(new RegExp("\\b"+b+"\\b(?=\\s*\\()","g"),x))}}let l=Eh(t,u,r);l=l.replace(/(#define\s+bufferRes\s+)(\d+)/g,(A,b,v)=>b+Math.min(Number(v),24)),l=l.replace(/(\b(?:varying|out|in)\s+vec4\s+audioValue\s*\[\s*)(\d+)(\s*\])/g,(A,b,v,x)=>b+Math.min(Number(v),24)+x),l=Sh(l,20),l=l.replace(/^[ \t]*#define[^\n]*\n?/gm,"");{const w=new Set,A=/\[COMBO\][^\n]*"combo"\s*:\s*"([^"]+)"/g;let b;for(;(b=A.exec(s))!==null;)w.add(b[1]);for(const v of Object.keys(u))w.add(v);w.delete("GLSL");for(const v of w){const x=u[v]!==void 0?u[v]:0;l=Zs(l,v,String(x))}}l=Zs(l,"sample","smp"),l=l.replace(/(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)[fh]\b/g,"$1"),l=l.replace(/\bfloat4x4\b/g,"mat4").replace(/\bfloat3x3\b/g,"mat3").replace(/\bfloat2x2\b/g,"mat2").replace(/\bfloat4\b/g,"vec4").replace(/\bfloat3\b/g,"vec3").replace(/\bfloat2\b/g,"vec2").replace(/\bhalf4\b/g,"vec4").replace(/\bhalf3\b/g,"vec3").replace(/\bhalf2\b/g,"vec2").replace(/\bhalf\b/g,"float"),l=l.replace(/\btexSample2DLod\b/g,"textureLod").replace(/\btexSample2D\b/g,"texture"),l=Ft(l,"saturate",w=>"clamp("+w+", 0.0, 1.0)"),l=Ft(l,"CAST4",w=>"vec4("+w+")"),l=Ft(l,"CAST3",w=>"vec3("+w+")"),l=Ft(l,"CAST2",w=>"vec2("+w+")"),l=l.replace(/\b(max|min)\(\s*(-?\d+(?:\.\d+)?)\s*,\s*([A-Za-z_]\w*\.(rgb|xyz|rg|xy|r|x))\s*\)/g,(w,A,b,v,x)=>{const P=x.length;return A+"(vec"+P+"("+b+"), "+v+")"}),l=l.replace(/(\.([xyzwrgba]{2,4})\s*=\s*)(max|min)\(\s*(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\s*,\s*([^;]+?)\s*\)\s*;/g,(w,A,b,v,x,P)=>/\.[xyzwrgba]{2,4}\b|\bvec[234]\s*\(/.test(P)?`${A}${v}(vec${b.length}(${x}), ${P});`:w),l=l.replace(/(^|[^\w)\]])([+-])([+-])(?=[\d.])/g,(w,A,b,v)=>A+(b===v?"+":"-"));const d=[];l=l.replace(/\b\d+(?:\.\d+)?[eE][+-]?\d+\b/g,w=>(d.push(w),""+"".repeat(d.length)+""));const f=[];l=l.replace(/\bfor\s*\(\s*int\s+([A-Za-z_]\w*)([^)]*)\)/g,(w,A,b)=>(f.push(b+")"),`for (int ${A}${"".repeat(f.length)}`));for(let w=0;w<8;w++){const A=l;l=l.replace(/(^|[^\w.])(\d+)\s*([*/])\s*([A-Za-z_][A-Za-z0-9_]*)/g,"$1$2.0 $3 $4"),l=l.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(\d+\.\d+)\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(^|[^\w.])(\d+)\s*([*/])\s*(\d+\.\d+)/g,"$1$2.0 $3 $4"),l=l.replace(/(\.\d+)\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/([A-Za-z_]\w*\.(?:xyzw|xyz|xy|zw|rgba|rgb|rg|x|y|z|w|r|g|b|a))\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/(^|[^\w.])(\d+)\s*([+-])\s*(\d+\.\d+)/g,"$1$2.0 $3 $4"),l=l.replace(/(^|[^\w.])(\d+)\s*([+-])\s*([A-Za-z_]\w*\.(?:xyzw|xyz|xy|zw|rgba|rgb|rg|x|y|z|w|r|g|b|a))/g,"$1$2.0 $3 $4"),l=l.replace(/(^|[^\w.])(\d+)\s*([*/+-])\s*(\()/g,(b,v,x,P,S,k,_)=>{let I=0,B=k+b.length-1;for(;B<_.length;B++){const O=_[B];if(O==="(")I++;else if(O===")"){if(I--,I===0){B++;break}}else if(I===0&&(O===";"||O===","||O===`
15
+ `))break}for(;B<_.length;B++){const O=_[B];if(O===";"||O===","||O===`
16
+ `||O===")")break}const V=_.slice(k,B);return/\d\.\d/.test(V)?`${v}${x}.0 ${P} ${S}`:b});{const b=new Set,v=/\b(?:uniform\s+)?(?:highp|mediump|lowp\s+)?(?:float|vec2|vec3|vec4|mat2|mat3|mat4)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let x;for(;(x=v.exec(l))!==null;)b.add(x[1]);if(b.size>0){const P=Array.from(b).sort((S,k)=>k.length-S.length).join("|");l=l.replace(new RegExp("(^|[^\\w.])(\\d+)\\s*([+-])\\s*("+P+")(?![A-Za-z0-9_])","g"),"$1$2.0 $3 $4"),l=l.replace(new RegExp("\\b("+P+")\\s*([+-])\\s*(\\d+)(?![\\d.])","g"),"$1 $2 $3.0")}}if(l===A)break}{const w=["smoothstep","step","mix","clamp","max","min","pow","mod","atan","sqrt","inversesqrt","exp","log","exp2","log2","abs","sign","floor","ceil","fract","length","distance","dot","reflect","refract","faceforward","normalize","cross"],A=/\b(ApplyBlending|ApplyComposite|BlendTransparency)\s*\(/;for(const b of w)l=Ft(l,b,v=>{const P=kr(v).map(S=>{if(A.test(S))return S;const k=[];let _=S.replace(/\[[^\]]*\]/g,I=>(k.push(I),"\0"+(k.length-1)+"\0")).replace(/\b(?:ivec[234]|uvec[234]|int|uint)\s*\([^()]*\)/g,I=>(k.push(I),"\0"+(k.length-1)+"\0"));return _=_.replace(/(?<![A-Za-z0-9_.\u0000])(\d+)(?![.\d])(?![A-Za-z_])/g,"$1.0"),_.replace(/\u0000(\d+)\u0000/g,(I,B)=>k[Number(B)])});return b+"("+P.join(",")+")"});l=Ft(l,"pow",b=>{const v=kr(b);if(v.length!==2)return"pow("+b+")";const x=v[0].trim(),P=v[1].trim(),S=/\.(xyzw|rgba|xyz|rgb|xy|rg|zw)\s*$/.exec(x),_=S?{xyzw:4,rgba:4,xyz:3,rgb:3,xy:2,rg:2,zw:2}[S[1]]:0,I=/\bvec[234]\s*\(/.test(P)||/\.(xyzw|rgba|xyz|rgb|xy|rg|zw)\b/.test(P);return _>=2&&!I?"pow("+x+", vec"+_+"("+P+"))":"pow("+x+", "+P+")"})}l=l.replace(/([)\]])\s*([*/])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/\)\s*([+-])\s*(\d+)(?![\d.])/g,") $1 $2.0"),l=l.replace(/(^|[^\w.])(\d+)(?![.\d])\s*([+-])\s*((?:step|smoothstep|mix|mod|fract|abs|sin|cos|tan|atan|sqrt|pow|inversesqrt|floor|ceil|sign|length|normalize|distance|dot|cross|exp|log|exp2|log2|clamp|min|max)\s*\()/g,"$1$2.0 $3 $4");{const w=new Set,A=/\b(?:vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)/g;let b;for(;(b=A.exec(l))!==null;)w.add(b[1]);if(w.size>0){const v=Array.from(w).sort((x,P)=>P.length-x.length).join("|");l=l.replace(new RegExp("\\b("+v+")\\s*([+-])\\s*(\\d+)(?![\\d.])","g"),"$1 $2 $3.0")}}{const w=new Set,A=/\b(?:int|uint)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let b;for(;(b=A.exec(l))!==null;)w.add(b[1]);l=l.replace(/\buint\b/g,"int"),l=l.replace(/\b([A-Za-z_][A-Za-z0-9_]*)\s*%\s*(\d+)(?![\d.])/g,(v,x,P)=>w.has(x)?v:"mod("+x+", "+P+".0)"),l=l.replace(/\bint\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*mod\(([^;]*)\);/g,"int $1 = int(mod($2));")}l=l.replace(/\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^;()\n,]+);/g,(w,A,b,v)=>{const x=v.trim();return/^(vec[234]|mat[234]|int\b|float\b)/.test(x)?w:A+" "+b+" = "+A+"("+x+");"});for(const w of["mix","clamp","step","smoothstep","min","max","mod","pow"])l=Ft(l,w,A=>w+"("+A.replace(/(?<![A-Za-z0-9_.])(\d+)(?![.\d])/g,"$1.0")+")");l=Ft(l,"clamp",w=>{const A=kr(w);if(A.length!==3)return"clamp("+w+")";const b=A[0].trim(),v=A[1].trim(),x=P=>/^-?\d+\.?\d*$/.test(P);return x(b)&&x(v)&&Number(b)===0&&Number(v)===1?"clamp("+A[2].trim()+", "+b+", "+v+")":"clamp("+w+")"}),l=l.replace(/(\.\d+)\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=l.replace(/([)\]])\s*([+-])\s*(\d+)(?![\d.])/g,"$1 $2 $3.0"),l=Ft(l,"smoothstep",w=>{const A=kr(w);return A.length===3&&A[1].trim()==="0.0"&&A[0].trim()!=="0.0"?"(1.0 - smoothstep(0.0, "+A[0].trim()+", "+A[2].trim()+"))":"smoothstep("+w+")"});{const w=new Map,A=/\b(?:uniform|varying|attribute|in|out)?\s*\b(vec([234]))\s+([A-Za-z_]\w*)/g;let b;for(;(b=A.exec(l))!==null;)w.set(b[3],Number(b[2]));if(w.size>0){const v={2:"xy",3:"xyz",4:"xyzw"};l=l.replace(/(^|[;{}\n]\s*)([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*)\s*;/g,(x,P,S,k)=>{const _=w.get(S),I=w.get(k);return!_||!I||_>=I?x:P+S+" = "+k+"."+v[_]+";"}),l=l.replace(/(^|[;{}\n]\s*)([A-Za-z_]\w*)\s*(\*=|\/=|\+=|-=)\s*([^;\n]+);/g,(x,P,S,k,_)=>{const I=w.get(S);if(!I)return x;const B=/^\s*(-?\s*(?:\d+(?:\.\d+)?f?|([A-Za-z_]\w*))\s*(?:[*/+\-]\s*(-?\s*(?:\d+(?:\.\d+)?f?|[A-Za-z_]\w*))\s*)?)$/.exec(_);if(!B)return x;const V=[B[2],B[3]].filter(Boolean);let O=null,U=0;for(const ie of V){const we=w.get(ie);if(we){O=ie,U=we;break}}if(!O||U<=I)return x;const W=v[I];return P+S+" "+k+" "+_.replace(O,O+"."+W)+";"})}{const v=new Set;{const S=/\b(?:uniform|varying|attribute|in|out|const)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let k;for(;(k=S.exec(l))!==null;)v.add(k[1])}const x=S=>{const k=S.trim();{const B=/^vec([234])\s*\(/.exec(k);if(B){let V=0;for(let O=k.indexOf("(");O<k.length;O++)if(k[O]==="(")V++;else if(k[O]===")"&&(V--,V===0))return O===k.length-1?Number(B[1]):0;return 0}}if(/^texture(?:Lod)?\s*\(/.test(k)){let B=0;for(let V=k.indexOf("(");V<k.length;V++)if(k[V]==="(")B++;else if(k[V]===")"&&(B--,B===0))return V===k.length-1?4:0;return 0}const _=/^([A-Za-z_]\w*)(?:\.([xyzwrgba]{2,4}))?\s*[*/]\s*([^*/]+)$/.exec(k);if(!_)return 0;const I=_[3];return/\bvec[234]\s*\(|\.[xyzwrgba]{2,4}\b/.test(I)?0:_[2]?_[2].length:v.has(_[1])?0:w.get(_[1])||0};l=l.replace(/(^|[;{}\n]\s*)float\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(S,k,_,I)=>x(I)<2?S:`${k}float ${_} = (${I.trim()}).x;`);const P={2:"xy",3:"xyz"};l=l.replace(/(^|[;{}\n]\s*)vec([23])\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(S,k,_,I,B)=>{const V=Number(_);return x(B)<=V?S:`${k}vec${_} ${I} = (${B.trim()}).${P[V]};`})}if(w.size>0){const v=new Set,x=/\b(?:uniform|varying|attribute|in|out)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let P;for(;(P=x.exec(l))!==null;)v.add(P[1]);const S="pow|saturate|clamp|smoothstep|step|abs|floor|ceil|fract|frac|sin|cos|tan|asin|acos|atan|sqrt|length|distance|dot|exp|log|sign|fmod|mod|min|max|mix|lerp",k=/^(?:length|distance|dot)$/,_=B=>{const V=B.match(new RegExp("^(?:"+S+")\\s*\\("));if(!V)return!1;let O=0;const U=V[0].length-1;let W=-1;for(let Y=U;Y<B.length;Y++)if(B[Y]==="(")O++;else if(B[Y]===")"&&(O--,O===0)){W=Y;break}if(W!==B.length-1)return!1;const ie=V[0].replace(/\s*\($/,"");if(k.test(ie))return!0;const we=B.slice(U+1,W);if(/\bvec[234]\s*\(/.test(we)||/\.[xyzwrgba]{2,4}\b/.test(we))return!1;for(const Y of w.keys()){const oe=Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp("(?<!\\.)\\b"+oe+"\\b(?!\\s*\\.[xyzwrgba]\\b)").test(we))return!1}return!0},I=new Set;if(l=l.replace(/(^|[;{}\n]\s*)([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(B,V,O,U)=>{const W=w.get(O);if(!W||v.has(O))return B;const ie=U.trim();if(new RegExp("^vec"+W+"\\s*\\(").test(ie)||w.has(ie))return B;const we=/^-?\d+(?:\.\d+)?(?:e[-+]?\d+)?$/i.test(ie),Y=v.has(ie);return!we&&!Y&&!_(ie)?B:(I.add(O),V+O+" = vec"+W+"("+ie+");")}),I.size>0){const B=[...I].sort((V,O)=>O.length-V.length).join("|");l=l.replace(new RegExp(`\\b([A-Za-z_]\\w*)\\s*([*/])\\s*(${B})\\b`,"g"),(V,O,U,W)=>w.has(O)?V:`${O} ${U} ${W}.x`),l=l.replace(new RegExp(`\\b(${B})\\s*([*/])\\s*([A-Za-z_]\\w*)\\b`,"g"),(V,O,U,W)=>w.has(W)?V:`${O}.x ${U} ${W}`)}}}l=l.replace(/(\.[xyzwrgba]{1,4}\s*=\s*)(-?\d+)\s*;/g,"$1$2.0;"),l=l.replace(/\b(float|vec2|vec3|vec4)\s+([A-Za-z_]\w*)\s*=\s*(-?\d+)\s*;/g,(w,A,b,v)=>A==="float"?`${A} ${b} = ${v}.0;`:`${A} ${b} = ${A}(${v}.0);`);{const w=new Set,A=/\b(?:uniform|varying|attribute|in|out)?\s*\bfloat\s+([A-Za-z_]\w*)/g;let b;for(;(b=A.exec(l))!==null;)w.add(b[1]);if(w.size>0){const v=[...w].sort((x,P)=>P.length-x.length).join("|");l=l.replace(new RegExp(`\\b(${v})\\s*=\\s*(-?\\d+)\\s*;`,"g"),"$1 = $2.0;"),l=l.replace(new RegExp(`\\b(${v})\\s*([-+*/]=)\\s*(-?\\d+)\\s*;`,"g"),"$1 $2 $3.0;")}}l=l.replace(/(\.[xyzwrgba]{1,4}\s*[-+*/]=\s*)(-?\d+)\s*;/g,"$1$2.0;");const h="step|smoothstep|saturate|clamp|mix|lerp|frac|fract|abs|floor|ceil|min|max|pow|sqrt|length|dot|distance";l=l.replace(new RegExp(`\\bint\\s+([A-Za-z_]\\w*)\\s*=\\s*((?:${h})\\s*\\()`,"g"),"float $1 = $2"),l=l.replace(/\bfloat\s+([A-Za-z_]\w*)\s*=\s*(int\s*\([^;]*\))\s*;/g,"float $1 = float($2);");{const w=Ch(l);w.size>0&&(l=l.replace(/\b(const\s+)?float\s+([A-Za-z_]\w*)\s*=\s*([^;{}]+);/g,(A,b,v,x)=>{const P=x.trim();if(/\./.test(P)||/[A-Za-z_]\w*\s*\(/.test(P))return A;const S=P.match(/[A-Za-z_]\w*/g);return!S||!S.length||!S.every(k=>w.has(k))?A:`${b||""}float ${v} = float(${P});`}))}{const w=Ch(l),A=new Set;let b;const v=/\b(?:const\s+|uniform\s+|varying\s+|in\s+|out\s+)*float\s+([A-Za-z_]\w*)/g;for(;(b=v.exec(l))!==null;)A.add(b[1]);for(const x of[...w])A.has(x)&&(w.delete(x),A.delete(x));if(w.size>0&&A.size>0){const x=[...w].sort((S,k)=>k.length-S.length).join("|"),P=[...A].sort((S,k)=>k.length-S.length).join("|");l=l.replace(new RegExp(`\\b(${x})\\s*([*/+-])\\s*(${P})\\b`,"g"),(S,k,_,I)=>`float(${k}) ${_} ${I}`),l=l.replace(new RegExp(`\\b(${P})\\s*([*/+-])\\s*(${x})\\b`,"g"),(S,k,_,I)=>`${k} ${_} float(${I})`)}}{const w=new Set,A=/\bbool\s+([A-Za-z_]\w*)\s*=/g;let b;for(;(b=A.exec(l))!==null;)w.add(b[1]);if(w.size>0){const v=[...w].join("|");l=l.replace(new RegExp(`([-+*/]=\\s*)(${v})\\b`,"g"),(x,P,S)=>`${P}float(${S})`)}}{const w=/\(\s*([^()&|]+?)\s*(<=|>=|<|>|==|!=)\s*([^()&|]+?)\s*\)/g;l=l.replace(new RegExp(w.source+"\\s*([*/])","g"),(A,b,v,x,P)=>`float(${b.trim()} ${v} ${x.trim()}) ${P}`),l=l.replace(new RegExp("([-+*/]=\\s*)"+w.source,"g"),(A,b,v,x,P)=>`${b}float(${v.trim()} ${x} ${P.trim()})`)}{const w=new Set;for(const A of l.matchAll(/\bbool\s+([A-Za-z_]\w*)\s*(?=[=;,)\[])/g))w.add(A[1]);l=Ab(l,w)}{const w=new Set;for(const A of l.matchAll(/\b(?:uniform\s+)?(?:highp|mediump|lowp\s+)?float\s+([A-Za-z_]\w*)\s*\[/g))w.add(A[1]);if(w.size){const A=[...w].sort((S,k)=>k.length-S.length).join("|"),b=new RegExp("\\b("+A+")\\s*\\[","g");let v="",x=0,P;for(;P=b.exec(l);){const S=P.index+P[0].length-1,k=fo(l,S,"[","]");if(k<0)break;let _=k+1;for(;_<l.length&&/[ \t]/.test(l[_]);)_++;if(l[_]!=="["){const U=l.slice(S+1,k).trim(),W=/\d\.\d/.test(U)||/^[A-Za-z_]\w*$/.test(U)&&new RegExp("\\bfloat\\s+"+U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b").test(l),ie=/^\s*int\s*\(/.test(U)||/^-?\d+$/.test(U);if(W&&!ie){v+=l.slice(x,P.index),v+=P[1]+"[int("+U+")]",x=k+1,b.lastIndex=x;continue}b.lastIndex=k+1;continue}const I=fo(l,_,"[","]");if(I<0)break;const B=l.slice(S+1,k),V=l.slice(_+1,I);v+=l.slice(x,P.index),v+=P[1]+"[int(("+B+")) * 4 + int(("+V+"))]",x=I+1,b.lastIndex=x}l=v+l.slice(x)}}l=Ft(l,"mix",(w,A)=>{const b=kr(w);if(b.length!==3)return"mix("+w+")";const v=_=>{const I=_.trim(),B=/\.([xyzwrgba]{1,4})\s*$/.exec(I);if(B)return B[1].length;const V=/^vec([234])\s*\(/.exec(I);if(V)return Number(V[1]);if(!/^[A-Za-z_]\w*$/.test(I))return 0;const O=new RegExp("\\b(vec([234])|float)\\s+"+I+"\\b","g");let U=0,W;for(;(W=O.exec(l))!==null&&W.index<A;)U=W[1].startsWith("vec")?Number(W[2]):1;return U},x=b[0].trim(),P=b[1].trim(),S=v(x),k=v(P);if(S>=2&&k>=2&&S!==k){const _=Math.min(S,k),I=_===2?".xy":_===3?".xyz":"";return I?"mix("+(S>_?x+I:x)+", "+(k>_?P+I:P)+", "+b[2].trim()+")":"mix("+w+")"}return"mix("+w+")"});{const w=/\b(vec([234]))\s+([A-Za-z_]\w*)\s*\(/g;let A="",b=0,v;for(;v=w.exec(l);){const x=Mh(l,v.index+v[0].length-1);if(x<0)break;let P=x+1;for(;P<l.length&&/\s/.test(l[P]);)P++;if(l[P]!=="{")continue;const S=fo(l,P,"{","}");if(S<0)break;const k=Number(v[2]);if(k>=4){w.lastIndex=S;continue}let _=l.slice(P+1,S);const I=new Map;for(const V of l.slice(0,v.index).matchAll(/\buniform\s+(?:highp|mediump|lowp\s+)?(vec([234]))\s+([A-Za-z_]\w*)/g))I.set(V[3],Number(V[2]));for(const V of _.matchAll(/\b(vec([234]))\s+([A-Za-z_]\w*)/g))I.set(V[3],Number(V[2]));const B=k===2?"xy":"xyz";_=_.replace(/\breturn\s+([A-Za-z_]\w*)\s*;/g,(V,O)=>{const U=I.get(O);return U&&U>k?"return "+O+"."+B+";":V}),A+=l.slice(b,P+1)+_,b=S,w.lastIndex=S}l=A+l.slice(b)}const p=new Set,m=/\b(?:uniform\s+)?(?:mat4|mat3|mat2|float4x4)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let g;for(;(g=m.exec(l))!==null;)p.add(g[1]);if(l=Ft(l,"mul",w=>{const A=kr(w);if(A.length!==2)return"mul("+w+")";const b=A[0].trim(),v=A[1].trim(),x=P=>p.has(P.split(/[\[.\s]/)[0])||/^mat[234]\(/.test(P);return x(b)&&x(v)?"(transpose("+v+") * transpose("+b+"))":x(v)?"(transpose("+v+") * "+b+")":"("+b+" * "+v+")"}),l=l.replace(/\blerp\b/g,"mix").replace(/\bfrac\b/g,"fract"),l=Ft(l,"atan2",w=>"atan("+w+")"),l=Ft(l,"fmod",w=>{const A=kr(w);if(A.length!==2)return"mod("+w+")";const b=A[0].trim(),v=A[1].trim();return"(("+b+") - ("+v+") * trunc(("+b+") / ("+v+")))"}),l=Ft(l,"ddx",w=>"dFdx("+w+")"),l=Ft(l,"ddy",w=>"dFdy("+w+")"),l=Ft(l,"CAST3X3",w=>"mat3("+w+")"),e==="vert")l=l.replace(/\battribute\b/g,"in").replace(/\bvarying\b/g,"out");else{if(l=l.replace(/\bvarying\b/g,"in").replace(/\battribute\b/g,"in"),typeof i=="string"&&i){const b=new Map,v=new Set,x=/^\s*(?:varying|out)\s+(?:highp|mediump|lowp\s+)?(vec[234]|float)\s+([A-Za-z_]\w*)\s*;/gm;let P;for(;(P=x.exec(i))!==null;){const _=b.get(P[2]);_!==void 0&&_!==P[1]&&v.add(P[2]),b.set(P[2],P[1])}const S={float:1,vec2:2,vec3:3,vec4:4},k=new Map;if(l=l.replace(/^(\s*in\s+(?:highp|mediump|lowp\s+)?)(vec[234]|float)(\s+)([A-Za-z_]\w*)(\s*;)/gm,(_,I,B,V,O,U)=>{const W=b.get(O);return!W||v.has(O)||S[W]<=S[B]?_:(k.set(O,S[B]),I+W+V+O+U)}),k.size>0){const _={1:"x",2:"xy",3:"xyz"};for(const[I,B]of k){const V=_[B];V&&(l=l.split(`
17
+ `).map(O=>/^\s*in\s/.test(O)?O:O.replace(new RegExp("\\b"+I+"\\b(?!\\s*[.\\w])","g"),I+"."+V)).join(`
18
+ `))}}l=l.replace(/^(\s*in\s+(?:highp|mediump|lowp\s+)?)(vec[234]|float)(\s+)([A-Za-z_]\w*)(\s*;)/gm,(_,I,B,V,O,U)=>{const W=b.get(O);if(!W||v.has(O)||S[W]>=S[B])return _;const ie="xyzw",we="rgba";return new RegExp("\\b"+O+"\\s*\\.\\s*["+ie+we+"]*["+ie.slice(S[W])+we.slice(S[W])+"]").test(l)?_:I+W+V+O+U})}{const b=new Map,v=/^\s*in\s+(?:highp|mediump|lowp\s+)?(vec[34])\s+([A-Za-z_]\w*)\s*;/gm;let x;for(;(x=v.exec(l))!==null;)b.set(x[2],Number(x[1].slice(3)));const P=new Map(b),S=/\b(vec[34])\s+([A-Za-z_]\w*)\s*[=;]/g;for(;(x=S.exec(l))!==null;)P.has(x[2])||P.set(x[2],Number(x[1].slice(3)));if(P.size>0){const k=_=>{const I=_.trim();if(!I)return _;const B=/^([A-Za-z_]\w*)$/.exec(I);if(B&&P.has(B[1]))return B[1]+".xy";const V=/^([A-Za-z_]\w*)(\s*[+\-].+)$/.exec(I);return V&&P.has(V[1])?"("+V[1]+".xy"+V[2]+")":_};for(const _ of["textureLod","texture"])l=Ft(l,_,I=>{const B=kr(I);return B.length>=2&&(B[1]=k(B[1])),_+"("+B.join(", ")+")"})}b.size>0&&(l=l.split(`
19
+ `).map(k=>{if(!/\bvec2\s+[A-Za-z_]\w*\s*=/.test(k))return k;let _=k;for(const I of b.keys())_=_.replace(new RegExp("\\b"+I+"\\b(?!\\s*[.\\w])","g"),I+".xy");return _}).join(`
20
+ `))}const w=new Set,A=new Set;{const b=/^\s*in\s+(?:highp|mediump|lowp\s+)?(vec[234]|float)\s+([A-Za-z_]\w*)\s*;/gm;let v;for(;(v=b.exec(l))!==null;)A.add(v[2])}for(const b of A)new RegExp("\\b"+b+"\\b\\s*(?:\\.[xyzwrgba]{1,4})?\\s*(?:[-+*/]?=(?!=)|\\+\\+|--)").test(l)&&w.add(b);if(w.size>0){const b=l.search(/\bvoid\s+main\s*\([^)]*\)\s*\{/);if(b!==-1){const v=l.indexOf("{",b),x=l.slice(0,v+1);let P=l.slice(v+1);const S=[];for(const k of w){if(new RegExp("(?:^|[;{}\\n])\\s*(?:highp|mediump|lowp\\s+)?(?:vec[234]|float|int|bool)\\s+"+k+"\\s*[=;]").test(P))continue;const I=new RegExp("^\\s*in\\s+(?:highp|mediump|lowp\\s+)?(vec[234]|float)\\s+"+k+"\\s*;","m").exec(l),B=I?I[1]:"vec4";S.push(" "+B+" "+k+"_rw = "+k+";"),P=Zs(P,k,k+"_rw")}S.length>0&&(P=`
21
+ `+S.map(k=>k.replace(/= (\w+)_rw;/,"= $1;")).join(`
22
22
  `)+`
23
- `+T),l=A+T}}}l=l.replace(/\[(?:unroll|loop|branch|flatten)\]\s*/g,""),l=l.replace(/\bstatic\s+/g,""),d.length>0&&(l=l.replace(/\u0003(\u0004+)\u0003/g,(y,b)=>d[b.length-1]));{const y=new Set;for(const b of l.matchAll(/\b(?:uniform[ \t]+)?(?:highp|mediump|lowp)?[ \t]*float[ \t]+([A-Za-z_]\w*)[ \t]*[;=]/g))y.add(b[1]);if(y.size){const b=v=>{const k=v.trim().startsWith("-"),A=v.replace(/^-\s*/,"").trim();return y.has(A)?(k?"-":"")+"int("+A+")":v};l=l.replace(/(for\s*\(\s*(?:int|uint)\s+(\w+)\s*=\s*)(-?\s*[A-Za-z_]\w*|-?\s*\d+)(\s*;\s*\2\s*[<>]=?\s*)(-?\s*[A-Za-z_]\w*|-?\s*\d+)(\s*;)/g,(v,k,A,T,S,P,M)=>k+b(T)+S+b(P)+M)}}{const y=new Set;l=l.split(`
24
- `).map(b=>{const v=/^[ \t]*uniform[ \t]+(?:highp|mediump|lowp[ \t]+)?[A-Za-z0-9_]+[ \t]+([A-Za-z_][A-Za-z0-9_]*)/.exec(b);if(!v)return b;const k=v[1];return y.has(k)?"":(y.add(k),b)}).join(`
25
- `)}f.length>0&&(l=l.replace(/\u0001(\u0002+)\u0001/g,(y,b)=>f[b.length-1]));let w=`#version 300 es
26
- `;return e==="vert"&&(w+=`precision highp float;
27
- `),e==="frag"&&(w+=`precision highp float;
28
- `,/\bgl_FragColor\b/.test(l)&&(w+=`out vec4 fragColor;
29
- `,l=l.replace(/\bgl_FragColor\b/g,"fragColor"))),w+l}const Zf={center:[.5,.5],centre:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],topleft:[0,0],topright:[1,0],bottomleft:[0,1],bottomright:[1,1]},Jf={2:"multiply",6:"additive",7:"screen",9:"additive",31:"additive"},ny={screen:1,multiply:2},ed=`// WE common_blending.h\uFF08\u91CD\u5EFA\u5B50\u96C6\uFF09
23
+ `+P),l=x+P}}}l=l.replace(/\[(?:unroll|loop|branch|flatten)\]\s*/g,""),l=l.replace(/\bstatic\s+/g,""),f.length>0&&(l=l.replace(/\u0003(\u0004+)\u0003/g,(w,A)=>f[A.length-1]));{const w=new Set;for(const A of l.matchAll(/\b(?:uniform[ \t]+)?(?:highp|mediump|lowp)?[ \t]*float[ \t]+([A-Za-z_]\w*)[ \t]*[;=]/g))w.add(A[1]);if(w.size){const A=b=>{const v=b.trim().startsWith("-"),x=b.replace(/^-\s*/,"").trim();return w.has(x)?(v?"-":"")+"int("+x+")":b};l=l.replace(/(for\s*\(\s*(?:int|uint)\s+(\w+)\s*=\s*)(-?\s*[A-Za-z_]\w*|-?\s*\d+)(\s*;\s*\2\s*[<>]=?\s*)(-?\s*[A-Za-z_]\w*|-?\s*\d+)(\s*;)/g,(b,v,x,P,S,k,_)=>v+A(P)+S+A(k)+_)}}{const w=new Set;l=l.split(`
24
+ `).map(A=>{const b=/^[ \t]*uniform[ \t]+(?:highp|mediump|lowp[ \t]+)?[A-Za-z0-9_]+[ \t]+([A-Za-z_][A-Za-z0-9_]*)/.exec(A);if(!b)return A;const v=b[1];return w.has(v)?"":(w.add(v),A)}).join(`
25
+ `)}{const w=()=>{const S=new Set,k=/\b(?:uniform\s+)?(?:highp\s+|mediump\s+|lowp\s+)?(?:float|vec2|vec3|vec4|mat2|mat3|mat4)\s+([A-Za-z_][A-Za-z0-9_]*)/g;let _;for(;(_=k.exec(l))!==null;)S.add(_[1]);return S},A=(S,k)=>{if(!S)return!1;if(/\d*\.\d|\d\./.test(S)||/^float\s*\(/.test(S))return!0;const _=/^[A-Za-z_]\w*/.exec(S);return!!(_&&k.has(_[0]))},b=(S,k)=>{let _="",I=0;for(;I<S.length;){const B=/\bint\s*\(/.exec(S.slice(I));if(!B){_+=S.slice(I);break}const V=I+B.index;_+=S.slice(I,V);let O=0,U=V+B[0].length-1;for(;U<S.length;U++)if(S[U]==="(")O++;else if(S[U]===")"&&(O--,O===0)){U++;break}const W=S.slice(V,U),ie=S.slice(0,V),we=S.slice(U);if(/\b(?:float|int|uint)\s*\(\s*$/.test(ie)){_+=W,I=U;continue}{const Le=/\bfor\s*\(/g;let Ne=-1,De;for(;(De=Le.exec(ie))!==null;)Ne=De.index;if(Ne>=0){const Re=ie.slice(Ne);let Fe=0,Xe=!1;for(const $e of Re)$e==="("?(Fe++,Xe=!0):$e===")"&&(Fe--,Fe<=0&&(Xe=!1));if(Xe&&Fe>0){_+=W,I=U;continue}}}const Y=/(?:([^\s;,(]+)\s*)?([+\-*/%<>=!]=?|[<>])\s*$/.exec(ie),oe=/^\s*([+\-*/%<>=!]=?|[<>])\s*([^\s;,)]+)?/.exec(we),he=Y&&Y[1]?Y[1]:null,Ae=oe&&oe[2]?oe[2]:null,Pe=!!(Y&&Y[2])||!!(oe&&oe[1]),Ce=(he&&A(he,k)?he:null)||(Ae&&A(Ae,k)?Ae:null);Pe&&Ce?_+="float("+W+")":_+=W,I=U}return _},v=(S,k)=>{S=S.replace(/\b([A-Za-z_]\w*)\s*%=\s*([^;]+);/g,(I,B,V)=>{if(!k.has(B))return I;const O=/^\s*(\d+)\s*$/.exec(V);return`${B} = mod(${B}, ${O?O[1]+".0":V.trim()});`});const _=Array.from(k).sort((I,B)=>B.length-I.length).join("|");return _&&(S=S.replace(new RegExp("\\b("+_+")\\s*%\\s*([^=;]+)","g"),(I,B,V)=>/^\s*[A-Za-z_]/.test(V)&&!k.has(V.trim())?I:`${B} % ${V}`)),S},x=S=>S.replace(/\bconst\s+((?:highp|mediump|lowp)\s+)?(float|int|bool|vec2|vec3|vec4|mat2|mat3|mat4)\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g,(k,_,I,B,V,O)=>{let U=0;for(let ie=0;ie<O;ie++){const we=S[ie];we==="{"?U++:we==="}"&&U--}if(U<=0)return k;const W=V.replace(/\b(vec2|vec3|vec4|mat2|mat3|mat4|float|int|bool|true|false)\b/g," ");return/[A-Za-z_]/.test(W)?`${I} ${B} = ${V};`:k});l=l.replace(/\b((?:highp|mediump|lowp)\s+)?(float|vec2|vec3|vec4)(\s+[A-Za-z_]\w*\s*=\s*)(\((?:[^()]|\([^()]*\))*\s*(?:[<>]=?|==|!=)\s*(?:[^()]|\([^()]*\))*\))\s*;/g,(S,k,_,I,B)=>`${k||""}${_}${I}${_}(${B});`);const P=w();l=b(l,P),l=v(l,P),l=x(l)}d.length>0&&(l=l.replace(/\u0001(\u0002+)\u0001/g,(w,A)=>d[A.length-1]));let y=`#version 300 es
26
+ `;return e==="vert"&&(y+=`precision highp float;
27
+ `),e==="frag"&&(y+=`precision highp float;
28
+ `,/\bgl_FragColor\b/.test(l)&&(y+=`out vec4 fragColor;
29
+ `,l=l.replace(/\bgl_FragColor\b/g,"fragColor"))),y+l}const Rh={center:[.5,.5],centre:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],topleft:[0,0],topright:[1,0],bottomleft:[0,1],bottomright:[1,1]},Bh={2:"multiply",6:"additive",7:"screen",9:"additive",31:"additive"},xb={screen:1,multiply:2},Fh=`// WE common_blending.h\uFF08\u91CD\u5EFA\u5B50\u96C6\uFF09
30
30
  vec3 weBlendOverlay(vec3 a, vec3 b) {
31
31
  return vec3(
32
32
  a.r < 0.5 ? 2.0 * a.r * b.r : 1.0 - 2.0 * (1.0 - a.r) * (1.0 - b.r),
@@ -158,7 +158,6 @@ vec3 ApplyBlending(int mode, vec3 A, vec3 B, float opacity) {
158
158
  else { r = mix(A, B, opacity); } // Normal(\u542B 0)
159
159
  // CPU \u53C2\u8003\uFF08effects.js applyBlending\uFF09\uFF1A5/10/30/31/32 \u76F4\u63A5\u8FD4\u56DE\u4E0D\u7ECF opacity \u6743\u91CD\uFF0C
160
160
  // \u5176\u4F59\u7EDF\u4E00 mix(A, r, opacity) \u56DE\u5F52\u539F\u8272\u3002
161
- //
162
161
  // [we-scene patch] **mode 0 \u4E5F\u5FC5\u987B\u6392\u9664**\uFF1A\u5B83\u7684\u5206\u652F\u5DF2\u7ECF\u662F mix(A, B, opacity)\uFF0C
163
162
  // \u518D\u5957\u4E00\u5C42\u7B49\u4E8E\u6309 opacity\xB2 \u52A0\u6743\u3002effects.js \u7684 default \u5206\u652F\u662F switch \u5185\u76F4\u63A5
164
163
  // return mix3(A, B, opacity)\u3001\u4E0D\u8D70 per() \u7684\u4E8C\u6B21\u52A0\u6743\uFF0C\u8FD9\u91CC\u6F0F\u6392\u4E86 0\u3002
@@ -170,7 +169,15 @@ vec3 ApplyBlending(int mode, vec3 A, vec3 B, float opacity) {
170
169
  r = mix(A, r, opacity);
171
170
  }
172
171
  return r;
173
- }`,ry=`#version 300 es
172
+ }
173
+ // [we-scene patch 3351179520] combo \u66FF\u6362\u4F1A\u628A int \u578B combo \u503C\u5199\u6210\u6D6E\u70B9\u5B57\u9762\u91CF
174
+ // \uFF08BLENDMODE \u2192 0.0\uFF09\uFF0CGLSL ES \u6CA1\u6709 float\u2192int \u9690\u5F0F\u8F6C\u6362\uFF0Ccircular_text \u7B49
175
+ // workshop shader \u6309 \`ApplyBlending(0.0, \u2026)\` \u8C03\u7528\u4F1A\u300Cno matching overloaded
176
+ // function found\u300D\u6574\u6761 pass \u62A5\u5E9F\u3002\u52A0\u4E00\u4E2A float \u91CD\u8F7D\u8F6C\u56DE int\uFF1A\u5DF2\u6709\u8C03\u7528\u70B9
177
+ // \uFF08int \u5B57\u9762\u91CF/uniform\uFF09\u4ECD\u7CBE\u786E\u547D\u4E2D\u539F\u91CD\u8F7D\uFF0C\u4E0D\u53D7\u5F71\u54CD\u3002
178
+ vec3 ApplyBlending(float mode, vec3 A, vec3 B, float opacity) {
179
+ return ApplyBlending(int(mode + 0.5), A, B, opacity);
180
+ }`,kb=`#version 300 es
174
181
  precision mediump float;
175
182
  in vec2 v_UV;
176
183
  uniform sampler2D u_Tex;
@@ -179,7 +186,7 @@ uniform int u_BlendMode;
179
186
  uniform vec2 u_CanvasSize;
180
187
  uniform float u_Opacity;
181
188
  out vec4 fragColor;
182
- ${ed}
189
+ ${Fh}
183
190
  void main() {
184
191
  vec4 src = texture(u_Tex, v_UV);
185
192
  // \u80CC\u666F\u6309**\u7247\u5143\u7684\u5C4F\u5E55\u4F4D\u7F6E**\u91C7\u6837\uFF1Agl_FragCoord \u539F\u70B9\u5728\u5DE6\u4E0B\uFF0C\u4E0E copyTexImage2D
@@ -188,7 +195,7 @@ void main() {
188
195
  vec3 r = ApplyBlending(u_BlendMode, dst, src.rgb, src.a * u_Opacity);
189
196
  // GL \u6DF7\u5408\u5DF2\u5173\u95ED\uFF1A\u8FD9\u91CC\u5199\u51FA\u7684\u5C31\u662F\u6700\u7EC8\u50CF\u7D20\uFF0Calpha \u6052 1\uFF08\u753B\u5E03\u65E0 alpha \u901A\u9053\uFF09\u3002
190
197
  fragColor = vec4(r, 1.0);
191
- }`,iy=`#version 300 es
198
+ }`,Tb=`#version 300 es
192
199
  in vec3 a_Position;
193
200
  in vec2 a_TexCoord;
194
201
  uniform vec2 u_Texel; // 1/\u573A\u666F\u7EB9\u7406\u5C3A\u5BF8
@@ -203,7 +210,7 @@ void main() {
203
210
  v_TexCoord[1] = a_TexCoord + vec2(offsets.x, -offsets.y);
204
211
  v_TexCoord[2] = a_TexCoord + vec2(-offsets.x, offsets.y);
205
212
  v_TexCoord[3] = a_TexCoord + offsets;
206
- }`,sy=`#version 300 es
213
+ }`,Sb=`#version 300 es
207
214
  precision mediump float;
208
215
  in vec2 v_TexCoord[4];
209
216
  in float v_Damp;
@@ -247,7 +254,7 @@ void main() {
247
254
  }
248
255
  }
249
256
  fragColor = vec4(lightMap, 1.0);
250
- }`,ay=`#version 300 es
257
+ }`,Pb=`#version 300 es
251
258
  in vec3 a_Position;
252
259
  in vec2 a_TexCoord;
253
260
  uniform vec2 u_Texel; // 1/\u6E90\u7EB9\u7406\u5C3A\u5BF8
@@ -260,7 +267,7 @@ void main() {
260
267
  v_SizeMultiplier = u_Texel * vec2(1.0, ratio.x / ratio.y) * u_Radius;
261
268
  gl_Position = vec4(a_Position, 1.0);
262
269
  v_TexCoord = a_TexCoord;
263
- }`,oy=`#version 300 es
270
+ }`,_b=`#version 300 es
264
271
  precision mediump float;
265
272
  in vec2 v_TexCoord;
266
273
  in vec2 v_SizeMultiplier;
@@ -289,7 +296,7 @@ void main() {
289
296
  albedo = albedo / divisor;
290
297
  }
291
298
  fragColor = albedo;
292
- }`,cy=`#version 300 es
299
+ }`,Eb=`#version 300 es
293
300
  precision mediump float;
294
301
  in vec2 v_UV;
295
302
  uniform sampler2D u_Tex; // \u6A21\u7CCA\u540E\u7684 bloom
@@ -303,7 +310,7 @@ void main() {
303
310
  // Add\uFF08ApplyBlending 31\uFF09\uFF1Argb = base + bloom\uFF1BGL \u4FA7 blendFunc(ONE, ONE)\uFF0C
304
311
  // dst \u5C31\u662F\u753B\u5E03\u91CC\u7684 base\u3002alpha +0 = \u4FDD\u6301\u573A\u666F alpha\uFF08\u753B\u5E03\u672C\u5C31\u65E0 alpha \u901A\u9053\uFF09\u3002
305
312
  fragColor = vec4(bloom, 0.0);
306
- }`,ds=`#version 300 es
313
+ }`,hs=`#version 300 es
307
314
  in vec3 a_Position;
308
315
  in vec2 a_TexCoord;
309
316
  uniform mat4 u_MVP;
@@ -311,7 +318,7 @@ out vec2 v_UV;
311
318
  void main() {
312
319
  gl_Position = u_MVP * vec4(a_Position, 1.0);
313
320
  v_UV = a_TexCoord;
314
- }`,ly=`#version 300 es
321
+ }`,Mb=`#version 300 es
315
322
  precision mediump float;
316
323
  in vec2 v_UV;
317
324
  uniform sampler2D u_Tex;
@@ -327,7 +334,7 @@ void main() {
327
334
  if (u_BlendPrep == 1) c.rgb *= c.a;
328
335
  else if (u_BlendPrep == 2) c.rgb = mix(vec3(1.0), c.rgb, c.a);
329
336
  fragColor = c;
330
- }`,uy=`#version 300 es
337
+ }`,Cb=`#version 300 es
331
338
  precision mediump float;
332
339
  in vec2 v_UV;
333
340
  uniform sampler2D u_Tex;
@@ -338,15 +345,52 @@ void main() {
338
345
  if (u_BlendPrep == 1) c.rgb *= c.a;
339
346
  else if (u_BlendPrep == 2) c.rgb = mix(vec3(1.0), c.rgb, c.a);
340
347
  fragColor = c;
341
- }`,fy=`#version 300 es
348
+ }`,Ib=`#version 300 es
342
349
  precision mediump float;
343
350
  in vec2 v_UV;
344
351
  uniform sampler2D u_Tex;
345
352
  out vec4 fragColor;
346
353
  void main() {
347
354
  fragColor = vec4(texture(u_Tex, v_UV).rgb, 1.0);
348
- }`;function dy(t,e){return new Float32Array([0,e,0,0,1,0,0,0,0,0,t,e,0,1,1,t,e,0,1,1,0,0,0,0,0,t,0,0,1,0])}function hy(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,1,0,1,1,-1,-1,0,0,0,1,-1,0,1,0])}function my(){return new Float32Array([-.5,.5,0,0,1,-.5,-.5,0,0,0,.5,.5,0,1,1,.5,.5,0,1,1,-.5,-.5,0,0,0,.5,-.5,0,1,0])}const py={5126:"float",35664:"vec2",35665:"vec3",35666:"vec4",5124:"int",35667:"ivec2",35668:"ivec3",35669:"ivec4",35670:"bool",35676:"mat4",35675:"mat3"};function dr(t,e,n){const r=td(t,t.VERTEX_SHADER,e),i=td(t,t.FRAGMENT_SHADER,n),s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,i),t.bindAttribLocation(s,0,"a_Position"),t.bindAttribLocation(s,1,"a_TexCoord"),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error("\u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25: "+t.getProgramInfoLog(s));return s}function td(t,e,n){const r=t.createShader(e);if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("\u7740\u8272\u5668\u7F16\u8BD1\u5931\u8D25: "+t.getShaderInfoLog(r));return r}function mc(t){t!==null&&typeof t=="object"&&"value"in t&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return[e[0]||0,e[1]||0,e[2]||0]}function pc(t,e,n,r,i=null){const s=t.createTexture();return t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i?(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i),t.generateMipmap(t.TEXTURE_2D)):(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,n,r,0,t.RGBA,t.UNSIGNED_BYTE,e)),s}function gy(t,e,n=!1){const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR);const i=e[0];if(i.bitmap)t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i.bitmap);else if(n&&i.rgba){const s=i.width*i.height,a=new Uint8Array(s*2);for(let c=0;c<s;c++)a[c*2]=i.rgba[c*4+3],a[c*2+1]=i.rgba[c*4];const o=t.getParameter(t.UNPACK_ALIGNMENT);t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RG8,i.width,i.height,0,t.RG,t.UNSIGNED_BYTE,a),t.pixelStorei(t.UNPACK_ALIGNMENT,o)}else t.texImage2D(t.TEXTURE_2D,0,t.RGBA,i.width,i.height,0,t.RGBA,t.UNSIGNED_BYTE,i.rgba);return t.generateMipmap(t.TEXTURE_2D),r}function gc(t,e,n,r,i){const s=1-i;return s*s*s*t+3*s*s*i*e+3*s*i*i*n+i*i*i*r}function yy(t,e,n,r,i){if(i<=t)return 0;if(i>=r)return 1;let s=r-t>1e-9?(i-t)/(r-t):.5;for(let c=0;c<8;c++){const u=gc(t,e,n,r,s)-i;if(Math.abs(u)<1e-6)return s;const l=1-s,f=3*l*l*(e-t)+6*l*s*(n-e)+3*s*s*(r-n);if(Math.abs(f)<1e-9)break;const d=s-u/f;if(d<0||d>1||!Number.isFinite(d))break;s=d}let a=0,o=1;for(let c=0;c<40;c++)s=(a+o)/2,gc(t,e,n,r,s)<i?a=s:o=s;return s}function ba(t,e,n){if(!t||t.length===0)return 0;if(t.length===1)return Number(t[0].value)||0;if(n&&n.length>0){const P=t[0],M=t[t.length-1],B=n.length-M.frame;if(B>1e-9&&e>M.frame&&e<=n.length)return ba([{frame:0,value:M.value,front:M.front,back:M.back},{frame:B,value:P.value,front:P.front,back:P.back}],e-M.frame)}if(e<=t[0].frame)return Number(t[0].value)||0;const r=t[t.length-1];if(e>=r.frame)return Number(r.value)||0;let i=0,s=t.length-1;for(;s-i>1;){const P=i+s>>1;t[P].frame<=e?i=P:s=P}const a=t[i],o=t[s],c=a.frame,u=o.frame,l=Number(a.value)||0,f=Number(o.value)||0,d=u-c;if(d<=0)return f;const h=a.front,p=o.back,m=d/3,g=!!(h&&h.enabled),w=!!(p&&p.enabled),y=g?Math.abs(Number(h.x)||0):1,b=w?Math.abs(Number(p.x)||0):1,v=c+Math.min(y,1.5)*m,k=u-Math.min(b,1.5)*m,A=g?l+(Number(h.y)||0):l+(f-l)/3,T=w?f+(Number(p.y)||0):f-(f-l)/3,S=yy(c,v,k,u,e);return gc(l,A,T,f,S)}function nd(t,e,n){const r=e>0?e:1;if(n==="loop"){let i=t%r;return i<0&&(i+=r),i}if(n==="mirror"){const i=r*2;let s=t%i;return s<0&&(s+=i),s<=r?s:i-s}return Math.max(0,Math.min(r,t))}function by(t){return Array.isArray(t)?t:typeof t=="string"?t.trim().split(/\s+/).map(Number):Number.isFinite(t)?[t]:[]}function rd(t,e,n,r,i){if(!t||!t.length||e===n)return[];const s=n>e,a=r>0?r:1,o=[];if(i==="single")for(const c of t)(s?c.frame>e&&c.frame<=n:c.frame>=n&&c.frame<e)&&o.push({at:c.frame,e:c});else if(i==="loop"){const c=Math.floor(Math.min(e,n)/a),u=Math.floor(Math.max(e,n)/a);for(let l=c;l<=u;l++)for(const f of t){const d=l*a+f.frame;(s?d>e&&d<=n:d>=n&&d<e)&&o.push({at:d,e:f})}}else{const c=a*2,u=Math.floor(Math.min(e,n)/c),l=Math.floor(Math.max(e,n)/c);for(let f=u;f<=l;f++)for(const d of t){const h=f*c+d.frame,p=f*c+2*a-d.frame;for(const m of h===p?[h]:[h,p])(s?m>e&&m<=n:m>=n&&m<e)&&o.push({at:m,e:d})}}return o.sort((c,u)=>s?c.at-u.at:u.at-c.at),o.map(c=>c.e)}function wy(t,e,n){const r=rd(t._events,e,n,t.frameCount||1,t.mode);for(const i of r)t._eventQueue.push(i)}function id(t,e){const n=t instanceof Map?t:new Map(Object.entries(t||{}));for(const[r,i]of n){if(!i||!i.parentKey)continue;const s=n.get(i.parentKey);if(!s||s===i){e&&e(`\u52A8\u753B\u8054\u52A8 parent \u60AC\u7A7A\uFF08\u9000\u5316\u4E3A\u72EC\u7ACB\uFF09\uFF1A${r} -> ${i.parentKey}`);continue}if(s.parentKey){e&&e(`\u52A8\u753B\u8054\u52A8\u591A\u7EA7 parent\uFF08\u4E0D\u652F\u6301\uFF0C\u9000\u5316\u4E3A\u72EC\u7ACB\uFF09\uFF1A${r} -> ${i.parentKey}`);continue}i.parent=s}return n}function sd(t){const e=t&&t.options||{},n=Number(e.fps)>0?Number(e.fps):30,r=Number(e.length)>0?Number(e.length):0,i=e.mode==="loop"||e.mode==="mirror"?e.mode:"single",s=typeof e.name=="string"?e.name:"",a=!!(t&&t.relative),o=e.wraploop===!0&&i==="loop",c=[];for(let m=0;;m++){const g=t&&t["c"+m];if(!Array.isArray(g))break;c.push(g)}const u=e.startpaused!==!0,l=[],f=e.parent&&typeof e.parent.key=="string"?e.parent.key:null,d=Array.isArray(e.children)?e.children.map(m=>m&&typeof m.key=="string"?m.key:null).filter(Boolean):[],h=Array.isArray(e.events)?e.events.filter(m=>m&&Number.isFinite(Number(m.frame))&&typeof m.name=="string").map(m=>({frame:Number(m.frame),name:m.name})):[],p={name:s,mode:i,fps:n,relative:a,channelCount:c.length,parentKey:f,childKeys:d,parent:null,frame:0,_playing:u,_rate:1,_ended:!1,_events:h,_eventQueue:[],get frameCount(){return r},get playing(){return p.parent?p.parent.playing:p._playing},set playing(m){p.parent?p.parent.playing=!!m:p._playing=!!m},get rate(){return p.parent?p.parent.rate:p._rate},set rate(m){const g=Number(m);Number.isFinite(g)&&(p.parent?p.parent.rate=g:p._rate=g)},get ended(){return p.parent?p.parent.ended:p._ended},set ended(m){p.parent?p.parent.ended=!!m:p._ended=!!m},play(){return p.parent?p.parent.play():(p._playing=!0,p._ended=!1,p)},pause(){return p.parent?p.parent.pause():(p._playing=!1,p)},stop(){return p.parent?p.parent.stop():(p._playing=!1,p.frame=0,p._ended=!1,p)},setFrame(m){if(p.parent)return p.parent.setFrame(m);const g=Number(m);return Number.isFinite(g)&&(p.frame=g),p},getFrame(){return p.parent?p.parent.getFrame():p.frame},setRate(m){return p.parent?p.parent.setRate(m):(p.rate=m,p)},addEndedCallback(m){return p.parent?p.parent.addEndedCallback(m):(typeof m=="function"&&l.push(m),p)},isPlaying(){return p.playing},setBlend(){return p},setVisible(){return p},advance(m){if(p.parent||!p._playing)return;const g=p.frame;if(p.frame+=(Number(m)||0)*n*p._rate,i==="single")if(p.frame>=r){if(p.frame=r,p._playing=!1,!p._ended){p._ended=!0;for(const w of l)try{w()}catch{}}}else p.frame<0&&(p.frame=0,p._playing=!1);wy(p,g,p.frame)},takeEvents(){if(!p._eventQueue.length)return[];const m=p._eventQueue.slice();return p._eventQueue.length=0,m},value(){const m=nd(p.parent?p.parent.frame:p.frame,r,i),g=o?{length:r}:void 0;if(c.length===1)return ba(c[0],m,g);const w=[];for(const y of c)w.push(ba(y,m,g));return w},applyTo(m){const g=p.value();if(!a)return g;const w=by(m);return Array.isArray(g)?g.map((y,b)=>y+(Number(w[b])||0)):g+(Number(w[0])||0)}};return p}function vy(){const t={name:"",mode:"single",fps:30,relative:!1,channelCount:0,parentKey:null,childKeys:[],parent:null,frame:0,rate:1,playing:!1,ended:!1,get frameCount(){return 0},play(){return t},pause(){return t},stop(){return t},setFrame(){return t},getFrame(){return 0},setRate(){return t},addEndedCallback(){return t},isPlaying(){return!1},setBlend(){return t},setVisible(){return t},advance(){},takeEvents(){return[]},value(){return 0},applyTo(e){return e}};return t}const ky=Object.freeze(Object.defineProperty({__proto__:null,createAnimation:sd,createNeutralAnimation:vy,crossedEvents:rd,linkAnimations:id,sampleChannel:ba,wrapFrame:nd},Symbol.toStringTag,{value:"Module"}));function Ay(t,e,n,r){const i=s=>wa(e,s(e,n),r);switch(t){case 1:return i((s,a)=>[Math.min(a[0],s[0]),Math.min(a[1],s[1]),Math.min(a[2],s[2])]);case 2:return i((s,a)=>[s[0]*a[0],s[1]*a[1],s[2]*a[2]]);case 3:return i((s,a)=>[a[0]===0?0:Math.max(1-(1-s[0])/a[0],0),a[1]===0?0:Math.max(1-(1-s[1])/a[1],0),a[2]===0?0:Math.max(1-(1-s[2])/a[2],0)]);case 4:return i((s,a)=>[Math.max(s[0]+a[0]-1,0),Math.max(s[1]+a[1]-1,0),Math.max(s[2]+a[2]-1,0)]);case 5:return[Math.min(e[0],n[0]),Math.min(e[1],n[1]),Math.min(e[2],n[2])];case 6:return i((s,a)=>[Math.max(a[0],s[0]),Math.max(a[1],s[1]),Math.max(a[2],s[2])]);case 7:return i((s,a)=>[1-(1-s[0])*(1-a[0]),1-(1-s[1])*(1-a[1]),1-(1-s[2])*(1-a[2])]);case 8:return i((s,a)=>[a[0]===1?1:Math.min(s[0]/(1-a[0]),1),a[1]===1?1:Math.min(s[1]/(1-a[1]),1),a[2]===1?1:Math.min(s[2]/(1-a[2]),1)]);case 9:return i((s,a)=>[Math.min(s[0]+a[0],1),Math.min(s[1]+a[1],1),Math.min(s[2]+a[2],1)]);case 10:return[Math.max(e[0],n[0]),Math.max(e[1],n[1]),Math.max(e[2],n[2])];case 11:return i((s,a)=>ad(s,a));case 12:return i((s,a)=>xy(s,a));case 13:return i((s,a)=>ad(a,s));case 14:return i((s,a)=>[Ti(s[0],a[0]),Ti(s[1],a[1]),Ti(s[2],a[2])]);case 15:return i((s,a)=>[a[0]<.5?Math.max(s[0]+2*a[0]-1,0):Math.min(s[0]+2*(a[0]-.5),1),a[1]<.5?Math.max(s[1]+2*a[1]-1,0):Math.min(s[1]+2*(a[1]-.5),1),a[2]<.5?Math.max(s[2]+2*a[2]-1,0):Math.min(s[2]+2*(a[2]-.5),1)]);case 16:return i((s,a)=>[a[0]<.5?Math.min(s[0],2*a[0]):Math.max(s[0],2*(a[0]-.5)),a[1]<.5?Math.min(s[1],2*a[1]):Math.max(s[1],2*(a[1]-.5)),a[2]<.5?Math.min(s[2],2*a[2]):Math.max(s[2],2*(a[2]-.5))]);case 17:return i((s,a)=>[Ti(s[0],a[0])<.5?0:1,Ti(s[1],a[1])<.5?0:1,Ti(s[2],a[2])<.5?0:1]);case 18:return i((s,a)=>[Math.abs(s[0]-a[0]),Math.abs(s[1]-a[1]),Math.abs(s[2]-a[2])]);case 19:return i((s,a)=>[s[0]+a[0]-2*s[0]*a[0],s[1]+a[1]-2*s[1]*a[1],s[2]+a[2]-2*s[2]*a[2]]);case 20:return i((s,a)=>[Math.max(s[0]+a[0]-1,0),Math.max(s[1]+a[1]-1,0),Math.max(s[2]+a[2]-1,0)]);case 21:return i((s,a)=>[a[0]===1?1:Math.min(s[0]*s[0]/(1-a[0]),1),a[1]===1?1:Math.min(s[1]*s[1]/(1-a[1]),1),a[2]===1?1:Math.min(s[2]*s[2]/(1-a[2]),1)]);case 22:return i((s,a)=>[s[0]===1?1:Math.min(a[0]*a[0]/(1-s[0]),1),s[1]===1?1:Math.min(a[1]*a[1]/(1-s[1]),1),s[2]===1?1:Math.min(a[2]*a[2]/(1-s[2]),1)]);case 23:return i((s,a)=>[Math.min(s[0],a[0])-Math.max(s[0],a[0])+1,Math.min(s[1],a[1])-Math.max(s[1],a[1])+1,Math.min(s[2],a[2])-Math.max(s[2],a[2])+1]);case 24:return i((s,a)=>[(s[0]+a[0])/2,(s[1]+a[1])/2,(s[2]+a[2])/2]);case 25:return i((s,a)=>[1-Math.abs(1-s[0]-a[0]),1-Math.abs(1-s[1]-a[1]),1-Math.abs(1-s[2]-a[2])]);case 26:return i((s,a)=>Ty(s,a));case 27:return i((s,a)=>Sy(s,a));case 28:return i((s,a)=>Py(s,a));case 29:return i((s,a)=>_y(s,a));case 30:{const s=Math.max(e[0],Math.max(e[1],e[2]));return wa(e,[s*n[0],s*n[1],s*n[2]],r)}case 31:return[e[0]+n[0]*r,e[1]+n[1]*r,e[2]+n[2]*r];case 32:return wa(e,[e[0]+e[0]*n[0],e[1]+e[1]*n[1],e[2]+e[2]*n[2]],r);default:return wa(e,n,r)}}function wa(t,e,n){return[t[0]*(1-n)+e[0]*n,t[1]*(1-n)+e[1]*n,t[2]*(1-n)+e[2]*n]}function ad(t,e){const n=(r,i)=>r<.5?2*r*i:1-2*(1-r)*(1-i);return[n(t[0],e[0]),n(t[1],e[1]),n(t[2],e[2])]}function xy(t,e){const n=(r,i)=>i<.5?2*r*i+r*r*(1-2*i):Math.sqrt(r)*(2*i-1)+2*r*(1-i);return[n(t[0],e[0]),n(t[1],e[1]),n(t[2],e[2])]}function Ti(t,e){if(e<.5){const r=2*e;return r===0?0:Math.max(1-(1-t)/r,0)}const n=2*(e-.5);return n===1?1:Math.min(t/(1-n),1)}function hr(t){const e=Math.min(t[0],Math.min(t[1],t[2])),n=Math.max(t[0],Math.max(t[1],t[2])),r=n-e,i=[0,0,0];if(i[2]=(n+e)/2,r===0)i[0]=0,i[1]=0;else{i[1]=i[2]<.5?r/(n+e):r/(2-n-e);const s=((n-t[0])/6+r/2)/r,a=((n-t[1])/6+r/2)/r,o=((n-t[2])/6+r/2)/r;t[0]===n?i[0]=o-a:t[1]===n?i[0]=1/3+s-o:t[2]===n&&(i[0]=2/3+a-s),i[0]<0?i[0]+=1:i[0]>1&&(i[0]-=1)}return i}function yc(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*6*n:2*n<1?e:3*n<2?t+(e-t)*((2/3-n)*6):t}function va(t){if(t[1]===0)return[t[2],t[2],t[2]];const e=t[2]<.5?t[2]*(1+t[1]):t[2]+t[1]-t[1]*t[2],n=2*t[2]-e;return[yc(n,e,t[0]+1/3),yc(n,e,t[0]),yc(n,e,t[0]-1/3)]}function Ty(t,e){const n=hr(t);return va([hr(e)[0],n[1],n[2]])}function Sy(t,e){const n=hr(t);return va([n[0],hr(e)[1],n[2]])}function Py(t,e){const n=hr(e);return va([n[0],n[1],hr(t)[2]])}function _y(t,e){const n=hr(t);return va([n[0],n[1],hr(e)[2]])}function od(t){const e=t&&t.puppet&&t.puppet.animBound;return e?[e.x*Math.abs(t.scale[0]),e.y*Math.abs(t.scale[1])]:[0,0]}function cd(t){for(const e of t&&t.effects||[]){if(e.visible===!1)continue;const n=Math.max((e.passes||[]).length,(e.materialPasses||[]).length);for(let r=0;r<n;r++){const i=e.passes&&e.passes[r]&&e.passes[r].combos||{},s=e.materialPasses&&e.materialPasses[r]&&e.materialPasses[r].combos||{},a=i.TRANSPARENCY!==void 0?i.TRANSPARENCY:s.TRANSPARENCY;if(Number(a)===0)return!0}}return!1}function ka(t,e,n){if(n||(n=new Set),!e)return n;for(const r of t.childIds||[]){const i=e.get(r);!i||i.particle||i.isPostProcess||(n.add(r),ka(i,e,n))}return n}function bc(t){const e=Jf[t]||"translucent";return{mode:e,prep:ny[e]||0}}function ld(t,e){const n=Number(t);return Number.isFinite(n)&&n!==0?n:e==="additive"?9:Number.isFinite(n)?n:0}function wc(t){const e=Number(t);return!Number.isFinite(e)||e===0?!1:!Jf[e]}function Ey(t,e,n,r){if(wc(t))return Ay(t,[e,e,e],[n,n,n],r)[0];const{mode:i,prep:s}=bc(t);let a=n;return s===1?a=n*r:s===2&&(a=1-r+n*r),i==="screen"?a+e*(1-a):i==="multiply"?e*a:i==="additive"?e+n*r:e*(1-r)+n*r}function ud(t,e,n){const r=t&&Number(t.scale)||1;let i=Math.max(1,Math.round(e/r)),s=Math.max(1,Math.round(n/r));const a=t&&Number(t.fit);if(Number.isFinite(a)&&a>0){const o=Math.max(i,s);if(o>a){const c=a/o;i=Math.max(1,Math.round(i*c)),s=Math.max(1,Math.round(s*c))}}return[i,s]}function fd(t){const e=t||{},n=(o,c)=>{const u=o!==null&&typeof o=="object"?o.value:o;return u===!0||u===1?!0:u===!1||u===0?!1:c},r=(o,c)=>{const u=o!==null&&typeof o=="object"?o.value:o;return typeof u=="number"&&Number.isFinite(u)?u:c};if(!n(e.bloom,!1))return null;const i=n(e.hdr,!1),s=r(i?e.bloomhdrstrength:e.bloomstrength,1.5),a=mc(e.bloomtint||"1 1 1");return{enabled:!0,hdr:i,strength:s,threshold:i?r(e.bloomhdrthreshold,.1):r(e.bloomthreshold,.65),iterations:Math.max(1,Math.round(i?r(e.bloomhdriterations,8):8)),radius:Math.max(0,i?r(e.bloomhdrscatter,3):3),damp:i?r(e.bloomhdrfeather,.5):.5,alpha:1,tint:a,metric:i?1:0}}function Cy(t){const e=Number(t);return!Number.isFinite(e)||e<.001?999:1/e}const hs=-1;function vc(t,e){return!!e&&!t}const Iy="mix(999.0, 1.0 / max(g_PointerScale, 0.001), step(0.001, g_PointerScale))";function dd(t){if(typeof t!="string"||/unprojectedUVs\s*\*=\s*mix\(999\.0,\s*1\.0\s*\/\s*max\(\s*g_PointerScale/.test(t))return t;const e=/unprojectedUVs\s*\*=\s*v_PointerScale\s*\*/.test(t),n=/unprojectedUVs\s*\*=\s*g_PointerScale\s*\*/.test(t);if(!e&&!n)return t;let r=t;/uniform\s+float\s+g_PointerScale\b/.test(r)||(r=r.replace(/void\s+main\s*\(/,`uniform float g_PointerScale;
349
- void main(`));const i=e?/unprojectedUVs\s*\*=\s*v_PointerScale\s*\*/:/unprojectedUVs\s*\*=\s*g_PointerScale\s*\*/;return r.replace(i,"unprojectedUVs *= "+Iy+" *")}const hd=1;function md(t,e){return t==="g_PointerScale"?hd:e}function My(t,e={}){const n=t.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0});if(!n)throw new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 WebGL2");const r=e.shaderResolver||(async()=>null),i=e.diag||(()=>{}),s=typeof document<"u"?document.createElement("canvas"):null;s&&(s.style.cssText="position:fixed;left:-9999px;top:-9999px;width:2px;height:2px;opacity:0");let a=!1,o="";const c=3840,u=1024;let l=e.fboCapFactor===void 0?0:e.fboCapFactor,f=null,d=null,h=null;const p=[["g_AudioSpectrum16Left","left16"],["g_AudioSpectrum16Right","right16"],["g_AudioSpectrum32Left","left32"],["g_AudioSpectrum32Right","right32"],["g_AudioSpectrum64Left","left64"],["g_AudioSpectrum64Right","right64"]];function m(x){h=x||null}let g=null,w=null,y=null,b=null,v=null,k=null,A=null;const T=new Map,S=new Map,P=new Set;let M=null;const B={total:0,ok:0,failed:0};function N(x,_){g=typeof x=="function"?x:null,w=_&&_.userProperties||null,y=_&&_.audioViews||null,b=_&&_.shared||null,v=_&&_.inputView||null,k=_&&_.timers||null,A=_&&typeof _.onSandbox=="function"?_.onSandbox:null,M=_&&Array.isArray(_.animEventQueue)?_.animEventQueue:null,T.clear(),S.clear(),P.clear()}let O=!1,q=!1,H=0;typeof e.bloomDebugFrames=="number"&&e.bloomDebugFrames;const G=dr(n,ds,ly),Y=dr(n,ds,uy),J=dr(n,ds,fy),ne=dr(n,iy,sy),fe=dr(n,ay,oy),Ne=dr(n,ds,cy),Qe=dr(n,ds,ry),Ve=n.createVertexArray();n.bindVertexArray(Ve);const Fe=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,Fe),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,20,12),n.bindVertexArray(null);const Le=new Map;let Tt=1;function Xe(x,_,V){const F=(V||"")+"|"+x+"x"+_;if(Le.has(F)){const D=Le.get(F);return D.stamp=Tt,D}const j=n.createFramebuffer(),X=n.createTexture();n.bindTexture(n.TEXTURE_2D,X),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,x,_,0,n.RGBA,n.UNSIGNED_BYTE,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.bindFramebuffer(n.FRAMEBUFFER,j),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,X,0),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindFramebuffer(n.FRAMEBUFFER,null);const K={fbo:j,tex:X,width:x,height:_,stamp:Tt};return Le.set(F,K),K}function It(){for(const[x,_]of Le)_.stamp!==Tt&&(_.fbo&&n.deleteFramebuffer(_.fbo),_.tex&&n.deleteTexture(_.tex),Le.delete(x))}const Ue=new Map,We=new Map,Oe=new Map;function it(x){const _={},V=/uniform\s+[A-Za-z0-9_]+\s+([A-Za-z_][A-Za-z0-9_]*)[^;]*;\s*\/\/([^\n]*)/g;let F;for(;(F=V.exec(x))!==null;){const j=F[1],X=F[2],K=/"material"\s*:\s*"([^"]+)"/.exec(X);if(!K)continue;const D=/"default"\s*:\s*("(?:[^"]*)"|-?\d+(?:\.\d+)?)/.exec(X);_[K[1]]={uniform:j,default:D?jr(D[1]):void 0}}return _}function ve(x){const _=new Map,V=/uniform\s+sampler2D\s+g_Texture(\d+)\s*;\s*\/\/([^\n]*)/g;let F;for(;(F=V.exec(x))!==null;){const j=Number(F[1]),X=/"default"\s*:\s*"([^"]+)"/.exec(F[2]);X&&X[1]&&_.set(j,X[1])}return _}function un(x){const _=[],V=/uniform\s+sampler2D\s+(g_Texture(\d+))[^;]*;\s*\/\/([^\n]*)/g;let F;for(;(F=V.exec(x))!==null;){const j=/"combo"\s*:\s*"([^"]+)"/.exec(F[3]);j&&_.push({slot:Number(F[2]),name:F[1],combo:j[1]})}return _}function jr(x){if(x.startsWith('"'))return x.slice(1,-1);const _=Number(x);return Number.isFinite(_)?_:void 0}async function Zt(x,_,V){let F=Oe.get(x);if(F===void 0){const K=await r("shaders/"+x+".frag")||"",D=await r("shaders/"+x+".vert")||"";F={frag:K,vert:D,texCombos:un(K)},Oe.set(x,F)}const j={..._};for(const K of F.texCombos)V&&V[K.slot]&&j[K.combo]===void 0&&(j[K.combo]=1);const X=x+"|"+JSON.stringify(j);if(Ue.has(X)){const K=Ue.get(X);if(K===null)throw new Error("shader="+x+" \u7F16\u8BD1\u5931\u8D25\uFF08\u5DF2\u7F13\u5B58\uFF09");return K}for(let K=0;K<4;K++){const D=new Set,z=I=>We.has(I)?We.get(I):(D.add(I),null),L=dd(Kf(F.frag,"frag",j,z,F.vert)),E=Kf(F.vert,"vert",j,z,F.frag);if(D.size===0){let I;try{I=dr(n,E,L)}catch(ee){throw Ue.set(X,null),new Error("shader="+x+" "+(ee&&ee.message))}const U=new Map,Q=n.getProgramParameter(I,n.ACTIVE_UNIFORMS);for(let ee=0;ee<Q;ee++){const ue=n.getActiveUniform(I,ee),we=ue.name.replace(/\[0\]$/,"");U.set(we,{loc:n.getUniformLocation(I,ue.name),type:py[ue.type]||"unknown",size:ue.size})}const $={...it(F.vert),...it(F.frag)},Z=/gl_Position\s*=\s*vec4\s*\(\s*a_Position/.test(F.vert)&&!/[aA]_Position[\s\S]{0,40}mul\s*\(/.test(F.vert),se=new Map([...ve(F.vert),...ve(F.frag)]),te={prog:I,uni:U,matMeta:$,samplerDefaults:se,fragGlsl:L,vertGlsl:E,ndcDirect:Z};return Ue.set(X,te),te}await Promise.all(Array.from(D).map(async I=>{We.set(I,await r("shaders/"+I)||"")}))}throw new Error("include \u89E3\u6790\u5931\u8D25: "+x)}const St=pc(n,new Uint8Array([255,255,255,255]),1,1),ct=pc(n,new Uint8Array([0,0,0,0]),1,1);let mt=null;function Kn(x){mt=x||null}function _n(){if(!mt)return null;const x=typeof mt=="function"?mt():mt;return x&&x.state?x.state:x}const Ae={x:0,y:0,sx:0,sy:0};let _i=0,Jt=0,Zn=0,en=1/60,qr=-1;const Ps=typeof e.fadeDuration=="number"&&e.fadeDuration>=0?e.fadeDuration:1,_s=(x,_)=>{const V=x!==null&&typeof x=="object"?x.value:x;return V===!0||V===1?!0:V===!1||V===0?!1:_},En=(x,_)=>{const V=x!==null&&typeof x=="object"?x.value:x;return typeof V=="number"&&Number.isFinite(V)?V:_},Pt=x=>e.fade!==!1&&_s(x.camerafade,!1);function Ei(x,_){if(!_s(x.camerashake,!1))return null;const V=En(x.camerashakeamplitude,0);if(V===0)return null;const F=Math.max(0,Math.min(1,En(x.camerashakeroughness,0))),j=En(x.camerashakespeed,1),X=_*j,K=Math.sin(X*2.1)*Math.cos(X*.7),D=Math.cos(X*1.7)*Math.sin(X*.9),z=Math.sin(X*11.3)*Math.cos(X*7.1),L=Math.cos(X*9.7)*Math.sin(X*13.1);return{x:(K*(1-F)+z*F)*V,y:(D*(1-F)+L*F)*V}}function fn(){const x=new Date;return(x.getHours()*3600+x.getMinutes()*60+x.getSeconds())/86400}function Be(x,_,V){const F=x.get(_);F&&F.loc!==null&&V(F.loc,F.type,F.size)}function Xr(x){if(typeof x=="number")return[x,x,x,x];const _=String(x).trim().split(/[\s,]+/).map(Number);return[_[0]||0,_[1]||0,_[2]||0,_[3]||0]}function Es(x,_,V){const F=x.get(_);if(!F||F.loc===null)return;const j=V&&V.value!==void 0?V.value:V,X=Xr(j);switch(F.type){case"float":n.uniform1f(F.loc,X[0]);break;case"int":case"bool":n.uniform1i(F.loc,j===!0||j===1?1:Math.round(X[0]));break;case"vec2":n.uniform2f(F.loc,X[0],X[1]);break;case"vec3":n.uniform3f(F.loc,X[0],X[1],X[2]);break;case"vec4":n.uniform4f(F.loc,X[0],X[1],X[2],X[3]);break;case"mat4":n.uniformMatrix4fv(F.loc,!1,Gt);break;case"mat3":n.uniformMatrix3fv(F.loc,!1,Tr);break}}const Ci=()=>new Float32Array([1,0,0,0,1,0,0,0,1]);function Gr(x,_,V,F,j,X,K,D,z,L,E){if(Be(x,"g_Time",te=>n.uniform1f(te,V)),Be(x,"g_Daytime",te=>n.uniform1f(te,fn())),Be(x,"g_ModelViewProjectionMatrix",te=>n.uniformMatrix4fv(te,!1,X)),Be(x,"g_ModelMatrix",te=>n.uniformMatrix4fv(te,!1,K)),Be(x,"g_ViewProjectionMatrix",te=>n.uniformMatrix4fv(te,!1,D)),x.get("g_ModelViewProjectionMatrixInverse")){let te=null;for(const[ue,we]of z)ue===0&&(te=we);const ee=te&&te[0]>0&&te[1]>0?$c(Li(Kr(),te[0]/2,te[1]/2,1)):Gt;Be(x,"g_ModelViewProjectionMatrixInverse",ue=>n.uniformMatrix4fv(ue,!1,ee))}Be(x,"g_Brightness",te=>n.uniform1f(te,_.brightness)),Be(x,"g_UserAlpha",te=>n.uniform1f(te,_.alpha)),Be(x,"g_Alpha",te=>n.uniform1f(te,_.alpha)),Be(x,"g_Color",te=>n.uniform3f(te,_.color[0],_.color[1],_.color[2])),Be(x,"g_Color4",te=>n.uniform4f(te,_.color[0],_.color[1],_.color[2],1)),Be(x,"g_CompositeColor",te=>n.uniform3f(te,_.color[0],_.color[1],_.color[2])),Be(x,"g_TexelSize",te=>n.uniform2f(te,1/F,1/j)),Be(x,"g_TexelSizeHalf",te=>n.uniform2f(te,.5/F,.5/j)),Be(x,"g_TextureReductionScale",te=>n.uniform1f(te,1));const I=_n(),U=vc(!!(I&&I.has),!!x.get("g_PointerScale"));let Q=U?hs:I?I.u:.5,$=U?hs:I?I.v:.5,Z=U?hs:I?I.lastU:.5,se=U?hs:I?I.lastV:.5;if(E&&_&&_.size&&_.size[0]>0&&_.size[1]>0){const te=Math.abs(_.size[0]*_.scale[0]),ee=Math.abs(_.size[1]*_.scale[1]);if(te>0&&ee>0){const ue=_.origin[0]-te/2,we=E.projH-_.origin[1]-ee/2,ke=Je=>(E.offX+Je*E.viewW-ue)/te,ge=Je=>(E.offY+Je*E.viewH-we)/ee;Q=ke(Q),$=ge($),Z=ke(Z),se=ge(se)}}Be(x,"g_PointerPosition",te=>n.uniform2f(te,Q,$)),Be(x,"g_PointerPositionLast",te=>n.uniform2f(te,Z,se)),Be(x,"g_PointerState",te=>n.uniform4f(te,Q,$,I&&I.leftDown?1:0,0)),Be(x,"g_ParallaxPosition",te=>n.uniform2f(te,Ae.sx*.5+.5,Ae.sy*.5+.5)),Be(x,"g_Frametime",te=>n.uniform1f(te,en)),x.get("g_EffectTextureProjectionMatrixInverse")&&Be(x,"g_EffectTextureProjectionMatrixInverse",te=>n.uniformMatrix4fv(te,!1,Gt));for(let te=0;te<8;te++)Be(x,"g_Texture"+te,ee=>n.uniform1i(ee,te));for(const[te,ee]of z)Be(x,"g_Texture"+te+"Resolution",ue=>n.uniform4f(ue,ee[0],ee[1],ee[2],ee[3]));if(h){const te=typeof h=="function"?h():h;if(te)for(const[ee,ue]of p){const we=te[ue];we&&Be(x,ee,ke=>n.uniform1fv(ke,we))}}}function Ua(x,_,V){for(const[F,j]of Object.entries(_||{})){const X=V&&V[F];X&&Es(x,X.uniform,j)}for(const[F,j]of Object.entries(V||{}))if(!_||!(F in _)){const X=md(j.uniform,j.default);X!==void 0&&Es(x,j.uniform,X)}}function $r(x){const _=_n();vc(!!(_&&_.has),!!x.get("g_PointerScale"))&&Be(x,"g_PointerScale",V=>n.uniform1f(V,0))}function kr(x,_){return _?typeof x=="number"&&Number.isFinite(x):!!x&&typeof x=="object"&&Number.isFinite(Number(x.x))&&Number.isFinite(Number(x.y))}function dn(x,_,V,F){if(!x)return x;let j=!1;for(const K of Object.values(x))if(K!==null&&typeof K=="object"&&typeof K.script=="string"){j=!0;break}if(!j||!g)return x;const X={...x};for(const[K,D]of Object.entries(x)){if(D===null||typeof D!="object"||typeof D.script!="string")continue;const z=_+"|"+K;let L=T.get(z);if(L===void 0){B.total++;try{L=g(D.script,D.scriptproperties||D.scriptProperties||null,{userProperties:w||{},audioViews:y||void 0,layer:F||null,shared:b||{},inputView:v||void 0,setTimeout:k?k.setTimeout:void 0,clearTimeout:k?k.clearTimeout:void 0,setInterval:k?k.setInterval:void 0,clearInterval:k?k.clearInterval:void 0,getAnimationForProperty:()=>{const $=S.get(_+"|anim|"+K);return $?$.ctrl:null}})}catch{L=null}if(L?B.ok++:B.failed++,T.set(z,L),L){const $=D.value!==void 0?D.value:D,Z=Xr($),se=typeof $=="number",te=se?Z[0]:{x:Z[0],y:Z[1],z:Z[2]},ee=L.init(te);L.__lastConstValue=kr(ee,se)?ee:te}if(L&&typeof L.applyUserProperties=="function")try{L.applyUserProperties(w||{})}catch{}if(L&&(L.hasMediaHook||L.hasAnimEventHook)&&A)try{A(L,{layer:F,key:K})}catch{}}if(!L||L.disabled||!L.hasUpdate)continue;if(L.engine){L.engine.runtime=V,L.engine.frametime=en,L.engine.timeOfDay=fn();const $=_n();$&&$.screenW&&$.screenH&&(L.engine.screenResolution={x:$.screenW,y:$.screenH})}const E=typeof(D.value!==void 0?D.value:D)=="number";if(!kr(L.__lastConstValue,E)){const $=Xr(D.value!==void 0?D.value:D);L.__lastConstValue=E?$[0]:{x:$[0],y:$[1],z:$[2]}}const I=L.__lastConstValue;let U;try{U=L.callUpdate(I)}catch{U=void 0}const Q=U??I;if(kr(Q,E)&&(L.__lastConstValue=Q),typeof Q=="number"&&Number.isFinite(Q))X[K]=Q;else if(Q&&typeof Q=="object"){const $=Number(Q.x),Z=Number(Q.y),se=Number(Q.z);Number.isFinite($)&&Number.isFinite(Z)&&(X[K]=Number.isFinite(se)?`${$} ${Z} ${se}`:`${$} ${Z} 0`)}}return X}function Cs(x,_,V,F){if(!x)return x;let j=!1;for(const D of Object.values(x))if(D&&typeof D=="object"&&D.animation&&D.animation.options){j=!0;break}if(!j)return x;const X={...x},K=new Map;for(const[D,z]of Object.entries(x)){if(!z||typeof z!="object"||!z.animation||!z.animation.options)continue;const L=_+"|anim|"+D;let E=S.get(L);if(!E){const I=sd(z.animation),U=z.value!==void 0?z.value:0;I.baseNumeric=Array.isArray(U)?U.slice():U,E={ctrl:I,prevTime:V},S.set(L,E)}K.set(D,E.ctrl)}P.has(_)||(P.add(_),id(K,D=>i(`${_}: ${D}`)));for(const[D,z]of Object.entries(x)){if(!z||typeof z!="object"||!z.animation||!z.animation.options)continue;const L=_+"|anim|"+D,E=S.get(L),I=V-E.prevTime;if(E.prevTime=V,E.ctrl.playing&&E.ctrl.advance(Math.max(0,I)),M){const U=E.ctrl.takeEvents();U.length&&M.push({layer:F,events:U})}else E.ctrl.takeEvents();X[D]=E.ctrl.applyTo(E.ctrl.baseNumeric)}return X}function Ii(x,_,V,F){return x==null||x===""?null:x.startsWith("_rt_")?x.startsWith("_rt_imageLayerComposite")?Bi&&Lt.has(x)?Lt.get(x):_:V.has(x)?V.get(x):null:V.has(x)?V.get(x):F.get(x)||null}const Ar=hy(),xr=my(),Jn=new Map;function Cn(x,_){const V=x+"x"+_;let F=Jn.get(V);return F===void 0&&(F=dy(x,_),Jn.set(V,F)),F}let _t=null;function qt(x,_){_t!==x&&(n.bindBuffer(n.ARRAY_BUFFER,Fe),n.bufferData(n.ARRAY_BUFFER,_,n.DYNAMIC_DRAW),_t=x)}const De={mvp:n.getUniformLocation(G,"u_MVP"),tex:n.getUniformLocation(G,"u_Tex"),color:n.getUniformLocation(G,"u_Color4"),frameOrigin:n.getUniformLocation(G,"u_FrameOrigin"),frameU:n.getUniformLocation(G,"u_FrameU"),frameV:n.getUniformLocation(G,"u_FrameV"),blendPrep:n.getUniformLocation(G,"u_BlendPrep")},Xt={mvp:n.getUniformLocation(Y,"u_MVP"),tex:n.getUniformLocation(Y,"u_Tex"),blendPrep:n.getUniformLocation(Y,"u_BlendPrep")},tn={mvp:n.getUniformLocation(J,"u_MVP"),tex:n.getUniformLocation(J,"u_Tex")},hn={mvp:n.getUniformLocation(Qe,"u_MVP"),tex:n.getUniformLocation(Qe,"u_Tex"),backdrop:n.getUniformLocation(Qe,"u_Backdrop"),blendMode:n.getUniformLocation(Qe,"u_BlendMode"),canvasSize:n.getUniformLocation(Qe,"u_CanvasSize"),opacity:n.getUniformLocation(Qe,"u_Opacity")},mn={tex:n.getUniformLocation(ne,"u_Tex"),texel:n.getUniformLocation(ne,"u_Texel"),damp:n.getUniformLocation(ne,"u_Damp"),alpha:n.getUniformLocation(ne,"u_Alpha"),strength:n.getUniformLocation(ne,"u_Strength"),threshold:n.getUniformLocation(ne,"u_Threshold"),metric:n.getUniformLocation(ne,"u_Metric")},Mt={tex:n.getUniformLocation(fe,"u_Tex"),texel:n.getUniformLocation(fe,"u_Texel"),res:n.getUniformLocation(fe,"u_Res"),radius:n.getUniformLocation(fe,"u_Radius"),dir:n.getUniformLocation(fe,"u_Dir"),alpha:n.getUniformLocation(fe,"u_Alpha"),strength:n.getUniformLocation(fe,"u_Strength"),iterations:n.getUniformLocation(fe,"u_Iterations")},In={mvp:n.getUniformLocation(Ne,"u_MVP"),tex:n.getUniformLocation(Ne,"u_Tex"),alpha:n.getUniformLocation(Ne,"u_Alpha"),strength:n.getUniformLocation(Ne,"u_Strength"),tint:n.getUniformLocation(Ne,"u_Tint")},Gt=Kr(),Tr=Ci();function pn(x){x==="translucent"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):x==="additive"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE)):n.disable(n.BLEND)}let Sr=0;function Qr(x){const{mode:_,prep:V}=bc(x);Sr=V,_==="additive"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE)):_==="multiply"?(n.enable(n.BLEND),n.blendFuncSeparate(n.DST_COLOR,n.ZERO,n.ONE,n.ONE_MINUS_SRC_ALPHA)):_==="screen"?(n.enable(n.BLEND),n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_COLOR,n.ONE,n.ONE_MINUS_SRC_ALPHA)):pn("translucent")}function Pr(x,_){if(_&&_.perspective)return!1;const V=x.size[0]*x.scale[0],F=x.size[1]*x.scale[1];if(V===0||F===0)return!1;let j=Math.abs(V)/2,X=Math.abs(F)/2;const K=x.angles[2];if(K!==0){const Q=Math.abs(Math.cos(K)),$=Math.abs(Math.sin(K)),Z=j*Q+X*$,se=j*$+X*Q;j=Z,X=se}const D=x.origin[0],z=_.projH-x.origin[1];let L=64;x.parallaxDepth&&(L+=Math.abs(ei(x.parallaxDepth[0])*Jt),L+=Math.abs(ei(x.parallaxDepth[1])*Zn));const E=od(x),I=L+E[0],U=L+E[1];return D+j+I<_.offX||D-j-I>_.offX+_.viewW||z+X+U<_.offY||z-X-U>_.offY+_.viewH}function Mi(x,_,V){if(!x.spriteSheet)return null;const F=_&&_.frames,j=Array.isArray(F)?F:F&&F.list;if(!j||j.length===0)return null;const X=F&&F.atlasWidth||_.width||0,K=F&&F.atlasHeight||_.height||0;if(X<=0||K<=0)return null;x.spriteFrameCount=j.length;let D=0;const z=x.textureAnimation;if(z&&z.frame!==null&&z.frame!==void 0)D=Math.floor(Number(z.frame))||0,D>=0||(D=0),D>=j.length&&(D=j.length-1);else if(j.length>1){const $=z&&z.playing===!1;let Z=0;for(const se of j)Z+=se.duration>0?se.duration:1/30;if(!$&&Z>0){let se=V%Z;se<0&&(se+=Z);for(let te=0;te<j.length;te++){const ee=j[te].duration>0?j[te].duration:.03333333333333333;if(se<ee){D=te;break}se-=ee,D=te}}}const L=j[D],E=L.uDir?L.uDir[0]:L.width,I=L.uDir?L.uDir[1]:0,U=L.vDir?L.vDir[0]:0,Q=L.vDir?L.vDir[1]:L.height;return[L.x/X,L.y/K,E/X,I/K,U/X,Q/K]}function _r(x,_){const V=x.size[0]*x.scale[0],F=x.size[1]*x.scale[1];let j=Kr();if(_&&_.perspective){const K=Ah(x,_);j=Jr(j,K[0],K[1],K[2]);const D=x.angles[0]||0,z=x.angles[1]||0;z&&(j=wh(j,z)),D&&(j=bh(j,D)),j=Qc(j,-x.angles[2])}else{if(j=Jr(j,x.origin[0],_.projH-x.origin[1],x.origin[2]),x.parallaxDepth&&(Jt!==0||Zn!==0)){const K=ei(x.parallaxDepth[0]),D=ei(x.parallaxDepth[1]);j=Jr(j,K*Jt,D*Zn,0)}j=Qc(j,-x.angles[2])}const X=Zf[x.alignment]||[.5,.5];return(X[0]!==.5||X[1]!==.5)&&(j=Jr(j,(.5-X[0])*V,(.5-X[1])*F,0)),{m:j,w:V,h:F}}function Er(x,_,V,F,j,X,K,D,z=!1,L=null,E=null){const I=_r(F,j);let U=I.m;if(E){const se=(E[0]+E[2]/2)*F.scale[0],te=(E[1]+E[3]/2)*F.scale[1];U=Jr(U,se,-te,0),U=Li(U,E[2]*F.scale[0],E[3]*F.scale[1],1)}else U=Li(U,I.w,I.h,1);const Q=wn(X,U);if(!z&&!lt&&wc(F.colorBlendMode)){const se=tr(K,D);n.useProgram(Qe),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,K,D),n.bindVertexArray(Ve),qt("local",xr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,_),n.uniform1i(hn.tex,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,se),n.uniform1i(hn.backdrop,1),n.uniform1i(hn.blendMode,Number(F.colorBlendMode)|0),n.uniform2f(hn.canvasSize,K,D),n.uniform1f(hn.opacity,V[3]),n.uniformMatrix4fv(hn.mvp,!1,Q),n.drawArrays(n.TRIANGLES,0,6),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,null),n.activeTexture(n.TEXTURE0);return}const Z=x===Y?Xt:De;n.useProgram(x),z?(Sr=0,n.enable(n.BLEND),F.containerAlphaMeaningful?n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA):n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):Qr(ld(F.colorBlendMode,F.materialBlending)),Z.blendPrep!==null&&Z.blendPrep!==void 0&&n.uniform1i(Z.blendPrep,Sr),lt?(n.bindFramebuffer(n.FRAMEBUFFER,lt.fbo.fbo),n.viewport(0,0,lt.w,lt.h)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,K,D)),n.bindVertexArray(Ve),qt("local",xr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,_),n.uniform1i(Z.tex,0),n.uniformMatrix4fv(Z.mvp,!1,Q),Z.color!==null&&Z.color!==void 0&&n.uniform4f(Z.color,V[0],V[1],V[2],V[3]),nn(Z,L),n.drawArrays(n.TRIANGLES,0,6)}function nn(x,_){!x||x.frameOrigin===null||x.frameOrigin===void 0||(_?(n.uniform2f(x.frameOrigin,_[0],_[1]),n.uniform2f(x.frameU,_[2],_[3]),n.uniform2f(x.frameV,_[4],_[5])):(n.uniform2f(x.frameOrigin,0,0),n.uniform2f(x.frameU,1,0),n.uniform2f(x.frameV,0,1)))}let Cr=null,lt=null;const Lt=new Map,Ir=new Map;let Bi=!0;function Is(x,_){const V=_r(x,_),F=_&&_.perspective?x.scale[1]:-x.scale[1],j=_&&_.perspective&&x.scale[2]||1;return Li(V.m,x.scale[0],F,j)}function er(x,_,V,F,j,X,K){lt?(n.bindFramebuffer(n.FRAMEBUFFER,lt.fbo.fbo),n.viewport(0,0,lt.w,lt.h)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,F,j)),K&&(n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,K),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR),n.generateMipmap(n.TEXTURE_2D));const D=wn(V,Is(x,_));Cr(x,D,{time:X,overrideTex:K||null}),K&&(n.bindTexture(n.TEXTURE_2D,K),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR)),_t=null}let gn=null;function tr(x,_){return gn===null&&(gn=n.createTexture(),n.bindTexture(n.TEXTURE_2D,gn),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindTexture(n.TEXTURE_2D,gn),n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB8,0,0,x,_,0),gn}function Ms(x,_,V){const F=tr(_,V),j=Math.max(1,Math.round(_/4)),X=Math.max(1,Math.round(V/4)),K=Xe(j,X,"bloomA"),D=Xe(j,X,"bloomB");n.bindVertexArray(Ve),qt("pass",Ar),n.activeTexture(n.TEXTURE0),n.useProgram(ne),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,K.fbo),n.viewport(0,0,j,X),n.bindTexture(n.TEXTURE_2D,F),n.uniform1i(mn.tex,0),n.uniform2f(mn.texel,1/_,1/V),n.uniform1f(mn.damp,x.damp),n.uniform1f(mn.alpha,x.alpha),n.uniform1f(mn.strength,x.strength),n.uniform1f(mn.threshold,x.threshold),n.uniform1i(mn.metric,x.metric),n.drawArrays(n.TRIANGLES,0,6),n.useProgram(fe);const z=(L,E,I,U)=>{n.bindFramebuffer(n.FRAMEBUFFER,E.fbo),n.viewport(0,0,E.width,E.height),n.bindTexture(n.TEXTURE_2D,L.tex),n.uniform1i(Mt.tex,0),n.uniform2f(Mt.texel,1/L.width,1/L.height),n.uniform2f(Mt.res,L.width,L.height),n.uniform1f(Mt.radius,x.radius),n.uniform2f(Mt.dir,I,U),n.uniform1f(Mt.alpha,x.alpha),n.uniform1f(Mt.strength,x.strength),n.uniform1f(Mt.iterations,x.iterations),n.drawArrays(n.TRIANGLES,0,6)};if(z(K,D,1,0),z(D,K,0,1),n.useProgram(Ne),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,_,V),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE),n.bindTexture(n.TEXTURE_2D,K.tex),n.uniform1i(In.tex,0),n.uniformMatrix4fv(In.mvp,!1,Gt),n.uniform1f(In.alpha,x.alpha),n.uniform1f(In.strength,x.strength),n.uniform3f(In.tint,x.tint[0],x.tint[1],x.tint[2]),n.drawArrays(n.TRIANGLES,0,6),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA),H++,H===1||H===120||H===600){const L=new Uint8Array(4);n.bindFramebuffer(n.FRAMEBUFFER,K.fbo),n.readPixels(j>>1,X>>1,1,1,n.RGBA,n.UNSIGNED_BYTE,L),n.bindFramebuffer(n.FRAMEBUFFER,null),i(`bloom frame ${H}: center=[${[...L].join(",")}] glErr=${n.getError()} threshold=${x.threshold} strength=${x.strength} metric=${x.metric}`)}}function Ri(x,_,V,F,j,X,K,D){const z=tr(K,D),L=_r(x,j);let E=L.m;E=Li(E,L.w,L.h,1);const I=wn(X,E),U=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]].map(([ee,ue])=>{const we=Th(I,ee,ue,0);return[we[0]*.5+.5,we[1]*.5+.5]}),[Q,$,Z,se]=U,te=new Float32Array([0,F,0,Q[0],Q[1],0,0,0,Z[0],Z[1],V,F,0,$[0],$[1],V,F,0,$[0],$[1],0,0,0,Z[0],Z[1],V,0,0,se[0],se[1]]);n.useProgram(J),pn("normal"),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,_.fbo),n.viewport(0,0,V,F),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(Ve),n.bindBuffer(n.ARRAY_BUFFER,Fe),n.bufferData(n.ARRAY_BUFFER,te,n.DYNAMIC_DRAW),_t=null,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,z),n.uniform1i(tn.tex,0),n.uniformMatrix4fv(tn.mvp,!1,Zr(0,V,0,F,-1e4,1e4)),n.drawArrays(n.TRIANGLES,0,6),n.enable(n.BLEND)}function Yr(x,_,V,F,j){if(!Bi||lt)return;const X=Ir.get(x.id);if(!X||X.size===0)return;const K=Math.max(1,Math.round(Math.abs(x.size[0]*(x.scale[0]||1)))),D=Math.max(1,Math.round(Math.abs(x.size[1]*(x.scale[1]||1))));if(K<=1&&D<=1)return;const z=Xe(K,D,"lc:"+x.id);Ri(x,z,K,D,_,V,F,j);for(const L of X)Lt.set(L,z);Ir.delete(x.id),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,F,j)}async function Bs(x,_,V,F,j,X,K,D){Tt++,n.viewport(0,0,V,F);const z=x.general||{};if(z.clearenabled!==!1){const ee=mc(z.clearcolor||"0 0 0");n.clearColor(ee[0],ee[1],ee[2],1)}else n.clearColor(0,0,0,1);if(n.clear(n.COLOR_BUFFER_BIT),qr>=0){const ee=j-qr;en=ee>0&&ee<1?ee:Math.min(.1,Math.max(.001,ee||1/60))}qr=j;const L=Eh(x,V,F,X,K,D);let E=wn(L.projection,L.view);const I=z.cameraparallax,U=I===!0||I!==null&&typeof I=="object"&&I.value===!0;Jt=0,Zn=0;const Q=_n();if(Q&&(Ae.x=Q.u*2-1,Ae.y=Q.v*2-1),!L.perspective&&e.parallax!==!1&&U){const ee=(be,Se)=>{const ye=be!==null&&typeof be=="object"?be.value:be;return typeof ye=="number"&&Number.isFinite(ye)?ye:Se},ue=ee(z.cameraparallaxamount,0),we=ee(z.cameraparallaxmouseinfluence,1),ke=ee(z.cameraparallaxdelay,1),ge=j-_i;_i=j;const Je=ge>0?1-Math.exp(-ge/Math.max(.05,ke)):1;Ae.sx+=(Ae.x-Ae.sx)*Je,Ae.sy+=(Ae.y-Ae.sy)*Je;const Re=ue*we,Ut=60,$t=Ae.sx*Re*L.viewW,st=Ae.sy*Re*L.viewH,pt=Math.max(Math.abs($t),Math.abs(st))/Ut,yn=pt>1?1/pt:1;Jt=-($t*yn),Zn=-(st*yn)}if(!L.perspective&&e.shake!==!1){const ee=Ei(z,j);if(ee){const ue=ee.x*L.viewW*.02,we=ee.y*L.viewH*.02;(ue!==0||we!==0)&&(E=wn(E,Jr(Kr(),ue,we,0)))}}if(mt){const ee=typeof mt=="function"?mt():mt;ee&&typeof ee.syncWorld=="function"&&ee.syncWorld(L,0,0)}if(!O){O=!0;const ee=(x.layers||[]).filter(ke=>ke.isContainer),ue=ee.filter(ke=>(ke.effects||[]).some(ge=>ge.visible)&&!ke.hasChildren),we=ue.filter(ke=>(ke.effects||[]).some(ge=>(ge.materialPasses||[]).length>0));i(`containers total=${ee.length} canvasCandidates=${ue.length} passesResolved=${we.length} names=${ue.slice(0,4).map(ke=>ke.name||"?").join("/")}`)}await Rs(x,_,L,V,F,j);const $=new Map;for(const ee of x.layers)ee.id!==void 0&&$.set(ee.id,ee);const Z=new Set;for(const ee of x.layers)!ee.visible||ee.destroyed||!ee.isContainer||!ee.hasChildren||!(ee.effects||[]).some(we=>we.visible)||(ee.childIds||[]).length===0||ka(ee,$,Z);if(f)try{f()}catch(ee){i("particle advance error: "+(ee&&ee.message))}const se=L.perspective?x.layers.slice().sort((ee,ue)=>+!!ue.isSkybox-+!!ee.isSkybox):x.layers;for(const ee of se)if(!ee.destroyed){if(!ee.visible){Ir.has(ee.id)&&Yr(ee,L,E,V,F);continue}if(!(ee.isPostProcess&&!(ee.effects||[]).some(ue=>ue.visible))&&!Z.has(ee.id)){if(ee.isContainer){if(!(ee.effects||[]).some(we=>we.visible)){Yr(ee,L,E,V,F);continue}if(ee.hasChildren){(ee.childIds||[]).length>0&&await C(ee,x,_,L,E,V,F,j);continue}}if(ee.particle){if(d)try{await d(ee.id,L,E,V,F)}catch(ue){i("particle render error: "+(ue&&ue.message))}continue}Pr(ee,L)||await W(ee,_,L,E,V,F,j)}}if(Pt(z)&&j<Ps){const ee=Math.max(0,Math.min(1,j/Ps)),ue=1-ee*ee*(3-2*ee);if(ue>.002){const we=mc(z.clearcolor||"0 0 0");n.useProgram(G),n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,V,F),n.bindVertexArray(Ve),qt("pass",Ar),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,St),n.uniform1i(De.tex,0),n.uniform4f(De.color,we[0],we[1],we[2],ue),nn(De,null),De.blendPrep!==null&&De.blendPrep!==void 0&&n.uniform1i(De.blendPrep,0),n.uniformMatrix4fv(De.mvp,!1,Gt),n.drawArrays(n.TRIANGLES,0,6)}}const te=fd(z);q||(q=!0,i(te?`bloom post: on strength=${te.strength} threshold=${te.threshold} iter=${te.iterations} radius=${te.radius} damp=${te.damp} hdr=${te.hdr}`:"bloom post: off")),te&&te.strength>.001&&Ms(te,V,F),n.bindVertexArray(null),It()}async function Rs(x,_,V,F,j,X){Lt.clear(),Ir.clear();const K=new Map,D=new Set;let z=null;const L=E=>{if(typeof E!="string")return;const I=/^_rt_imageLayerComposite_(\d+)_[a-z]$/.exec(E);if(!I)return;const U=Number(I[1]);z!==null&&U===z&&D.add(U);let Q=K.get(U);Q||(Q=new Set,K.set(U,Q)),Q.add(E)};for(const E of x.layers||[]){z=E.id;for(const I of E.effects||[])if(I.visible){for(const U of I.passes||[])for(const Q of U.textures||[])L(Q);for(const U of I.materialPasses||[]){for(const Q of U.binds||[])L(Q&&Q.name);for(const Q of U.textures||[])L(Q)}}}if(K.size!==0){for(const[E,I]of K){const U=(x.layers||[]).find(Re=>Re.id===E);if(!U||U.particle||U.isPostProcess||D.has(E))continue;const Q=typeof U.image=="string"?U.image:"";if(U.isContainer&&!U.hasChildren&&Q.indexOf("models/util/composelayer")===0&&!(U.effects||[]).some(Re=>Re.visible)){Ir.set(E,I);continue}const Z=Math.max(1,Math.round(Math.abs(U.size[0]*(U.scale[0]||1)))),se=Math.max(1,Math.round(Math.abs(U.size[1]*(U.scale[1]||1))));if(Z<=1&&se<=1)continue;const te=Xe(Z,se,"lc:"+E);n.bindFramebuffer(n.FRAMEBUFFER,te.fbo),n.viewport(0,0,Z,se),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT);const ee={view:V.view,projection:Zr(0,Z,0,se,-1e4,1e4),eye:V.eye,projW:Z,projH:se,offX:0,offY:0,viewW:Z,viewH:se},ue=lt,we=U.origin,ke=U.scale,ge=U.angles,Je=U.visible;lt={fbo:te,w:Z,h:se},U.origin=[Z/2,ee.projH-se/2,we[2]],U.scale=[Math.sign(ke[0])||1,Math.sign(ke[1])||1,ke[2]],U.angles=[0,0,0],U.visible=!0;try{await W(U,_,ee,ee.projection,Z,se,X);for(const Re of I)Lt.set(Re,te)}catch(Re){i(`composite \u6E90\u5C42 ${E} \u6E32\u67D3\u5931\u8D25: ${Re&&Re.message}`)}finally{lt=ue,U.origin=we,U.scale=ke,U.angles=ge,U.visible=Je}}n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,F,j)}}async function C(x,_,V,F,j,X,K,D){const z=Math.max(1,Math.round(Math.abs(x.size[0]))),L=Math.max(1,Math.round(Math.abs(x.size[1])));if((x.childIds||[]).length===0)return;const I=new Map;for(const ge of _.layers)ge.id!==void 0&&I.set(ge.id,ge);const U=ka(x,I),Q=_.layers.filter(ge=>U.has(ge.id)&&ge.visible);if(Q.length===0)return;const $=Xe(z,L,"group");n.bindFramebuffer(n.FRAMEBUFFER,$.fbo),n.viewport(0,0,z,L),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT);const Z={view:F.view,projection:Zr(0,z,0,L,-1e4,1e4),eye:F.eye,projW:z,projH:L,offX:0,offY:0,viewW:z,viewH:L},se=Z.projection,te=x.scale[0]||1,ee=x.scale[1]||1,ue=x.angles[2]||0,we=Math.cos(-ue),ke=Math.sin(-ue);lt={fbo:$,w:z,h:L};try{for(const ge of Q){if(ge.isPostProcess||ge.particle||ge.isContainer&&(ge.childIds||[]).length>0)continue;const Je=ge.origin,Re=ge.scale,Ut=ge.angles,$t=Je[0]-x.origin[0],st=Je[1]-x.origin[1],pt=($t*we-st*ke)/te,yn=($t*ke+st*we)/ee;ge.origin=[z/2+pt,L/2+yn,Je[2]],ge.scale=[Re[0]/te,Re[1]/ee,Re[2]],ge.angles=[Ut[0],Ut[1],Ut[2]-ue];try{await W(ge,V,Z,se,z,L,D)}finally{ge.origin=Je,ge.scale=Re,ge.angles=Ut}}}finally{lt=null}x.groupTex=$.tex,x.groupW=z,x.groupH=L;try{await W(x,V,F,j,X,K,D)}finally{x.groupTex=null}}async function W(x,_,V,F,j,X,K){const D=!!(x.puppet&&Cr),z=!x.solid&&x.textureName?_.get(x.textureName):null;if(z&&z.video){const be=z.video;if(be.readyState>=2&&be.currentTime!==z.lastUploaded){n.bindTexture(n.TEXTURE_2D,z.glTex);try{let Se=be.videoWidth||z.width,ye=be.videoHeight||z.height;const ze=Math.max(j||0,X||0),Mn=n.getParameter(n.MAX_TEXTURE_SIZE)||0;let at=c;Mn>0&&(at=Math.min(at,Mn)),ze>0&&(at=Math.min(at,ze)),at=Math.max(at,u);let nr=1;Math.max(Se,ye)>at&&(nr=at/Math.max(Se,ye));const Ot=Math.max(1,Math.round(Se*nr)),et=Math.max(1,Math.round(ye*nr));let Fs=be;if(s&&Ot>0&&et>0){(s.width!==Ot||s.height!==et)&&(s.width=Ot,s.height=et);const Bn=s.getContext("2d");Bn&&(Bn.clearRect(0,0,Ot,et),Bn.drawImage(be,0,0,Ot,et),Fs=s)}if(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,Fs),n.getError()!==n.NO_ERROR&&s)try{const Bt=s.getContext("2d").getImageData(0,0,s.width,s.height);for(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,s.width,s.height,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array(Bt.data.buffer));n.getError()!==n.NO_ERROR;);}catch{}z.width=Ot,z.height=et,z.lastUploaded=be.currentTime,o!==Ot+"x"+et&&(o=Ot+"x"+et,a=!0,i("video tex ready "+Ot+"x"+et+" (src "+Se+"x"+ye+", limit "+at+")"))}catch(Se){a||(a=!0,i("video upload FAIL: "+(Se&&Se.message||Se))),console.warn("[we-scene] \u89C6\u9891\u5E27\u4E0A\u4F20\u5931\u8D25:",Se&&Se.message,"readyState=",be.readyState,"cur=",be.currentTime)}}}const L=x.groupTex?x.groupTex:z&&z.glTex?z.glTex:x.solid?St:ct,E=(!!x.passthrough||!!x.isPostProcess||cd(x))&&!x.groupTex&&!z&&!D;let I,U;if(x.groupTex?(I=x.groupW||x.size[0],U=x.groupH||x.size[1]):D||!z?(I=x.size[0],U=x.size[1]):(I=z.width,U=z.height),!D&&z&&x.spriteSheet){const be=z.frames,Se=Array.isArray(be)?be:be&&be.list;Se&&Se.length&&(I=Se[0].width||I,U=Se[0].height||U)}const Q=Math.max(1,Math.round(I)),$=Math.max(1,Math.round(U)),Z=[x.color[0]*x.brightness,x.color[1]*x.brightness,x.color[2]*x.brightness,x.alpha],se=(x.effects||[]).filter(be=>be.visible);let te=Q,ee=$;if(l>0&&V.projW>0&&V.projH>0){const be=Math.min(Math.abs(x.size[0]*x.scale[0]),V.viewW),Se=Math.min(Math.abs(x.size[1]*x.scale[1]),V.viewH),ye=be*(j/V.projW),ze=Se*(X/V.projH);if(ye>0&&ze>0){const Mn=Math.max(64,Math.round(ye*l)),at=Math.max(64,Math.round(ze*l));Mn<Q&&(te=Mn),at<$&&(ee=at)}}if(se.length===0){D?er(x,V,F,j,X,K):Er(G,L,Z,x,V,F,j,X,!1,Mi(x,z,K));return}const ue=Xe(te,ee,"ping"),we=Xe(te,ee,"pong"),ke=Zr(0,te,0,ee,-1e4,1e4);if(D)n.useProgram(G),pn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,ue.fbo),n.viewport(0,0,te,ee),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(Ve),_t=null,qt("layer"+te+"x"+ee,Cn(te,ee)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,L),n.uniform1i(De.tex,0),n.uniform4f(De.color,1,1,1,1),nn(De,null),De.blendPrep!==null&&De.blendPrep!==void 0&&n.uniform1i(De.blendPrep,0),n.uniformMatrix4fv(De.mvp,!1,ke),n.drawArrays(n.TRIANGLES,0,6);else if(E)Ri(x,ue,te,ee,V,F,j,X);else{n.useProgram(G),pn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,ue.fbo),n.viewport(0,0,te,ee),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(Ve),qt("layer"+te+"x"+ee,Cn(te,ee)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,L),n.uniform1i(De.tex,0);const be=se.some(Se=>Se&&Se.layerMaterial)?[1,1,1,Z[3]]:Z;n.uniform4f(De.color,be[0],be[1],be[2],be[3]),nn(De,Mi(x,z,K)),De.blendPrep!==null&&De.blendPrep!==void 0&&n.uniform1i(De.blendPrep,0),n.uniformMatrix4fv(De.mvp,!1,ke),n.drawArrays(n.TRIANGLES,0,6)}let ge=ue,Je=we;const Re=new Map;let Ut=!1,$t=ue;const st=[],pt=new Set;for(const be of se){for(const ye of be.fbos||[])if(!Re.has(ye.name)){const[ze,Mn]=ud(ye,te,ee),at=ye.unique?x.id+":"+ye.name:ye.name;Re.set(ye.name,Xe(ze,Mn,at))}const Se=be.materialPasses||[];for(let ye=0;ye<Se.length;ye++)st.push({eff:be,mp:Se[ye],ov:be.passes&&be.passes[ye]})}const yn=[];for(let be=0;be<st.length;be++){const{eff:Se,mp:ye,ov:ze}=st[be];if(pt.has(Se))continue;const Mn={...ye.combos||{},...ze&&ze.combos||{}},at=ye.textures||[],nr=ze&&ze.textures||[],Ot=[];for(let Ie=0;Ie<Math.max(at.length,nr.length);Ie++)nr[Ie]!==void 0&&nr[Ie]!==null?Ot[Ie]=nr[Ie]:Ot[Ie]=at[Ie]!==void 0?at[Ie]:null;if(ye.copyCommand){const Ie=ye.source?Re.get(ye.source):null,tt=ye.target?Re.get(ye.target):null;Ie&&tt&&(n.useProgram(Y),pn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,tt.fbo),n.viewport(0,0,tt.width,tt.height),n.bindVertexArray(Ve),qt("pass",Ar),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,Ie.tex),n.uniform1i(Xt.tex,0),Xt.blendPrep!==null&&Xt.blendPrep!==void 0&&n.uniform1i(Xt.blendPrep,0),n.uniformMatrix4fv(Xt.mvp,!1,Gt),n.drawArrays(n.TRIANGLES,0,6),n.bindFramebuffer(n.FRAMEBUFFER,null));continue}let et;try{et=await Zt(ye.shader,Mn,Ot)}catch(Ie){const tt=Ie&&Ie.message||String(Ie);/已缓存/.test(tt)||console.warn("[we-scene] \u8DF3\u8FC7\u6548\u679C\uFF08pass \u7F16\u8BD1\u5931\u8D25\uFF09:",ye.shader,tt),pt.add(Se);continue}const Fs=et.prog,Bn=et.uni;et.fragGlsl&&yn.push(et.fragGlsl);let Bt,Fi;ye.target?(Ut||($t=ge,Ut=!0),Bt=Re.get(ye.target)||ge,Fi=$t):(Ut=!1,Bt=Je,Fi=ge),n.useProgram(Fs),pn(ye.blending||"normal"),n.bindFramebuffer(n.FRAMEBUFFER,Bt.fbo),n.viewport(0,0,Bt.width,Bt.height),n.bindVertexArray(Ve);const Xc=!et.ndcDirect;Xc?qt("passPx"+Bt.width+"x"+Bt.height,Cn(Bt.width,Bt.height)):qt("pass",Ar);const ph=Xc?$c(Zr(0,Bt.width,0,Bt.height,-1e4,1e4)):Gt,Oa=ye.textures||[],gh=Math.max(Oa.length,8),Gc=new Map,yh=new Set;for(let Ie=0;Ie<gh;Ie++){let tt=Ie<Oa.length?Oa[Ie]:null;ze&&ze.textures&&ze.textures[Ie]!==void 0&&ze.textures[Ie]!==null&&(tt=ze.textures[Ie]);for(const Ni of ye.binds||[])Ni.index===Ie&&(tt=Ni.name);let bn;if(Ie===0&&(tt==null||tt===""))bn=Fi;else{if((tt==null||tt==="")&&et.samplerDefaults){const Ni=et.samplerDefaults.get(Ie);Ni&&(tt=Ni)}bn=Ii(tt,Fi,Re,_)}tt==="previous"&&(bn=Fi),bn===null&&(bn={glTex:St,width:1,height:1,tex:St});const Di=bn.fbo?bn:{tex:bn.glTex||St,width:bn.width||1,height:bn.height||1};n.activeTexture(n.TEXTURE0+Ie),n.bindTexture(n.TEXTURE_2D,Di.tex),yh.add(Ie),Gc.set(Ie,[Di.width,Di.height,Di.width,Di.height])}Gr(Bn,x,K,V.projW,V.projH,ph,ke,Gt,Gc,ke,V),Ua(Bn,Cs(dn({...ye.constants||{},...ze&&ze.constantshadervalues||{}},(x.id||x.name||"?")+"|"+(ye.shader||"?")+"|"+be,K,x),(x.id||x.name||"?")+"|"+(ye.shader||"?")+"|"+be,K,x),et.matMeta),$r(Bn),n.drawArrays(n.TRIANGLES,0,6),ye.target||(Je=ge,ge=Bt)}if(x.isContainer&&!x.groupTex&&!E&&x.containerAlphaMeaningful===void 0){let be=!1;for(const Se of yn){if(typeof Se!="string")continue;const ye=Se.match(/\bfloat\s+alpha\s*=\s*([^;]+);/);if(ye&&!/^\s*scene\s*\.\s*a\s*$/.test(ye[1])){be=!0;break}}x.containerAlphaMeaningful=be,i(`container "${x.name||"?"}" alpha ${be?"\u643A\u5E26\u5F62\u72B6 \u2192 SRC_ALPHA":"\u65E0\u4FE1\u606F \u2192 \u52A0\u6CD5"}`)}if(D){er(x,V,F,j,X,K,ge.tex);return}Er(Y,ge.tex,[1,1,1,1],x,V,F,j,X,!!x.isContainer&&!x.groupTex&&!E,null,null)}return{gl:n,render:Bs,getFBO:Xe,getEffectProgram:Zt,progCache:Ue,shaderResolver:r,whiteTex:St,resetShaderCaches:function(){Ue.clear(),We.clear(),Oe&&Oe.clear()},setFboCapFactor:function(x){l=x},setParticleRenderer:function(x,_){f=typeof x=="function"?x:null,d=typeof _=="function"?_:null},setConstantScriptRuntime:N,applyConstUserProperties:function(x){if(x){for(const _ of T.values())if(_&&typeof _.applyUserProperties=="function")try{_.applyUserProperties(x)}catch{}}},constantScriptStats:function(){return{...B,cached:T.size}},setCompositeEnabled:function(x){Bi=!!x},compositeStats:function(){const x=[],_=new Uint8Array(4);for(const[V,F]of Lt){let j=null;try{n.bindFramebuffer(n.FRAMEBUFFER,F.fbo),n.readPixels(F.w>>1,F.h>>1,1,1,n.RGBA,n.UNSIGNED_BYTE,_),j=[_[0],_[1],_[2],_[3]]}catch{}x.push({name:V,w:F.w,h:F.h,center:j})}return n.bindFramebuffer(n.FRAMEBUFFER,null),x},setPuppetRenderer:function(x){Cr=x},setAudioProvider:m,setPointerProvider:Kn,getParallaxOffset:function(){return{x:Jt,y:Zn}},dispose:function(){try{const x=n.getExtension("WEBGL_lose_context");x&&x.loseContext()}catch{}}}}const By=Object.freeze(Object.defineProperty({__proto__:null,ALIGN:Zf,XRAY_IDLE_SCREEN_UV:hs,XRAY_SIZE_FALLBACK:hd,applyColorBlendCPU:Ey,bloomPostParams:fd,collectGroupDescendantIds:ka,colorBlendPlan:bc,constantFallback:md,createRenderer:My,effectFboSize:ud,layerCompositeBlendMode:ld,layerWantsPreserveBackdrop:cd,makeTexture:pc,makeTextureMip:gy,needsShaderBlend:wc,puppetAnimMargin:od,rewriteXrayFragScale:dd,xrayShouldParkPointer:vc,xrayUvScale:Cy},Symbol.toStringTag,{value:"Module"}));function Ry(t=256,e=8){const n=t/e,r=pd(1337),i=pd(4242),s=new Float32Array(n*n),a=new Float32Array(n*n);for(let u=0;u<n*n;u++)s[u]=r(),a[u]=i();const o=new Uint8Array(t*t*4),c=e;for(let u=0;u<t;u++){const l=Math.floor(u/c),f=u%c/c,d=f*f*(3-2*f);for(let h=0;h<t;h++){const p=Math.floor(h/c),m=h%c/c,g=m*m*(3-2*m),w=p%n,y=(p+1)%n,b=l%n,v=(l+1)%n,k=s[b*n+w],A=s[b*n+y],T=s[v*n+w],S=s[v*n+y],P=a[b*n+w],M=a[b*n+y],B=a[v*n+w],N=a[v*n+y],O=k+(A-k)*g+(T-k)*d+(k-A-T+S)*g*d,q=P+(M-P)*g+(B-P)*d+(P-M-B+N)*g*d,H=(u*t+h)*4;o[H]=Math.round(O*255),o[H+1]=Math.round(q*255),o[H+2]=0,o[H+3]=255}}return o}function pd(t){let e=t>>>0;return()=>{e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const Fy=Object.freeze(Object.defineProperty({__proto__:null,generateNoiseTexture:Ry},Symbol.toStringTag,{value:"Module"})),sn=Math.PI*2;function nt(t,e){return t==null?Math.random():e==null?t:t+Math.random()*(e-t)}function gd(t,e,n){if(t==null)return Math.random();if(e==null)return t;const r=n&&n!==1?Math.pow(Math.random(),n):Math.random();return t+r*(e-t)}function Ce(t,e){if(Array.isArray(t))return[t[0]||0,t[1]||0,t[2]||0];if(t==null)return e?e.slice():[0,0,0];if(typeof t=="object")return Ce(t.value,e);if(typeof t=="number")return[t,t,t];const n=String(t).trim().split(/\s+/).map(Number);return[n[0]||0,n[1]||0,n[2]||0]}function yd(t){return t==null?null:typeof t=="number"?[t,t,t]:Ce(t)}function oe(t,e){if(t==null)return e;if(typeof t=="object")return oe(t.value,e);const n=Number(t);return Number.isFinite(n)?n:e}function kc(t,e){const n=t[0],r=t[1]>n?t[1]:n+1e-6,i=Math.min(1,Math.max(0,(e-n)/(r-n)));return i*i*(3-2*i)}function mr(t,e,n){const r=Math.sin(t*127.1+e*311.7+n*74.7)*43758.5453;return r-Math.floor(r)}function Dy(t,e,n){const r=Math.floor(t),i=Math.floor(e),s=Math.floor(n),a=t-r,o=e-i,c=n-s,u=a*a*(3-2*a),l=o*o*(3-2*o),f=c*c*(3-2*c),d=(w,y,b)=>w+(y-w)*b,h=d(mr(r,i,s),mr(r+1,i,s),u),p=d(mr(r,i+1,s),mr(r+1,i+1,s),u),m=d(mr(r,i,s+1),mr(r+1,i,s+1),u),g=d(mr(r,i+1,s+1),mr(r+1,i+1,s+1),u);return d(d(h,p,l),d(m,g,l),f)}function Ac(t,e,n,r){let i=0,s=.5,a=1,o=0;for(let c=0;c<r;c++)i+=s*Dy(t*a,e*a,n*a),o+=s,s*=.5,a*=2;return i/(o||1)}function xc(t,e,n,r){return[Ac(t,e,n,r)*2-1,Ac(t+31.7,e+11.3,n+57.1,r)*2-1,Ac(t+73.9,e+92.1,n+13.7,r)*2-1]}function Ny(t){const e=`#version 300 es
355
+ }`,Rb=`#version 300 es
356
+ precision highp float;
357
+ in vec2 v_UV;
358
+ uniform sampler2D u_Tex;
359
+ uniform vec2 u_Texel; // 1/width, 1/height
360
+ out vec4 fragColor;
361
+ void main() {
362
+ const float SPAN_MAX = 8.0;
363
+ const float REDUCE_MUL = 1.0 / 8.0;
364
+ const float REDUCE_MIN = 1.0 / 128.0;
365
+ const vec3 LUMA = vec3(0.299, 0.587, 0.114);
366
+ vec3 rgbNW = texture(u_Tex, v_UV + vec2(-1.0, -1.0) * u_Texel).rgb;
367
+ vec3 rgbNE = texture(u_Tex, v_UV + vec2( 1.0, -1.0) * u_Texel).rgb;
368
+ vec3 rgbSW = texture(u_Tex, v_UV + vec2(-1.0, 1.0) * u_Texel).rgb;
369
+ vec3 rgbSE = texture(u_Tex, v_UV + vec2( 1.0, 1.0) * u_Texel).rgb;
370
+ vec3 rgbM = texture(u_Tex, v_UV).rgb;
371
+ float lumaNW = dot(rgbNW, LUMA);
372
+ float lumaNE = dot(rgbNE, LUMA);
373
+ float lumaSW = dot(rgbSW, LUMA);
374
+ float lumaSE = dot(rgbSE, LUMA);
375
+ float lumaM = dot(rgbM, LUMA);
376
+ float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
377
+ float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
378
+ vec2 dir = vec2(
379
+ -((lumaNW + lumaNE) - (lumaSW + lumaSE)),
380
+ ((lumaNW + lumaSW) - (lumaNE + lumaSE)));
381
+ float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * REDUCE_MUL), REDUCE_MIN);
382
+ float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
383
+ dir = min(vec2(SPAN_MAX), max(vec2(-SPAN_MAX), dir * rcpDirMin)) * u_Texel;
384
+ vec3 rgbA = 0.5 * (
385
+ texture(u_Tex, v_UV + dir * (1.0 / 3.0 - 0.5)).rgb +
386
+ texture(u_Tex, v_UV + dir * (2.0 / 3.0 - 0.5)).rgb);
387
+ vec3 rgbB = rgbA * 0.5 + 0.25 * (
388
+ texture(u_Tex, v_UV + dir * -0.5).rgb +
389
+ texture(u_Tex, v_UV + dir * 0.5).rgb);
390
+ float lumaB = dot(rgbB, LUMA);
391
+ fragColor = vec4((lumaB < lumaMin || lumaB > lumaMax) ? rgbA : rgbB, 1.0);
392
+ }`;function Bb(t,e){return new Float32Array([0,e,0,0,1,0,0,0,0,0,t,e,0,1,1,t,e,0,1,1,0,0,0,0,0,t,0,0,1,0])}function Fb(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,1,0,1,1,-1,-1,0,0,0,1,-1,0,1,0])}function Db(){return new Float32Array([-.5,.5,0,0,1,-.5,-.5,0,0,0,.5,.5,0,1,1,.5,.5,0,1,1,-.5,-.5,0,0,0,.5,-.5,0,1,0])}const Nb={5126:"float",35664:"vec2",35665:"vec3",35666:"vec4",5124:"int",35667:"ivec2",35668:"ivec3",35669:"ivec4",35670:"bool",35676:"mat4",35675:"mat3"};function Tr(t,e,n){const r=Dh(t,t.VERTEX_SHADER,e),i=Dh(t,t.FRAGMENT_SHADER,n),s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,i),t.bindAttribLocation(s,0,"a_Position"),t.bindAttribLocation(s,1,"a_TexCoord"),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error("\u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25: "+t.getProgramInfoLog(s));return s}function Dh(t,e,n){const r=t.createShader(e);if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("\u7740\u8272\u5668\u7F16\u8BD1\u5931\u8D25: "+t.getShaderInfoLog(r));return r}function ho(t){t!==null&&typeof t=="object"&&"value"in t&&(t=t.value);const e=String(t??"").trim().split(/\s+/).map(Number);return[e[0]||0,e[1]||0,e[2]||0]}function Tl(t,e,n,r,i=null,s=null){const a=t.createTexture();t.bindTexture(t.TEXTURE_2D,a);const o=s&&s.wrap==="repeat"?t.REPEAT:t.CLAMP_TO_EDGE;return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,o),i?(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i),t.generateMipmap(t.TEXTURE_2D)):(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,n,r,0,t.RGBA,t.UNSIGNED_BYTE,e)),a}function Lb(t,e,n=!1,r=null){const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=r&&r.wrap==="repeat"?t.REPEAT:t.CLAMP_TO_EDGE;t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR);const a=e[0];if(a.bitmap)t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,a.bitmap);else if(n&&a.rgba){const o=a.width*a.height,c=new Uint8Array(o*2);for(let l=0;l<o;l++)c[l*2]=a.rgba[l*4+3],c[l*2+1]=a.rgba[l*4];const u=t.getParameter(t.UNPACK_ALIGNMENT);t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RG8,a.width,a.height,0,t.RG,t.UNSIGNED_BYTE,c),t.pixelStorei(t.UNPACK_ALIGNMENT,u)}else t.texImage2D(t.TEXTURE_2D,0,t.RGBA,a.width,a.height,0,t.RGBA,t.UNSIGNED_BYTE,a.rgba);return t.generateMipmap(t.TEXTURE_2D),i}function Ub(t,e,n,r=null){const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=r&&r.wrap==="repeat"?t.REPEAT:t.CLAMP_TO_EDGE;t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR);for(let a=0;a<e.length;a++){const o=e[a];t.compressedTexImage2D(t.TEXTURE_2D,a,n,o.width,o.height,0,o.data)}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAX_LEVEL,Math.max(0,e.length-1)),i}function Ob(t,e){const n=Number(e);if(n===7){const r=t.getExtension("WEBGL_compressed_texture_s3tc");return r?{internalFormat:r.COMPRESSED_RGBA_S3TC_DXT1_EXT,blockBytes:8}:null}if(n===6){const r=t.getExtension("WEBGL_compressed_texture_s3tc");return r?{internalFormat:r.COMPRESSED_RGBA_S3TC_DXT3_EXT,blockBytes:16}:null}if(n===4){const r=t.getExtension("WEBGL_compressed_texture_s3tc");return r?{internalFormat:r.COMPRESSED_RGBA_S3TC_DXT5_EXT,blockBytes:16}:null}if(n===12){const r=t.getExtension("WEBGL_compressed_texture_bptc");return r?{internalFormat:r.COMPRESSED_RGBA_BPTC_UNORM_EXT,blockBytes:16}:null}return n===5?{internalFormat:t.COMPRESSED_RGBA8_ETC2_EAC,blockBytes:16}:n===3?{internalFormat:t.COMPRESSED_RGB8_ETC2,blockBytes:8}:null}function zb(t,e,n=null){const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);const i=n&&n.wrap==="repeat"?t.REPEAT:t.CLAMP_TO_EDGE;t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR);const s=e[0],a=t.getParameter(t.UNPACK_ALIGNMENT);return t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.R8,s.width,s.height,0,t.RED,t.UNSIGNED_BYTE,s.data),t.pixelStorei(t.UNPACK_ALIGNMENT,a),t.generateMipmap(t.TEXTURE_2D),r}function Sl(t,e,n,r,i){const s=1-i;return s*s*s*t+3*s*s*i*e+3*s*i*i*n+i*i*i*r}function Hb(t,e,n,r,i){if(i<=t)return 0;if(i>=r)return 1;let s=r-t>1e-9?(i-t)/(r-t):.5;for(let c=0;c<8;c++){const u=Sl(t,e,n,r,s)-i;if(Math.abs(u)<1e-6)return s;const l=1-s,d=3*l*l*(e-t)+6*l*s*(n-e)+3*s*s*(r-n);if(Math.abs(d)<1e-9)break;const f=s-u/d;if(f<0||f>1||!Number.isFinite(f))break;s=f}let a=0,o=1;for(let c=0;c<40;c++)s=(a+o)/2,Sl(t,e,n,r,s)<i?a=s:o=s;return s}function mo(t,e,n){if(!t||t.length===0)return 0;if(t.length===1)return Number(t[0].value)||0;if(n&&n.length>0){const k=t[0],_=t[t.length-1],I=n.length-_.frame;if(I>1e-9&&e>_.frame&&e<=n.length)return mo([{frame:0,value:_.value,front:_.front,back:_.back},{frame:I,value:k.value,front:k.front,back:k.back}],e-_.frame)}if(e<=t[0].frame)return Number(t[0].value)||0;const r=t[t.length-1];if(e>=r.frame)return Number(r.value)||0;let i=0,s=t.length-1;for(;s-i>1;){const k=i+s>>1;t[k].frame<=e?i=k:s=k}const a=t[i],o=t[s],c=a.frame,u=o.frame,l=Number(a.value)||0,d=Number(o.value)||0,f=u-c;if(f<=0)return d;const h=a.front,p=o.back,m=f/3,g=!!(h&&h.enabled),y=!!(p&&p.enabled),w=g?Math.abs(Number(h.x)||0):1,A=y?Math.abs(Number(p.x)||0):1,b=c+Math.min(w,1.5)*m,v=u-Math.min(A,1.5)*m,x=g?l+(Number(h.y)||0):l+(d-l)/3,P=y?d+(Number(p.y)||0):d-(d-l)/3,S=Hb(c,b,v,u,e);return Sl(l,x,P,d,S)}function Nh(t,e,n){const r=e>0?e:1;if(n==="loop"){let i=t%r;return i<0&&(i+=r),i}if(n==="mirror"){const i=r*2;let s=t%i;return s<0&&(s+=i),s<=r?s:i-s}return Math.max(0,Math.min(r,t))}function Vb(t){return Array.isArray(t)?t:typeof t=="string"?t.trim().split(/\s+/).map(Number):Number.isFinite(t)?[t]:[]}function Lh(t,e,n,r,i){if(!t||!t.length||e===n)return[];const s=n>e,a=r>0?r:1,o=[];if(i==="single")for(const c of t)(s?c.frame>e&&c.frame<=n:c.frame>=n&&c.frame<e)&&o.push({at:c.frame,e:c});else if(i==="loop"){const c=Math.floor(Math.min(e,n)/a),u=Math.floor(Math.max(e,n)/a);for(let l=c;l<=u;l++)for(const d of t){const f=l*a+d.frame;(s?f>e&&f<=n:f>=n&&f<e)&&o.push({at:f,e:d})}}else{const c=a*2,u=Math.floor(Math.min(e,n)/c),l=Math.floor(Math.max(e,n)/c);for(let d=u;d<=l;d++)for(const f of t){const h=d*c+f.frame,p=d*c+2*a-f.frame;for(const m of h===p?[h]:[h,p])(s?m>e&&m<=n:m>=n&&m<e)&&o.push({at:m,e:f})}}return o.sort((c,u)=>s?c.at-u.at:u.at-c.at),o.map(c=>c.e)}function Wb(t,e,n){const r=Lh(t._events,e,n,t.frameCount||1,t.mode);for(const i of r)t._eventQueue.push(i)}function Uh(t,e){const n=t instanceof Map?t:new Map(Object.entries(t||{}));for(const[r,i]of n){if(!i||!i.parentKey)continue;const s=n.get(i.parentKey);if(!s||s===i){e&&e(`\u52A8\u753B\u8054\u52A8 parent \u60AC\u7A7A\uFF08\u9000\u5316\u4E3A\u72EC\u7ACB\uFF09\uFF1A${r} -> ${i.parentKey}`);continue}if(s.parentKey){e&&e(`\u52A8\u753B\u8054\u52A8\u591A\u7EA7 parent\uFF08\u4E0D\u652F\u6301\uFF0C\u9000\u5316\u4E3A\u72EC\u7ACB\uFF09\uFF1A${r} -> ${i.parentKey}`);continue}i.parent=s}return n}function Pl(t){const e=t&&t.options||{},n=Number(e.fps)>0?Number(e.fps):30,r=Number(e.length)>0?Number(e.length):0,i=e.mode==="loop"||e.mode==="mirror"?e.mode:"single",s=typeof e.name=="string"?e.name:"",a=!!(t&&t.relative),o=e.wraploop===!0&&i==="loop",c=[];for(let m=0;;m++){const g=t&&t["c"+m];if(!Array.isArray(g))break;c.push(g)}const u=e.startpaused!==!0,l=[],d=e.parent&&typeof e.parent.key=="string"?e.parent.key:null,f=Array.isArray(e.children)?e.children.map(m=>m&&typeof m.key=="string"?m.key:null).filter(Boolean):[],h=Array.isArray(e.events)?e.events.filter(m=>m&&Number.isFinite(Number(m.frame))&&typeof m.name=="string").map(m=>({frame:Number(m.frame),name:m.name})):[],p={name:s,mode:i,fps:n,relative:a,channelCount:c.length,parentKey:d,childKeys:f,parent:null,frame:0,_playing:u,_rate:1,_ended:!1,_events:h,_eventQueue:[],get frameCount(){return r},get playing(){return p.parent?p.parent.playing:p._playing},set playing(m){p.parent?p.parent.playing=!!m:p._playing=!!m},get rate(){return p.parent?p.parent.rate:p._rate},set rate(m){const g=Number(m);Number.isFinite(g)&&(p.parent?p.parent.rate=g:p._rate=g)},get ended(){return p.parent?p.parent.ended:p._ended},set ended(m){p.parent?p.parent.ended=!!m:p._ended=!!m},play(){return p.parent?p.parent.play():(p._playing=!0,p._ended=!1,p)},pause(){return p.parent?p.parent.pause():(p._playing=!1,p)},stop(){return p.parent?p.parent.stop():(p._playing=!1,p.frame=0,p._ended=!1,p)},setFrame(m){if(p.parent)return p.parent.setFrame(m);const g=Number(m);return Number.isFinite(g)&&(p.frame=g),p},getFrame(){return p.parent?p.parent.getFrame():p.frame},setRate(m){return p.parent?p.parent.setRate(m):(p.rate=m,p)},addEndedCallback(m){return p.parent?p.parent.addEndedCallback(m):(typeof m=="function"&&l.push(m),p)},isPlaying(){return p.playing},setBlend(){return p},setVisible(){return p},advance(m){if(p.parent||!p._playing)return;const g=p.frame;if(p.frame+=(Number(m)||0)*n*p._rate,i==="single")if(p.frame>=r){if(p.frame=r,p._playing=!1,!p._ended){p._ended=!0;for(const y of l)try{y()}catch{}}}else p.frame<0&&(p.frame=0,p._playing=!1);Wb(p,g,p.frame)},takeEvents(){if(!p._eventQueue.length)return[];const m=p._eventQueue.slice();return p._eventQueue.length=0,m},value(){const m=Nh(p.parent?p.parent.frame:p.frame,r,i),g=o?{length:r}:void 0;if(c.length===1)return mo(c[0],m,g);const y=[];for(const w of c)y.push(mo(w,m,g));return y},applyTo(m){const g=p.value();if(!a)return g;const y=Vb(m);return Array.isArray(g)?g.map((w,A)=>w+(Number(y[A])||0)):g+(Number(y[0])||0)}};return p}function jb(){const t={name:"",mode:"single",fps:30,relative:!1,channelCount:0,parentKey:null,childKeys:[],parent:null,frame:0,rate:1,playing:!1,ended:!1,get frameCount(){return 0},play(){return t},pause(){return t},stop(){return t},setFrame(){return t},getFrame(){return 0},setRate(){return t},addEndedCallback(){return t},isPlaying(){return!1},setBlend(){return t},setVisible(){return t},advance(){},takeEvents(){return[]},value(){return 0},applyTo(e){return e}};return t}const qb=Object.freeze(Object.defineProperty({__proto__:null,createAnimation:Pl,createNeutralAnimation:jb,crossedEvents:Lh,linkAnimations:Uh,sampleChannel:mo,wrapFrame:Nh},Symbol.toStringTag,{value:"Module"}));function Xb(t,e,n,r){const i=s=>po(e,s(e,n),r);switch(t){case 1:return i((s,a)=>[Math.min(a[0],s[0]),Math.min(a[1],s[1]),Math.min(a[2],s[2])]);case 2:return i((s,a)=>[s[0]*a[0],s[1]*a[1],s[2]*a[2]]);case 3:return i((s,a)=>[a[0]===0?0:Math.max(1-(1-s[0])/a[0],0),a[1]===0?0:Math.max(1-(1-s[1])/a[1],0),a[2]===0?0:Math.max(1-(1-s[2])/a[2],0)]);case 4:return i((s,a)=>[Math.max(s[0]+a[0]-1,0),Math.max(s[1]+a[1]-1,0),Math.max(s[2]+a[2]-1,0)]);case 5:return[Math.min(e[0],n[0]),Math.min(e[1],n[1]),Math.min(e[2],n[2])];case 6:return i((s,a)=>[Math.max(a[0],s[0]),Math.max(a[1],s[1]),Math.max(a[2],s[2])]);case 7:return i((s,a)=>[1-(1-s[0])*(1-a[0]),1-(1-s[1])*(1-a[1]),1-(1-s[2])*(1-a[2])]);case 8:return i((s,a)=>[a[0]===1?1:Math.min(s[0]/(1-a[0]),1),a[1]===1?1:Math.min(s[1]/(1-a[1]),1),a[2]===1?1:Math.min(s[2]/(1-a[2]),1)]);case 9:return i((s,a)=>[Math.min(s[0]+a[0],1),Math.min(s[1]+a[1],1),Math.min(s[2]+a[2],1)]);case 10:return[Math.max(e[0],n[0]),Math.max(e[1],n[1]),Math.max(e[2],n[2])];case 11:return i((s,a)=>Oh(s,a));case 12:return i((s,a)=>$b(s,a));case 13:return i((s,a)=>Oh(a,s));case 14:return i((s,a)=>[ms(s[0],a[0]),ms(s[1],a[1]),ms(s[2],a[2])]);case 15:return i((s,a)=>[a[0]<.5?Math.max(s[0]+2*a[0]-1,0):Math.min(s[0]+2*(a[0]-.5),1),a[1]<.5?Math.max(s[1]+2*a[1]-1,0):Math.min(s[1]+2*(a[1]-.5),1),a[2]<.5?Math.max(s[2]+2*a[2]-1,0):Math.min(s[2]+2*(a[2]-.5),1)]);case 16:return i((s,a)=>[a[0]<.5?Math.min(s[0],2*a[0]):Math.max(s[0],2*(a[0]-.5)),a[1]<.5?Math.min(s[1],2*a[1]):Math.max(s[1],2*(a[1]-.5)),a[2]<.5?Math.min(s[2],2*a[2]):Math.max(s[2],2*(a[2]-.5))]);case 17:return i((s,a)=>[ms(s[0],a[0])<.5?0:1,ms(s[1],a[1])<.5?0:1,ms(s[2],a[2])<.5?0:1]);case 18:return i((s,a)=>[Math.abs(s[0]-a[0]),Math.abs(s[1]-a[1]),Math.abs(s[2]-a[2])]);case 19:return i((s,a)=>[s[0]+a[0]-2*s[0]*a[0],s[1]+a[1]-2*s[1]*a[1],s[2]+a[2]-2*s[2]*a[2]]);case 20:return i((s,a)=>[Math.max(s[0]+a[0]-1,0),Math.max(s[1]+a[1]-1,0),Math.max(s[2]+a[2]-1,0)]);case 21:return i((s,a)=>[a[0]===1?1:Math.min(s[0]*s[0]/(1-a[0]),1),a[1]===1?1:Math.min(s[1]*s[1]/(1-a[1]),1),a[2]===1?1:Math.min(s[2]*s[2]/(1-a[2]),1)]);case 22:return i((s,a)=>[s[0]===1?1:Math.min(a[0]*a[0]/(1-s[0]),1),s[1]===1?1:Math.min(a[1]*a[1]/(1-s[1]),1),s[2]===1?1:Math.min(a[2]*a[2]/(1-s[2]),1)]);case 23:return i((s,a)=>[Math.min(s[0],a[0])-Math.max(s[0],a[0])+1,Math.min(s[1],a[1])-Math.max(s[1],a[1])+1,Math.min(s[2],a[2])-Math.max(s[2],a[2])+1]);case 24:return i((s,a)=>[(s[0]+a[0])/2,(s[1]+a[1])/2,(s[2]+a[2])/2]);case 25:return i((s,a)=>[1-Math.abs(1-s[0]-a[0]),1-Math.abs(1-s[1]-a[1]),1-Math.abs(1-s[2]-a[2])]);case 26:return i((s,a)=>Gb(s,a));case 27:return i((s,a)=>Qb(s,a));case 28:return i((s,a)=>Yb(s,a));case 29:return i((s,a)=>Kb(s,a));case 30:{const s=Math.max(e[0],Math.max(e[1],e[2]));return po(e,[s*n[0],s*n[1],s*n[2]],r)}case 31:return[e[0]+n[0]*r,e[1]+n[1]*r,e[2]+n[2]*r];case 32:return po(e,[e[0]+e[0]*n[0],e[1]+e[1]*n[1],e[2]+e[2]*n[2]],r);default:return po(e,n,r)}}function po(t,e,n){return[t[0]*(1-n)+e[0]*n,t[1]*(1-n)+e[1]*n,t[2]*(1-n)+e[2]*n]}function Oh(t,e){const n=(r,i)=>r<.5?2*r*i:1-2*(1-r)*(1-i);return[n(t[0],e[0]),n(t[1],e[1]),n(t[2],e[2])]}function $b(t,e){const n=(r,i)=>i<.5?2*r*i+r*r*(1-2*i):Math.sqrt(r)*(2*i-1)+2*r*(1-i);return[n(t[0],e[0]),n(t[1],e[1]),n(t[2],e[2])]}function ms(t,e){if(e<.5){const r=2*e;return r===0?0:Math.max(1-(1-t)/r,0)}const n=2*(e-.5);return n===1?1:Math.min(t/(1-n),1)}function $r(t){const e=Math.min(t[0],Math.min(t[1],t[2])),n=Math.max(t[0],Math.max(t[1],t[2])),r=n-e,i=[0,0,0];if(i[2]=(n+e)/2,r===0)i[0]=0,i[1]=0;else{i[1]=i[2]<.5?r/(n+e):r/(2-n-e);const s=((n-t[0])/6+r/2)/r,a=((n-t[1])/6+r/2)/r,o=((n-t[2])/6+r/2)/r;t[0]===n?i[0]=o-a:t[1]===n?i[0]=1/3+s-o:t[2]===n&&(i[0]=2/3+a-s),i[0]<0?i[0]+=1:i[0]>1&&(i[0]-=1)}return i}function _l(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*6*n:2*n<1?e:3*n<2?t+(e-t)*((2/3-n)*6):t}function go(t){if(t[1]===0)return[t[2],t[2],t[2]];const e=t[2]<.5?t[2]*(1+t[1]):t[2]+t[1]-t[1]*t[2],n=2*t[2]-e;return[_l(n,e,t[0]+1/3),_l(n,e,t[0]),_l(n,e,t[0]-1/3)]}function Gb(t,e){const n=$r(t);return go([$r(e)[0],n[1],n[2]])}function Qb(t,e){const n=$r(t);return go([n[0],$r(e)[1],n[2]])}function Yb(t,e){const n=$r(e);return go([n[0],n[1],$r(t)[2]])}function Kb(t,e){const n=$r(t);return go([n[0],n[1],$r(e)[2]])}function zh(t){const e=t&&t.puppet&&t.puppet.animBound;return e?[e.x*Math.abs(t.scale[0]),e.y*Math.abs(t.scale[1])]:[0,0]}function Hh(t){for(const e of t||[]){if(typeof e!="string")continue;const n=e.match(/\bfloat\s+alpha\s*=\s*([^;]+);/);if(n&&!/^\s*scene\s*\.\s*a\s*$/.test(n[1]))return!0;if(e.includes("BlendTransparency(")){if(/ApplyBlending\s*\([^;]*wave\.a/.test(e)||/vec4\s*\(\s*u_color\s*,\s*u_brightness\s*\*\s*smoothed\s*\)/.test(e))return!0;continue}}return!1}function Vh(t){for(const e of t&&t.effects||[]){if(e.visible===!1)continue;const n=Math.max((e.passes||[]).length,(e.materialPasses||[]).length);for(let r=0;r<n;r++){const i=e.passes&&e.passes[r]&&e.passes[r].combos||{},s=e.materialPasses&&e.materialPasses[r]&&e.materialPasses[r].combos||{},a=i.TRANSPARENCY!==void 0?i.TRANSPARENCY:s.TRANSPARENCY;if(Number(a)===0)return!0}}return!1}function Wh(t){return!!(t&&t.isContainer&&!t.hasChildren)}function yo(t,e,n){if(n||(n=new Set),!e)return n;for(const r of t.childIds||[]){const i=e.get(r);!i||i.particle||i.isPostProcess||(n.add(r),yo(i,e,n))}return n}function El(t){const e=Bh[t]||"translucent";return{mode:e,prep:xb[e]||0}}function jh(t,e){const n=Number(t);return Number.isFinite(n)&&n!==0?n:e==="additive"?9:Number.isFinite(n)?n:0}function Ml(t){const e=Number(t);return!Number.isFinite(e)||e===0?!1:!Bh[e]}function Zb(t,e,n,r){if(Ml(t))return Xb(t,[e,e,e],[n,n,n],r)[0];const{mode:i,prep:s}=El(t);let a=n;return s===1?a=n*r:s===2&&(a=1-r+n*r),i==="screen"?a+e*(1-a):i==="multiply"?e*a:i==="additive"?e+n*r:e*(1-r)+n*r}function qh(t,e,n){const r=t&&Number(t.scale)||1;let i=Math.max(1,Math.round(e/r)),s=Math.max(1,Math.round(n/r));const a=t&&Number(t.fit);if(Number.isFinite(a)&&a>0){const o=Math.max(i,s);if(o>a){const c=a/o;i=Math.max(1,Math.round(i*c)),s=Math.max(1,Math.round(s*c))}}return[i,s]}function Xh(t,e,n){const r=Math.max(1,Math.round(Math.abs(t)||1)),i=Math.max(1,Math.round(Math.abs(e)||1)),s=Math.max(1,Math.floor(Number(n)||1)),a=Math.min(1,s/r,s/i);return{width:Math.max(1,Math.round(r*a)),height:Math.max(1,Math.round(i*a)),k:a}}function Cl(t,e){if(!t)return[1,1,1];const n=e||[0,0,0];return[Math.min(1,Math.max(.001,Number(n[0])||0)*Math.PI),Math.min(1,Math.max(.001,Number(n[1])||0)*Math.PI),Math.min(1,Math.max(.001,Number(n[2])||0)*Math.PI)]}function $h(t){const e=t||{},n=(o,c)=>{const u=o!==null&&typeof o=="object"?o.value:o;return u===!0||u===1?!0:u===!1||u===0?!1:c},r=(o,c)=>{const u=o!==null&&typeof o=="object"?o.value:o;return typeof u=="number"&&Number.isFinite(u)?u:c};if(!n(e.bloom,!1))return null;const i=n(e.hdr,!1),s=r(i?e.bloomhdrstrength:e.bloomstrength,1.5),a=ho(e.bloomtint||"1 1 1");return{enabled:!0,hdr:i,strength:s,threshold:i?r(e.bloomhdrthreshold,.1):r(e.bloomthreshold,.65),iterations:Math.max(1,Math.round(i?r(e.bloomhdriterations,8):8)),radius:Math.max(0,i?r(e.bloomhdrscatter,3):3),damp:i?r(e.bloomhdrfeather,.5):.5,alpha:1,tint:a,metric:i?1:0}}function Jb(t){const e=Number(t);return!Number.isFinite(e)||e<.001?999:1/e}const ea=-1;function Il(t,e){return!!e&&!t}const ew="mix(999.0, 1.0 / max(g_PointerScale, 0.001), step(0.001, g_PointerScale))";function Gh(t){if(typeof t!="string"||/unprojectedUVs\s*\*=\s*mix\(999\.0,\s*1\.0\s*\/\s*max\(\s*g_PointerScale/.test(t))return t;const e=/unprojectedUVs\s*\*=\s*v_PointerScale\s*\*/.test(t),n=/unprojectedUVs\s*\*=\s*g_PointerScale\s*\*/.test(t);if(!e&&!n)return t;let r=t;/uniform\s+float\s+g_PointerScale\b/.test(r)||(r=r.replace(/void\s+main\s*\(/,`uniform float g_PointerScale;
393
+ void main(`));const i=e?/unprojectedUVs\s*\*=\s*v_PointerScale\s*\*/:/unprojectedUVs\s*\*=\s*g_PointerScale\s*\*/;return r.replace(i,"unprojectedUVs *= "+ew+" *")}const Qh=1;function Yh(t,e){return t==="g_PointerScale"?Qh:e}function Kh(t,e,n,r,i){const s=e&&e[0]||1,a=e&&e[1]||1;if(!(Math.abs((t&&t[0])*s)<1||Math.abs((t&&t[1])*a)<1))return null;const c=i||1;return[n/c,r/c]}function Zh(t,e,n,r,i){const s=Array.isArray(t)&&t.length>=2?t:[1,1],a=Array.isArray(e)&&e.length>=2?e:[1,1,1],o=i||1,c=Kh(s,a,n,r,o);return c?{size:c,scale:[(Math.sign(a[0])||1)*o,(Math.sign(a[1])||1)*o,a[2]]}:{size:s,scale:[a[0]*o,a[1]*o,a[2]]}}function tw(t,e={}){const n=t.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0});if(!n)throw new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 WebGL2");const r=e.shaderResolver||(async()=>null),i=e.diag||(()=>{}),s=typeof document<"u"?document.createElement("canvas"):null;s&&(s.style.cssText="position:fixed;left:-9999px;top:-9999px;width:2px;height:2px;opacity:0");let a=!1,o="";const c=3840,u=1024;let l=e.fboCapFactor===void 0?0:e.fboCapFactor,d="off",f=!0,h=null,p=!1;function m(){return d==="msaa2"?2:d==="msaa4"?4:0}function g(){n.bindFramebuffer(n.FRAMEBUFFER,h?h.fbo:null)}function y(M,j){const te=m();if(!te||!(M>0)||!(j>0)){h&&w();return}if(h&&h.width===M&&h.height===j&&h.samples===te)return;w();let Z=te;try{const ye=n.getInternalformatParameter(n.RENDERBUFFER,n.RGBA8,n.SAMPLES);let fe=0;if(ye&&ye.length)for(const se of ye)se>fe&&(fe=se);fe>=te||(Z=0)}catch{Z=0}if(!Z){p||(p=!0,i(`msaa: \u9A71\u52A8\u4E0D\u652F\u6301 ${te}x \u591A\u91CD\u91C7\u6837\uFF0C\u56DE\u9000 off`)),d="off";return}const ne=n.createFramebuffer(),de=n.createRenderbuffer();n.bindRenderbuffer(n.RENDERBUFFER,de),n.renderbufferStorageMultisample(n.RENDERBUFFER,Z,n.RGBA8,M,j),n.bindFramebuffer(n.FRAMEBUFFER,ne),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,de);const me=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;if(n.bindRenderbuffer(n.RENDERBUFFER,null),n.bindFramebuffer(n.FRAMEBUFFER,null),!me){n.deleteFramebuffer(ne),n.deleteRenderbuffer(de),p||(p=!0,i(`msaa: FBO \u4E0D\u5B8C\u6574\uFF08${te}x ${M}x${j}\uFF09\uFF0C\u56DE\u9000 off`)),d="off";return}h={fbo:ne,rbo:de,width:M,height:j,samples:Z},p||(p=!0,i(`msaa: on ${Z}x ${M}x${j}`))}function w(){h&&(n.deleteFramebuffer(h.fbo),n.deleteRenderbuffer(h.rbo),h=null)}let A=!1;function b(M,j){if(!h)return;const te=Pt(M,j,"msaaResolve");if(n.bindFramebuffer(n.READ_FRAMEBUFFER,h.fbo),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,te.fbo),n.blitFramebuffer(0,0,M,j,0,0,M,j,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.READ_FRAMEBUFFER,null),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.useProgram(De),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,M,j),n.bindVertexArray(st),rn("pass",ir),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,te.tex),n.uniform1i(Ze.tex,0),n.uniform4f(Ze.color,1,1,1,1),sr(Ze,null),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,sn),n.drawArrays(n.TRIANGLES,0,6),!A){A=!0;const Z=n.getError();Z!==n.NO_ERROR&&i(`msaa resolve: glErr=${Z}`)}}let v=null,x=null,P=null;const S=[["g_AudioSpectrum16Left","left16"],["g_AudioSpectrum16Right","right16"],["g_AudioSpectrum32Left","left32"],["g_AudioSpectrum32Right","right32"],["g_AudioSpectrum64Left","left64"],["g_AudioSpectrum64Right","right64"]];function k(M){P=M||null}let _=null,I=null,B=null,V=null,O=null,U=null,W=null,ie=null;const we=new Map,Y=new Map,oe=new Set;let he=null;const Ae={total:0,ok:0,failed:0};function Pe(M,j){_=typeof M=="function"?M:null,I=j&&j.userProperties||null,B=j&&j.audioViews||null,V=j&&j.shared||null,O=j&&j.inputView||null,U=j&&j.timers||null,W=j&&j.storage||null,ie=j&&typeof j.onSandbox=="function"?j.onSandbox:null,he=j&&Array.isArray(j.animEventQueue)?j.animEventQueue:null,we.clear(),Y.clear(),oe.clear()}let Ce=!1,Le=!1,Ne=0;typeof e.bloomDebugFrames=="number"&&e.bloomDebugFrames;const De=Tr(n,hs,Mb),Re=Tr(n,hs,Cb),Fe=Tr(n,hs,Ib),Xe=Tr(n,Tb,Sb),$e=Tr(n,Pb,_b),Ye=Tr(n,hs,Eb),nt=Tr(n,hs,kb),dn=Tr(n,hs,Rb),st=n.createVertexArray();n.bindVertexArray(st);const gt=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,gt),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,20,12),n.bindVertexArray(null);const Vt=new Map;let xn=1;function Pt(M,j,te){const Z=(te||"")+"|"+M+"x"+j;if(Vt.has(Z)){const ye=Vt.get(Z);return ye.stamp=xn,ye}const ne=n.createFramebuffer(),de=n.createTexture();n.bindTexture(n.TEXTURE_2D,de),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,M,j,0,n.RGBA,n.UNSIGNED_BYTE,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.bindFramebuffer(n.FRAMEBUFFER,ne),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,de,0),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindFramebuffer(n.FRAMEBUFFER,null);const me={fbo:ne,tex:de,width:M,height:j,stamp:xn};return Vt.set(Z,me),me}function xt(){for(const[M,j]of Vt)j.stamp!==xn&&(j.fbo&&n.deleteFramebuffer(j.fbo),j.tex&&n.deleteTexture(j.tex),Vt.delete(M))}const tn=new Map,Mt=new Map,Pi=new Map;function nn(M){const j={},te=/uniform\s+[A-Za-z0-9_]+\s+([A-Za-z_][A-Za-z0-9_]*)[^;]*;\s*\/\/([^\n]*)/g;let Z;for(;(Z=te.exec(M))!==null;){const ne=Z[1],de=Z[2],me=/"material"\s*:\s*"([^"]+)"/.exec(de);if(!me)continue;const ye=/"default"\s*:\s*("(?:[^"]*)"|-?\d+(?:\.\d+)?)/.exec(de);j[me[1]]={uniform:ne,default:ye?tr(ye[1]):void 0}}return j}function _i(M){const j=new Map,te=/uniform\s+sampler2D\s+g_Texture(\d+)\s*;\s*\/\/([^\n]*)/g;let Z;for(;(Z=te.exec(M))!==null;){const ne=Number(Z[1]),de=/"default"\s*:\s*"([^"]+)"/.exec(Z[2]);de&&de[1]&&j.set(ne,de[1])}return j}function ct(M){const j=[],te=/uniform\s+sampler2D\s+(g_Texture(\d+))[^;]*;\s*\/\/([^\n]*)/g;let Z;for(;(Z=te.exec(M))!==null;){const ne=/"combo"\s*:\s*"([^"]+)"/.exec(Z[3]);ne&&j.push({slot:Number(Z[2]),name:Z[1],combo:ne[1]})}return j}function tr(M){if(M.startsWith('"'))return M.slice(1,-1);const j=Number(M);return Number.isFinite(j)?j:void 0}async function pa(M,j,te){let Z=Pi.get(M);if(Z===void 0){const me=await r("shaders/"+M+".frag")||"",ye=await r("shaders/"+M+".vert")||"";Z={frag:me,vert:ye,texCombos:ct(me)},Pi.set(M,Z)}const ne={...j};for(const me of Z.texCombos)te&&te[me.slot]&&ne[me.combo]===void 0&&(ne[me.combo]=1);const de=M+"|"+JSON.stringify(ne);if(tn.has(de)){const me=tn.get(de);if(me===null)throw new Error("shader="+M+" \u7F16\u8BD1\u5931\u8D25\uFF08\u5DF2\u7F13\u5B58\uFF09");return me}for(let me=0;me<4;me++){const ye=new Set,fe=xe=>Mt.has(xe)?Mt.get(xe):(ye.add(xe),null),se=Gh(Ih(Z.frag,"frag",ne,fe,Z.vert)),_e=Ih(Z.vert,"vert",ne,fe,Z.frag);if(ye.size===0){let xe;try{xe=Tr(n,_e,se)}catch(L){throw tn.set(de,null),new Error("shader="+M+" "+(L&&L.message))}const T=new Map,C=n.getProgramParameter(xe,n.ACTIVE_UNIFORMS);for(let L=0;L<C;L++){const X=n.getActiveUniform(xe,L),Q=X.name.replace(/\[0\]$/,"");T.set(Q,{loc:n.getUniformLocation(xe,X.name),type:Nb[X.type]||"unknown",size:X.size})}const R={...nn(Z.vert),...nn(Z.frag)},F=/gl_Position\s*=\s*vec4\s*\(\s*a_Position/.test(Z.vert)&&!/[aA]_Position[\s\S]{0,40}mul\s*\(/.test(Z.vert),$=new Map([..._i(Z.vert),..._i(Z.frag)]),H={prog:xe,uni:T,matMeta:R,samplerDefaults:$,fragGlsl:se,vertGlsl:_e,ndcDirect:F};return tn.set(de,H),H}await Promise.all(Array.from(ye).map(async xe=>{Mt.set(xe,await r("shaders/"+xe)||"")}))}throw new Error("include \u89E3\u6790\u5931\u8D25: "+M)}const hn=Tl(n,new Uint8Array([255,255,255,255]),1,1),Cr=Tl(n,new Uint8Array([0,0,0,0]),1,1);let lt=null;function Un(M){lt=M||null}function kn(){if(!lt)return null;const M=typeof lt=="function"?lt():lt;return M&&M.state?M.state:M}const nr=_p(e),yt=nr==="mirage"?{x:.5,y:.5,sx:.5,sy:.5}:{x:0,y:0,sx:0,sy:0},Oe={mode:nr,mx:0,my:0,amount:0,cx:0,cy:0,lx:0,ly:0,active:!1};let Ke=0,Ei=null,ni=0,On=null,Ir=0,Rr=0,ga=1/60,Ve=-1;const ya=typeof e.fadeDuration=="number"&&e.fadeDuration>=0?e.fadeDuration:1,ba=(M,j)=>{const te=M!==null&&typeof M=="object"?M.value:M;return te===!0||te===1?!0:te===!1||te===0?!1:j},bs=(M,j)=>{const te=M!==null&&typeof M=="object"?M.value:M;return typeof te=="number"&&Number.isFinite(te)?te:j},ws=M=>e.fade===!0&&ba(M.camerafade,!1);function wa(M,j){if(!ba(M.camerashake,!1))return null;const te=bs(M.camerashakeamplitude,0);if(te===0)return null;const Z=Math.max(0,Math.min(1,bs(M.camerashakeroughness,0))),ne=bs(M.camerashakespeed,1),de=j*ne,me=Math.sin(de*2.1)*Math.cos(de*.7),ye=Math.cos(de*1.7)*Math.sin(de*.9),fe=Math.sin(de*11.3)*Math.cos(de*7.1),se=Math.cos(de*9.7)*Math.sin(de*13.1);return{x:(me*(1-Z)+fe*Z)*te,y:(ye*(1-Z)+se*Z)*te}}function ri(){const M=new Date;return(M.getHours()*3600+M.getMinutes()*60+M.getSeconds())/86400}function rt(M,j,te){const Z=M.get(j);Z&&Z.loc!==null&&te(Z.loc,Z.type,Z.size)}function Mi(M){if(typeof M=="number")return[M,M,M,M];const j=String(M).trim().split(/[\s,]+/).map(Number);return[j[0]||0,j[1]||0,j[2]||0,j[3]||0]}function va(M,j,te){const Z=M.get(j);if(!Z||Z.loc===null)return;const ne=te&&te.value!==void 0?te.value:te,de=Mi(ne);switch(Z.type){case"float":n.uniform1f(Z.loc,de[0]);break;case"int":case"bool":n.uniform1i(Z.loc,ne===!0||ne===1?1:Math.round(de[0]));break;case"vec2":n.uniform2f(Z.loc,de[0],de[1]);break;case"vec3":n.uniform3f(Z.loc,de[0],de[1],de[2]);break;case"vec4":n.uniform4f(Z.loc,de[0],de[1],de[2],de[3]);break;case"mat4":n.uniformMatrix4fv(Z.loc,!1,sn);break;case"mat3":n.uniformMatrix3fv(Z.loc,!1,Fi);break}}const Aa=()=>new Float32Array([1,0,0,0,1,0,0,0,1]);function Ci(M,j,te,Z,ne,de,me,ye,fe,se,_e,xe){if(rt(M,"g_Time",L=>n.uniform1f(L,te)),rt(M,"g_Daytime",L=>n.uniform1f(L,ri())),rt(M,"g_ModelViewProjectionMatrix",L=>n.uniformMatrix4fv(L,!1,de)),rt(M,"g_ModelMatrix",L=>n.uniformMatrix4fv(L,!1,me)),rt(M,"g_ViewProjectionMatrix",L=>n.uniformMatrix4fv(L,!1,ye)),xe&&rt(M,"g_EffectModelViewProjectionMatrix",L=>n.uniformMatrix4fv(L,!1,xe)),M.get("g_ModelViewProjectionMatrixInverse")){let L=null;for(const[Q,re]of fe)Q===0&&(L=re);const X=L&&L[0]>0&&L[1]>0?$o(Lr(Nr(),L[0]/2,L[1]/2,1)):sn;rt(M,"g_ModelViewProjectionMatrixInverse",Q=>n.uniformMatrix4fv(Q,!1,X))}rt(M,"g_Brightness",L=>n.uniform1f(L,j.brightness)),rt(M,"g_UserAlpha",L=>n.uniform1f(L,j.alpha)),rt(M,"g_Alpha",L=>n.uniform1f(L,j.alpha)),rt(M,"g_Color",L=>n.uniform3f(L,j.color[0],j.color[1],j.color[2])),rt(M,"g_Color4",L=>n.uniform4f(L,j.color[0],j.color[1],j.color[2],1)),rt(M,"g_CompositeColor",L=>n.uniform3f(L,j.color[0],j.color[1],j.color[2])),rt(M,"g_TexelSize",L=>n.uniform2f(L,1/Z,1/ne)),rt(M,"g_TexelSizeHalf",L=>n.uniform2f(L,.5/Z,.5/ne)),rt(M,"g_TextureReductionScale",L=>n.uniform1f(L,1));const T=kn(),C=Il(!!(T&&T.has),!!M.get("g_PointerScale"));let R=C?ea:T?T.u:.5,F=C?ea:T?T.v:.5,$=C?ea:T?T.lastU:.5,H=C?ea:T?T.lastV:.5;if(_e&&j&&j.size&&j.size[0]>0&&j.size[1]>0){const L=Math.abs(j.size[0]*j.scale[0]),X=Math.abs(j.size[1]*j.scale[1]);if(L>0&&X>0){const Q=j.origin[0]-L/2,re=_e.projH-j.origin[1]-X/2,q=D=>(_e.offX+D*_e.viewW-Q)/L,K=D=>(_e.offY+D*_e.viewH-re)/X;R=q(R),F=K(F),$=q($),H=K(H)}}rt(M,"g_PointerPosition",L=>n.uniform2f(L,R,F)),rt(M,"g_PointerPositionLast",L=>n.uniform2f(L,$,H)),rt(M,"g_PointerState",L=>n.uniform4f(L,R,F,T&&T.leftDown?1:0,0)),rt(M,"g_ParallaxPosition",L=>{Oe.mode==="mirage"?n.uniform2f(L,yt.sx,yt.sy):n.uniform2f(L,yt.sx*.5+.5,yt.sy*.5+.5)}),rt(M,"g_Frametime",L=>n.uniform1f(L,ga)),M.get("g_EffectTextureProjectionMatrixInverse")&&rt(M,"g_EffectTextureProjectionMatrixInverse",L=>n.uniformMatrix4fv(L,!1,sn));for(let L=0;L<8;L++)rt(M,"g_Texture"+L,X=>n.uniform1i(X,L));for(const[L,X]of fe)rt(M,"g_Texture"+L+"Resolution",Q=>n.uniform4f(Q,X[0],X[1],X[2],X[3]));if(P){const L=typeof P=="function"?P():P;if(L)for(const[X,Q]of S){const re=L[Q];re&&rt(M,X,q=>n.uniform1fv(q,re))}}}function Wo(M,j,te){for(const[Z,ne]of Object.entries(j||{})){const de=te&&te[Z];de&&va(M,de.uniform,ne)}for(const[Z,ne]of Object.entries(te||{}))if(!j||!(Z in j)){const de=Yh(ne.uniform,ne.default);de!==void 0&&va(M,ne.uniform,de)}}function zn(M){const j=kn();Il(!!(j&&j.has),!!M.get("g_PointerScale"))&&rt(M,"g_PointerScale",te=>n.uniform1f(te,0))}function Ii(M,j){return j?typeof M=="number"&&Number.isFinite(M):!!M&&typeof M=="object"&&Number.isFinite(Number(M.x))&&Number.isFinite(Number(M.y))}let vs=[1,1,1],xa=1920,rr=1080;function Ct(M,j,te,Z){if(!M)return M;let ne=!1;for(const me of Object.values(M))if(me!==null&&typeof me=="object"&&typeof me.script=="string"){ne=!0;break}if(!ne||!_)return M;const de={...M};for(const[me,ye]of Object.entries(M)){if(ye===null||typeof ye!="object"||typeof ye.script!="string")continue;const fe=j+"|"+me;let se=we.get(fe);if(se===void 0){Ae.total++;try{se=_(ye.script,ye.scriptproperties||ye.scriptProperties||null,{userProperties:I||{},screenResolution:{x:xa,y:rr},timeOfDay:ri(),audioViews:B||void 0,layer:Z||null,shared:V||{},inputView:O||void 0,setTimeout:U?U.setTimeout:void 0,clearTimeout:U?U.clearTimeout:void 0,setInterval:U?U.setInterval:void 0,clearInterval:U?U.clearInterval:void 0,storage:W||void 0,getAnimationForProperty:()=>{const R=Y.get(j+"|anim|"+me);return R?R.ctrl:null}})}catch{se=null}if(se?Ae.ok++:Ae.failed++,we.set(fe,se),se){const R=ye.value!==void 0?ye.value:ye,F=Mi(R),$=typeof R=="number",H=$?F[0]:{x:F[0],y:F[1],z:F[2]},L=se.init(H);se.__lastConstValue=Ii(L,$)?L:H}if(se&&typeof se.applyUserProperties=="function")try{se.applyUserProperties(I||{})}catch{}if(se&&(se.hasMediaHook||se.hasAnimEventHook||se.hasResizeHook)&&ie)try{ie(se,{layer:Z,key:me})}catch{}}if(!se||se.disabled||!se.hasUpdate)continue;if(se.engine){se.engine.runtime=te,se.engine.frametime=ga,se.engine.timeOfDay=ri();const R=kn();R&&R.screenW&&R.screenH&&(se.engine.screenResolution={x:R.screenW,y:R.screenH})}const _e=typeof(ye.value!==void 0?ye.value:ye)=="number";if(!Ii(se.__lastConstValue,_e)){const R=Mi(ye.value!==void 0?ye.value:ye);se.__lastConstValue=_e?R[0]:{x:R[0],y:R[1],z:R[2]}}const xe=se.__lastConstValue;let T;try{T=se.callUpdate(xe)}catch{T=void 0}const C=T??xe;if(Ii(C,_e)&&(se.__lastConstValue=C),typeof C=="number"&&Number.isFinite(C))de[me]=C;else if(C&&typeof C=="object"){const R=Number(C.x),F=Number(C.y),$=Number(C.z);Number.isFinite(R)&&Number.isFinite(F)&&(de[me]=Number.isFinite($)?`${R} ${F} ${$}`:`${R} ${F} 0`)}}return de}function As(M,j,te){if(M)for(const[Z,ne]of Object.entries(M)){if(!ne||typeof ne!="object"||!ne.animation||!ne.animation.options)continue;const de=j+"|anim|"+Z;let me=Y.get(de);if(!me){const ye=Pl(ne.animation),fe=ne.value!==void 0?ne.value:0;ye.baseNumeric=Array.isArray(fe)?fe.slice():fe,me={ctrl:ye,prevTime:te},Y.set(de,me)}}}function Hn(M,j,te,Z){if(!M)return M;let ne=!1;for(const ye of Object.values(M))if(ye&&typeof ye=="object"&&ye.animation&&ye.animation.options){ne=!0;break}if(!ne)return M;const de={...M},me=new Map;for(const[ye,fe]of Object.entries(M)){if(!fe||typeof fe!="object"||!fe.animation||!fe.animation.options)continue;const se=j+"|anim|"+ye;let _e=Y.get(se);if(!_e){const xe=Pl(fe.animation),T=fe.value!==void 0?fe.value:0;xe.baseNumeric=Array.isArray(T)?T.slice():T,_e={ctrl:xe,prevTime:te},Y.set(se,_e)}me.set(ye,_e.ctrl)}oe.has(j)||(oe.add(j),Uh(me,ye=>i(`${j}: ${ye}`)));for(const[ye,fe]of Object.entries(M)){if(!fe||typeof fe!="object"||!fe.animation||!fe.animation.options)continue;const se=j+"|anim|"+ye,_e=Y.get(se),xe=te-_e.prevTime;if(_e.prevTime=te,_e.ctrl.playing&&_e.ctrl.advance(Math.max(0,xe)),he){const T=_e.ctrl.takeEvents();T.length&&he.push({layer:Z,events:T})}else _e.ctrl.takeEvents();de[ye]=_e.ctrl.applyTo(_e.ctrl.baseNumeric)}return de}function ka(M,j,te,Z){if(M==null||M==="")return null;if(M==="_rt_FullFrameBuffer"){if(!On||On.stamp!==ni){const ne=n.getParameter(n.FRAMEBUFFER_BINDING),de=n.getParameter(n.TEXTURE_BINDING_2D);On={glTex:_n(Ir||1,Rr||1),width:Ir||1,height:Rr||1,stamp:ni},n.bindFramebuffer(n.FRAMEBUFFER,ne),n.bindTexture(n.TEXTURE_2D,de)}return On}return M.startsWith("_rt_")?M.startsWith("_rt_imageLayerComposite")?Li&&gn.has(M)?gn.get(M):j:te.has(M)?te.get(M):null:te.has(M)?te.get(M):Z.get(M)||null}const ir=Fb(),Ta=Db(),Ri=new Map;function Br(M,j){const te=M+"x"+j;let Z=Ri.get(te);return Z===void 0&&(Z=Bb(M,j),Ri.set(te,Z)),Z}let Gt=null;function rn(M,j){Gt!==M&&(n.bindBuffer(n.ARRAY_BUFFER,gt),n.bufferData(n.ARRAY_BUFFER,j,n.DYNAMIC_DRAW),Gt=M)}const Ze={mvp:n.getUniformLocation(De,"u_MVP"),tex:n.getUniformLocation(De,"u_Tex"),color:n.getUniformLocation(De,"u_Color4"),frameOrigin:n.getUniformLocation(De,"u_FrameOrigin"),frameU:n.getUniformLocation(De,"u_FrameU"),frameV:n.getUniformLocation(De,"u_FrameV"),blendPrep:n.getUniformLocation(De,"u_BlendPrep")},Tn={mvp:n.getUniformLocation(Re,"u_MVP"),tex:n.getUniformLocation(Re,"u_Tex"),blendPrep:n.getUniformLocation(Re,"u_BlendPrep")},Bi={mvp:n.getUniformLocation(Fe,"u_MVP"),tex:n.getUniformLocation(Fe,"u_Tex")},Vn={mvp:n.getUniformLocation(nt,"u_MVP"),tex:n.getUniformLocation(nt,"u_Tex"),backdrop:n.getUniformLocation(nt,"u_Backdrop"),blendMode:n.getUniformLocation(nt,"u_BlendMode"),canvasSize:n.getUniformLocation(nt,"u_CanvasSize"),opacity:n.getUniformLocation(nt,"u_Opacity")},Wn={tex:n.getUniformLocation(Xe,"u_Tex"),texel:n.getUniformLocation(Xe,"u_Texel"),damp:n.getUniformLocation(Xe,"u_Damp"),alpha:n.getUniformLocation(Xe,"u_Alpha"),strength:n.getUniformLocation(Xe,"u_Strength"),threshold:n.getUniformLocation(Xe,"u_Threshold"),metric:n.getUniformLocation(Xe,"u_Metric")},It={tex:n.getUniformLocation($e,"u_Tex"),texel:n.getUniformLocation($e,"u_Texel"),res:n.getUniformLocation($e,"u_Res"),radius:n.getUniformLocation($e,"u_Radius"),dir:n.getUniformLocation($e,"u_Dir"),alpha:n.getUniformLocation($e,"u_Alpha"),strength:n.getUniformLocation($e,"u_Strength"),iterations:n.getUniformLocation($e,"u_Iterations")},Fr={mvp:n.getUniformLocation(Ye,"u_MVP"),tex:n.getUniformLocation(Ye,"u_Tex"),alpha:n.getUniformLocation(Ye,"u_Alpha"),strength:n.getUniformLocation(Ye,"u_Strength"),tint:n.getUniformLocation(Ye,"u_Tint")},ii={mvp:n.getUniformLocation(dn,"u_MVP"),tex:n.getUniformLocation(dn,"u_Tex"),texel:n.getUniformLocation(dn,"u_Texel")},sn=Nr(),Fi=Aa();function mn(M){M==="translucent"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):M==="additive"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE)):n.disable(n.BLEND)}let jn=0;function Sn(M){const{mode:j,prep:te}=El(M);jn=te,j==="additive"?(n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE)):j==="multiply"?(n.enable(n.BLEND),n.blendFuncSeparate(n.DST_COLOR,n.ZERO,n.ONE,n.ONE_MINUS_SRC_ALPHA)):j==="screen"?(n.enable(n.BLEND),n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_COLOR,n.ONE,n.ONE_MINUS_SRC_ALPHA)):mn("translucent")}function Sa(M,j){if(j&&j.perspective||M.perspective)return!1;const te=M.size[0]*M.scale[0],Z=M.size[1]*M.scale[1];if(te===0||Z===0)return!1;let ne=Math.abs(te)/2,de=Math.abs(Z)/2;const me=M.angles[2];if(me!==0){const C=Math.abs(Math.cos(me)),R=Math.abs(Math.sin(me)),F=ne*C+de*R,$=ne*R+de*C;ne=F,de=$}const ye=M.origin[0],fe=j.projH-M.origin[1];let se=64;if(M.parallaxDepthOwn||M.parallaxDepth||M.parallaxDepthProp)if(Oe.active&&Oe.mode==="mirage"){const C=M.parallaxDepthProp||M.parallaxDepth||[0,0],R=M.parallaxAnchor||[ye,j.projH-fe],F=Math.abs(R[0]-Oe.cx+Oe.mx)*Math.abs(C[0])*Oe.amount,$=Math.abs(R[1]-Oe.cy+Oe.my)*Math.abs(C[1])*Oe.amount;se+=F+$}else Oe.active&&M.parallaxDepth&&(se+=Math.abs(Ea(M.parallaxDepth[0])*Oe.lx),se+=Math.abs(Ea(M.parallaxDepth[1])*Oe.ly));const _e=zh(M),xe=se+_e[0],T=se+_e[1];return ye+ne+xe<j.offX||ye-ne-xe>j.offX+j.viewW||fe+de+T<j.offY||fe-de-T>j.offY+j.viewH}function Di(M,j,te){if(!M.spriteSheet)return null;const Z=j&&j.frames,ne=Array.isArray(Z)?Z:Z&&Z.list;if(!ne||ne.length===0)return null;const de=Z&&Z.atlasWidth||j.width||0,me=Z&&Z.atlasHeight||j.height||0;if(de<=0||me<=0)return null;M.spriteFrameCount=ne.length;let ye=0;const fe=M.textureAnimation;if(fe&&fe.frame!==null&&fe.frame!==void 0)ye=Math.floor(Number(fe.frame))||0,ye>=0||(ye=0),ye>=ne.length&&(ye=ne.length-1);else if(ne.length>1){const R=fe&&fe.playing===!1;let F=0;for(const $ of ne)F+=$.duration>0?$.duration:1/30;if(!R&&F>0){let $=te%F;$<0&&($+=F);for(let H=0;H<ne.length;H++){const L=ne[H].duration>0?ne[H].duration:.03333333333333333;if($<L){ye=H;break}$-=L,ye=H}}}const se=ne[ye],_e=se.uDir?se.uDir[0]:se.width,xe=se.uDir?se.uDir[1]:0,T=se.vDir?se.vDir[0]:0,C=se.vDir?se.vDir[1]:se.height;return[se.x/de,se.y/me,_e/de,xe/me,T/de,C/me]}function pn(M,j){const te=M.size[0]*M.scale[0],Z=M.size[1]*M.scale[1];let ne=Nr();if(j&&j.perspective){const me=wp(M,j);ne=ui(ne,me[0],me[1],me[2]);const ye=M.angles[0]||0,fe=M.angles[1]||0;fe&&(ne=Tu(ne,fe)),ye&&(ne=ku(ne,ye)),ne=xu(ne,-M.angles[2])}else{if(ne=ui(ne,M.origin[0],j.projH-M.origin[1],M.origin[2]),M.parallaxDepth&&Oe.active){const me=Ko(M,Oe);(me[0]!==0||me[1]!==0)&&(ne=ui(ne,me[0],me[1],0))}ne=xu(ne,-M.angles[2]),M.perspective&&(M.angles[1]&&(ne=Tu(ne,-M.angles[1])),M.angles[0]&&(ne=ku(ne,M.angles[0])))}const de=Rh[M.alignment]||[.5,.5];return(de[0]!==.5||de[1]!==.5)&&(ne=ui(ne,(.5-de[0])*te,(.5-de[1])*Z,0)),{m:ne,w:te,h:Z}}function Pn(M,j,te,Z,ne,de,me,ye,fe=!1,se=null,_e=null){const xe=pn(Z,ne);let T=xe.m;if(_e){const $=(_e[0]+_e[2]/2)*Z.scale[0],H=(_e[1]+_e[3]/2)*Z.scale[1];T=ui(T,$,-H,0),T=Lr(T,_e[2]*Z.scale[0],_e[3]*Z.scale[1],1)}else T=Lr(T,xe.w,xe.h,1);const C=Wt(de,T);if(!fe&&!it&&Ml(Z.colorBlendMode)){const $=_n(me,ye);n.useProgram(nt),n.disable(n.BLEND),g(),n.viewport(0,0,me,ye),n.bindVertexArray(st),rn("local",Ta),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,j),n.uniform1i(Vn.tex,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,$),n.uniform1i(Vn.backdrop,1),n.uniform1i(Vn.blendMode,Number(Z.colorBlendMode)|0),n.uniform2f(Vn.canvasSize,me,ye),n.uniform1f(Vn.opacity,te[3]),n.uniformMatrix4fv(Vn.mvp,!1,C),n.drawArrays(n.TRIANGLES,0,6),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,null),n.activeTexture(n.TEXTURE0);return}const F=M===Re?Tn:Ze;n.useProgram(M),fe?(jn=0,n.enable(n.BLEND),Z.containerAlphaMeaningful?n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA):n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):Sn(jh(Z.colorBlendMode,Z.materialBlending)),F.blendPrep!==null&&F.blendPrep!==void 0&&n.uniform1i(F.blendPrep,jn),it?(n.bindFramebuffer(n.FRAMEBUFFER,it.fbo.fbo),n.viewport(0,0,it.w,it.h)):(g(),n.viewport(0,0,me,ye)),n.bindVertexArray(st),rn("local",Ta),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,j),n.uniform1i(F.tex,0),n.uniformMatrix4fv(F.mvp,!1,C),F.color!==null&&F.color!==void 0&&n.uniform4f(F.color,te[0],te[1],te[2],te[3]),sr(F,se),n.drawArrays(n.TRIANGLES,0,6)}function sr(M,j){!M||M.frameOrigin===null||M.frameOrigin===void 0||(j?(n.uniform2f(M.frameOrigin,j[0],j[1]),n.uniform2f(M.frameU,j[2],j[3]),n.uniform2f(M.frameV,j[4],j[5])):(n.uniform2f(M.frameOrigin,0,0),n.uniform2f(M.frameU,1,0),n.uniform2f(M.frameV,0,1)))}let Ni=null,it=null;const gn=new Map;let si=0;const ar=new Map,ai=new Map;let Li=!0;function oi(M,j){const te=pn(M,j),Z=j&&j.perspective?M.scale[1]:-M.scale[1],ne=j&&j.perspective&&M.scale[2]||1;return Lr(te.m,M.scale[0],Z,ne)}function Ui(M,j,te,Z,ne,de,me){it?(n.bindFramebuffer(n.FRAMEBUFFER,it.fbo.fbo),n.viewport(0,0,it.w,it.h)):(g(),n.viewport(0,0,Z,ne)),me&&(n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,me),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR),n.generateMipmap(n.TEXTURE_2D));const ye=Wt(te,oi(M,j));Ni(M,ye,{time:de,overrideTex:me||null,ambient:Cl(M.lightingEnabled,vs),keepZ:!!(j&&j.perspective)}),me&&(n.bindTexture(n.TEXTURE_2D,me),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR)),Gt=null}let or=null;function _n(M,j){if(it)return it.fbo.tex;if(h){const te=Pt(M,j,"msaaBackdrop");return n.bindFramebuffer(n.READ_FRAMEBUFFER,h.fbo),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,te.fbo),n.blitFramebuffer(0,0,M,j,0,0,M,j,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.READ_FRAMEBUFFER,null),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),te.tex}return or===null&&(or=n.createTexture(),n.bindTexture(n.TEXTURE_2D,or),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindTexture(n.TEXTURE_2D,or),n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB8,0,0,M,j,0),or}function ci(M,j,te){const Z=_n(j,te),ne=Math.max(1,Math.round(j/4)),de=Math.max(1,Math.round(te/4)),me=Pt(ne,de,"bloomA"),ye=Pt(ne,de,"bloomB");n.bindVertexArray(st),rn("pass",ir),n.activeTexture(n.TEXTURE0),n.useProgram(Xe),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,me.fbo),n.viewport(0,0,ne,de),n.bindTexture(n.TEXTURE_2D,Z),n.uniform1i(Wn.tex,0),n.uniform2f(Wn.texel,1/j,1/te),n.uniform1f(Wn.damp,M.damp),n.uniform1f(Wn.alpha,M.alpha),n.uniform1f(Wn.strength,M.strength),n.uniform1f(Wn.threshold,M.threshold),n.uniform1i(Wn.metric,M.metric),n.drawArrays(n.TRIANGLES,0,6),n.useProgram($e);const fe=(se,_e,xe,T)=>{n.bindFramebuffer(n.FRAMEBUFFER,_e.fbo),n.viewport(0,0,_e.width,_e.height),n.bindTexture(n.TEXTURE_2D,se.tex),n.uniform1i(It.tex,0),n.uniform2f(It.texel,1/se.width,1/se.height),n.uniform2f(It.res,se.width,se.height),n.uniform1f(It.radius,M.radius),n.uniform2f(It.dir,xe,T),n.uniform1f(It.alpha,M.alpha),n.uniform1f(It.strength,M.strength),n.uniform1f(It.iterations,M.iterations),n.drawArrays(n.TRIANGLES,0,6)};if(fe(me,ye,1,0),fe(ye,me,0,1),n.useProgram(Ye),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,j,te),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE),n.bindTexture(n.TEXTURE_2D,me.tex),n.uniform1i(Fr.tex,0),n.uniformMatrix4fv(Fr.mvp,!1,sn),n.uniform1f(Fr.alpha,M.alpha),n.uniform1f(Fr.strength,M.strength),n.uniform3f(Fr.tint,M.tint[0],M.tint[1],M.tint[2]),n.drawArrays(n.TRIANGLES,0,6),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA),Ne++,Ne===1||Ne===120||Ne===600){const se=new Uint8Array(4);n.bindFramebuffer(n.FRAMEBUFFER,me.fbo),n.readPixels(ne>>1,de>>1,1,1,n.RGBA,n.UNSIGNED_BYTE,se),n.bindFramebuffer(n.FRAMEBUFFER,null),i(`bloom frame ${Ne}: center=[${[...se].join(",")}] glErr=${n.getError()} threshold=${M.threshold} strength=${M.strength} metric=${M.metric}`)}}function xs(M,j,te,Z,ne,de,me,ye){const fe=_n(me,ye),se=pn(M,ne);let _e=se.m;_e=Lr(_e,se.w,se.h,1);const xe=Wt(de,_e),T=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]].map(([L,X])=>{const Q=Ap(xe,L,X,0);return[Q[0]*.5+.5,Q[1]*.5+.5]}),[C,R,F,$]=T,H=new Float32Array([0,Z,0,C[0],C[1],0,0,0,F[0],F[1],te,Z,0,R[0],R[1],te,Z,0,R[0],R[1],0,0,0,F[0],F[1],te,0,0,$[0],$[1]]);n.useProgram(Fe),mn("normal"),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,j.fbo),n.viewport(0,0,te,Z),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(st),n.bindBuffer(n.ARRAY_BUFFER,gt),n.bufferData(n.ARRAY_BUFFER,H,n.DYNAMIC_DRAW),Gt=null,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,fe),n.uniform1i(Bi.tex,0),n.uniformMatrix4fv(Bi.mvp,!1,Hi(0,te,0,Z,-1e4,1e4)),n.drawArrays(n.TRIANGLES,0,6),n.enable(n.BLEND)}async function Oi(M,j,te,Z,ne,de){if(!Li||it)return;const me=ar.get(M.id);if(!me||me.size===0)return;const ye=Math.max(1,Math.round(Math.abs(M.size[0]*(M.scale[0]||1)))),fe=Math.max(1,Math.round(Math.abs(M.size[1]*(M.scale[1]||1))));if(ye<=1&&fe<=1)return;const se=Pt(ye,fe,"lc:"+M.id);if((M.effects||[]).some(xe=>xe.visible)){const xe=it;it={fbo:se,w:ye,h:fe};try{li(M,textures,j,te,Z,ne,de)}catch(T){i(`z \u5E8F\u5408\u6210\u6E90 ${M.id} \u6548\u679C\u94FE\u5931\u8D25: ${T&&T.message}`)}finally{it=xe}}else xs(M,se,ye,fe,j,te,Z,ne);for(const xe of me)gn.set(xe,se);if(ar.delete(M.id),M.copybackground)for(const xe of me)ai.set(xe,se);g(),n.viewport(0,0,Z,ne)}async function Pa(M,j,te,Z,ne,de,me,ye){xa=te,rr=Z,xn++,y(te,Z),g(),n.viewport(0,0,te,Z);const fe=M.general||{};if(vs=ho(fe.ambientcolor||"1 1 1"),fe.clearenabled!==!1){const Q=ho(fe.clearcolor||"0 0 0");n.clearColor(Q[0],Q[1],Q[2],1)}else n.clearColor(0,0,0,1);if(n.clear(n.COLOR_BUFFER_BIT),Ve>=0){const Q=ne-Ve;ga=Q>0&&Q<1?Q:Math.min(.1,Math.max(.001,Q||1/60))}Ve=ne;const se=Tp(M,te,Z,de,me,ye);let _e=Wt(se.projection,se.view);ni++,Ir=te,Rr=Z;const xe=fe.cameraparallax,T=xe===!0||xe!==null&&typeof xe=="object"&&xe.value===!0,C=kn();if(C&&(Oe.mode==="mirage"?(yt.x=C.u,yt.y=C.v):(yt.x=C.u*2-1,yt.y=C.v*2-1)),!se.perspective&&e.parallax!==!1&&T){const Q=(z,ee)=>{const G=z!==null&&typeof z=="object"?z.value:z;return typeof G=="number"&&Number.isFinite(G)?G:ee},re=Q(fe.cameraparallaxamount,0),q=Q(fe.cameraparallaxmouseinfluence,1),K=Q(fe.cameraparallaxdelay,1),D=ne-Ke;Ke=ne;const E=D>0?1-Math.exp(-D/Math.max(.05,K)):1;if(yt.sx+=(yt.x-yt.sx)*E,yt.sy+=(yt.y-yt.sy)*E,Oe.mode==="mirage")Oe.mx=(.5-yt.sx)*se.projW*q,Oe.my=(yt.sy-.5)*se.projH*q,Oe.amount=re,Oe.cx=se.projW/2,Oe.cy=se.projH/2,Oe.lx=0,Oe.ly=0;else{const z=re*q,ee=60,G=yt.sx*z*se.viewW,J=yt.sy*z*se.viewH,ge=Math.max(Math.abs(G),Math.abs(J))/ee,ae=ge>1?1/ge:1;Oe.lx=-(G*ae),Oe.ly=-(J*ae),Oe.mx=0,Oe.my=0,Oe.amount=0}Oe.active=!0}else Oe.active=!1,Oe.lx=0,Oe.ly=0;let R=null;if(!se.perspective&&e.shake!==!1){const Q=wa(fe,ne);if(Q){const re=Q.x*se.viewW*.02,q=Q.y*se.viewH*.02;(re!==0||q!==0)&&(R=ui(Nr(),re,q,0),_e=Wt(_e,R))}}let F=null;if(Ei=null,!se.perspective)for(const Q of M.layers){if(!Q.perspective||Q.destroyed)continue;const re=Sp(se,fe);re&&(F=R?Wt(re.viewProj,R):re.viewProj,Ei=re.eye);break}if(lt){const Q=typeof lt=="function"?lt():lt;Q&&typeof Q.syncWorld=="function"&&Q.syncWorld(se,0,0)}if(!Ce){Ce=!0;const Q=(M.layers||[]).filter(K=>K.isContainer),re=Q.filter(K=>(K.effects||[]).some(D=>D.visible)&&!K.hasChildren),q=re.filter(K=>(K.effects||[]).some(D=>(D.materialPasses||[]).length>0));i(`containers total=${Q.length} canvasCandidates=${re.length} passesResolved=${q.length} names=${re.slice(0,4).map(K=>K.name||"?").join("/")}`)}await jo(M,j,se,te,Z,ne);const $=new Map;for(const Q of M.layers)Q.id!==void 0&&$.set(Q.id,Q);const H=new Set;for(const Q of M.layers)!Q.visible||Q.destroyed||!Q.isContainer||!Q.hasChildren||!(Q.effects||[]).some(q=>q.visible)||(Q.childIds||[]).length===0||yo(Q,$,H);if(v)try{v()}catch(Q){i("particle advance error: "+(Q&&Q.message))}const L=se.perspective?M.layers.slice().sort((Q,re)=>+!!re.isSkybox-+!!Q.isSkybox):M.layers;for(const Q of L){if(Q.destroyed)continue;const re=Q.perspective&&F?F:_e;if(!Q.visible){ar.has(Q.id)&&await Oi(Q,se,re,te,Z,ne);continue}if(!(Q.isPostProcess&&!(Q.effects||[]).some(q=>q.visible))&&!(!f&&Q.isPostProcess)&&!H.has(Q.id)){if(Q.isContainer){if(!(Q.effects||[]).some(K=>K.visible)){await Oi(Q,se,re,te,Z,ne);continue}if(Q.hasChildren){(Q.childIds||[]).length>0&&await Dr(Q,M,j,se,re,te,Z,ne);continue}}if(Q.particle){if(x)try{await x(Q.id,se,re,te,Z)}catch(q){i("particle render error: "+(q&&q.message))}continue}Sa(Q,se)||await li(Q,j,se,re,te,Z,ne)}}if(ws(fe)&&ne<ya){const Q=Math.max(0,Math.min(1,ne/ya)),re=1-Q*Q*(3-2*Q);if(re>.002){const q=ho(fe.clearcolor||"0 0 0");n.useProgram(De),n.enable(n.BLEND),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA),g(),n.viewport(0,0,te,Z),n.bindVertexArray(st),rn("pass",ir),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,hn),n.uniform1i(Ze.tex,0),n.uniform4f(Ze.color,q[0],q[1],q[2],re),sr(Ze,null),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,sn),n.drawArrays(n.TRIANGLES,0,6)}}b(te,Z);const X=f?$h(fe):null;if(Le||(Le=!0,i(X?`bloom post: on strength=${X.strength} threshold=${X.threshold} iter=${X.iterations} radius=${X.radius} damp=${X.damp} hdr=${X.hdr}`:"bloom post: off")),X&&X.strength>.001&&ci(X,te,Z),d==="fxaa"){const Q=_n(te,Z);n.useProgram(dn),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,te,Z),n.bindVertexArray(st),rn("pass",ir),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,Q),n.uniform1i(ii.tex,0),n.uniform2f(ii.texel,1/te,1/Z),n.uniformMatrix4fv(ii.mvp,!1,sn),n.drawArrays(n.TRIANGLES,0,6)}n.bindVertexArray(null),xt()}async function jo(M,j,te,Z,ne,de){gn.clear(),ar.clear();for(const[xe,T]of ai)gn.set(xe,T);const me=new Map,ye=new Set;let fe=null;const se=xe=>{if(typeof xe!="string")return;const T=/^_rt_imageLayerComposite_(\d+)_[a-z]$/.exec(xe);if(!T)return;const C=Number(T[1]);fe!==null&&C===fe&&ye.add(C);let R=me.get(C);R||(R=new Set,me.set(C,R)),R.add(xe)};for(const xe of M.layers||[]){fe=xe.id;for(const T of xe.effects||[])if(T.visible){for(const C of T.passes||[])for(const R of C.textures||[])se(R);for(const C of T.materialPasses||[]){for(const R of C.binds||[])se(R&&R.name);for(const R of C.textures||[])se(R)}}}for(const xe of[...ai.keys()]){let T=!1;for(const C of me.values())if(C.has(xe)){T=!0;break}T||ai.delete(xe)}if(me.size===0)return;const _e=(()=>{const xe=[...me.keys()],T=new Map;for(const $ of xe){const H=(M.layers||[]).find(X=>X.id===$),L=new Set;if(H){const X=Q=>{if(typeof Q=="string"){const re=/^_rt_imageLayerComposite_(\d+)_[a-z]$/.exec(Q);if(re){const q=Number(re[1]);q!==$&&me.has(q)&&L.add(q)}}else Array.isArray(Q)&&Q.forEach(X)};for(const Q of H.effects||[])if(Q.visible){for(const re of Q.passes||[])for(const q of re.textures||[])X(q);for(const re of Q.materialPasses||[]){for(const q of re.binds||[])X(q&&q.name);for(const q of re.textures||[])X(q)}}}T.set($,L)}const C=[],R=new Map,F=$=>{if((R.get($)||0)===0){R.set($,1);for(const L of T.get($)||[])F(L);R.set($,2),C.push($)}};for(const $ of xe)F($);return C})();for(const xe of _e){const T=me.get(xe),C=(M.layers||[]).find(pe=>pe.id===xe);if(!C||C.particle||C.isPostProcess||ye.has(xe))continue;const R=typeof C.image=="string"?C.image:"",F=C.isContainer&&!C.hasChildren&&R.indexOf("models/util/composelayer")===0&&!(C.effects||[]).some(pe=>pe.visible),$=!C.solid&&!!C.textureName,H=!!C.copybackground&&!$;if(F||H){ar.set(xe,T);continue}const L=Math.max(1,Math.round(Math.abs(C.size[0]*(C.scale[0]||1)))),X=Math.max(1,Math.round(Math.abs(C.size[1]*(C.scale[1]||1))));if(L<=1&&X<=1)continue;si<=0&&(si=Math.max(1,n.getParameter(n.MAX_TEXTURE_SIZE)||8192));const Q=Xh(L,X,si),re=Q.width,q=Q.height,K=Q.k,D=Pt(re,q,"lc:"+xe);n.bindFramebuffer(n.FRAMEBUFFER,D.fbo),n.viewport(0,0,re,q),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT);const E={view:te.view,projection:Hi(0,re,0,q,-1e4,1e4),eye:te.eye,projW:re,projH:q,offX:0,offY:0,viewW:re,viewH:q},z=it,ee=C.origin,G=C.scale,J=C.angles,ge=C.visible,ae=C.size;it={fbo:D,w:re,h:q};const ue=Zh(C.size,G,re,q,K);C.origin=[re/2,E.projH-q/2,ee[2]],C.size=ue.size,C.scale=ue.scale,C.angles=[0,0,0],C.visible=!0;try{await li(C,j,E,E.projection,re,q,de);for(const pe of T)gn.set(pe,D)}catch(pe){i(`composite \u6E90\u5C42 ${xe} \u6E32\u67D3\u5931\u8D25: ${pe&&pe.message}`)}finally{it=z,C.origin=ee,C.scale=G,C.angles=J,C.visible=ge,C.size=ae}}g(),n.viewport(0,0,Z,ne)}async function Dr(M,j,te,Z,ne,de,me,ye){const fe=Math.max(1,Math.round(Math.abs(M.size[0]))),se=Math.max(1,Math.round(Math.abs(M.size[1])));if((M.childIds||[]).length===0)return;const xe=new Map;for(const q of j.layers)q.id!==void 0&&xe.set(q.id,q);const T=yo(M,xe),C=j.layers.filter(q=>T.has(q.id)&&q.visible);if(C.length===0)return;const R=Pt(fe,se,"group");n.bindFramebuffer(n.FRAMEBUFFER,R.fbo),n.viewport(0,0,fe,se),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT);const F={view:Z.view,projection:Hi(0,fe,0,se,-1e4,1e4),eye:Z.eye,projW:fe,projH:se,offX:0,offY:0,viewW:fe,viewH:se},$=F.projection,H=M.scale[0]||1,L=M.scale[1]||1,X=M.angles[2]||0,Q=Math.cos(-X),re=Math.sin(-X);it={fbo:R,w:fe,h:se};try{for(const q of C){if(q.isPostProcess||q.particle||q.isContainer&&(q.childIds||[]).length>0)continue;const K=q.origin,D=q.scale,E=q.angles,z=K[0]-M.origin[0],ee=K[1]-M.origin[1],G=(z*Q-ee*re)/H,J=(z*re+ee*Q)/L;q.origin=[fe/2+G,se/2+J,K[2]],q.scale=[D[0]/H,D[1]/L,D[2]],q.angles=[E[0],E[1],E[2]-X];try{await li(q,te,F,$,fe,se,ye)}finally{q.origin=K,q.scale=D,q.angles=E}}}finally{it=null}M.groupTex=R.tex,M.groupW=fe,M.groupH=se;try{await li(M,te,Z,ne,de,me,ye)}finally{M.groupTex=null}}async function li(M,j,te,Z,ne,de,me){const ye=!!(M.puppet&&Ni),fe=!M.solid&&M.textureName?j.get(M.textureName):null;if(fe&&fe.video){const ae=fe.video;if(ae.readyState>=2&&ae.currentTime!==fe.lastUploaded){n.bindTexture(n.TEXTURE_2D,fe.glTex);try{let ue=ae.videoWidth||fe.width,pe=ae.videoHeight||fe.height;const Ie=Math.max(ne||0,de||0),je=n.getParameter(n.MAX_TEXTURE_SIZE)||0;let qe=c;je>0&&(qe=Math.min(qe,je)),Ie>0&&(qe=Math.min(qe,Ie)),qe=Math.max(qe,u);let Tt=1;Math.max(ue,pe)>qe&&(Tt=qe/Math.max(ue,pe));const bt=Math.max(1,Math.round(ue*Tt)),wt=Math.max(1,Math.round(pe*Tt));let En=ae;if(s&&bt>0&&wt>0){(s.width!==bt||s.height!==wt)&&(s.width=bt,s.height=wt);const yn=s.getContext("2d");yn&&(yn.clearRect(0,0,bt,wt),yn.drawImage(ae,0,0,bt,wt),En=s)}if(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,En),n.getError()!==n.NO_ERROR&&s)try{const ut=s.getContext("2d").getImageData(0,0,s.width,s.height);for(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,s.width,s.height,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array(ut.data.buffer));n.getError()!==n.NO_ERROR;);}catch{}fe.width=bt,fe.height=wt,fe.lastUploaded=ae.currentTime,o!==bt+"x"+wt&&(o=bt+"x"+wt,a=!0,i("video tex ready "+bt+"x"+wt+" (src "+ue+"x"+pe+", limit "+qe+")"))}catch(ue){a||(a=!0,i("video upload FAIL: "+(ue&&ue.message||ue))),console.warn("[we-scene] \u89C6\u9891\u5E27\u4E0A\u4F20\u5931\u8D25:",ue&&ue.message,"readyState=",ae.readyState,"cur=",ae.currentTime)}}}const se=M.groupTex?M.groupTex:fe&&fe.glTex?fe.glTex:M.solid?hn:Cr,_e=(!!M.passthrough||!!M.isPostProcess||Vh(M)||Wh(M))&&!M.groupTex&&!fe&&!ye&&!it;let xe,T;if(M.groupTex)xe=M.groupW||M.size[0],T=M.groupH||M.size[1];else if(ye||!fe)xe=M.size[0],T=M.size[1];else{const ae=Math.round(Math.abs(M.size&&M.size[0]||0)*Math.abs(M.scale&&M.scale[0]||1)),ue=Math.round(Math.abs(M.size&&M.size[1]||0)*Math.abs(M.scale&&M.scale[1]||1));xe=ae>0?ae:fe.width,T=ue>0?ue:fe.height}if(!ye&&fe&&M.spriteSheet){const ae=fe.frames,ue=Array.isArray(ae)?ae:ae&&ae.list;ue&&ue.length&&(xe=ue[0].width||xe,T=ue[0].height||T)}const C=Math.max(1,Math.round(xe)),R=Math.max(1,Math.round(T)),F=Cl(M.lightingEnabled,vs),$=[M.color[0]*M.brightness*F[0],M.color[1]*M.brightness*F[1],M.color[2]*M.brightness*F[2],M.alpha],H=f?(M.effects||[]).filter(ae=>ae.visible):[];let L=C,X=R;if(l>0&&te.projW>0&&te.projH>0){const ae=Math.min(Math.abs(M.size[0]*M.scale[0]),te.viewW),ue=Math.min(Math.abs(M.size[1]*M.scale[1]),te.viewH),pe=ae*(ne/te.projW),Ie=ue*(de/te.projH);if(pe>0&&Ie>0){const je=Math.max(64,Math.round(pe*l)),qe=Math.max(64,Math.round(Ie*l));je<C&&(L=je),qe<R&&(X=qe)}}if(H.length===0){ye?Ui(M,te,Z,ne,de,me):Pn(De,se,$,M,te,Z,ne,de,!1,Di(M,fe,me));return}const Q=Pt(L,X,"ping"),re=Pt(L,X,"pong"),q=Hi(0,L,0,X,-1e4,1e4);if(ye)n.useProgram(De),mn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,Q.fbo),n.viewport(0,0,L,X),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(st),Gt=null,rn("layer"+L+"x"+X,Br(L,X)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,se),n.uniform1i(Ze.tex,0),n.uniform4f(Ze.color,1,1,1,1),sr(Ze,null),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,q),n.drawArrays(n.TRIANGLES,0,6);else if(_e)xs(M,Q,L,X,te,Z,ne,de);else{n.useProgram(De),mn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,Q.fbo),n.viewport(0,0,L,X),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.bindVertexArray(st),rn("layer"+L+"x"+X,Br(L,X)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,se),n.uniform1i(Ze.tex,0);const ae=H.some(ue=>ue&&ue.layerMaterial)?[1,1,1,$[3]]:$;n.uniform4f(Ze.color,ae[0],ae[1],ae[2],ae[3]),sr(Ze,Di(M,fe,me)),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,q),n.drawArrays(n.TRIANGLES,0,6)}let K=Q,D=re;const E=new Map;let z=!1,ee=Q;const G=[],J=new Set;for(const ae of H){for(const pe of ae.fbos||[])if(!E.has(pe.name)){const[Ie,je]=qh(pe,L,X),qe=pe.unique?M.id+":"+pe.name:pe.name;E.set(pe.name,Pt(Ie,je,qe))}const ue=ae.materialPasses||[];for(let pe=0;pe<ue.length;pe++)G.push({eff:ae,mp:ue[pe],ov:ae.passes&&ae.passes[pe]})}const ge=[];for(let ae=0;ae<G.length;ae++){const{eff:ue,mp:pe,ov:Ie}=G[ae];if(J.has(ue))continue;const je={...pe.combos||{},...Ie&&Ie.combos||{}};if(/audio_responsive_oscilloscope/i.test(pe.shader||"")){const ze=Ie&&Ie.combos||{},Je=pe.combos||{};ze.WRITEALPHA===void 0&&Je.WRITEALPHA===void 0&&(je.WRITEALPHA=1),ze.TRANSPARENCY===void 0&&Je.TRANSPARENCY===void 0&&(je.TRANSPARENCY=1)}const qe=pe.textures||[],Tt=Ie&&Ie.textures||[],bt=[];for(let ze=0;ze<Math.max(qe.length,Tt.length);ze++)Tt[ze]!==void 0&&Tt[ze]!==null?bt[ze]=Tt[ze]:bt[ze]=qe[ze]!==void 0?qe[ze]:null;if(Ie&&Array.isArray(Ie.textureFallbacks))for(let ze=0;ze<bt.length;ze++){const Je=bt[ze];if(typeof Je!="string"||Je===""||j&&j.get(Je))continue;const on=Ie.textureFallbacks[ze];on&&(bt[ze]=on)}if(pe.copyCommand){const ze=pe.source?E.get(pe.source):null,Je=pe.target?E.get(pe.target):null;ze&&Je&&(n.useProgram(Re),mn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,Je.fbo),n.viewport(0,0,Je.width,Je.height),n.bindVertexArray(st),rn("pass",ir),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,ze.tex),n.uniform1i(Tn.tex,0),Tn.blendPrep!==null&&Tn.blendPrep!==void 0&&n.uniform1i(Tn.blendPrep,0),n.uniformMatrix4fv(Tn.mvp,!1,sn),n.drawArrays(n.TRIANGLES,0,6),g());continue}let wt;try{wt=await pa(pe.shader,je,bt)}catch(ze){const Je=ze&&ze.message||String(ze);/已缓存/.test(Je)||console.warn("[we-scene] \u8DF3\u8FC7\u6548\u679C\uFF08pass \u7F16\u8BD1\u5931\u8D25\uFF09:",pe.shader,Je),J.add(ue);continue}const En=wt.prog,yn=wt.uni;wt.fragGlsl&&ge.push(wt.fragGlsl);let ut,Qt;pe.target?(z||(ee=K,z=!0),ut=E.get(pe.target)||K,Qt=ee):(z=!1,ut=D,Qt=K),n.useProgram(En),mn(pe.blending||"normal"),n.bindFramebuffer(n.FRAMEBUFFER,ut.fbo),n.viewport(0,0,ut.width,ut.height),n.bindVertexArray(st);const zi=!wt.ndcDirect;zi?rn("passPx"+ut.width+"x"+ut.height,Br(ut.width,ut.height)):rn("pass",ir);const qo=zi?$o(Hi(0,ut.width,0,ut.height,-1e4,1e4)):sn,_a=pe.textures||[],ks=Math.max(_a.length,8),an=new Map,yp=new Set;for(let ze=0;ze<ks;ze++){let Je=bt[ze]!==void 0?bt[ze]:null;for(const Ss of pe.binds||[])Ss.index===ze&&(Je=Ss.name);let on;if(ze===0&&(Je==null||Je===""))on=Qt;else{if((Je==null||Je==="")&&wt.samplerDefaults){const Ss=wt.samplerDefaults.get(ze);Ss&&(Je=Ss)}on=ka(Je,Qt,E,j)}Je==="previous"&&(on=Qt),on===null&&(on={glTex:hn,width:1,height:1,tex:hn});const Ts=on.fbo?on:{tex:on.glTex||hn,width:on.width||1,height:on.height||1};n.activeTexture(n.TEXTURE0+ze),n.bindTexture(n.TEXTURE_2D,Ts.tex),yp.add(ze),an.set(ze,[Ts.width,Ts.height,Ts.width,Ts.height])}let vu=null;if(yn.get("g_EffectModelViewProjectionMatrix")){const ze=pn(M,te);let Je=Lr(ze.m,ze.w,ze.h,1);Je=zi?Wt(Je,Lr(ui(Nr(),-.5,-.5,0),1/ut.width,1/ut.height,1)):Wt(Je,Lr(Nr(),.5,.5,1)),vu=$o(Wt(Z,Je))}Ci(yn,M,me,te.projW,te.projH,qo,q,sn,an,q,te,vu);const Xo=(M.id||M.name||"?")+"|"+(pe.shader||"?")+"|"+ae,Au={...pe.constants||{},...Ie&&Ie.constantshadervalues||{}};As(Au,Xo,me),Wo(yn,Hn(Ct(Au,Xo,me,M),Xo,me,M),wt.matMeta),zn(yn),n.drawArrays(n.TRIANGLES,0,6),pe.target||(D=K,K=ut)}if(M.isContainer&&!M.groupTex&&!_e&&M.containerAlphaMeaningful===void 0&&(M.containerAlphaMeaningful=Hh(ge),i(`container "${M.name||"?"}" alpha ${M.containerAlphaMeaningful?"\u643A\u5E26\u5F62\u72B6 \u2192 SRC_ALPHA":"\u65E0\u4FE1\u606F \u2192 \u52A0\u6CD5"}`)),ye){Ui(M,te,Z,ne,de,me,K.tex);return}Pn(Re,K.tex,[1,1,1,1],M,te,Z,ne,de,!!M.isContainer&&!M.groupTex&&!_e,null,null)}return{gl:n,render:Pa,getFBO:Pt,getEffectProgram:pa,progCache:tn,shaderResolver:r,whiteTex:hn,resetShaderCaches:function(){tn.clear(),Mt.clear(),Pi&&Pi.clear()},setFboCapFactor:function(M){l=M},setAntiAliasing:function(M){d=M==="fxaa"||M==="msaa2"||M==="msaa4"?M:"off"},setEffectsEnabled:function(M){f=!!M},getFrameTarget:function(){return h?h.fbo:null},captureSceneTexture:function(M,j){return _n(M,j)},setParticleRenderer:function(M,j){v=typeof M=="function"?M:null,x=typeof j=="function"?j:null},setConstantScriptRuntime:Pe,applyConstUserProperties:function(M){if(M){for(const j of we.values())if(j&&typeof j.applyUserProperties=="function")try{j.applyUserProperties(M)}catch{}}},constantScriptStats:function(){return{...Ae,cached:we.size}},setCompositeEnabled:function(M){Li=!!M},compositeStats:function(){const M=[],j=new Uint8Array(4);for(const[te,Z]of gn){let ne=null;try{n.bindFramebuffer(n.FRAMEBUFFER,Z.fbo),n.readPixels(Z.w>>1,Z.h>>1,1,1,n.RGBA,n.UNSIGNED_BYTE,j),ne=[j[0],j[1],j[2],j[3]]}catch{}M.push({name:te,w:Z.w,h:Z.h,center:ne})}return n.bindFramebuffer(n.FRAMEBUFFER,null),M},setPuppetRenderer:function(M){Ni=M},setAudioProvider:k,setPointerProvider:Un,getParallaxOffset:function(){return Oe},getPerspectiveEye:function(){return Ei},dispose:function(){try{const M=n.getExtension("WEBGL_lose_context");M&&M.loseContext()}catch{}}}}const nw=Object.freeze(Object.defineProperty({__proto__:null,ALIGN:Rh,XRAY_IDLE_SCREEN_UV:ea,XRAY_SIZE_FALLBACK:Qh,applyColorBlendCPU:Zb,bloomPostParams:$h,chainAlphaMeaningful:Hh,clampCompositeFboSize:Xh,collectGroupDescendantIds:yo,colorBlendPlan:El,compositeSourcePlacement:Zh,compositeSourceQuadSize:Kh,compressedFormatFor:Ob,constantFallback:Yh,createRenderer:tw,effectFboSize:qh,layerColorAmbient:Cl,layerCompositeBlendMode:jh,layerWantsComposeBackdrop:Wh,layerWantsPreserveBackdrop:Vh,makeCompressedTextureMip:Ub,makeR8TextureMip:zb,makeTexture:Tl,makeTextureMip:Lb,needsShaderBlend:Ml,puppetAnimMargin:zh,rewriteXrayFragScale:Gh,xrayShouldParkPointer:Il,xrayUvScale:Jb},Symbol.toStringTag,{value:"Module"})),Gr=Math.PI*2;function _t(t,e){return t==null?Math.random():e==null?t:t+Math.random()*(e-t)}function Qr(t,e,n){if(t==null)return Math.random();if(e==null)return t;const r=n&&n!==1?Math.pow(Math.random(),n):Math.random();return t+r*(e-t)}function ht(t,e){if(Array.isArray(t))return[t[0]||0,t[1]||0,t[2]||0];if(t==null)return e?e.slice():[0,0,0];if(typeof t=="object")return ht(t.value,e);if(typeof t=="number")return[t,t,t];const n=String(t).trim().split(/\s+/).map(Number);return[n[0]||0,n[1]||0,n[2]||0]}function Sr(t){if(t==null)return null;if(Array.isArray(t)){if(t.length!==3)return null;const r=t.map(Number);return r.every(Number.isFinite)?r:null}if(typeof t=="object")return Sr(t.value);if(typeof t=="number")return Number.isFinite(t)?[t,0,0]:null;const e=String(t).trim().split(/\s+/);if(e.length!==3)return null;const n=e.map(Number);return n.every(Number.isFinite)?n:null}function Jh(t){return t==null?null:typeof t=="number"?[t,t,t]:ht(t)}function Te(t,e){if(t==null)return e;if(typeof t=="object")return Te(t.value,e);const n=Number(t);return Number.isFinite(n)?n:e}function Rl(t,e){const n=t[0],r=t[1]>n?t[1]:n+1e-6,i=Math.min(1,Math.max(0,(e-n)/(r-n)));return i*i*(3-2*i)}function Yr(t,e,n){const r=Math.sin(t*127.1+e*311.7+n*74.7)*43758.5453;return r-Math.floor(r)}function rw(t,e,n){const r=Math.floor(t),i=Math.floor(e),s=Math.floor(n),a=t-r,o=e-i,c=n-s,u=a*a*(3-2*a),l=o*o*(3-2*o),d=c*c*(3-2*c),f=(y,w,A)=>y+(w-y)*A,h=f(Yr(r,i,s),Yr(r+1,i,s),u),p=f(Yr(r,i+1,s),Yr(r+1,i+1,s),u),m=f(Yr(r,i,s+1),Yr(r+1,i,s+1),u),g=f(Yr(r,i+1,s+1),Yr(r+1,i+1,s+1),u);return f(f(h,p,l),f(m,g,l),d)}function Bl(t,e,n,r){let i=0,s=.5,a=1,o=0;for(let c=0;c<r;c++)i+=s*rw(t*a,e*a,n*a),o+=s,s*=.5,a*=2;return i/(o||1)}function Fl(t,e,n,r){return[Bl(t,e,n,r)*2-1,Bl(t+31.7,e+11.3,n+57.1,r)*2-1,Bl(t+73.9,e+92.1,n+13.7,r)*2-1]}function iw(t){const e=`#version 300 es
350
394
  // \u5355\u4F4D quad\uFF08TRIANGLE_STRIP 4 \u9876\u70B9\uFF09\uFF0C\u6309\u5B9E\u4F8B\u7684 size/rot \u5C55\u5F00\u4E3A\u671D\u5C4F\u5E55\u7684\u7CBE\u7075
351
395
  layout(location=0) in vec2 a_corner; // -0.5..0.5
352
396
  layout(location=1) in vec3 a_pos; // \u5B9E\u4F8B\u4E2D\u5FC3\uFF08\u6295\u5F71\u7A7A\u95F4\u4E16\u754C\u5750\u6807\uFF09
@@ -354,32 +398,65 @@ layout(location=2) in vec2 a_sizeRot; // x=size(\u50CF\u7D20) y=rot(\u5F27\u
354
398
  layout(location=3) in vec4 a_color; // rgb + alpha
355
399
  layout(location=4) in vec3 a_stretchFrame; // xy=\u975E\u7B49\u6BD4\u62C9\u4F38 z=\u5E27\u5E8F\u53F7
356
400
  layout(location=5) in vec2 a_vrange; // \u6BB5\u4E24\u7AEF\u6CBF\u8D34\u56FE v \u7684\u53D6\u503C\uFF08rope \u8FDE\u7EBF\u7528\uFF1B\u666E\u901A\u7CBE\u7075 0..1\uFF09
401
+ layout(location=6) in vec4 a_frameBlend; // xy=\u4E0B\u4E00\u5E27\u5E8F\u53F7/\u5E27\u95F4\u6DF7\u5408\u6743\u91CD zw=rotation.x/rotation.y
357
402
  uniform mat4 u_mvp;
403
+ // \u5B98\u65B9 g_RefractAmount\uFF08common_particles.h \u7684 uniform \u58F0\u660E\uFF1A\u9ED8\u8BA4 0.05\u3001range [-1,1]\uFF09
404
+ uniform float u_refractScale;
358
405
  // \u5E8F\u5217\u5E27 uv \u53D8\u6362\u8868\uFF08TEXS \u5E27\u77E9\u5F62\u5F52\u4E00\u5316\u540E\u7684 offset/scale\uFF09\uFF0C\u6700\u591A 128 \u5E27
359
406
  // \uFF08matrix spritesheet 72 \u6709 71 \u5E27\uFF0C\u65E7\u4E0A\u9650 64 \u4F1A\u4E22\u672B\u5C3E\u5B57\u7B26\uFF09
360
407
  uniform int u_frameCount;
361
408
  uniform vec4 u_frames[128]; // xy=offset zw=scale
409
+ out vec4 v_refract; // \u5B98\u65B9 v_ScreenTangents\uFF1Axy=\u7CBE\u7075 x \u8F74\u3001zw=\u7CBE\u7075 y \u8F74\uFF08\u5DF2\u4E58 Refract Amount\uFF09
362
410
  out vec2 v_uv;
411
+ out vec2 v_uv2; // \u4E0B\u4E00\u5E27\u7684 uv\uFF08\u540C\u4E00 quad \u4F4D\u7F6E\u3001\u6362\u5E27\u77E9\u5F62\uFF09
412
+ out float v_frameMix; // \u5E27\u95F4\u6DF7\u5408\u6743\u91CD\uFF080 = \u4E0D\u6DF7\u5408\uFF0C\u786C\u5207\uFF09
363
413
  out vec4 v_color;
364
414
  void main(){
365
415
  float size = a_sizeRot.x;
366
- float rot = a_sizeRot.y;
367
- float c = cos(rot), s = sin(rot);
416
+ float rz = a_sizeRot.y;
417
+ float rx = a_frameBlend.z;
418
+ float ry = a_frameBlend.w;
419
+ // \u5B98\u65B9 ComputeParticleTangents\uFF1Aright/up = \u65CB\u8F6C\u57FA\uFF08Rz\xB7Rx\xB7Ry\uFF09\u7684\u4E24\u4E2A\u8F74\u3002\u6B63\u4EA4\u6295\u5F71\u4E0B
420
+ // \u7CBE\u7075\u7684\u5C4F\u5E55\u5F62\u72B6 = \u8FD9\u4E24\u4E2A\u8F74\u5728\u5C4F\u5E55\u5E73\u9762\u7684\u6295\u5F71\uFF08x/y \u4FA7\u503E \u21D2 \u5BF9\u5E94\u8F74\u6309 cos \u538B\u7F29\uFF09\u3002
421
+ // z \u7684\u7B26\u53F7\u6CBF\u7528\u65E2\u6709\u6807\u5B9A\uFF08652 \u4E2A\u7EAF z \u6A21\u578B\u7684\u671D\u5411\u9010\u4F4D\u4E0D\u80FD\u53D8\uFF09\uFF1Aright=(cos rz, sin rz)\u3001
422
+ // up=(-sin rz, cos rz)\uFF1Bx/y \u7684\u4EA4\u53C9\u9879\u6309\u5B98\u65B9 Rz\xB7Rx\xB7Ry \u7684\u987A\u5E8F\u5C55\u5F00\u3002
423
+ float cz = cos(rz), sz = sin(rz);
424
+ float cx = cos(rx), sx = sin(rx);
425
+ float cy = cos(ry), sy = sin(ry);
426
+ // R = Rz * Rx * Ry\uFF08\u5217\u5411\u91CF\u7EA6\u5B9A\uFF0C\u4E0E\u5B98\u65B9 mul(mul(Rz,Rx),Ry) \u540C\u5E8F\uFF09
427
+ vec2 rightXY = vec2(cz * cy - sz * sx * sy, sz * cy + cz * sx * sy);
428
+ vec2 upXY = vec2(-sz * cx, cz * cx);
368
429
  // \u5148\u6309 size \u4E0E\u975E\u7B49\u6BD4\u62C9\u4F38\u5C55\u5F00\uFF0C\u518D\u65CB\u8F6C\uFF08\u987A\u5E8F\u53CD\u4E86\u4F1A\u628A\u62C9\u4F38\u65B9\u5411\u4E5F\u8F6C\u8D70\uFF09
369
430
  vec2 corner = a_corner * size * a_stretchFrame.xy;
370
- vec2 rotated = vec2(corner.x * c - corner.y * s, corner.x * s + corner.y * c);
431
+ vec2 rotated = vec2(corner.x * rightXY.x + corner.y * upXY.x,
432
+ corner.x * rightXY.y + corner.y * upXY.y);
371
433
  gl_Position = u_mvp * vec4(a_pos.xy + rotated, a_pos.z, 1.0);
372
434
  // quad \u89D2 \u2192 \u8D34\u56FE uv\u3002\u4E16\u754C y \u5DF2\u7FFB\u8F6C\u5230\u6295\u5F71\u7A7A\u95F4\uFF08y \u5411\u4E0B\uFF09\uFF0C\u6545 quad \u7684 +y \u89D2
373
435
  // \u5BF9\u5E94\u5C4F\u5E55\u4E0A\u65B9\uFF0C\u5E94\u91C7\u6837\u7EB9\u7406\u9876\u884C v=1\uFF08\u4E0E renderer.js \u7684 layerQuadVerts \u540C\u7EA6\u5B9A\uFF09\u3002
374
436
  // a_vrange \u8BA9 rope \u6BB5\u4E24\u7AEF\u5404\u53D6\u81EA\u5DF1\u7684 v\uFF08\u6CBF\u7EF3\u8FDE\u7EED\u6E10\u53D8\uFF09\uFF1B\u666E\u901A\u7CBE\u7075\u662F (0,1) \u6052\u7B49\u3002
375
437
  vec2 uv = vec2(a_corner.x + 0.5, mix(a_vrange.x, a_vrange.y, a_corner.y + 0.5));
438
+ // \u5B98\u65B9 ComputeScreenRefractionTangents\uFF1A\u628A\u7CBE\u7075\u7684 x/y \u8F74\uFF08\u5F52\u4E00\u5316\u65CB\u8F6C\u57FA\uFF09\u6295\u5F71\u5230\u5C4F\u5E55\u53F3/\u4E0A
439
+ // \u65B9\u5411\u540E\u4E58 g_RefractAmount\u30022D \u6B63\u4EA4\u573A\u666F\u91CC\u89C6\u56FE\u53F3=(1,0)\u3001\u89C6\u56FE\u4E0A=(0,1)\uFF08\u5C4F\u5E55 y \u5411\u4E0B\uFF09\uFF0C
440
+ // \u4E8E\u662F\u5207\u7EBF\u5C31\u662F\u65CB\u8F6C\u540E\u7684\u4E24\u4E2A\u8F74\u672C\u8EAB \u2014\u2014 \u7CBE\u7075\u4E00\u8F6C\uFF0C\u6298\u5C04\u504F\u79FB\u65B9\u5411\u8DDF\u7740\u8F6C\uFF08\u65E7\u5B9E\u73B0\u6052\u6309\u5C4F\u5E55\u8F74\uFF09\u3002
441
+ v_refract = vec4(rightXY, upXY) * u_refractScale;
442
+ v_uv2 = uv;
443
+ v_frameMix = 0.0;
376
444
  if (u_frameCount > 0) {
377
445
  // \u5E27\u77E9\u5F62\u4EE5\u5DE6\u4E0A\u4E3A\u539F\u70B9\uFF08TEXS \u662F top-down \u50CF\u7D20\u5750\u6807\uFF09\uFF0C\u6545\u5148\u628A v \u7FFB\u6210 top-down
446
+ vec2 uv2 = uv;
378
447
  int fi = int(a_stretchFrame.z);
379
448
  fi = clamp(fi, 0, u_frameCount - 1);
380
449
  vec4 fr = u_frames[fi];
381
450
  vec2 cell = vec2(uv.x, 1.0 - uv.y) * fr.zw + fr.xy;
382
451
  uv = vec2(cell.x, 1.0 - cell.y);
452
+ // \u5B98\u65B9 ComputeSpriteFrame\uFF1AnextFrame = min(n-1, cur+1)\u3001frameBlend = frac(lifetime*n)\uFF1B
453
+ // frag \u7528 mix(\u5F53\u524D\u5E27, \u4E0B\u4E00\u5E27, blend) \u505A\u4EA4\u53C9\u6DE1\u5165\uFF08\u786C\u5207\u4F1A\u8DF3\u5E27\uFF09\u3002
454
+ int fj = clamp(int(a_frameBlend.x), 0, u_frameCount - 1);
455
+ vec4 fr2 = u_frames[fj];
456
+ vec2 cell2 = vec2(uv2.x, 1.0 - uv2.y) * fr2.zw + fr2.xy;
457
+ uv2 = vec2(cell2.x, 1.0 - cell2.y);
458
+ v_uv2 = uv2;
459
+ v_frameMix = clamp(a_frameBlend.y, 0.0, 1.0);
383
460
  }
384
461
  v_uv = uv;
385
462
  v_color = a_color;
@@ -390,38 +467,68 @@ uniform sampler2D u_normal;
390
467
  uniform sampler2D u_scene;
391
468
  uniform int u_refract;
392
469
  uniform int u_sampleScene;
470
+ // [we-scene patch 2026-09-20] \u53CD\u7167\u7387\u662F **R8 \u5355\u901A\u9053**\uFF08WE \u8BED\u4E49 vec4(1,1,1,r)\uFF09\uFF1A
471
+ // \u4E0A\u4F20\u65F6\u6309 GL_R8 \u5B58\uFF08\u7701 4 \u500D\u663E\u5B58\uFF09\uFF0C\u8FD9\u91CC\u8865\u4E0A\u300Crgb \u767D\u3001\u5F62\u72B6\u53D6 .r\u300D\u7684\u6620\u5C04\u3002
472
+ uniform int u_albedoR8;
473
+ // \u6CD5\u7EBF\u901A\u9053\u5E03\u5C40\uFF1A1 = \u5B98\u65B9\u6253\u5305\uFF08x \u5728 A\u3001\u8499\u7248\u5728 R\uFF09\uFF0C0 = \u6211\u4EEC\u81EA\u5DF1\u7684\u751F\u6210\u5668/RG88 \u8F6C\u6362\uFF08x \u5728 R\u3001A \u6052 255\uFF09
474
+ uniform int u_normalPacked;
393
475
  uniform vec2 u_resolution;
394
- uniform float u_refractScale;
476
+ in vec4 v_refract;
395
477
  in vec2 v_uv;
478
+ in vec2 v_uv2;
479
+ in float v_frameMix;
396
480
  in vec4 v_color;
397
481
  out vec4 fragColor;
398
482
  void main(){
399
483
  vec4 t = texture(u_tex, v_uv);
400
- vec4 col = vec4(t.rgb * v_color.rgb, t.a * v_color.a);
484
+ // \u5E27\u95F4\u4EA4\u53C9\u6DE1\u5165\uFF08\u5B98\u65B9 SPRITESHEETBLEND\uFF1Amix(frame, nextFrame, frac(lifetime*n))\uFF09\u3002
485
+ // \u6CD5\u7EBF\u69FD\u4ECD\u53EA\u91C7\u5F53\u524D\u5E27 \u2014\u2014 \u5B98\u65B9 frag \u4E5F\u662F\u53EA\u5BF9 albedo \u505A mix\u3002
486
+ if (v_frameMix > 0.0) t = mix(t, texture(u_tex, v_uv2), v_frameMix);
487
+ // R8 \u4E0A\u4F20\uFF08GL_R8\uFF09\u91C7\u6837\u5F97\u5230 (r,0,0,1)\uFF1A\u6309 WE \u8BED\u4E49\u6062\u590D\u6210\u300Crgb \u767D + \u5F62\u72B6\u5728 alpha\u300D
488
+ vec3 albedoRgb = u_albedoR8 == 1 ? vec3(1.0) : t.rgb;
489
+ float albedoA = u_albedoR8 == 1 ? t.r : t.a;
490
+ vec4 col = vec4(albedoRgb * v_color.rgb, albedoA * v_color.a);
401
491
  if (u_refract == 1) {
402
492
  // genericparticle REFRACT\uFF1A\u69FD 0 \u7ECF\u5E38\u662F\u7A7A\u767D\u767D\u56FE\uFF08Rain2 \u7684
403
493
  // "particles 256x1280 blank"\u3001firework \u7684 util/white\uFF09\uFF0C\u6C34\u73E0\u5F62\u72B6\u5728\u6CD5\u7EBF\u91CC\u3002
404
- // \u6309\u666E\u901A\u7CBE\u7075\u753B\u4F1A\u628A\u6574\u5757 quad \u6D82\u6210\u767D\u65B9\u5757\u3002\u8FD9\u91CC\u7528\u6CD5\u7EBF AG\uFF08DXT5nm \u6253\u5305\uFF09
405
- // \u626D\u66F2\u5DF2\u7ED8\u5236\u7684\u753B\u9762\uFF0C\u7A7A\u767D albedo \u6539\u7528\u6CD5\u7EBF\u504F\u79BB\u5F53 alpha\u3002
494
+ // \u5B98\u65B9\u505A\u6CD5\uFF1Aalbedo **\u7167\u5E38**\u53C2\u4E0E\uFF08\u7A7A\u767D\u767D\u56FE = alpha 1 \u7684\u767D quad\uFF09\uFF0C\u753B\u9762\u8272\u662F
495
+ // \u300Ccolor.rgb *= scene(uv+offset)\u300D**\u4E58\u8FDB\u53BB**\u7684 \u2014\u2014 \u6CD5\u7EBF\u5E73\u5766\u5904 offset=0\uFF0C\u91C7\u5230\u7684\u5C31\u662F
496
+ // \u539F\u753B\u9762\uFF0C\u5929\u7136\u300C\u9690\u5F62\u300D\uFF1B\u53EA\u6709\u6CD5\u7EBF\u504F\u79BB\u5904\u624D\u51FA\u73B0\u626D\u66F2\uFF0C\u6240\u4EE5\u7A7A\u767D albedo \u4E0D\u4F1A\u753B\u6210\u767D\u5757\u3002
406
497
  vec4 ntex = texture(u_normal, v_uv);
407
- // \u5DE5\u574A DXT5nm\uFF1AR=255 B=0\uFF0CXY \u5728 AG\uFF082464842912 Rain2\uFF09\u3002
408
- // \u5B98\u65B9 DecompressNormal\uFF08common_fragment.h\uFF09\u4E0E\u7A0B\u5E8F\u5316\u6CD5\u7EBF\uFF1AXY \u5728 RG\u3002
409
- vec2 nxy = (ntex.r > 0.85 && ntex.b < 0.15) ? (ntex.ag * 2.0 - 1.0) : (ntex.rg * 2.0 - 1.0);
410
- // \u5E73\u5766\u5904 AG\u2248128\uFF0C\u91CF\u5316\u566A\u58F0\u4F1A\u8BA9 length*2.2 \u4ECD\u6709 ~0.04\uFF0C\u6574\u5757 quad \u5269\u6DE1\u65B9\u5757\u3002
411
- float drop = smoothstep(0.06, 0.28, length(nxy));
412
- float blank = step(0.95, min(min(t.r, t.g), min(t.b, t.a)));
413
- float alpha = mix(t.a, drop, blank) * v_color.a;
414
- vec3 rgb = t.rgb * v_color.rgb;
498
+ // \u5B98\u65B9 DecompressNormalWithMask\uFF08common_fragment.h\uFF09\u5BF9**\u975E RG88** \u7684\u6CD5\u7EBF\u4E00\u5F8B
499
+ // normal.xw = normal.wx\uFF1Ax \u2190 \u539F A \u901A\u9053\u3001y \u2190 G\uFF0C\u8499\u7248 = normal.a\uFF08= \u539F R \u901A\u9053\uFF09\u3002
500
+ // \u4E5F\u5C31\u662F\u5B98\u65B9\u6253\u5305\u6CD5\u7EBF\u662F\u300Cx \u5728 A\u3001\u5F62\u72B6/\u8499\u7248\u5728 R\u300D\uFF08DXT5nm \u4E0E RGBA8888 \u90FD\u662F\u8FD9\u6761\uFF0C
501
+ // \u53EA\u662F\u538B\u7F29\u65CF\u591A\u4E00\u4E2A 0.965 \u7684\u7F29\u653E\uFF0C2% \u91CF\u7EA7\uFF09\uFF1A\u5B9E\u6D4B
502
+ // particle/water/rain_drops_sheet_normal\uFF08RGBA8888\uFF09R=35/255\uFF08\u6C34\u6EF4\u526A\u5F71\uFF09\u3001G=190\u3001A=190\uFF1B
503
+ // particle/water/splash_1_normal\uFF08DXT5nm\uFF09R=11.8\uFF08\u6C34\u82B1\u526A\u5F71\uFF09\u3001G=128\u3001A=128\u3002
504
+ // \u6211\u4EEC\u81EA\u5DF1\u7684\u751F\u6210\u5668\uFF08heightToNormal\uFF09\u4E0E RG88 \u8F6C\u6362\u7ED3\u679C\u662F (x,y,z,255)\uFF1Ax \u5728 R\u3001\u8499\u7248\u6052 1\u3002
505
+ // \u65E7\u5B9E\u73B0\u6309\u300CR \u5F88\u4EAE\u300D\u7684\u542F\u53D1\u5F0F\u731C DXT5nm \u2014\u2014 \u4E0A\u9762\u4E24\u5F20\u7684 R \u662F**\u526A\u5F71**\uFF08\u5F88\u6697\uFF09\uFF0C\u731C\u53CD\u4E86\uFF1A
506
+ // x \u53D6\u6210\u526A\u5F71\uFF080/1 \u4E8C\u503C\uFF09\u800C\u8499\u7248\u53D6\u6210\u5E38\u91CF A\uFF0C\u6298\u5C04\u65B9\u5411\u4E0E\u4F5C\u7528\u8303\u56F4\u90FD\u9519\uFF083801012392 \u7684
507
+ // \u300C\u548C\u539F\u7248\u7D20\u6750\u4E0B\u6709\u7EC6\u5FAE\u5DEE\u522B\u300D\uFF09\u3002\u73B0\u5728\u5E03\u5C40\u7531\u8D34\u56FE\u5C42\u5224\u5B9A\u540E\u7ECF uniform \u4F20\u8FDB\u6765\u3002
508
+ vec2 nxy = u_normalPacked == 1 ? (ntex.ag * 2.0 - 1.0) : (ntex.rg * 2.0 - 1.0);
509
+ float nMask = min(u_normalPacked == 1 ? ntex.r : ntex.a, 1.0);
510
+ // \u5B98\u65B9 alpha \u5C31\u662F albedo.a \xD7 \u9876\u70B9 alpha\uFF08\u4E0D\u518D\u62FF\u6CD5\u7EBF\u504F\u79BB\u9876\u66FF \u2014\u2014 \u90A3\u662F\u4E3A\u4E86\u7ED5\u5F00
511
+ // \u300C\u6CA1\u91C7\u5230\u753B\u9762\u65F6\u4F1A\u628A\u767D quad \u753B\u51FA\u6765\u300D\u7684\u65E7\u5B9E\u73B0\uFF0C\u73B0\u5728 rgb \u6052\u4E3A albedo\xD7\u9876\u70B9\u8272\xD7\u753B\u9762\uFF09\u3002
512
+ float alpha = albedoA * v_color.a;
513
+ vec3 rgb = albedoRgb * v_color.rgb;
415
514
  if (u_sampleScene == 1) {
416
515
  vec2 screenUV = gl_FragCoord.xy / max(u_resolution, vec2(1.0));
417
- vec3 scene = texture(u_scene, clamp(screenUV + nxy * u_refractScale, 0.0, 1.0)).rgb;
418
- rgb = scene * v_color.rgb;
516
+ // \u5B98\u65B9 frag\uFF1Aoffset = v_ScreenTangents.xy*normal.x + v_ScreenTangents.zw*normal.y\uFF0C
517
+ // \u518D\u4E58 normal.a\uFF08\u8499\u7248\uFF09\xD7 v_Color.a\uFF08\u7C92\u5B50 alpha\uFF09\u3002y \u7684\u7B26\u53F7\u5728\u5B98\u65B9\u91CC\u4E3A\u9002\u914D GLSL \u53D6\u8D1F\uFF1B
518
+ // \u6211\u4EEC\u7684\u5207\u7EBF\u672C\u6765\u5C31\u5728\u5C4F\u5E55 y \u5411\u4E0B\u7A7A\u95F4\uFF0C\u6545\u4E0D\u7FFB\u3002
519
+ vec2 offset = vec2(
520
+ v_refract.x * nxy.x + v_refract.z * nxy.y,
521
+ v_refract.y * nxy.x + v_refract.w * nxy.y
522
+ ) * (nMask * v_color.a);
523
+ vec3 scene = texture(u_scene, clamp(screenUV + offset, 0.0, 1.0)).rgb;
524
+ // \u5B98\u65B9\u662F\u300Ccolor.rgb *= scene\u300D\uFF08albedo \xD7 \u9876\u70B9\u8272 \xD7 \u753B\u9762\uFF09\uFF0C\u4E0D\u662F\u7528\u753B\u9762\u66FF\u6362 albedo
525
+ rgb = albedoRgb * v_color.rgb * scene;
419
526
  }
420
527
  col = vec4(rgb, alpha);
421
528
  if (col.a < 0.004) discard;
422
529
  }
423
530
  fragColor = col;
424
- }`,r=(u,l)=>{const f=t.createShader(u);if(t.shaderSource(f,l),t.compileShader(f),!t.getShaderParameter(f,t.COMPILE_STATUS))throw new Error("\u7C92\u5B50 shader: "+t.getShaderInfoLog(f));return f},i=t.createProgram();if(t.attachShader(i,r(t.VERTEX_SHADER,e)),t.attachShader(i,r(t.FRAGMENT_SHADER,n)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS))throw new Error("\u7C92\u5B50 shader \u94FE\u63A5\u5931\u8D25: "+t.getProgramInfoLog(i));const s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-.5,-.5,.5,-.5,-.5,.5,.5,.5]),t.STATIC_DRAW);const a=t.createBuffer(),o=t.createVertexArray();t.bindVertexArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,2,t.FLOAT,!1,8,0),t.vertexAttribDivisor(0,0),t.bindBuffer(t.ARRAY_BUFFER,a);const c=56;return t.enableVertexAttribArray(1),t.vertexAttribPointer(1,3,t.FLOAT,!1,c,0),t.vertexAttribDivisor(1,1),t.enableVertexAttribArray(2),t.vertexAttribPointer(2,2,t.FLOAT,!1,c,12),t.vertexAttribDivisor(2,1),t.enableVertexAttribArray(3),t.vertexAttribPointer(3,4,t.FLOAT,!1,c,20),t.vertexAttribDivisor(3,1),t.enableVertexAttribArray(4),t.vertexAttribPointer(4,3,t.FLOAT,!1,c,36),t.vertexAttribDivisor(4,1),t.enableVertexAttribArray(5),t.vertexAttribPointer(5,2,t.FLOAT,!1,c,48),t.vertexAttribDivisor(5,1),t.bindVertexArray(null),{prog:{prog:i,uniTex:t.getUniformLocation(i,"u_tex"),uniNormal:t.getUniformLocation(i,"u_normal"),uniScene:t.getUniformLocation(i,"u_scene"),uniRefract:t.getUniformLocation(i,"u_refract"),uniSampleScene:t.getUniformLocation(i,"u_sampleScene"),uniResolution:t.getUniformLocation(i,"u_resolution"),uniRefractScale:t.getUniformLocation(i,"u_refractScale"),uniMvp:t.getUniformLocation(i,"u_mvp"),uniFrameCount:t.getUniformLocation(i,"u_frameCount"),uniFrames:t.getUniformLocation(i,"u_frames")},quadBuf:s,vbuf:a,vao:o}}function bd(t){const e=t&&t.passes&&t.passes[0]&&t.passes[0].combos;return!!(e&&Number(e.REFRACT)===1)}function Ly(t){if(!t||t.length<16)return!1;const e=t.length/4,n=Math.max(1,e/64|0);let r=0;for(let i=0;i<e;i+=n){const s=i*4;if(t[s]<250||t[s+1]<250||t[s+2]<250||t[s+3]<250)return!1;r++}return r>0}function wd(t,e,n,r){let i=Math.abs(Number(t)||0)*(Number(e)||0);const s=Number(n)||0,a=Number(r)||0;return s>0&&(i=Math.max(s,i)),a>0&&(i=Math.min(a,i)),i}function Tc(t,e){return t||e?Math.atan2(e,t)-Math.PI/2:0}function vd(t,e){return t&&t.kind==="ropetrail"?Math.max(1,e||1):1}function kd(t){if(!t||t.kind!=="ropetrail")return 1;const e=Math.round(Number(t.segments)||0);return e>=2?Math.min(32,e):8}function Ad(t){if(!t||t.kind!=="ropetrail")return 0;const e=Number(t.length);return Number.isFinite(e)&&e>0?e:.2}function Sc(t){return t.life>0?t.age/t.life:0}class Uy{constructor(){this.alive=!1,this.x=this.y=this.z=0,this.vx=this.vy=this.vz=0,this.bx=this.by=this.bz=0,this.age=0,this.life=1,this.size=1,this.baseSize=1,this.rot=0,this.rotVel=0,this.r=this.g=this.b=1,this.baseR=this.baseG=this.baseB=1,this.alpha=1,this.baseAlpha=1,this.seed=0,this.frame=0,this.oscPhase=0,this.oscFreq=0,this.oscAmp=0,this.oscAPhase=0,this.oscAFreq=0,this.oscSPhase=0,this.oscSFreq=0,this.turbSpeed=0,this.turbPhase=0,this.trail=null,this.trailClock=0,this.seq=0}}class Oy{constructor(e,n,r,i){this.gl=e,this.model=n||{},this.override=r||{},this.layer=i||null,this.syncLayerTransform(),this.maxCount=Math.max(1,Math.min(2e4,oe(this.model.maxcount,100))),this.simTime=0,this.paused=!1,this.texture=null,this.normalTex=null,this.material=null,this.blend="translucent",this.refract=!1,this.refractAmount=.04,this.opacityMul=1,this.lifetimeMul=1,this.visible=!0,this._ready=!1,this._prog=null,this._vbuf=null,this._quadBuf=null,this._vao=null,this._data=null,this._sceneTex=null,this.sequenceMul=Math.max(1,Math.round(oe(this.model.sequencemultiplier,1))),this.animationMode=this.model.animationmode||null,this.texFrames=null,this.frameCount=this.sequenceMul*this.sequenceMul,this.texAspectX=1,this.texAspectY=1,this.controlPoints=(this.model.controlpoint||[]).filter(Boolean).map(s=>({id:oe(s.id,0),lockToPointer:!!s.locktopointer||(oe(s.flags,0)&1)!==0,offset:Ce(s.offset),x:0,y:0,z:0})),this.pointer=null,this._followParent=null,this._followMode=null,this._followOffset=[0,0,0],this.ropeRenderer=null,this._seq=0,this._ropeOrder=[],this._ov={},this._applyOverride(),this.startTime=Math.max(0,Math.min(30,oe(this.model.starttime,0))),this._warmed=!1,this._compile()}reapplyOverride(){this._applyOverride()}setOverrideValue(e,n){const r=Number(n);Number.isFinite(r)&&(e==="alpha"?this.opacityMul=r:e==="count"?this._ov.countMul=r:e==="size"?this._ov.size=r:e==="rate"?this._ov.rateMul=r:e==="speed"?this._ov.speed=r:e==="lifetime"?this.lifetimeMul=r:e==="brightness"?this._ov.brightness=r:this._ov[e]=r)}_applyOverride(){this._ov={},this.opacityMul=1,this.lifetimeMul=1,this.maxCount=Math.max(1,Math.min(2e4,oe(this.model.maxcount,100)));const e=this.override||{};for(const n of Object.keys(e)){if(n==="id")continue;const r=e[n],i=r&&typeof r=="object"&&"value"in r?r.value:r;if(n==="count"){const s=oe(this.model.maxcount,100),a=Number(i),o=Number.isFinite(a)?a:1;this.maxCount=Math.max(1,Math.min(2e4,Math.round(s*o))),this._ov.countMul=o}else if(n==="alpha")this.opacityMul=Number(i),Number.isFinite(this.opacityMul)||(this.opacityMul=1);else if(n==="color"||n==="colorn"){const s=Ce(i);this._ov.color=n==="colorn"?s:[s[0]/255,s[1]/255,s[2]/255]}else n==="size"?this._ov.size=Number(i)||1:n==="rate"?(this._ov.rateMul=Number(i),Number.isFinite(this._ov.rateMul)||(this._ov.rateMul=1)):n==="speed"?this._ov.speed=Number(i)||1:n==="lifetime"?this.lifetimeMul=Number(i)||1:n==="brightness"?this._ov.brightness=Number(i)||1:this._ov[n]=i}this.pool=[];for(let n=0;n<this.maxCount;n++)this.pool.push(new Uy)}_compile(){const e=this.model;this.emitters=(e.emitter||[]).map(c=>({kind:c.name==="boxrandom"?"box":"sphere",origin:Ce(c.origin),directions:Ce(c.directions,[1,1,1]),distanceMin:yd(c.distancemin),distanceMax:yd(c.distancemax),sign:c.sign?Ce(c.sign):null,rate:oe(c.rate,0),audioDriven:c.audioprocessingmode!==void 0,audioBounds:Ce(c.audioprocessingbounds,[0,1]),fill:c.rate===void 0&&c.instantaneous===void 0&&c.audioprocessingmode===void 0,instantaneous:oe(c.instantaneous,0),speedMin:oe(c.speedmin,0),speedMax:oe(c.speedmax,0),controlPoint:c.controlpoint!==void 0&&c.controlpoint!==null?oe(c.controlpoint,0):0,_burst:!1}));const n=e.initializer||[];this.init={life:null,size:null,color:null,alpha:null,velocity:null,rotation:null,angularVelocity:null,turbulentVelocity:null,mapAround:null};for(const c of n)switch(c.name){case"lifetimerandom":this.init.life={min:oe(c.min,1),max:oe(c.max,1),exp:oe(c.exponent,1)};break;case"sizerandom":this.init.size={min:oe(c.min,1),max:oe(c.max,1),exp:oe(c.exponent,1)};break;case"colorrandom":this.init.color={min:Ce(c.min,[255,255,255]),max:Ce(c.max,[255,255,255])};break;case"alpharandom":this.init.alpha={min:oe(c.min,1),max:oe(c.max,1)};break;case"velocityrandom":this.init.velocity={min:Ce(c.min),max:Ce(c.max)};break;case"rotationrandom":this.init.rotation={min:Ce(c.min),max:Ce(c.max,[0,0,0]),exp:oe(c.exponent,1)};break;case"angularvelocityrandom":this.init.angularVelocity={min:Ce(c.min),max:Ce(c.max),exp:oe(c.exponent,1)};break;case"mapsequencearoundcontrolpoint":this.init.mapAround={count:Math.max(1,oe(c.count,1)),bounds:Ce(c.bounds,[0,1]),speedMin:Ce(c.speedmin),speedMax:Ce(c.speedmax,[0,0,0]),cp:oe(c.controlpoint,0)},this._mapAroundSeq=0;break;case"turbulentvelocityrandom":this.init.turbulentVelocity={scale:oe(c.scale,.1),offset:oe(c.offset,0),speedMin:oe(c.speedmin,0),speedMax:oe(c.speedmax,0),phaseMax:oe(c.phasemax,0),timeScale:oe(c.timescale,0),audioMode:oe(c.audioprocessingmode,0),audioBounds:Ce(c.audioprocessingbounds,[0,1])};break}const r=e.operator||[];this.ops={movement:null,angularMovement:null,alphaFade:null,alphaChange:null,sizeChange:null,colorChange:null,turbulence:[],oscAlpha:null,oscSize:null,oscPos:null,attract:[],vortex:[],remap:[]};for(const c of r)switch(c.name){case"movement":this.ops.movement={gravity:Ce(c.gravity),drag:oe(c.drag,0)};break;case"angularmovement":this.ops.angularMovement={force:Ce(c.force),drag:oe(c.drag,0)};break;case"alphafade":this.ops.alphaFade={fadeIn:oe(c.fadeintime,.1),fadeOut:oe(c.fadeouttime,.9)};break;case"alphachange":this.ops.alphaChange={startTime:oe(c.starttime,0),endTime:oe(c.endtime,1),startValue:oe(c.startvalue,1),endValue:oe(c.endvalue,0)};break;case"sizechange":this.ops.sizeChange={startTime:oe(c.starttime,0),endTime:oe(c.endtime,1),startValue:oe(c.startvalue,1),endValue:oe(c.endvalue,1)};break;case"colorchange":this.ops.colorChange={startTime:oe(c.starttime,0),endTime:oe(c.endtime,1),startValue:c.startvalue!==void 0?Ce(c.startvalue):null,endValue:Ce(c.endvalue,[1,1,1])};break;case"turbulence":this.ops.turbulence.push({scale:oe(c.scale,.01),speedMin:oe(c.speedmin,0),speedMax:oe(c.speedmax,0),timeScale:oe(c.timescale,1),phaseMin:oe(c.phasemin,0),phaseMax:oe(c.phasemax,0),mask:c.mask!==void 0?Ce(c.mask,[1,1,1]):[1,1,1]});break;case"oscillatealpha":this.ops.oscAlpha={freqMin:oe(c.frequencymin,oe(c.frequencymax,1)),freqMax:oe(c.frequencymax,1),scaleMin:oe(c.scalemin,0),scaleMax:oe(c.scalemax,1),phaseMax:oe(c.phasemax,sn)};break;case"oscillatesize":this.ops.oscSize={freqMin:oe(c.frequencymin,oe(c.frequencymax,1)),freqMax:oe(c.frequencymax,oe(c.frequencymin,1)),scaleMin:oe(c.scalemin,1),scaleMax:oe(c.scalemax,1),phaseMax:oe(c.phasemax,sn)};break;case"oscillateposition":this.ops.oscPos={freqMin:oe(c.frequencymin,oe(c.frequencymax,.5)),freqMax:oe(c.frequencymax,.5),scaleMin:oe(c.scalemin,0),scaleMax:oe(c.scalemax,1),phaseMin:oe(c.phasemin,0),phaseMax:oe(c.phasemax,sn),mask:c.mask!==void 0?Ce(c.mask,[1,1,0]):[1,1,0]};break;case"controlpointattract":this.ops.attract.push({cp:oe(c.controlpoint,0),origin:Ce(c.origin),scale:oe(c.scale,0),threshold:oe(c.threshold,0)});break;case"vortex":this.ops.vortex.push({axis:Ce(c.axis,[0,0,1]),offset:Ce(c.offset),distanceInner:oe(c.distanceinner,0),distanceOuter:oe(c.distanceouter,0),speedInner:oe(c.speedinner,0),speedOuter:oe(c.speedouter,0),cp:c.controlpoint!==void 0&&c.controlpoint!==null?oe(c.controlpoint,0):0,audioMode:oe(c.audioprocessingmode,0),audioBounds:Ce(c.audioprocessingbounds,[0,1])});break;case"remapvalue":this.ops.remap.push({output:c.output||"velocity",rangeMin:Ce(c.outputrangemin),rangeMax:Ce(c.outputrangemax),fn:c.transformfunction||"simplexnoise",inputScale:oe(c.transforminputscale,1)});break}const i=this.model.renderer,s=i==null,a=Array.isArray(i)?i:i?[i]:[];this.renderers=a.map(c=>{const u=c&&c.name||"sprite";return{kind:u,length:oe(c&&c.length,u==="spritetrail"?.1:u==="ropetrail"?.2:0),maxLength:oe(c&&c.maxlength,0),minLength:oe(c&&c.minlength,0),subdivision:oe(c&&c.subdivision,1),segments:oe(c&&c.segments,0),orientation:c&&c.orientation||null}}),s&&!this.renderers.length&&(this.renderers=[{kind:"sprite",length:0,maxLength:0,minLength:0,subdivision:1,segments:0,orientation:null}]);const o=this.renderers.find(c=>c.kind==="spritetrail"||c.kind==="ropetrail");if(this.trailCfg=o||null,this.trailSegments=1,this.trailDuration=0,this.trailSampleDt=0,o&&o.kind==="ropetrail"){const c=kd(o);this.trailSegments=c,this.trailDuration=Ad(o),this.trailSampleDt=this.trailDuration/Math.max(1,c-1);for(const u of this.pool)u.trail=new Float32Array(c*3),u.trailClock=0}this.ropeRenderer=this.renderers.find(c=>c.kind==="rope")||null}setModel(e){this.model=e,this._compile()}setMaterial(e){this.material=e;const n=e&&e.passes&&e.passes[0];this.blend=n&&n.blending||"translucent",this.refract=bd(e);const r=n&&n.constantshadervalues,i=r&&r.ui_editor_properties_refract_amount,s=Number(i);this.refractAmount=Number.isFinite(s)?Math.min(.35,Math.max(0,s)):.04}setNormalTexture(e){this.normalTex=e||null}setTexture(e){this.texture=e,this._ready=!!e;const n=e&&e.frames,r=Array.isArray(n)?n:n&&n.list&&n.list.length?n.list:null,i=e&&e.width||r&&(n&&n.atlasWidth||r.atlasWidth)||0,s=e&&e.height||r&&(n&&n.atlasHeight||r.atlasHeight)||0;r&&i>0&&s>0?(this.texFrames=r.map(u=>({ou:u.x/i,ov:u.y/s,su:u.width/i,sv:u.height/s})),this.frameCount=this.texFrames.length):(this.texFrames=null,this.frameCount=this.sequenceMul*this.sequenceMul);let a=1,o=1;this.texFrames&&r?(a=r[0].width||1,o=r[0].height||1):e&&e.width>0&&e.height>0&&(a=e.width,o=e.height);const c=Math.max(a,o)||1;this.texAspectX=a/c,this.texAspectY=o/c,this._frameData=void 0}setVisible(e){this.visible=e}syncLayerTransform(){const e=this.layer,n=e&&e.origin?e.origin:[0,0,0],r=e&&e.scale?e.scale:[1,1,1],i=e&&e.angles?e.angles:[0,0,0];this.originX=n[0]||0,this.originY=n[1]||0,this.originZ=n[2]||0,this.scaleX=r[0]===0?1:r[0],this.scaleY=r[1]===0?1:r[1],this.angleZ=(i[2]||0)*Math.PI/180;const s=Math.abs(this.scaleX),a=Math.abs(this.scaleY);this.sysScale=Math.min(s,a)||1,this.spriteStretchX=s/this.sysScale,this.spriteStretchY=a/this.sysScale}setPointer(e,n){const r=e-this.originX,i=n-this.originY,s=Math.cos(-this.angleZ),a=Math.sin(-this.angleZ);this.pointer={x:(r*s-i*a)/(this.scaleX||1),y:(r*a+i*s)/(this.scaleY||1)}}attachFollow(e,n,r){this._followParent=e||null,this._followMode=n==="particle"||n==="origin"?n:null;const i=r||[0,0,0];this._followOffset=[i[0]||0,i[1]||0,i[2]||0],this._syncFollow()}leaderParticle(){const e=this.pool;for(let n=0;n<e.length;n++)if(e[n].alive)return e[n];return null}localToWorld(e,n){const r=e*this.scaleX,i=n*this.scaleY,s=Math.cos(this.angleZ),a=Math.sin(this.angleZ);return[this.originX+r*s-i*a,this.originY+r*a+i*s]}_syncFollow(){const e=this._followParent,n=this._followMode;if(!e||!n)return;const r=this._followOffset;if(n==="particle"){const i=e.leaderParticle();if(!i)return;const s=e.localToWorld(i.x+r[0],i.y+r[1]);this.originX=s[0],this.originY=s[1]}else{const i=e.localToWorld(r[0],r[1]);this.originX=i[0],this.originY=i[1]}}spawn(e){const n=this.pool,r=n.length;let i=null,s=this._cursor||0;for(let f=0;f<r;f++){const d=n[(s+f)%r];if(!d.alive){i=d,this._cursor=(s+f+1)%r;break}}if(!i)return;i.alive=!0,i.age=0,i.seed=Math.random(),i.rot=0,i.rotVel=0,i.vx=i.vy=i.vz=0,i.frame=0,i.seq=this._seq++;const a=e.origin;if(e.kind==="box"){const f=e.distanceMax||[0,0,0],d=e.distanceMin;i.x=a[0]+nt(-f[0],f[0])+(d?d[0]:0),i.y=a[1]+nt(-f[1],f[1])+(d?d[1]:0),i.z=a[2]+nt(-f[2],f[2])+(d?d[2]:0)}else{const f=e.directions,d=e.distanceMin?e.distanceMin[0]:0,h=e.distanceMax?e.distanceMax[0]:0,p=Math.random()*2-1,m=Math.random()*sn,g=Math.sqrt(Math.max(0,1-p*p));let w=g*Math.cos(m),y=g*Math.sin(m),b=p;e.sign&&(e.sign[0]&&(w=Math.abs(w)*Math.sign(e.sign[0])),e.sign[1]&&(y=Math.abs(y)*Math.sign(e.sign[1])),e.sign[2]&&(b=Math.abs(b)*Math.sign(e.sign[2])));const v=nt(d,h);if(i.x=a[0]+w*v*f[0],i.y=a[1]+y*v*f[1],i.z=a[2]+b*v*f[2],e.speedMax||e.speedMin){const k=nt(e.speedMin,e.speedMax);i.vx+=w*k,i.vy+=y*k,i.vz+=b*k}}{const f=this._cpPos(e.controlPoint);if(f)i.x+=f[0],i.y+=f[1],i.z+=f[2];else{const d=this.controlPoints.find(h=>h.id===e.controlPoint);if(d&&d.lockToPointer){i.alive=!1;return}}}if(this.init.mapAround){const f=this.init.mapAround,d=this._cpPos(f.cp);if(d){const h=f.count,p=this._mapAroundSeq++,m=h>0?p%h/h:0,w=(f.bounds[0]+(f.bounds[1]-f.bounds[0])*m)*sn,y=e.distanceMin?e.distanceMin[0]:0,b=e.distanceMax?e.distanceMax[0]:0,v=b>0?b:y;i.x=d[0]+Math.cos(w)*v,i.y=d[1]+Math.sin(w)*v,i.z=d[2];const k=Math.random();i.vx+=f.speedMin[0]+(f.speedMax[0]-f.speedMin[0])*k,i.vy+=f.speedMin[1]+(f.speedMax[1]-f.speedMin[1])*k,i.vz+=f.speedMin[2]+(f.speedMax[2]-f.speedMin[2])*k}}const o=this.init,c=this._ov.speed||1,u=this._ov.size||1;if(i.life=o.life?Math.max(.001,gd(o.life.min,o.life.max,o.life.exp)*this.lifetimeMul):1,i.baseSize=o.size?gd(o.size.min,o.size.max,o.size.exp)*u:u,i.size=i.baseSize,o.color){const f=o.color.min,d=o.color.max,h=Math.random();i.baseR=(f[0]+(d[0]-f[0])*h)/255,i.baseG=(f[1]+(d[1]-f[1])*h)/255,i.baseB=(f[2]+(d[2]-f[2])*h)/255}else i.baseR=i.baseG=i.baseB=1;if(this._ov.color&&(i.baseR=this._ov.color[0],i.baseG=this._ov.color[1],i.baseB=this._ov.color[2]),i.r=i.baseR,i.g=i.baseG,i.b=i.baseB,i.baseAlpha=(o.alpha?nt(o.alpha.min,o.alpha.max):1)*this.opacityMul,i.alpha=i.baseAlpha,o.velocity&&(i.vx+=nt(o.velocity.min[0],o.velocity.max[0])*c,i.vy+=nt(o.velocity.min[1],o.velocity.max[1])*c,i.vz+=nt(o.velocity.min[2],o.velocity.max[2])*c),o.turbulentVelocity){const f=o.turbulentVelocity,d=f.audioMode?kc(f.audioBounds,this._audioLevel||0):1,h=nt(f.speedMin,f.speedMax)*c*d,p=this.simTime*(f.timeScale||0),m=xc(i.x*f.scale+f.offset,i.y*f.scale+f.offset,p+i.seed*(f.phaseMax||0),3);i.vx+=m[0]*h,i.vy+=m[1]*h,i.vz+=m[2]*h}o.rotation&&(i.rot=nt(o.rotation.min[2],o.rotation.max[2])),o.angularVelocity&&(i.rotVel=nt(o.angularVelocity.min[2],o.angularVelocity.max[2]));const l=this.ops;if(l.oscPos&&(i.oscFreq=nt(l.oscPos.freqMin,l.oscPos.freqMax),i.oscAmp=nt(l.oscPos.scaleMin,l.oscPos.scaleMax),i.oscPhase=nt(l.oscPos.phaseMin,l.oscPos.phaseMax)+i.seed*sn),l.oscAlpha&&(i.oscAFreq=nt(l.oscAlpha.freqMin,l.oscAlpha.freqMax),i.oscAPhase=Math.random()*(l.oscAlpha.phaseMax||sn)),l.oscSize&&(i.oscSFreq=nt(l.oscSize.freqMin,l.oscSize.freqMax),i.oscSPhase=Math.random()*(l.oscSize.phaseMax||sn)),l.turbulence.length){const f=l.turbulence[0];i.turbSpeed=nt(f.speedMin,f.speedMax),i.turbPhase=nt(f.phaseMin,f.phaseMax)}if(this.frameCount>1&&(i.frame=this.animationMode==="randomframe"?Math.floor(Math.random()*this.frameCount):0),i.bx=i.x,i.by=i.y,i.bz=i.z,i.trail){for(let f=0;f<i.trail.length;f+=3)i.trail[f]=i.x,i.trail[f+1]=i.y,i.trail[f+2]=i.z;i.trailClock=0}}updateParticle(e,n){if(e.age+=n,e.age>=e.life){e.alive=!1;return}const r=e.age/e.life,i=this.ops;if(i.movement&&(e.vx+=i.movement.gravity[0]*n,e.vy+=i.movement.gravity[1]*n,e.vz+=i.movement.gravity[2]*n,i.movement.drag>0)){const o=Math.exp(-i.movement.drag*n);e.vx*=o,e.vy*=o,e.vz*=o}i.angularMovement&&(e.rotVel+=(i.angularMovement.force[2]||0)*n,i.angularMovement.drag>0&&(e.rotVel*=Math.exp(-i.angularMovement.drag*n)));for(const o of i.turbulence){const c=o.timeScale||1,u=xc(e.bx*o.scale,e.by*o.scale,this.simTime*o.scale*c+e.turbPhase,3);e.vx+=u[0]*e.turbSpeed*o.mask[0]*n,e.vy+=u[1]*e.turbSpeed*o.mask[1]*n,e.vz+=u[2]*e.turbSpeed*o.mask[2]*n}for(const o of i.attract){const c=this._cpPos(o.cp);if(!c)continue;const u=c[0]+o.origin[0]-e.x,l=c[1]+o.origin[1]-e.y,f=Math.hypot(u,l);if(f<.001||o.threshold>0&&f>o.threshold)continue;const d=o.threshold>0?1-f/o.threshold:1,h=o.scale*d*n/Math.max(1,f);e.vx+=u*h,e.vy+=l*h}for(const o of i.vortex){const c=this._cpPos(o.cp)||[0,0,0],u=e.x-(c[0]+o.offset[0]),l=e.y-(c[1]+o.offset[1]),f=Math.hypot(u,l);if(f<.001)continue;const d=o.distanceOuter-o.distanceInner,h=d>0?Math.min(1,Math.max(0,(f-o.distanceInner)/d)):0,p=o.audioMode?kc(o.audioBounds,this._audioLevel||0):1,m=o.speedInner+(o.speedOuter-o.speedInner)*h;e.vx+=-l/f*m*n*p,e.vy+=u/f*m*n*p}for(const o of i.remap){const c=o.inputScale||1,u=xc(e.bx*.01*c,e.by*.01*c,this.simTime*.1,o.fn==="fbmnoise"?4:2);if(o.output==="velocity")for(let l=0;l<3;l++){const f=(u[l]+1)/2,d=o.rangeMin[l]+(o.rangeMax[l]-o.rangeMin[l])*f;l===0?e.vx=d:l===1?e.vy=d:e.vz=d}else if(o.output==="speed"){const l=(u[0]+1)/2,f=o.rangeMin[0]+(o.rangeMax[0]-o.rangeMin[0])*l,d=Math.hypot(e.vx,e.vy)||1;e.vx=e.vx/d*f,e.vy=e.vy/d*f}}if(e.bx+=e.vx*n,e.by+=e.vy*n,e.bz+=e.vz*n,e.rot+=e.rotVel*n,e.x=e.bx,e.y=e.by,e.z=e.bz,i.oscPos){const o=this.simTime*e.oscFreq*sn+e.oscPhase,c=i.oscPos.mask;e.x+=Math.sin(o)*e.oscAmp*c[0],e.y+=Math.cos(o)*e.oscAmp*c[1],e.z+=Math.sin(o*.7)*e.oscAmp*c[2]}let s=e.baseSize;if(i.sizeChange){const o=i.sizeChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0;s*=o.startValue+(o.endValue-o.startValue)*u}if(i.oscSize){const o=this.simTime*e.oscSFreq*sn+e.oscSPhase,c=i.oscSize,u=(c.scaleMin+c.scaleMax)/2,l=(c.scaleMax-c.scaleMin)/2;s*=u+Math.sin(o)*l}if(e.size=s,i.colorChange){const o=i.colorChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0,l=o.startValue||[e.baseR,e.baseG,e.baseB];e.r=l[0]+(o.endValue[0]-l[0])*u,e.g=l[1]+(o.endValue[1]-l[1])*u,e.b=l[2]+(o.endValue[2]-l[2])*u}let a=e.baseAlpha;if(i.alphaFade){const o=i.alphaFade.fadeIn,c=i.alphaFade.fadeOut;o>0&&r<o&&(a*=r/o),c<1&&r>c&&(a*=Math.max(0,(1-r)/(1-c)))}else i.alphaChange||(r<.1?a*=r/.1:r>.85&&(a*=(1-r)/.15));if(i.alphaChange){const o=i.alphaChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0;a*=o.startValue+(o.endValue-o.startValue)*u}if(i.oscAlpha){const o=this.simTime*e.oscAFreq*sn+e.oscAPhase,c=i.oscAlpha,u=(c.scaleMin+c.scaleMax)/2,l=(c.scaleMax-c.scaleMin)/2;a*=u+Math.sin(o)*l}if(e.alpha=Math.max(0,a),this.frameCount>1&&this.animationMode!=="randomframe"&&(e.frame=Math.min(this.frameCount-1,Math.floor(r*this.frameCount))),e.trail){const o=e.trail,c=this.trailSampleDt;if(c>0){e.trailClock=(e.trailClock||0)+n;let u=0;const l=this.trailSegments||8;for(;e.trailClock>=c&&u<l;){e.trailClock-=c,u++;for(let f=o.length-3;f>=3;f-=3)o[f]=o[f-3],o[f+1]=o[f-2],o[f+2]=o[f-1]}}o[0]=e.x,o[1]=e.y,o[2]=e.z}}_cpPos(e){const n=this.controlPoints.find(r=>r.id===e);return n?n.lockToPointer?this.pointer?[this.pointer.x+n.offset[0],this.pointer.y+n.offset[1],n.offset[2]]:null:n.offset:null}advance(e,n){if(!(this.paused||!this.visible)){if(this._syncFollow(),!this._warmed&&(this._warmed=!0,this.startTime>0)){const r=.03333333333333333,i=Math.min(900,Math.round(this.startTime/r));for(let s=0;s<i;s++)this._step(r)}this._step(e,n)}}_step(e,n){this.simTime+=e;const r=n&&Number.isFinite(n.level)?Math.max(0,Math.min(1,n.level)):0;this._audioLevel=r;for(const s of this.emitters){if(s.instantaneous>0&&!s._burst){s._burst=!0;for(let c=0;c<Math.min(s.instantaneous,this.maxCount);c++)this.spawn(s)}if(s.fill){const u=Math.min(this.maxCount,2048);let l=0;for(let d=0;d<this.pool.length;d++)this.pool[d].alive&&l++;let f=Math.min(u-l,512);for(;f-- >0;)this.spawn(s);continue}if(s.audioDriven){const c=kc(s.audioBounds,r);if(s.rate>0){const u=s.rate*c*(this._ov.rateMul!==void 0?this._ov.rateMul:1)*(this._ov.countMul!==void 0?this._ov.countMul:1);if(!(u>0))continue;s._accum=(s._accum||0)+u*e;let l=Math.floor(s._accum);if(l>0){s._accum-=l,l>this.maxCount&&(l=this.maxCount);for(let f=0;f<l;f++)this.spawn(s)}}else{const l=Math.round(Math.min(this.maxCount,2048)*c);let f=0;for(let h=0;h<this.pool.length;h++)this.pool[h].alive&&f++;let d=Math.min(l-f,256);for(;d-- >0;)this.spawn(s)}continue}const a=s.rate*(this._ov.rateMul!==void 0?this._ov.rateMul:1)*(this._ov.countMul!==void 0?this._ov.countMul:1);if(!(a>0))continue;s._accum=(s._accum||0)+a*e;let o=Math.floor(s._accum);if(o>0){s._accum-=o,o>this.maxCount&&(o=this.maxCount);for(let c=0;c<o;c++)this.spawn(s)}}const i=this.pool;for(let s=0;s<i.length;s++)i[s].alive&&this.updateParticle(i[s],e)}render(e,n,r,i,s){if(!this._ready||!this.visible||!this.renderers.length)return;const a=this.gl;this._prog||this._buildProgram(a);const o=this.trailCfg&&this.trailCfg.kind==="ropetrail"?this.trailCfg:null,c=this.trailCfg&&this.trailCfg.kind==="spritetrail"?this.trailCfg:null,u=this.ropeRenderer,l=vd(this.trailCfg,this.trailSegments),f=14,d=this.pool;let h=null;if(u){h=this._ropeOrder,h.length=0;for(let Y=0;Y<d.length;Y++)d[Y].alive&&h.push(d[Y]);h.sort((Y,J)=>Y.seq-J.seq)}let p=0;if(h)p=h.length;else for(let Y=0;Y<d.length;Y++)d[Y].alive&&p++;if(p===0||u&&p<2)return;const m=u?p-1:p*l,g=m*f;(!this._data||this._data.length<g)&&(this._data=new Float32Array(Math.max(g,1024)));const w=this._data;let y=0;const b=this._ov.brightness||1,v=this.sysScale,k=this.spriteStretchX*(this.texAspectX||1),A=this.spriteStretchY*(this.texAspectY||1),T=Math.cos(this.angleZ),S=Math.sin(this.angleZ),P=this.originX,M=this.originY,B=this.scaleX,N=this.scaleY,O=(Y,J)=>{const ne=Y*B,fe=J*N;return[P+ne*T-fe*S,s-(M+ne*S+fe*T)]};if(u)for(let Y=0;Y+1<p;Y++){const J=h[Y],ne=h[Y+1],fe=O(J.x,J.y),Ne=O(ne.x,ne.y),Qe=Ne[0]-fe[0],Ve=Ne[1]-fe[1],Fe=Math.hypot(Qe,Ve),Le=(Math.abs(J.size)+Math.abs(ne.size))*.5*v;Le>0&&(w[y++]=(fe[0]+Ne[0])*.5,w[y++]=(fe[1]+Ne[1])*.5,w[y++]=0,w[y++]=Le,w[y++]=Math.atan2(-Qe,Ve),w[y++]=(J.r+ne.r)*.5*b,w[y++]=(J.g+ne.g)*.5*b,w[y++]=(J.b+ne.b)*.5*b,w[y++]=(J.alpha+ne.alpha)*.5,w[y++]=1,w[y++]=Fe/Le,w[y++]=0,w[y++]=Sc(J),w[y++]=Sc(ne))}for(let Y=0;Y<d.length&&!u;Y++){const J=d[Y];if(J.alive)for(let ne=0;ne<l;ne++){let fe=J.x,Ne=J.y,Qe=1,Ve=1,Fe=J.rot,Le=k,Tt=A,Xe,It;if(o&&J.trail){fe=J.trail[ne*3],Ne=J.trail[ne*3+1];const Ue=l>1?ne/(l-1):0;Qe=1-Ue,Ve=1-Ue*.55;let We=0,Oe=0;ne+1<l?(We=J.trail[ne*3]-J.trail[(ne+1)*3],Oe=J.trail[ne*3+1]-J.trail[(ne+1)*3+1]):ne>0?(We=J.trail[(ne-1)*3]-J.trail[ne*3],Oe=J.trail[(ne-1)*3+1]-J.trail[ne*3+1]):(We=J.vx,Oe=J.vy);const it=O(fe,Ne),ve=O(fe-We,Ne-Oe),un=it[0]-ve[0],jr=it[1]-ve[1],Zt=Math.hypot(un,jr),St=Math.max(.001,Math.abs(J.size)*v*Ve);Zt>.001?(Fe=Tc(un,jr),Xe=(it[0]+ve[0])*.5,It=(it[1]+ve[1])*.5,Tt=Math.max(A,Zt/St)):(Xe=it[0],It=it[1])}else{const Ue=O(fe,Ne);Xe=Ue[0],It=Ue[1]}if(c){const Ue=O(J.x,J.y);Xe=Ue[0],It=Ue[1];const We=O(J.x+J.vx,J.y+J.vy);Fe=Tc(We[0]-Ue[0],We[1]-Ue[1]);const Oe=wd(Math.hypot(J.vx,J.vy),c.length,c.minLength,c.maxLength);Tt=A*Oe}w[y++]=Xe,w[y++]=It,w[y++]=0,w[y++]=Math.abs(J.size)*v*Ve,w[y++]=Fe,w[y++]=J.r*b,w[y++]=J.g*b,w[y++]=J.b*b,w[y++]=J.alpha*Qe,w[y++]=Le,w[y++]=Tt,w[y++]=J.frame,w[y++]=0,w[y++]=1}}const q=this._prog;a.useProgram(q.prog),a.bindVertexArray(this._vao),a.bindBuffer(a.ARRAY_BUFFER,this._vbuf),a.bufferData(a.ARRAY_BUFFER,w.subarray(0,y),a.DYNAMIC_DRAW),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),a.uniform1i(q.uniTex,0),a.uniformMatrix4fv(q.uniMvp,!1,e);const H=this.refract&&this.normalTex&&this.normalTex.glTex;if(q.uniRefract&&a.uniform1i(q.uniRefract,H?1:0),H){a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,this.normalTex.glTex),q.uniNormal&&a.uniform1i(q.uniNormal,1);const Y=this.blend!=="additive";if(q.uniSampleScene&&a.uniform1i(q.uniSampleScene,Y?1:0),Y){const J=a.drawingBufferWidth||n,ne=a.drawingBufferHeight||r;a.bindFramebuffer(a.FRAMEBUFFER,null),a.activeTexture(a.TEXTURE2),this._sceneTex?a.bindTexture(a.TEXTURE_2D,this._sceneTex):(this._sceneTex=a.createTexture(),a.bindTexture(a.TEXTURE_2D,this._sceneTex),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE)),a.copyTexImage2D(a.TEXTURE_2D,0,a.RGB8,0,0,J,ne,0),q.uniScene&&a.uniform1i(q.uniScene,2),q.uniResolution&&a.uniform2f(q.uniResolution,J,ne),q.uniRefractScale&&a.uniform1f(q.uniRefractScale,this.refractAmount||.04)}else a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),q.uniScene&&a.uniform1i(q.uniScene,2)}else q.uniNormal&&(a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),a.uniform1i(q.uniNormal,1),a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),q.uniScene&&a.uniform1i(q.uniScene,2),q.uniSampleScene&&a.uniform1i(q.uniSampleScene,0));const G=this._frameUniformData();G?(a.uniform1i(q.uniFrameCount,G.count),a.uniform4fv(q.uniFrames,G.arr)):a.uniform1i(q.uniFrameCount,0),a.enable(a.BLEND),this.blend==="additive"?a.blendFunc(a.SRC_ALPHA,a.ONE):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),a.depthMask(!1),a.drawArraysInstanced(a.TRIANGLE_STRIP,0,4,m),a.depthMask(!0),a.disable(a.BLEND),a.bindVertexArray(null)}_buildProgram(e){const n=Ny(e);this._quadBuf=n.quadBuf,this._vbuf=n.vbuf,this._vao=n.vao,this._prog=n.prog}_frameUniformData(){if(this._frameData!==void 0)return this._frameData;let e=this.texFrames;if(!e&&this.sequenceMul>1){const i=this.sequenceMul;e=[];for(let s=0;s<i;s++)for(let a=0;a<i;a++)e.push({ou:a/i,ov:s/i,su:1/i,sv:1/i})}if(!e||e.length===0)return this._frameData=null,null;const n=Math.min(e.length,128),r=new Float32Array(n*4);for(let i=0;i<n;i++)r[i*4]=e[i].ou,r[i*4+1]=e[i].ov,r[i*4+2]=e[i].su,r[i*4+3]=e[i].sv;return this._frameData={count:n,arr:r},this._frameData}liveCount(){let e=0;for(const n of this.pool)n.alive&&e++;return e}dispose(){this.paused=!0;const e=this.gl;if(e){try{this._vbuf&&e.deleteBuffer(this._vbuf),this._quadBuf&&e.deleteBuffer(this._quadBuf),this._vao&&e.deleteVertexArray(this._vao),this._prog&&this._prog.prog&&e.deleteProgram(this._prog.prog),this._sceneTex&&e.deleteTexture(this._sceneTex)}catch{}this._prog=null,this._vbuf=null,this._quadBuf=null,this._vao=null,this._data=null,this._sceneTex=null}}}const zy=Object.freeze(Object.defineProperty({__proto__:null,ParticleSystem:Oy,particleInstanceSegs:vd,particlePassRefract:bd,rgbaIsBlankWhite:Ly,ropeParticleV:Sc,ropeTrailDuration:Ad,ropeTrailHistoryCount:kd,spriteTrailLengthFactor:wd,spriteTrailRotation:Tc},Symbol.toStringTag,{value:"Module"})),ms=new Map,Pc=new Map;let Aa=null;function Hy(t,e){const n=String(t);Pc.set(n,e),ms.delete(n)}function Vy(t){Aa=typeof t=="function"?t:null}function Wy(){Pc.clear(),Aa=null,ms.clear()}function jy(){return Object.keys(vs)}function qe(t,e,n){t[e]=255,t[e+1]=255,t[e+2]=255,t[e+3]=Math.round(Math.min(1,Math.max(0,n))*255)}function ps(t,e){const{width:n,height:r,rgba:i}=t,s=Math.max(2,Math.round(Math.min(n,r)*.04));for(let a=0;a<r;a++)for(let o=0;o<n;o++){const c=Math.min(o,a,n-1-o,r-1-a);if(c>=s)continue;const u=c/s,l=(a*n+o)*4+3;i[l]=Math.round(i[l]*u)}if(e>0){let a=0;const o=n*r;for(let u=0;u<o;u++)a+=i[u*4+3];const c=a/o/255;if(c>e&&c>0){const u=e/c;for(let l=0;l<o;l++)i[l*4+3]=Math.round(i[l*4+3]*u)}}return t}function gs(t){let e=t>>>0;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const Si=t=>t*t*(3-2*t),xd=t=>t*t*t*(t*(t*6-15)+10),_c=(t,e,n)=>t+(e-t)*n,he=(t,e)=>Math.exp(-(t*t)/(e*e));function pr(t,e,n,r){const i=Math.min(t,e,n-1-t,n-1-e);return i>=r?1:i/r}function ys(t,e){const n=new Uint8Array(t*t*4),r=t/2;for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=Math.hypot((s+.5-r)/r,(i+.5-r)/r);let o=0;for(let c=0;c<e.length;c++)o+=e[c].w*he(a,e[c].r);qe(n,(i*t+s)*4,o)}return{width:t,height:t,rgba:n}}function $n(t,e,n){return ys(t,[e,n])}function gr(t,e,n,r,i){const s=new Uint8Array(t*t*4),a=t/2,o=Math.max(2,Math.round(t*.03));for(let c=0;c<t;c++)for(let u=0;u<t;u++){const l=(u+.5-a)/a,f=(c+.5-a)/a,d=Math.hypot(l,f),h=Math.atan2(f,l),p=Math.pow(.5+.5*Math.cos(e*h),r);let m=he(d,i)+p*he(d,n);m*=pr(u,c,t,o),qe(s,(c*t+u)*4,m)}return{width:t,height:t,rgba:s}}function Sn(t,e,n,r,i){const a=new Uint8Array(t*e*4);for(let o=0;o<e;o++){const c=o/(e-1),u=r?he(c-.5,.27):Si(Math.min(1,c/.06))*Math.pow(1-c,1.35);for(let l=0;l<t;l++){const f=l/(t-1)*2-1,d=he(f,n);qe(a,(o*t+l)*4,d*d*d*u*.55)}}return{width:t,height:e,rgba:a}}const xa=4,Ec=128,Cc=512;function Td(t,e,n,r,i){const s=i===void 0?.85:i,a=new Uint8Array(t*e*4),o=e/xa,c=gs(335009),u=Math.tan(n*Math.PI/180),l=t/2;for(let f=0;f<xa;f++){const d=s*(.8+c()*.35),h=r*(.85+c()*.5),p=(c()-.5)*t*.12;for(let m=0;m<o;m++){const g=m/(o-1),w=l+p+(o-1)*u/2-(o-1)*u*g,y=he(g-.5,.27);for(let b=0;b<t;b++){const v=Math.abs(b+.5-w),A=Math.exp(-(v*v)/(h*h))*y*d;A<.004||qe(a,((f*o+m)*t+b)*4,A)}}}return{width:t,height:e,rgba:a}}function qy(t){if(t==="particle/nature/rain1"||t==="particle/nature/rain2"){const e=[],n=Cc/xa;for(let r=0;r<xa;r++)e.push({x:0,y:r*n,width:Ec,height:n});return e}if(/^particle\/nature\/leaves\d*$/.test(t)){const e=[];for(let n=0;n<3;n++)for(let r=0;r<3;r++)e.push({x:r*ws,y:n*ws,width:ws,height:ws});return e}return null}function Ic(t,e,n){const r=new Uint8Array(t*t*4),i=t/2;for(let s=0;s<t;s++)for(let a=0;a<t;a++){const o=Math.hypot((a-i)/i,(s-i)/i);qe(r,(s*t+a)*4,he(o-e,n*.6)*Math.max(0,1-o))}return{width:t,height:t,rgba:r}}function Sd(t,e){const n={1:{r:.78,t:.048,inner:.06,hi:[[-.28,-.32,.22,.9],[.32,.36,.12,.28]]},2:{r:.7,t:.07,inner:.14,hi:[[-.2,-.28,.3,.72],[.38,.2,.14,.4]]},3:{r:.84,t:.036,inner:.04,hi:[[-.34,-.18,.16,.95],[.2,.42,.1,.22],[.04,-.08,.07,.18]]}},r=n[e]||n[1],i=new Uint8Array(t*t*4),s=t/2;for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=(o+.5-s)/s,u=(a+.5-s)/s,l=Math.hypot(c,u);let f=he(l-r.r,r.t*.85)*Math.max(0,1.05-l);l<r.r&&(f+=r.inner*he(l,.5));for(let d=0;d<r.hi.length;d++){const h=r.hi[d];f+=h[3]*he(Math.hypot(c-h[0],u-h[1]),h[2])}qe(i,(a*t+o)*4,f)}return ps({width:t,height:t,rgba:i},.05)}function bs(t,e){const n=t>>1,r=new Uint8Array(t*t*4),i=e===1?[1,2,1,3]:e===2?[2,1,2,3]:[3,1,2,3];for(let s=0;s<2;s++)for(let a=0;a<2;a++){const o=Sd(n,i[s*2+a]);for(let c=0;c<n;c++){const u=(s*n+c)*t,l=c*n;for(let f=0;f<n;f++){const d=(u+a*n+f)*4,h=(l+f)*4;r[d]=o.rgba[h],r[d+1]=o.rgba[h+1],r[d+2]=o.rgba[h+2],r[d+3]=o.rgba[h+3]}}}return{width:t,height:t,rgba:r}}function Pd(t){const e=new Uint8Array(t*t*4),n=t/2,r=[[.32,0],[1.1,.35],[2.2,-.3],[-.7,.2]];for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=s>=n?1:0,o=i>=n?1:0,c=o*2+a,u=a*n+n/2,l=o*n+n/2,f=r[c][0],d=r[c][1],h=(s+.5-u)/(n*.4),p=(i+.5-l)/(n*.4),m=Math.cos(f),g=Math.sin(f);let w=h*m+p*g;const y=-h*g+p*m;w+=d*y*.18;const b=1-Math.max(0,y)*.42,v=Math.hypot(w/(.52*b),y/.92);let k=v>=1.12?0:he(v,.48);k=Math.min(1,k+he(w,.07)*he(y,.65)*k*.4),qe(e,(i*t+s)*4,k)}return ps({width:t,height:t,rgba:e},.11)}const ws=256,wt=ws*3;function vt(t,e){const n={0:{rx:.36,ry:.92,wave:0,folds:0,rgb:[196,66,32]},1:{rx:.48,ry:.86,wave:.05,folds:7,rgb:[188,58,30]},2:{rx:.4,ry:.88,wave:.08,folds:5,rgb:[206,82,36]},3:{rx:.58,ry:.72,wave:0,folds:0,rgb:[214,148,40]},5:{rx:.44,ry:.8,wave:.12,folds:9,rgb:[220,158,48]},6:{rx:.52,ry:.78,wave:.07,folds:4,rgb:[122,150,52]},7:{rx:.5,ry:.9,wave:.16,folds:3,rgb:[96,138,50]},8:{rx:.38,ry:.94,wave:.2,folds:2,rgb:[110,148,56]}},r=n[e]||n[0],i=Math.floor(t/3),s=new Uint8Array(i*3*i*3*4),a=i/2,o=gs(7855+e*131);for(let c=0;c<9;c++){const u=c%3,l=c/3|0,f=c/9*Math.PI*2+(o()-.5)*.7,d=.9+o()*.16,h=.9+o()*.2,p=1+(o()-.5)*.12,m=Math.cos(f),g=Math.sin(f),w=c&1?-1:1;for(let y=0;y<i;y++)for(let b=0;b<i;b++){const v=(b+.5-a)/a*w,k=(y+.5-a)/a,A=(v*m+k*g)/d,T=(-v*g+k*m)/d,S=1-Math.pow(Math.min(1,Math.abs(T)),1.7)*.52,P=Math.atan2(A,T),M=r.wave?1+r.wave*Math.sin(P*r.folds):1,B=Math.hypot(A/(r.rx*M*S),T/r.ry),N=B>=1.08?0:Math.min(1,(1.08-B)/.14);if(N<=0)continue;const O=he(A,.028)*he(T,.72),q=(.8+.2*Math.max(0,1-B))*(1+O*.22)*h,H=((l*i+y)*i*3+u*i+b)*4;s[H]=Math.min(255,Math.round(r.rgb[0]*q*p)),s[H+1]=Math.min(255,Math.round(r.rgb[1]*q)),s[H+2]=Math.min(255,Math.round(r.rgb[2]*q*(2-p))),s[H+3]=Math.round(N*255)}}return ps({width:i*3,height:i*3,rgba:s},0)}function an(t,e){const n=t.width,r=t.height,i=t.rgba,s=e??2.8,a=new Uint8Array(n*r*4),o=(c,u)=>{const l=c<0?0:c>=n?n-1:c,f=u<0?0:u>=r?r-1:u;return i[(f*n+l)*4+3]/255};for(let c=0;c<r;c++)for(let u=0;u<n;u++){const l=(o(u-1,c)-o(u+1,c))*s,f=(o(u,c-1)-o(u,c+1))*s,d=1/Math.hypot(l,f,1),h=(c*n+u)*4;a[h]=Math.round((l*d*.5+.5)*255),a[h+1]=Math.round((f*d*.5+.5)*255),a[h+2]=Math.round((d*.5+.5)*255),a[h+3]=255}return{width:n,height:r,rgba:a}}function _d(t){const e=new Uint8Array(t*t*4),n=t/2;for(let r=0;r<t;r++)for(let i=0;i<t;i++){const s=(i+.5-n)/n,a=(r+.5-n)/n,o=Math.hypot(s,a),c=o>=1?0:Math.sqrt(Math.max(0,1-o*o)),u=he(o-.62,.11)*.55;qe(e,(r*t+i)*4,Math.min(1,c*.85+u))}return{width:t,height:t,rgba:e}}function Xy(t){const e=new Uint8Array(t*t*4),n=t/2;for(let r=0;r<t;r++)for(let i=0;i<t;i++){const s=(i+.5-n)/n,a=(r+.5-n)/n,o=Math.hypot(s,a),c=Math.atan2(a,s),u=he(o,.38)*(.55+.45*Math.cos(c*3+o*6));qe(e,(r*t+i)*4,u)}return{width:t,height:t,rgba:e}}function Ed(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=Math.hypot(a,o),u=Math.atan2(o,a),l=Si(Math.max(0,Math.cos(u)*.55+.45)),f=he(c-.68,.07)*l+.35*he(c-.78,.12)*he(u-.9,.55);qe(e,(i*t+s)*4,Math.min(1,f)*pr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Gy(t){if(!t||t.length<16)return!1;const e=t.length/4,n=Math.max(1,e/48|0);let r=0;for(let i=0;i<e;i+=n){const s=i*4;if(t[s]<240||t[s+1]<240||t[s+2]<240)return!1;r++}return r>0}function $y(t){return!t||!t.rgba?t:Gy(t.rgba)?an(t,2.8):t}const Qy={"particle/drop":"particle/drop_normal","particle/water/rain_drops_sheet":"particle/water/rain_drops_sheet_normal","particle/bubbles/bubble1":"particle/bubbles/bubble1normal","particle/bubbles/bubble2":"particle/bubbles/bubble2_normal","particle/sharp_halo":"particle/sharp_halo_normal","particle/misc/wave":"particle/normal_splash","particle/halo":"particle/sharp_halo_normal"};function Yy(t){if(!t)return null;const e=String(t);return/normal/i.test(e)?e:Qy[e]||e+"_normal"}function Ky(t){const e=String(t);return/(^|\/)normal_/.test(e)?null:/_normal$/i.test(e)?e.replace(/_normal$/i,""):/normal$/i.test(e)?e.replace(/normal$/i,""):null}function Zy(t){if(vs[t])return vs[t]();const e=String(t).toLowerCase();return/normal/.test(e)?$n(64,{r:.18,w:1},{r:.4,w:.2}):Nd(t)()}function Cd(t,e,n){const r=gs(n*7919+17);let i=t;const s=[];for(let c=0;c<e;c++){const u=i*i,l=new Float32Array(u*2);for(let f=0;f<u;f++){const d=r()*Math.PI*2;l[f*2]=Math.cos(d),l[f*2+1]=Math.sin(d)}s.push({f:i,g:l,ox:c*7.31,oy:c*3.17}),i*=2}const a=(c,u,l,f,d)=>{const h=c.f,p=(u%h+h)%h,g=((l%h+h)%h*h+p)*2;return c.g[g]*f+c.g[g+1]*d},o=(c,u,l)=>{const f=(u+c.ox)*c.f,d=(l+c.oy)*c.f,h=Math.floor(f),p=Math.floor(d),m=f-h,g=d-p,w=xd(m),y=xd(g);return _c(_c(a(c,h,p,m,g),a(c,h+1,p,m-1,g),w),_c(a(c,h,p+1,m,g-1),a(c,h+1,p+1,m-1,g-1),w),y)};return function(u,l,f){const d=f==null?s.length:Math.min(f,s.length);let h=1,p=0,m=0;for(let g=0;g<d;g++)p+=(o(s[g],u,l)*.5+.5)*h,m+=h,h*=.55;return p/m}}function Id(t,e,n){const{width:r,height:i,rgba:s}=t;if(r===e&&i===n)return t;const a=new Uint8Array(e*n*4);for(let o=0;o<n;o++){const c=(o+.5)/n*i-.5,u=Math.max(0,Math.min(i-1,Math.floor(c))),l=Math.max(0,Math.min(i-1,u+1)),f=c-Math.floor(c);for(let d=0;d<e;d++){const h=(d+.5)/e*r-.5,p=Math.max(0,Math.min(r-1,Math.floor(h))),m=Math.max(0,Math.min(r-1,p+1)),g=h-Math.floor(h),w=s[(u*r+p)*4+3],y=s[(u*r+m)*4+3],b=s[(l*r+p)*4+3],v=s[(l*r+m)*4+3],k=(w*(1-g)+y*g)*(1-f)+(b*(1-g)+v*g)*f;qe(a,(o*e+d)*4,k/255)}}return{width:e,height:n,rgba:a}}function yr(t,e,n,r,i,s,a){const o=s===void 0?1:s,c=a===void 0?200:a,u=256,l=Cd(e,n,r),f=new Uint8Array(u*u*4),d=u/2,h=u*u,p=new Float32Array(h);let m=1,g=0;for(let v=0;v<h;v++){const k=v%u,A=v/u|0,T=(k+.5)/u,S=(A+.5)/u,P=l(T+5.2,S+1.3,2)-.5,M=l(T+9.7,S+8.1,2)-.5,B=p[v]=l(T+P*.45,S+M*.45);B<m&&(m=B),B>g&&(g=B)}const w=g-m||1;for(let v=0;v<u;v++)for(let k=0;k<u;k++){const A=(p[v*u+k]-m)/w,T=Math.hypot((k+.5-d)/d,(v+.5-d)/d),S=Math.pow(Math.max(0,1-T),o);let P=Math.max(0,(A-(1-i))/(i||1));P=Si(Math.min(1,P))*S,qe(f,(v*u+k)*4,P)}let y=0;for(let v=0;v<h;v++)y=Math.max(y,f[v*4+3]);if(y>0&&y<c){const v=c/y;for(let k=0;k<h;k++)f[k*4+3]=Math.round(Math.min(255,f[k*4+3]*v))}const b={width:u,height:u,rgba:f};return u===t?b:Id(b,t,t)}function Mc(t,e){const n=t,r=Cd(3,5,e??23),i=new Uint8Array(n*n*4),s=n*n,a=new Float32Array(s);let o=1,c=0;for(let d=0;d<s;d++){const h=d%n,p=d/n|0,m=(h+.5)/n,g=(p+.5)/n,w=r(m+2.1,g+4.7,2)-.5,y=r(m+6.3,g+1.9,2)-.5,b=a[d]=r(m+w*.28,g+y*.55);b<o&&(o=b),b>c&&(c=b)}const u=c-o||1;for(let d=0;d<n;d++)for(let h=0;h<n;h++){const p=(d+.5)/n,m=(h+.5)/n*2-1,g=.1+.52*Math.pow(p,1.25),w=(a[d*n+h]-o)/u,y=he(m/(g||.01),.55)*he(p-.58,.42);let b=Si(Math.min(1,Math.max(0,(w-.18)/.72)))*y;b*=p<.06?p/.06:1,qe(i,(d*n+h)*4,b)}let l=0;for(let d=0;d<s;d++)l=Math.max(l,i[d*4+3]);if(l>0&&l<220){const d=220/l;for(let h=0;h<s;h++)i[h*4+3]=Math.round(Math.min(255,i[h*4+3]*d))}const f=ps({width:n,height:n,rgba:i},.08);return n===t?f:Id(f,t,t)}function Bc(t,e,n,r){const i=new Uint8Array(t*e*4),s=t/n,a=e/r;for(let o=0;o<e;o++)for(let c=0;c<t;c++){const u=Math.floor(c/s),l=Math.floor(o/a),f=(c+.5-u*s)/s*2-1,d=(o+.5-l*a)/a*2-1,h=1-Math.max(0,d)*.45,p=Math.hypot(f/(.52*h),d/.8),m=p>=1.12?0:he(p,.48);qe(i,(o*t+c)*4,m)}return{width:t,height:e,rgba:i}}function Md(t){const e=new Uint8Array(t*t*4),n=gs(7),r=[];for(let i=0;i<11;i++)r.push({x:.14+n()*.72,y:.14+n()*.72,rx:.025+n()*.03,ry:.018+n()*.024,rot:n()*Math.PI});for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5)/t,o=(i+.5)/t;let c=0;for(const u of r){const l=a-u.x,f=o-u.y,d=Math.cos(u.rot),h=Math.sin(u.rot),p=(l*d+f*h)/u.rx,m=(-l*h+f*d)/u.ry,g=he(Math.hypot(p,m),.55);g>c&&(c=g)}qe(e,(i*t+s)*4,c)}return{width:t,height:t,rgba:e}}function Ta(t,e){const n=e??19,r=gs(n),i=d=>Math.min(.86,Math.max(.14,d)),s=5+n%4,a=[];let o=i(.5+(r()-.5)*.16);for(let d=0;d<=s;d++){const h=.06+d/s*.86;d>0&&(o=i(o+(r()-.5)*.32)),a.push([o,h])}const c=[];for(let d=0;d<a.length-1;d++)c.push([a[d],a[d+1],1]);const u=1+n%2;for(let d=0;d<u;d++){const h=1+(n+d*3)%Math.max(1,a.length-2),p=a[h],m=[p];let g=p[0],w=p[1];const y=2+n%2;for(let b=0;b<y;b++)g=i(g+(r()-.5)*.36),w=Math.min(.92,w+.1+r()*.08),m.push([g,w]);for(let b=0;b<m.length-1;b++)c.push([m[b],m[b+1],.45+d*.1])}const l=new Uint8Array(t*t*4),f=Math.max(2,Math.round(t*.04));for(let d=0;d<t;d++)for(let h=0;h<t;h++){const p=(h+.5)/t,m=(d+.5)/t;let g=9,w=0;for(const[b,v,k]of c){const A=v[0]-b[0],T=v[1]-b[1],S=A*A+T*T||1e-8,P=Math.max(0,Math.min(1,((p-b[0])*A+(m-b[1])*T)/S)),M=Math.hypot(p-(b[0]+A*P),m-(b[1]+T*P));M/k<g&&(g=M/k,w=k)}const y=.95*he(g,.012)+.3*he(g,.05)*w;qe(l,(d*t+h)*4,Math.min(1,y)*pr(h,d,t,f))}return{width:t,height:t,rgba:l}}function Rc(t,e){const n=new Uint8Array(t*e*4);for(let r=0;r<e;r++)for(let i=0;i<t;i++){const s=(i+.5-t/2)/(t/2),a=(r+.5-e/2)/(e/2),o=he(s,.34)*Math.exp(-Math.max(0,-a-.05)*4.2)*(a<.1?1:Math.max(0,1-a*4)),c=Math.hypot(s/.34,(a-.42)/.3),u=c>=1?0:he(c,.5);qe(n,(r*t+i)*4,Math.max(o,u))}return{width:t,height:e,rgba:n}}function Jy(t){return $n(t,{r:.1,w:1},{r:.3,w:.16})}function Fc(t,e){const n=new Uint8Array(t*e*4);for(let r=0;r<e;r++){const i=(r+.5)/e,s=Si(Math.min(1,Math.min(i/.08,(1-i)/.08))),a=he(i-.46,.24)*s,o=.5*(1-Si(Math.min(1,Math.max(0,(i-.42)/.5)))*.6);for(let c=0;c<t;c++){const u=(c+.5-t/2)/(t/2);qe(n,(r*t+c)*4,he(Math.abs(u)/(o||.01),.5)*a)}}return{width:t,height:e,rgba:n}}function Bd(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=he(Math.hypot(a,o),.42),u=he(Math.hypot(a-.34,o),.36),l=Math.max(0,c-u*1.08)*pr(s,i,t,r);qe(e,(i*t+s)*4,l)}return{width:t,height:t,rgba:e}}function Rd(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n;let c=he(Math.hypot(a,o),.08);for(let u=0;u<6;u++){const l=u*Math.PI/3,f=Math.cos(l),d=Math.sin(l),h=a*f+o*d,p=-a*d+o*f;if(h<0)continue;const m=Math.max(0,1.02-h/.72);c+=he(p,.028)*he(h,.5)*m,c+=.55*he(p-(h-.28)*.65,.02)*he(h-.28,.12)*m,c+=.55*he(p+(h-.28)*.65,.02)*he(h-.28,.12)*m,c+=.4*he(p-(h-.48)*.7,.016)*he(h-.48,.08)*m,c+=.4*he(p+(h-.48)*.7,.016)*he(h-.48,.08)*m}qe(e,(i*t+s)*4,Math.min(1,c)*pr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Fd(t,e){const n=new Uint8Array(t*t*4),r=t/2,i=Math.max(2,Math.round(t*.04)),s=Math.abs(e|0)%3;for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=(o+.5-r)/r*1.55,u=(a+.5-r)/r*1.55,l=Math.abs(Math.abs(c)+Math.abs(u)-.55);let f=he(l,.016);s===0?(f+=he(c,.012)*he(u,.38),f+=he(u,.012)*he(c,.38)):s===1?(f+=he(c-u,.012)*he(c+u,.36),f+=he(c+u,.012)*he(c-u,.36)):(f+=he(Math.hypot(c,u)-.26,.014),f+=he(c,.012)*he(u,.22)),qe(n,(a*t+o)*4,Math.min(1,f)*pr(o,a,t,i))}return ps({width:t,height:t,rgba:n},.03)}function Dc(t){let e=0;const n=String(t);for(let r=0;r<n.length;r++)e=e*31+n.charCodeAt(r)|0;return e}function eb(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.03)),i=1.6/t;for(let s=0;s<t;s++)for(let a=0;a<t;a++){const o=(a+.5-n)/n,c=(s+.5-n)/n,u=Math.hypot(o,c);let l=he(u,.05)+.3*he(u,.15);l+=.9*he(c,i)*Math.exp(-Math.abs(o)/.3),l+=.9*he(o,i)*Math.exp(-Math.abs(c)/.3),l*=pr(a,s,t,r),qe(e,(s*t+a)*4,l)}return{width:t,height:t,rgba:e}}function Dd(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.03));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=Math.hypot(a,o),u=he(c,.07)+.85*he(a,.62)*he(o,.045)+.22*he(a,.92)*he(o,.018);qe(e,(i*t+s)*4,Math.min(1,u)*pr(s,i,t,r))}return{width:t,height:t,rgba:e}}const vs={"particle/halo_6":()=>$n(256,{r:.14,w:1},{r:.4,w:.17}),"particle/normal_splash":()=>an(_d(256),3.2),"particle/drop_normal":()=>an(Fc(128,512),3.4),"particle/normal_ring_smooth":()=>an(Ic(256,.55,.12),3.1),"particle/normal_pinch_rotate":()=>an(Xy(256),2.8),"particle/water/rain_drops_sheet_normal":()=>an(Bc(256,512,2,4),3.6),"particle/bubbles/bubble1normal":()=>an(bs(256,1),3.2),"particle/bubbles/bubble2_normal":()=>an(bs(256,2),3.2),"particle/sharp_halo_normal":()=>an(ys(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),3.4),"particle/beam/beam_0":()=>Sn(128,512,.46,!0),"particle/beam/beam_1":()=>Sn(128,512,.34,!0),"particle/beam/beam_2":()=>Sn(128,512,.22,!0),"particle/beam/beam_2_fade":()=>Sn(128,512,.24,!1),"particle/light/light_shafts_0":()=>Sn(128,512,.42,!0),"particle/light/light_shafts_1":()=>Sn(128,512,.3,!0),"particle/light/light_shafts_3":()=>Sn(128,512,.26,!0),"particle/light/light_shafts_5":()=>Sn(128,512,.23,!0),"particle/light/light_shafts_6":()=>Sn(128,512,.2,!0),"particle/nature/rosepetals":()=>Pd(256),"particle/nature/leaves":()=>vt(wt,0),"particle/nature/leaves1":()=>vt(wt,1),"particle/nature/leaves2":()=>vt(wt,2),"particle/nature/leaves3":()=>vt(wt,3),"particle/nature/leaves5":()=>vt(wt,5),"particle/nature/leaves6":()=>vt(wt,6),"particle/nature/leaves7":()=>vt(wt,7),"particle/nature/leaves8":()=>vt(wt,8),"particle/nature/snow":()=>Rd(256),"particle/halo":()=>$n(256,{r:.12,w:1},{r:.3,w:.15}),"particle/halo_1":()=>$n(256,{r:.1,w:1},{r:.3,w:.13}),"particle/halo_2":()=>$n(256,{r:.2,w:.9},{r:.44,w:.2}),"particle/halo_3":()=>ys(256,[{r:.045,w:1},{r:.13,w:.85},{r:.36,w:.15}]),"particle/halo_4":()=>$n(256,{r:.085,w:1},{r:.28,w:.12}),"particle/halo_5":()=>ys(256,[{r:.04,w:1},{r:.11,w:.8},{r:.34,w:.17}]),"particle/sharp_halo":()=>ys(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),"particle/chromaticdot":()=>Jy(128),"particle/light/flare_0":()=>gr(256,6,.58,10,.08),"particle/light/flare_1":()=>eb(512),"particle/light/flare_2":()=>Dd(256),"particle/drop":()=>Fc(128,512),"particle/nature/rain1":()=>Td(Ec,Cc,10,1,.78),"particle/nature/rain2":()=>Td(Ec,Cc,10,1.6,.66),"particle/water/rain_drops_sheet":()=>Bc(256,512,2,4),"particle/fog/fog1":()=>yr(512,4,5,1,.4,.9,150),"particle/fog/fog2":()=>yr(512,3,5,2,.45,.8,140),"particle/fog/fog3":()=>yr(512,6,4,3,.36,1,150),"particle/smoke/smoke1":()=>yr(512,3,5,7,.55,1.5,130),"particle/smoke/smoke2":()=>yr(512,2,5,11,.6,1.7,120),"particle/smoke/smoke2light":()=>yr(512,2,5,13,.4,1.7,110),"particle/misc/wave":()=>Ic(512,.72,.085),"particle/misc/star_0":()=>gr(256,5,.62,8,.1),"particle/bubbles/bubble1":()=>bs(256,1),"particle/bubbles/bubble2":()=>bs(256,2),"particle/bubbles/bubble3":()=>bs(256,3),"particle/debris/debris1":()=>Md(128),"particle/lightning/lightning1":()=>Ta(256,3),"particle/lightning/lightning2":()=>Ta(256,11),"particle/lightning/lightning3":()=>Ta(256,19),"particle/fire/fire1":()=>Mc(256,23),"particle/fire/fire2":()=>Mc(256,41),"particle/star":()=>gr(256,4,.58,12,.09),"particle/shape/circle_wind":()=>Ed(256),"particle/sickle":()=>Bd(256),"particle/magic/glyph_4":()=>Fd(256,4),"@sparkle":()=>gr(256,4,.6,16,.08),"@star":()=>gr(256,5,.62,8,.1),"@trail":()=>Rc(128,256)};function Nd(t){const e=String(t).toLowerCase();if(/normal/.test(e)){const n=Ky(t);return n?()=>an(Zy(n),2.8):()=>an(_d(128),2.6)}return/rosepetal|petal|sakura|blossom/.test(e)?()=>Pd(256):/leaf|leaves|foliage/.test(e)?/leaves8/.test(e)?()=>vt(wt,8):/leaves7/.test(e)?()=>vt(wt,7):/leaves6/.test(e)?()=>vt(wt,6):/leaves5/.test(e)?()=>vt(wt,5):/leaves3/.test(e)?()=>vt(wt,3):/leaves2/.test(e)?()=>vt(wt,2):/leaves1/.test(e)?()=>vt(wt,1):()=>vt(wt,0):/circle_wind|windcircle/.test(e)?()=>Ed(256):/fog|cloud|mist|vapor/.test(e)?()=>yr(512,4,5,5,.4,.9,150):/smoke/.test(e)?()=>yr(512,3,5,8,.55,1.5,130):/beam|shaft|ray|godray/.test(e)?()=>Sn(128,512,.3,!0):/flare/.test(e)?()=>Dd(256):/bubble/.test(e)?()=>Sd(256,1):/ring|wave/.test(e)?()=>Ic(512,.72,.085):/fire|flame|ember|ash/.test(e)?()=>Mc(256,Dc(e)):/sickle|crescent|moon/.test(e)?()=>Bd(256):/glyph|magic|rune/.test(e)?()=>Fd(256,Dc(e)):/snowflake|雪花|snow/.test(e)?()=>Rd(256):/流星|meteor|shooting/.test(e)?()=>Rc(128,256):/star|星/.test(e)?()=>gr(256,5,.62,8,.1):/sparkle|glint|twinkle/.test(e)?()=>gr(256,4,.6,16,.08):/rain_drops_sheet|drops_sheet/.test(e)?()=>Bc(256,512,2,4):/drop|rain/.test(e)?()=>Fc(128,512):/debris|dirt|rock/.test(e)?()=>Md(128):/lightning|bolt|arc/.test(e)?()=>Ta(256,Dc(e)):/note|music/.test(e)?()=>gr(256,4,.55,8,.12):/trail|streak/.test(e)?()=>Rc(128,256):()=>$n(256,{r:.12,w:1},{r:.3,w:.15})}function tb(t){if(ms.has(t))return ms.get(t);let e=null;const n=Pc.get(t);if(n)try{e=n()}catch{e=null}if(!e&&Aa)try{e=Aa(t)}catch{e=null}if(!e&&vs[t])try{e=vs[t]()}catch{e=null}if(!e)try{e=Nd(t)()}catch{e=null}return e||(e=$n(256,{r:.12,w:1},{r:.3,w:.15})),ms.set(t,e),e}function nb(t){return typeof t=="string"&&t.indexOf("particle/")===0}const rb=Object.freeze(Object.defineProperty({__proto__:null,buildBuiltinParticleTexture:tb,builtinParticleFrames:qy,isBuiltinParticleTextureName:nb,listBuiltinParticleTextureNames:jy,particleNormalNameForAlbedo:Yy,prepareParticleNormalTexture:$y,resetParticleTextureFactories:Wy,setParticleTextureFactory:Hy,setParticleTextureProvider:Vy},Symbol.toStringTag,{value:"Module"})),Ld=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function br(t,e,n){const r=n||new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)r[i*4+s]=t[s]*e[i*4]+t[4+s]*e[i*4+1]+t[8+s]*e[i*4+2]+t[12+s]*e[i*4+3];return r}function Ud(t){const e=[];for(let r=0;r<4;r++)e.push([t[r],t[4+r],t[8+r],t[12+r],0,0,0,0]),e[r][4+r]=1;for(let r=0;r<4;r++){let i=r;for(let o=r+1;o<4;o++)Math.abs(e[o][r])>Math.abs(e[i][r])&&(i=o);const s=e[r];e[r]=e[i],e[i]=s;const a=e[r][r];if(Math.abs(a)<1e-12)return Float32Array.from(Ld);for(let o=0;o<8;o++)e[r][o]/=a;for(let o=0;o<4;o++){if(o===r)continue;const c=e[o][r];if(c!==0)for(let u=0;u<8;u++)e[o][u]-=c*e[r][u]}}const n=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i][4+r];return n}function Nc(t,e,n,r,i,s,a,o,c,u){const l=u||new Float32Array(16),f=Math.cos(r),d=Math.sin(r),h=Math.cos(i),p=Math.sin(i),m=Math.cos(s),g=Math.sin(s);return l[0]=m*h*a,l[1]=g*h*a,l[2]=-p*a,l[3]=0,l[4]=(m*p*d-g*f)*o,l[5]=(g*p*d+m*f)*o,l[6]=h*d*o,l[7]=0,l[8]=(m*p*f+g*d)*c,l[9]=(g*p*f-m*d)*c,l[10]=h*f*c,l[11]=0,l[12]=t,l[13]=e,l[14]=n,l[15]=1,l}function wr(t,e){const n=[];for(;e<t.byteLength;){const i=t.getUint8(e++);if(i===0)break;n.push(i)}let r="";try{r=new TextDecoder("utf-8").decode(new Uint8Array(n))}catch{r=String.fromCharCode.apply(null,n)}return{value:r,next:e}}function Sa(t,e,n=0){const r=[];for(let i=0;i<e.length;i++)r.push(e.charCodeAt(i));e:for(let i=n;i<=t.length-r.length;i++){for(let s=0;s<r.length;s++)if(t[i+s]!==r[s])continue e;return i}return-1}function ib(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=String.fromCharCode.apply(null,Array.from(t.subarray(0,8)));if(!n.startsWith("MDLV"))throw new Error("\u4E0D\u662F MDL: "+n);const r=wr(e,21),s=parseInt(n.slice(4),10)>=23?[{lenOff:32,stride:80,uv:72,bone:40,weight:56},{lenOff:32,stride:84,uv:76,bone:44,weight:60,formatMarker:25231374},{lenOff:32,stride:48,uv:40,bone:-1,weight:-1}]:[{lenOff:8,stride:52,uv:44,bone:12,weight:28},{lenOff:4,stride:52,uv:44,bone:12,weight:28},{lenOff:32,stride:80,uv:72,bone:40,weight:56}];let a=null,o=0,c=0;for(const H of s){const G=r.next+H.lenOff;if(G+4>t.byteLength)continue;const Y=e.getUint32(G,!0);if((H.formatMarker===void 0||e.getUint32(r.next+28,!0)===H.formatMarker)&&Y>0&&Y%H.stride===0&&G+4+Y<=t.byteLength){a=H,o=Y,c=G;break}}if(!a)throw new Error("\u9876\u70B9\u533A\u957F\u5EA6\u5F02\u5E38\uFF08"+n+"\uFF0C\u5DF2\u8BD5 stride "+s.map(H=>H.stride).join("/")+"\uFF09");const u=c+4,l=o/a.stride,f=new Float32Array(l*3),d=new Float32Array(l*2),h=new Float32Array(l*4),p=new Float32Array(l*4);for(let H=0;H<l;H++){const G=u+H*a.stride;if(f[H*3]=e.getFloat32(G,!0),f[H*3+1]=e.getFloat32(G+4,!0),f[H*3+2]=e.getFloat32(G+8,!0),d[H*2]=e.getFloat32(G+a.uv,!0),d[H*2+1]=e.getFloat32(G+a.uv+4,!0),a.bone>=0&&a.weight>=0)for(let Y=0;Y<4;Y++)h[H*4+Y]=e.getUint32(G+a.bone+Y*4,!0),p[H*4+Y]=e.getFloat32(G+a.weight+Y*4,!0);else h[H*4]=0,p[H*4]=1}const m=e.getUint32(u+o,!0),g=u+o+4,w=l>65535&&m%4===0,y=w?m/4:m/2,b=w?new Uint32Array(y):new Uint16Array(y);if(w)for(let H=0;H<y;H++)b[H]=e.getUint32(g+H*4,!0);else for(let H=0;H<y;H++)b[H]=e.getUint16(g+H*2,!0);const v=ab(t,e),k=lb(t,e,v.length),A=fb(t,e,v),T=sb(t,e,v.length),S=[],P=[],M=[];if(v.length>0){const H=v.map((Y,J)=>{const ne=Y.matrix,fe=Math.hypot(ne[0],ne[1]),Ne=Math.hypot(ne[4],ne[5]);return M[J]=Float32Array.from([ne[12],ne[13],ne[14],0,0,Math.atan2(ne[1],ne[0]),fe||1,Ne||1,ne[10]||1]),Float32Array.from(ne)});for(let Y=0;Y<v.length;Y++){const J=M[Y],ne=v[Y].matrix;Math.hypot(J[0]-ne[12],J[1]-ne[13])>.001&&(H[Y]=Nc(J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],J[8],new Float32Array(16)))}const G=[];for(let Y=0;Y<v.length;Y++){const J=v[Y].parent;G[Y]=J>=0&&J<Y?br(G[J],H[Y]):Float32Array.from(H[Y])}for(let Y=0;Y<v.length;Y++)S[Y]=Float64Array.from(Ud(G[Y]));if(A){const Y=[];for(let J=0;J<v.length;J++){const ne=v[J].parent;Y[J]=ne>=0&&ne<J?br(Y[ne],A[J]):Float32Array.from(A[J])}for(let J=0;J<v.length;J++)P[J]=br(Y[J],S[J])}}let B=1/0,N=-1/0,O=1/0,q=-1/0;for(let H=0;H<l;H++){const G=f[H*3],Y=f[H*3+1];G<B&&(B=G),G>N&&(N=G),Y<O&&(O=Y),Y>q&&(q=Y)}return{magic:n,materialPath:r.value,vertexCount:l,positions:f,uvs:d,boneIdx:h,weights:p,indexCount:y,indexType:w?"u32":"u16",indices:b,bones:v,animations:k,animBound:ub(k,v),invBindWorld:S,bindTRS:M.length>0?M:null,attachments:T.length>0?T:null,restCorrection:P.length>0?P:null,bounds:{minX:B,maxX:N,minY:O,maxY:q}}}function sb(t,e,n){const r=Sa(t,"MDAT");if(r<0)return[];const i=e.getUint16(r+13,!0);if(i<=0||i>256)return[];const s=[];let a=r+15;for(let o=0;o<i&&!(a+2>t.length);o++){const c=e.getUint16(a,!0),u=wr(e,a+2);if(u.next+64>t.length)break;const l=new Float32Array(16);for(let f=0;f<16;f++)l[f]=e.getFloat32(u.next+f*4,!0);c<n&&s.push({bone:c,name:u.value,matrix:l}),a=u.next+64}return s}function ab(t,e){const n=Sa(t,"MDLS");if(n<0)return[];const r=e.getUint32(n+13,!0);if(r<=0||r>1024)return[];const i=[];let s=n+17;for(let a=0;a<r;a++){if(s+77>e.byteLength)return i;const o=e.getUint32(s+1,!0),c=e.getInt32(s+5,!0),u=new Float32Array(16);for(let f=0;f<16;f++)u[f]=e.getFloat32(s+13+f*4,!0);const l=wr(e,s+13+64);i.push({id:o,parent:c>=0&&c<r?c:-1,matrix:u}),s=l.next}return i}function ob(t,e,n){const r=Math.min(t.byteLength-24,n);for(let i=e;i<r;i++){if(t.getUint32(i+4,!0)!==0)continue;const s=wr(t,i+8);if(!s.value||s.value.length>64)continue;const a=wr(t,s.next);if(!a.value||a.value.length>16)continue;const o=t.getFloat32(a.next,!0);if(!(o>0&&o<=240))continue;const c=t.getUint32(a.next+4,!0);if(c<=0||c>1e5)continue;const u=t.getUint32(a.next+12,!0);if(!(u<=0||u>1024))return i}return-1}function cb(t,e,n){const r=[],i=Math.min(t.byteLength,n,e+64);let s=e,a=0;for(;s<i&&t.getUint8(s)!==123&&a++<64;)s++;if(s>=i||t.getUint8(s)!==123)return{events:r,next:e};const o=Math.min(t.byteLength,n,e+8192);for(let c=0;c<64&&s<o&&t.getUint8(s)===123;c++){const u=wr(t,s);let l=null;try{l=JSON.parse(u.value)}catch{l=null}if(!l||typeof l!="object"||!Number.isFinite(Number(l.frame))||typeof l.name!="string")break;r.push({frame:Number(l.frame),name:l.name}),s=u.next;let f=s,d=0;for(;f<o&&t.getUint8(f)!==123&&d<8;)f++,d++;if(d<8&&f<o&&t.getUint8(f)===123){s=f;continue}break}return{events:r,next:s}}function lb(t,e,n){const r=Sa(t,"MDLA");if(r<0)return[];let i=r+9;const s=e.getUint32(i,!0);i+=4;const a=e.getUint32(i,!0);if(i+=4,a<=0||a>256)return[];const o=[];for(let c=0;c<a&&!(i+16>e.byteLength);c++){const u=e.getUint32(i,!0);i+=8;const l=wr(e,i);i=l.next;const f=wr(e,i);if(i=f.next,i+16>e.byteLength)break;const d=e.getFloat32(i,!0);i+=4;const h=e.getUint32(i,!0);i+=8;const p=e.getUint32(i,!0);if(i+=4,p>1024)break;const m=[];for(let b=0;b<p&&!(i+8>e.byteLength);b++){i+=4;const v=e.getUint32(i,!0);i+=4;const k=Math.floor(v/36);if(i+v>e.byteLength)break;const A=new Float32Array(k*9);for(let T=0;T<k;T++){const S=i+T*36;for(let P=0;P<9;P++)A[T*9+P]=e.getFloat32(S+P*4,!0)}i+=v,m.push({frameCount:k,keyframes:A})}const g=s>0&&s<=e.byteLength?s:e.byteLength,w=cb(e,i,g);m.length>0&&h>0&&d>0&&o.push({id:u,name:l.value,mode:f.value,fps:d,frameCount:h,duration:h/d,tracks:m,events:w.events});const y=ob(e,w.next,g);if(y<0)break;i=y}return o}function ub(t,e){let n=0,r=0;for(const i of t)for(let s=0;s<i.tracks.length;s++){const a=i.tracks[s];if(!a)continue;const o=e[s],c=o?o.matrix[12]:0,u=o?o.matrix[13]:0,l=a.keyframes;for(let f=0;f<a.frameCount;f++){const d=Math.abs(l[f*9]-c),h=Math.abs(l[f*9+1]-u);d>n&&(n=d),h>r&&(r=h)}}return{x:n,y:r}}function fb(t,e,n){if(n.length===0)return null;const r=Sa(t,"MDLE");if(r<0)return null;const i=r+8+1+4+4;if(i+n.length*64>e.byteLength)return null;const s=[];for(let a=0;a<n.length;a++){const o=new Float32Array(16);for(let c=0;c<16;c++)o[c]=e.getFloat32(i+a*64+c*4,!0);s.push(o)}return s}function db(t,e,n,r){const i=t.frameCount;if(i===0)return r[0]=0,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=0,r[6]=1,r[7]=1,r[8]=1,r;const s=n*e.fps;let a,o,c;if(e.mode==="loop"){const h=Math.max(1,i-1),p=(s%h+h)%h;a=Math.floor(p),o=(a+1)%i,c=p-a}else if(e.mode==="mirror"){const h=Math.max(1,i-1),p=h*2;let m=(s%p+p)%p;m>h&&(m=p-m),a=Math.floor(m),o=Math.min(a+1,i-1),c=m-a}else{const h=Math.min(Math.max(s,0),i-1);a=Math.floor(h),o=Math.min(a+1,i-1),c=h-a}const u=t.keyframes,l=a*9,f=o*9,d=1-c;for(let h=0;h<9;h++)if(h>=3&&h<=5){let p=u[f+h]-u[l+h];p>Math.PI?p-=2*Math.PI:p<-Math.PI&&(p+=2*Math.PI),r[h]=u[l+h]+p*c}else r[h]=u[l+h]*d+u[f+h]*c;return r}function hb(t,e,n){const r=t.bindTRS&&t.bindTRS[e];if(r)return n.set(r),n;const i=t.bones[e].matrix;return n[0]=i[12],n[1]=i[13],n[2]=i[14],n[3]=0,n[4]=0,n[5]=Math.atan2(i[1],i[0]),n[6]=Math.hypot(i[0],i[1])||1,n[7]=Math.hypot(i[4],i[5])||1,n[8]=i[10]||1,n}function Lc(t,e,n,r){const i=t.bones,s=i.length;if(s===0)return null;const a=!!(r&&r.size>0);if(!t._skin||t._skin.length!==s*16){t._skin=new Float32Array(s*16),t._local=[],t._world=[],t._tmp=new Float32Array(16),t._tmp2=new Float32Array(16);for(let d=0;d<s;d++)t._local.push(new Float32Array(16)),t._world.push(new Float32Array(16))}const o=Array.isArray(n)&&n.length>0,c=[];if(o)for(const d of n){if(d.visible===!1||d.visible===0)continue;const h=t.animations.find(p=>p.id===d.animation);h&&c.push({anim:h,additive:!!d.additive,blend:typeof d.blend=="number"?d.blend:1,rate:typeof d.rate=="number"?d.rate:1})}if(c.length===0&&!o){const d=t.animations[0];if(d)c.push({anim:d,additive:!1,blend:1,rate:1});else if(!a)return null}const u=t._trsBase||(t._trsBase=new Float32Array(9)),l=t._trsAcc||(t._trsAcc=new Float32Array(9)),f=t._trsSmp||(t._trsSmp=new Float32Array(9));for(let d=0;d<s;d++){hb(t,d,u),l.set(u);let h=!1,p=0,m=!1,g=!1;const w=t._addDelta||(t._addDelta=new Float32Array(9));w.fill(0);for(const b of c){const v=b.anim.tracks[d];if(!v||!v.keyframes.length)continue;db(v,b.anim,e*b.rate,f);const k=b.blend;if(b.additive){const A=v.keyframes;if(!m&&!g){for(let T=0;T<9;T++)l[T]=A[T];g=!0}for(let T=0;T<9;T++){let S=f[T]-A[T];T>=3&&T<=5&&(S>Math.PI?S-=2*Math.PI:S<-Math.PI&&(S+=2*Math.PI)),w[T]+=S*k}p+=k}else{m=!0;for(let A=0;A<9;A++)l[A]=l[A]*(1-k)+f[A]*k}h=!0}if(p>1)for(let b=0;b<9;b++)w[b]/=p;if(p>0)for(let b=0;b<9;b++)l[b]+=w[b];const y=a?r.get(d):void 0;y&&(l[0]=y[0],l[1]=y[1],l[2]=y[2],h=!0),h?Nc(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],t._local[d]):Nc(u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8],t._local[d])}for(let d=0;d<s;d++){const h=i[d].parent;h>=0&&h<d?br(t._world[h],t._local[d],t._world[d]):t._world[d].set(t._local[d])}for(let d=0;d<s;d++)br(t._world[d],t.invBindWorld[d],t._tmp),t._skin.set(t._tmp,d*16);return t._skin}function Od(t,e){return!t||!t.invBindWorld||!(e>=0&&e<t.invBindWorld.length)?null:Ud(t.invBindWorld[e])}function mb(t,e){return br(t,e)}function zd(t,e){if(!t||!t.attachments||typeof e!="string"||e===""||!t._world)return null;for(const n of t.attachments)if(n.name===e)return n.bone<0||n.bone>=t._world.length?null:br(t._world[n.bone],n.matrix);return null}function Hd(t,e){if(!t||!t.attachments||typeof e!="string"||e==="")return null;for(const n of t.attachments){if(n.name!==e)continue;const r=Od(t,n.bone);return r?br(r,n.matrix):null}return null}function Uc(t,e,n){const r=t&&t.angles&&t.angles[2]||0,i=t&&t.scale?t.scale[0]:1,s=t&&t.scale?t.scale[1]:1,a=r*Math.PI/180,o=Math.cos(a),c=Math.sin(a),u=e*i,l=n*s;return[u*o-l*c,u*c+l*o]}function pb(t){const e=new Map,n=new Map;for(const s of t){if(!s||s.id===void 0||s.id===null||(e.set(s.id,s),s.parentId===void 0||s.parentId===null))continue;const a=n.get(s.parentId);a?a.push(s):n.set(s.parentId,[s])}const r=(s,a)=>{const o=n.get(s.id);if(o)for(const c of o)a.push(c),r(c,a)},i=[];for(const s of t){const a=s&&s.attachment;if(typeof a!="string"||a==="")continue;const o=e.get(s.parentId);if(!o||!o.puppet)continue;const c=Hd(o.puppet,a);if(!c)continue;const u=c[12],l=c[13],f=Uc(o,u,l),d=[];r(s,d),s.origin[0]+=f[0],s.origin[1]+=f[1];for(const h of d)h.origin[0]+=f[0],h.origin[1]+=f[1];s.parallaxDepth=o.parallaxDepth?o.parallaxDepth.slice():null;for(const h of d)h.parallaxDepth=s.parallaxDepth?s.parallaxDepth.slice():null;s.attachBindDelta=[f[0],f[1]],i.push({layer:s,parent:o,name:a,bindX:u,bindY:l,desc:d})}for(const s of i){s.baseX=s.layer.origin[0],s.baseY=s.layer.origin[1],s.subtree=[{layer:s.layer,x:s.layer.origin[0],y:s.layer.origin[1]}];for(const a of s.desc)s.subtree.push({layer:a,x:a.origin[0],y:a.origin[1]});for(const a of s.subtree)a.layer.attachBase||(a.layer.attachBase=[a.x,a.y])}return i}function gb(t,e,n){if(!t||t.length===0)return;const r=new Set,i=[];for(const o of t){const c=o.parent&&o.parent.puppet;if(!c){i.push(null);continue}if(!r.has(c)){r.add(c);const l=typeof n=="function"?n(o.parent):null;Lc(c,e,o.parent.animationLayers,l)}const u=zd(c,o.name);if(!u){i.push(null);continue}i.push(Uc(o.parent,u[12]-o.bindX,u[13]-o.bindY))}const s=o=>{const c=o.layer.attachBase;return c||[o.x,o.y]},a=new Set;for(const o of t){const c=o.subtree||[{layer:o.layer,x:o.baseX,y:o.baseY}];for(const u of c){if(a.has(u.layer))continue;a.add(u.layer);const l=s(u);u.layer.origin[0]=l[0],u.layer.origin[1]=l[1]}}for(let o=0;o<t.length;o++){const c=t[o],u=i[o],l=c.subtree||[{layer:c.layer,x:c.baseX,y:c.baseY}];if(u)for(const f of l)f.layer.origin[0]+=u[0],f.layer.origin[1]+=u[1]}}const yb=128,Pa=24;function bb(t){const e=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS)||256,n=Math.floor((e-32)/4);return Math.max(Pa,Math.min(yb,n))}const wb=t=>`#version 300 es
531
+ }`,r=(u,l)=>{const d=t.createShader(u);if(t.shaderSource(d,l),t.compileShader(d),!t.getShaderParameter(d,t.COMPILE_STATUS))throw new Error("\u7C92\u5B50 shader: "+t.getShaderInfoLog(d));return d},i=t.createProgram();if(t.attachShader(i,r(t.VERTEX_SHADER,e)),t.attachShader(i,r(t.FRAGMENT_SHADER,n)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS))throw new Error("\u7C92\u5B50 shader \u94FE\u63A5\u5931\u8D25: "+t.getProgramInfoLog(i));const s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-.5,-.5,.5,-.5,-.5,.5,.5,.5]),t.STATIC_DRAW);const a=t.createBuffer(),o=t.createVertexArray();t.bindVertexArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,2,t.FLOAT,!1,8,0),t.vertexAttribDivisor(0,0),t.bindBuffer(t.ARRAY_BUFFER,a);const c=72;return t.enableVertexAttribArray(1),t.vertexAttribPointer(1,3,t.FLOAT,!1,c,0),t.vertexAttribDivisor(1,1),t.enableVertexAttribArray(2),t.vertexAttribPointer(2,2,t.FLOAT,!1,c,12),t.vertexAttribDivisor(2,1),t.enableVertexAttribArray(3),t.vertexAttribPointer(3,4,t.FLOAT,!1,c,20),t.vertexAttribDivisor(3,1),t.enableVertexAttribArray(4),t.vertexAttribPointer(4,3,t.FLOAT,!1,c,36),t.vertexAttribDivisor(4,1),t.enableVertexAttribArray(5),t.vertexAttribPointer(5,2,t.FLOAT,!1,c,48),t.vertexAttribDivisor(5,1),t.enableVertexAttribArray(6),t.vertexAttribPointer(6,4,t.FLOAT,!1,c,56),t.vertexAttribDivisor(6,1),t.bindVertexArray(null),{prog:{prog:i,uniTex:t.getUniformLocation(i,"u_tex"),uniNormal:t.getUniformLocation(i,"u_normal"),uniScene:t.getUniformLocation(i,"u_scene"),uniRefract:t.getUniformLocation(i,"u_refract"),uniSampleScene:t.getUniformLocation(i,"u_sampleScene"),uniNormalPacked:t.getUniformLocation(i,"u_normalPacked"),uniAlbedoR8:t.getUniformLocation(i,"u_albedoR8"),uniResolution:t.getUniformLocation(i,"u_resolution"),uniRefractScale:t.getUniformLocation(i,"u_refractScale"),uniMvp:t.getUniformLocation(i,"u_mvp"),uniFrameCount:t.getUniformLocation(i,"u_frameCount"),uniFrames:t.getUniformLocation(i,"u_frames")},quadBuf:s,vbuf:a,vao:o}}function sw(t){let e=t>>>0;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function aw(t,e,n){const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)}function bo(t,e){const n=Math.floor(t),r=t-n,i=a=>{const o=Math.sin((a*127.1+e*311.7)*43758.5453)*43758.5453;return(o-Math.floor(o))*2-1},s=r*r*(3-2*r);return i(n)*(1-s)+i(n+1)*s}const ow=32,cw=112,em=60/cw,tm=3.2;function lw(t){const e=new Float32Array(16),n=new Float32Array(16),r=new Float32Array(16);for(let i=0;i<16;i++)e[i]=i%4===0?1:i%4===2?.38+t()*.15:t()<.08?.5:0,n[i]=i%8===4?1:t()<.06?.6:0,r[i]=i%2===1?.5+t()*.4:i%4===0?.25:t()<.3?.3:0;return{kick:e,snare:n,hat:r}}function nm(t=20260830){const e=sw(t),n=lw(e),r=new Float32Array(64);for(let w=0;w<64;w++)r[w]=e()*64;const i=64,s=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),c=new Float32Array(i),u=new Float32Array(i),l=new Float32Array(i),d=new Float32Array(32),f=new Float32Array(32),h=new Float32Array(16),p=new Float32Array(16),m={left64:u,right64:l,left32:d,right32:f,left16:h,right16:p,preL64:o,preR64:c,level:0,silent:!1};function g(w,A){const b=A.length/w.length;for(let v=0;v<w.length;v++){let x=0;const P=Math.floor(v*b),S=Math.floor((v+1)*b);for(let k=P;k<Math.max(P+1,S);k++)x+=A[k];w[v]=x/Math.max(1,S-P)}}function y(w){const A=w/em,b=A*4,v=(Math.floor(b)%16+16)%16,x=b-Math.floor(b),P=Math.exp(-x*em*14),S=w%ow,k=S>=27&&S<29,_=S>=29?(S-29)/3:0,I=S>=24&&S<27?1-(S-24)/3:0,B=k?0:_>0?_*_:I>0?0:1,V=k?0:I>0?.35:1,O=n.kick[v]*P*B,U=(n.snare[v]*P+n.hat[v]*P*.7)*B,W=n.hat[v]*P*B,ie=_>0?Math.pow(_,3)*(.4+.6*Math.abs(bo(b*2,7))):0;let we=0;for(let Y=0;Y<i;Y++){const oe=Y/i,he=Math.pow(1-oe*.85,1.6),Ae=V*(.5+.3*bo(A*.5+r[Y]*.05,Y%8)),Pe=V*(.5+.3*bo(A*.53+r[Y]*.05+31.7,Y%8+16));let Ce=Ae*(.35+.65*oe),Le=Pe*(.35+.65*oe);if(oe<.2){const nt=O*(1-oe/.2);Ce+=nt,Le+=nt}if(oe>=.12&&oe<.62){const nt=1-Math.abs(oe-.34)/.28;nt>0&&(Ce+=U*.55*nt,Le+=U*.35*nt)}if(oe>=.45){const nt=(oe-.45)/.55;Le+=W*.5*nt,Ce+=W*.3*nt}Ce+=ie*.5,Le+=ie*.5,Ce*=he,Le*=he;const Ne=Ce,De=Le;Ce=Math.min(1,Ce*tm),Le=Math.min(1,Le*tm);const Re=.06+oe*.2,Fe=bo(A*.13+Y*.35,11)*Re;let Xe=Math.min(1,Math.max(0,Ce*(1-Fe))),$e=Math.min(1,Math.max(0,Le*(1+Fe)));const Ye=k?.012:0;s[Y]=Math.max(Ye,Xe),a[Y]=Math.max(Ye,$e),o[Y]=Math.max(Ye,Math.max(0,Ne*(1-Fe))),c[Y]=Math.max(Ye,Math.max(0,De*(1+Fe))),Y<48&&(we+=(s[Y]+a[Y])*.5)}return u.set(s),l.set(a),g(d,s),g(f,a),g(h,s),g(p,a),m.level=Math.min(1,we/(48*1.2)),m.silent=k,m}return{update:y,snapshot:m,bands:i}}function rm(t,e){for(const n of t.values()){im(n.left,e.left64),im(n.right,e.right64);for(let r=0;r<n.average.length;r++)n.average[r]=(n.left[r]+n.right[r])*.5}}function im(t,e){const n=e.length/t.length;for(let r=0;r<t.length;r++){let i=0;const s=Math.floor(r*n),a=Math.max(s+1,Math.floor((r+1)*n));for(let o=s;o<a;o++)i+=e[o];t[r]=i/(a-s)}}function uw(t,e,n,r,i,s,a){if(!e)return 0;const o=t.left.length-1,c=Math.max(0,Math.min(o,Math.round(n))),u=Math.max(c,Math.min(o,Math.round(r)));let l=0,d=0;for(let h=c;h<=u;h++)e===1?l+=t.left[h]:e===2?l+=t.right[h]:l+=(t.left[h]+t.right[h])*.5,d++;let f=d>0?l/d:0;return f=aw(i[0],i[1],f),f=Math.min(1,Math.max(0,Math.pow(f,s)))*a,f}let ps=1;function fw(t){const e=Number(t);ps=Number.isFinite(e)&&e>=0?e:1}function dw(){return ps}const sm={low:3e3,medium:6e3,high:12e3},hw={low:3,medium:5,high:8};let wo="high";function mw(t){wo=sm[t]?t:"high"}function pw(){return wo}const Dl=2048,gw=256,yw=64;let Nl=null;function bw(t){Nl=typeof t=="function"?t:null}let Ll=null;function ww(t){Ll=typeof t=="function"?t:null}function am(t){const e=Nl?Nl():null;t.bindFramebuffer(t.FRAMEBUFFER,e||null)}function om(t){const e=t&&t.passes&&t.passes[0]&&t.passes[0].combos;return!!(e&&Number(e.REFRACT)===1)}function vw(t){if(!t||t.length<16)return!1;const e=t.length/4,n=Math.max(1,e/64|0);let r=0;for(let i=0;i<e;i+=n){const s=i*4;if(t[s]<250||t[s+1]<250||t[s+2]<250||t[s+3]<250)return!1;r++}return r>0}function cm(t,e,n,r){let i=Math.abs(Number(t)||0)*(Number(e)||0);const s=Number(r)||0;return s>0&&(i=Math.min(s,i)),i}function lm(t,e){return t||e?Math.atan2(e,t)-Math.PI/2:0}function um(t,e){return t&&t.kind==="ropetrail"?Math.max(1,e||1):1}function fm(t){if(!t||t.kind!=="ropetrail")return 1;const e=Math.round(Number(t.segments)||0);return e>=2?Math.min(32,e):8}function dm(t){if(!t||t.kind!=="ropetrail")return 0;const e=Number(t.length);return Number.isFinite(e)&&e>0?e:.2}function Ul(t){return t.life>0?t.age/t.life:0}class Aw{constructor(){this.alive=!1,this.x=this.y=this.z=0,this.vx=this.vy=this.vz=0,this.bx=this.by=this.bz=0,this.age=0,this.life=1,this.size=1,this.baseSize=1,this.rot=0,this.rotVel=0,this.rotX=0,this.rotY=0,this.rotVelX=0,this.rotVelY=0,this.r=this.g=this.b=1,this.baseR=this.baseG=this.baseB=1,this.alpha=1,this.baseAlpha=1,this.seed=0,this.frame=0,this.oscPFreq=[0,0,0],this.oscPAmp=[0,0,0],this.oscPPhase=[0,0,0],this.oscAPhase=0,this.oscAFreq=0,this.oscAAmp=[0,0],this.oscSPhase=0,this.oscSFreq=0,this.oscSAmp=[0,0],this.turbSpeed=0,this.turbPhase=0,this.trail=null,this.trailClock=0,this.seq=0}}class xw{constructor(e,n,r,i){this.gl=e,this.model=n||{},this.override=r||{},this.layer=i||null,this.syncLayerTransform(),this.maxCount=Math.max(1,Math.min(2e4,Te(this.model.maxcount,100)*ps)),this.simTime=0,this.paused=!1,this.texture=null,this.normalTex=null,this.material=null,this.blend="translucent",this.refract=!1,this.refractAmount=.05,this.normalPacked=!1,this.opacityMul=1,this.lifetimeMul=1,this.visible=!0,this._ready=!1,this._prog=null,this._vbuf=null,this._quadBuf=null,this._vao=null,this._data=null,this._sceneTex=null,this.frameBlend=(Te(n.flags,0)&2)===0,this.worldSpace=(Te(n.flags,0)&1)!==0,this.sequenceMul=Math.max(1,Math.round(Te(this.model.sequencemultiplier,1))),this.animationMode=this.model.animationmode||null,this.texFrames=null,this.frameCount=this.sequenceMul*this.sequenceMul,this.texAspectX=1,this.texAspectY=1,this.controlPoints=(this.model.controlpoint||[]).filter(Boolean).map(s=>({id:Te(s.id,0),lockToPointer:!!s.locktopointer||(Te(s.flags,0)&1)!==0,offset:ht(s.offset),x:0,y:0,z:0})),this.pointer=null,this._followParent=null,this._followMode=null,this._followOffset=[0,0,0],this._eventParent=null,this._eventType=null,this._eventOffset=null,this._eventChildren=[],this._burstQueue=[],this._bound=[],this._aliveCount=0,this._poolGen=0,this.ropeRenderer=null,this._seq=0,this._ropeOrder=[],this._ov={},this.timeScale=1,this._applyOverride(),this.startTime=Math.max(0,Math.min(30,Te(this.model.starttime,0))),this._warmed=!1,this._compile()}reapplyOverride(){this._applyOverride()}setColorOverride(e){const n=Array.isArray(e)?e:[e?.x||0,e?.y||0,e?.z||0];this._ov.color=[Number(n[0])||0,Number(n[1])||0,Number(n[2])||0]}setOverrideValue(e,n){const r=Number(n);Number.isFinite(r)&&(e==="alpha"?this.opacityMul=r:e==="count"?this._ov.countMul=r:e==="size"?this._ov.size=r:e==="rate"?this.timeScale=r:e==="speed"?this._ov.speed=r:e==="lifetime"?this.lifetimeMul=r:e==="brightness"?this._ov.brightness=r:this._ov[e]=r)}_applyOverride(){this._ov={},this.opacityMul=1,this.lifetimeMul=1,this.maxCount=Math.max(1,Math.min(2e4,Te(this.model.maxcount,100)*ps));const e=this.override||{};for(const n of Object.keys(e)){if(n==="id")continue;const r=e[n],i=r&&typeof r=="object"&&"value"in r?r.value:r;if(n==="count"){const s=Te(this.model.maxcount,100),a=Number(i),o=Number.isFinite(a)?a:1,c=sm[wo];this.maxCount=Math.max(1,Math.min(c,Math.round(s*o*ps)));const u=hw[wo],l=o<=1?o:Math.min(o,u);this._ov.countMul=l*ps,this._ov.countRaw=o}else if(n==="alpha")this.opacityMul=Number(i),Number.isFinite(this.opacityMul)||(this.opacityMul=1);else if(n==="color"||n==="colorn"){const s=ht(i);this._ov.color=n==="colorn"?s:[s[0]/255,s[1]/255,s[2]/255]}else n==="size"?this._ov.size=Number(i)||1:n==="rate"?(this.timeScale=Number(i),Number.isFinite(this.timeScale)||(this.timeScale=1)):n==="speed"?this._ov.speed=Number(i)||1:n==="lifetime"?this.lifetimeMul=Number(i)||1:n==="brightness"?this._ov.brightness=Number(i)||1:this._ov[n]=i}this.pool=[];for(let n=0;n<this.maxCount;n++)this.pool.push(new Aw);this._aliveCount=0,this._poolGen=(this._poolGen||0)+1,this.allocTrails()}_compile(){const e=this.model;this.emitters=(e.emitter||[]).map(c=>({kind:c.name==="boxrandom"?"box":"sphere",origin:ht(c.origin),directions:ht(c.directions,[1,1,1]),distanceMin:Jh(c.distancemin),distanceMax:Jh(c.distancemax),sign:c.sign?ht(c.sign):null,rate:Te(c.rate,0),audioDriven:c.audioprocessingmode!==void 0,audioBounds:ht(c.audioprocessingbounds,[.8,1]),audioMode:Te(c.audioprocessingmode,0),audioExponent:Te(c.audioprocessingexponent,2),audioFreqStart:Te(c.audioprocessingfrequencystart,0),audioFreqEnd:Te(c.audioprocessingfrequencyend,1),fill:c.rate===void 0&&c.instantaneous===void 0&&c.audioprocessingmode===void 0,instantaneous:Te(c.instantaneous,0),speedMin:Te(c.speedmin,0),speedMax:Te(c.speedmax,0),controlPoint:c.controlpoint!==void 0&&c.controlpoint!==null?Te(c.controlpoint,0):0,_burst:!1}));const n=e.initializer||[];this.init={life:null,size:null,color:null,alpha:null,velocity:null,rotation:null,angularVelocity:null,turbulentVelocity:null,mapAround:null};for(const c of n)switch(c.name){case"lifetimerandom":this.init.life={min:Te(c.min,1),max:Te(c.max,1),exp:Te(c.exponent,1)};break;case"sizerandom":this.init.size={min:Te(c.min,1),max:Te(c.max,1),exp:Te(c.exponent,1)};break;case"colorrandom":this.init.color={min:Sr(c.min)||[0,0,0],max:Sr(c.max)||[255,255,255]};break;case"alpharandom":this.init.alpha={min:Te(c.min,1),max:Te(c.max,1)};break;case"velocityrandom":this.init.velocity={min:Sr(c.min)||[-32,-32,0],max:Sr(c.max)||[32,32,0]};break;case"rotationrandom":this.init.rotation={min:Sr(c.min)||[0,0,0],max:Sr(c.max)||[0,0,Gr],exp:Te(c.exponent,1)};break;case"angularvelocityrandom":this.init.angularVelocity={min:Sr(c.min)||[0,0,-5],max:Sr(c.max)||[0,0,5],exp:Te(c.exponent,1)};break;case"mapsequencearoundcontrolpoint":this.init.mapAround={count:Math.max(1,Te(c.count,1)),bounds:ht(c.bounds,[0,1]),speedMin:ht(c.speedmin),speedMax:ht(c.speedmax,[0,0,0]),cp:Te(c.controlpoint,0)},this._mapAroundSeq=0;break;case"turbulentvelocityrandom":this.init.turbulentVelocity={scale:Te(c.scale,.1),offset:Te(c.offset,0),speedMin:Te(c.speedmin,0),speedMax:Te(c.speedmax,0),phaseMax:Te(c.phasemax,0),timeScale:Te(c.timescale,0),audioMode:Te(c.audioprocessingmode,0),audioBounds:ht(c.audioprocessingbounds,[0,1])};break}const r=e.operator||[];this.ops={movement:null,angularMovement:null,alphaFade:null,alphaChange:null,sizeChange:null,colorChange:null,turbulence:[],oscAlpha:null,oscSize:null,oscPos:null,attract:[],vortex:[],remap:[]};for(const c of r)switch(c.name){case"movement":this.ops.movement={gravity:ht(c.gravity),drag:Te(c.drag,0)};break;case"angularmovement":this.ops.angularMovement={force:ht(c.force),drag:Te(c.drag,0)};break;case"alphafade":this.ops.alphaFade={fadeIn:Te(c.fadeintime,.1),fadeOut:Te(c.fadeouttime,.9)};break;case"alphachange":this.ops.alphaChange={startTime:Te(c.starttime,0),endTime:Te(c.endtime,1),startValue:Te(c.startvalue,1),endValue:Te(c.endvalue,0)};break;case"sizechange":this.ops.sizeChange={startTime:Te(c.starttime,0),endTime:Te(c.endtime,1),startValue:Te(c.startvalue,1),endValue:Te(c.endvalue,1)};break;case"colorchange":this.ops.colorChange={startTime:Te(c.starttime,0),endTime:Te(c.endtime,1),startValue:c.startvalue!==void 0?ht(c.startvalue):null,endValue:ht(c.endvalue,[1,1,1])};break;case"turbulence":this.ops.turbulence.push({scale:Te(c.scale,.01),speedMin:Te(c.speedmin,0),speedMax:Te(c.speedmax,0),timeScale:Te(c.timescale,1),phaseMin:Te(c.phasemin,0),phaseMax:Te(c.phasemax,0),mask:c.mask!==void 0?ht(c.mask,[1,1,1]):[1,1,1]});break;case"oscillatealpha":case"oscillatesize":case"oscillateposition":{const u=c.name,l=u==="oscillateposition",d=Te(c.frequencymin,0);let f=c.frequencymax===void 0?l?5:10:Te(c.frequencymax);f===0&&(f=d);const h={freqMin:d,freqMax:f,scaleMin:Te(c.scalemin,u==="oscillatesize"?.8:0),scaleMax:Te(c.scalemax,u==="oscillatesize"?1.2:1),phaseMin:Te(c.phasemin,0),phaseMax:Te(c.phasemax,Gr)};u==="oscillatealpha"?this.ops.oscAlpha=h:u==="oscillatesize"?this.ops.oscSize=h:this.ops.oscPos={...h,mask:c.mask!==void 0?ht(c.mask,[1,1,0]):[1,1,0]};break}case"controlpointattract":this.ops.attract.push({cp:Te(c.controlpoint,0),origin:ht(c.origin),scale:Te(c.scale,0),threshold:Te(c.threshold,0)});break;case"vortex":this.ops.vortex.push({axis:ht(c.axis,[0,0,1]),offset:ht(c.offset),distanceInner:Te(c.distanceinner,0),distanceOuter:Te(c.distanceouter,0),speedInner:Te(c.speedinner,0),speedOuter:Te(c.speedouter,0),cp:c.controlpoint!==void 0&&c.controlpoint!==null?Te(c.controlpoint,0):0,audioMode:Te(c.audioprocessingmode,0),audioBounds:ht(c.audioprocessingbounds,[0,1])});break;case"remapvalue":this.ops.remap.push({output:c.output||"velocity",rangeMin:ht(c.outputrangemin),rangeMax:ht(c.outputrangemax),fn:c.transformfunction||"simplexnoise",inputScale:Te(c.transforminputscale,1)});break}const i=this.model.renderer,s=i==null,a=Array.isArray(i)?i:i?[i]:[];this.renderers=a.map(c=>{const u=c&&c.name||"sprite";return{kind:u,length:Te(c&&c.length,u==="spritetrail"?.1:u==="ropetrail"?.2:0),maxLength:Te(c&&c.maxlength,u==="ropetrail"?10:0),minLength:Te(c&&c.minlength,0),subdivision:Te(c&&c.subdivision,1),segments:Te(c&&c.segments,0),orientation:c&&c.orientation||null}}),s&&!this.renderers.length&&(this.renderers=[{kind:"sprite",length:0,maxLength:0,minLength:0,subdivision:1,segments:0,orientation:null}]);const o=this.renderers.find(c=>c.kind==="spritetrail"||c.kind==="ropetrail");if(this.trailCfg=o||null,this.trailSegments=1,this.trailDuration=0,this.trailSampleDt=0,o&&o.kind==="ropetrail"){const c=fm(o);this.trailSegments=c,this.trailDuration=dm(o),this.trailSampleDt=this.trailDuration/Math.max(1,c-1)}this.allocTrails(),this.ropeRenderer=this.renderers.find(c=>c.kind==="rope")||null}allocTrails(){const e=this.trailCfg;if(!e||e.kind!=="ropetrail")return;const n=Math.max(1,this.trailSegments||1);for(const r of this.pool)(!r.trail||r.trail.length!==n*3)&&(r.trail=new Float32Array(n*3)),r.trailClock=0}setModel(e){this.model=e,this._compile()}setMaterial(e){this.material=e;const n=e&&e.passes&&e.passes[0];this.blend=n&&n.blending||"translucent",this.refract=om(e);const r=n&&n.constantshadervalues,i=r&&r.ui_editor_properties_refract_amount,s=Number(i);this.refractAmount=Number.isFinite(s)?Math.min(1,Math.max(-1,s)):.05;const a=r?r.ui_editor_properties_overbright:void 0,o=Number(a);this.overbright=a==null||!Number.isFinite(o)?1:Math.max(0,o)}setNormalTexture(e){this.normalTex=e||null,this.normalPacked=!!(e&&e.packed)}setTexture(e){this.albedoR8=!!(e&&e.albedoR8),this.texture=e,this._ready=!!e;const n=e&&e.frames,r=Array.isArray(n)?n:n&&n.list&&n.list.length?n.list:null,i=e&&e.width||r&&(n&&n.atlasWidth||r.atlasWidth)||0,s=e&&e.height||r&&(n&&n.atlasHeight||r.atlasHeight)||0;r&&i>0&&s>0?(this.texFrames=r.map(u=>({ou:u.x/i,ov:u.y/s,su:u.width/i,sv:u.height/s})),this.frameCount=this.texFrames.length):(this.texFrames=null,this.frameCount=this.sequenceMul*this.sequenceMul);let a=1,o=1;this.texFrames&&r?(a=r[0].width||1,o=r[0].height||1):e&&e.width>0&&e.height>0&&(a=e.width,o=e.height);const c=Math.max(a,o)||1;this.texAspectX=.5,this.texAspectY=.5*((o||1)/(a||1)),this.frameLongPx=c,this._frameData=void 0}setVisible(e){this.visible=e}syncLayerTransform(){const e=this.layer,n=e&&e.origin?e.origin:[0,0,0],r=e&&e.scale?e.scale:[1,1,1],i=e&&e.angles?e.angles:[0,0,0];this.originX=n[0]||0,this.originY=n[1]||0,this.originZ=n[2]||0,this.scaleX=r[0]===0?1:r[0],this.scaleY=r[1]===0?1:r[1],this.angleZ=i[2]||0;const s=Math.abs(this.scaleX),a=Math.abs(this.scaleY);this.sysScale=Math.min(s,a)||1,this.spriteStretchX=s/this.sysScale,this.spriteStretchY=a/this.sysScale}setParallaxOffset(e,n){this.parallaxX=Number(e)||0,this.parallaxY=Number(n)||0}setPointer(e,n){const r=this.worldToLocal(e,n);this.pointer={x:r[0],y:r[1]}}attachFollow(e,n,r){this._followParent=e||null,this._followMode=n==="particle"||n==="origin"?n:null;const i=r||[0,0,0];this._followOffset=[i[0]||0,i[1]||0,i[2]||0],this._syncFollow()}leaderParticle(){const e=this.pool;for(let n=0;n<e.length;n++)if(e[n].alive)return e[n];return null}attachEventParent(e,n,r){if(!e||n!=="eventdeath"&&n!=="eventspawn")return;const i=r||[0,0,0];this._eventParent=e,this._eventType=n,this._eventOffset=[i[0]||0,i[1]||0,i[2]||0],e._eventChildren.includes(this)||e._eventChildren.push(this),this._syncEventOrigin()}_syncEventOrigin(){const e=this._eventParent;if(!e||!this._eventOffset)return;const n=e.localToWorld(this._eventOffset[0],this._eventOffset[1]);this.originX=n[0],this.originY=n[1]}localToWorld(e,n){const r=e*this.scaleX,i=n*this.scaleY,s=Math.cos(this.angleZ),a=Math.sin(this.angleZ);return[this.originX+r*s-i*a,this.originY+r*a+i*s]}worldToLocal(e,n){const r=e-this.originX,i=n-this.originY,s=Math.cos(-this.angleZ),a=Math.sin(-this.angleZ);return[(r*s-i*a)/(this.scaleX||1),(r*a+i*s)/(this.scaleY||1)]}onParentEvent(e,n,r,i,s,a){this._syncEventOrigin();const o=this.worldToLocal(i,s),c=this._burstQueue;if(c.length>=yw&&c.shift(),c.push([o[0],o[1],a]),e==="spawn"){for(const u of this.emitters)if(!(u.instantaneous>0)&&!(!(u.rate>0)&&!u.fill)){if(this._bound.length>=gw)break;this._bound.push({em:u,parent:n,particle:r,seq:r.seq,poolGen:n._poolGen,pos:[o[0],o[1],a],accum:0,parts:[],cap:u.fill?Math.min(this.maxCount,Dl):0})}}}_notifyChildren(e,n){const r=this._eventChildren;if(!r.length)return;const i=this.localToWorld(n.x,n.y);for(const s of r)(e==="death"?s._eventType!=="eventdeath":s._eventType!=="eventspawn")||s.onParentEvent(e,this,n,i[0],i[1],n.z)}_syncFollow(){const e=this._followParent,n=this._followMode;if(!e||!n)return;const r=this._followOffset;if(n==="particle"){const i=e.leaderParticle();if(!i)return;const s=e.localToWorld(i.x+r[0],i.y+r[1]);this.originX=s[0],this.originY=s[1]}else{const i=e.localToWorld(r[0],r[1]);this.originX=i[0],this.originY=i[1]}}spawn(e,n){if(this._aliveCount>=this.pool.length)return null;const r=this.pool,i=r.length;let s=null,a=this._cursor||0;for(let f=0;f<i;f++){const h=r[(a+f)%i];if(!h.alive){s=h,this._cursor=(a+f+1)%i;break}}if(!s)return null;s.alive=!0,s.age=0,s.seed=Math.random(),s.rot=0,s.rotVel=0,s.rotX=0,s.rotY=0,s.rotVelX=0,s.rotVelY=0,s.vx=s.vy=s.vz=0,s.frame=0,s.seq=this._seq++;const o=e.origin;if(e.kind==="box"){const f=e.distanceMax||[0,0,0],h=e.distanceMin;s.x=o[0]+_t(-f[0],f[0])+(h?h[0]:0),s.y=o[1]+_t(-f[1],f[1])+(h?h[1]:0),s.z=o[2]+_t(-f[2],f[2])+(h?h[2]:0)}else{const f=e.directions,h=e.distanceMin?e.distanceMin[0]:0,p=e.distanceMax?e.distanceMax[0]:0,m=Math.abs(f[2])>1e-6,g=Math.abs(f[0])>1e-6,y=Math.abs(f[1])>1e-6,w=Math.max(1,(g?1:0)+(y?1:0)+(m?1:0));let A,b,v;if(m){const k=Math.random()*2-1,_=Math.random()*Gr,I=Math.sqrt(Math.max(0,1-k*k));A=I*Math.cos(_),b=I*Math.sin(_),v=k}else{const k=Math.random()*Gr;A=Math.cos(k),b=Math.sin(k),v=0}e.sign&&(e.sign[0]&&(A=Math.abs(A)*Math.sign(e.sign[0])),e.sign[1]&&(b=Math.abs(b)*Math.sign(e.sign[1])),e.sign[2]&&(v=Math.abs(v)*Math.sign(e.sign[2])));const x=Math.max(0,h),P=Math.max(x,p),S=x===P?x:Math.pow(x**w+Math.random()*(P**w-x**w),1/w);if(s.x=o[0]+A*S*f[0],s.y=o[1]+b*S*f[1],s.z=o[2]+v*S*f[2],e.speedMax||e.speedMin){const k=_t(e.speedMin,e.speedMax);s.vx+=A*k,s.vy+=b*k,s.vz+=v*k}}{const f=this._cpPos(e.controlPoint);if(f)s.x+=f[0],s.y+=f[1],s.z+=f[2];else{const h=this.controlPoints.find(p=>p.id===e.controlPoint);if(h&&h.lockToPointer){s.alive=!1;return}}}if(this.init.mapAround){const f=this.init.mapAround,h=this._cpPos(f.cp);if(h){const p=f.count,m=this._mapAroundSeq++,g=p>0?m%p/p:0,w=(f.bounds[0]+(f.bounds[1]-f.bounds[0])*g)*Gr,A=e.distanceMin?e.distanceMin[0]:0,b=e.distanceMax?e.distanceMax[0]:0,v=b>0?b:A;s.x=h[0]+Math.cos(w)*v,s.y=h[1]+Math.sin(w)*v,s.z=h[2];const x=Math.random();s.vx+=f.speedMin[0]+(f.speedMax[0]-f.speedMin[0])*x,s.vy+=f.speedMin[1]+(f.speedMax[1]-f.speedMin[1])*x,s.vz+=f.speedMin[2]+(f.speedMax[2]-f.speedMin[2])*x}}n&&(s.x+=n[0],s.y+=n[1],s.z+=n[2]);const c=this.init,u=this._ov.speed||1,l=this._ov.size||1;if(s.life=c.life?Math.max(.001,Qr(c.life.min,c.life.max,c.life.exp)*this.lifetimeMul):1,s.baseSize=c.size?Qr(c.size.min,c.size.max,c.size.exp)*l:20*l,s.size=s.baseSize,c.color){const f=c.color.min,h=c.color.max,p=Math.random();s.baseR=(f[0]+(h[0]-f[0])*p)/255,s.baseG=(f[1]+(h[1]-f[1])*p)/255,s.baseB=(f[2]+(h[2]-f[2])*p)/255}else s.baseR=s.baseG=s.baseB=1;if(this._ov.color&&(s.baseR=this._ov.color[0],s.baseG=this._ov.color[1],s.baseB=this._ov.color[2]),s.r=s.baseR,s.g=s.baseG,s.b=s.baseB,s.baseAlpha=(c.alpha?_t(c.alpha.min,c.alpha.max):1)*this.opacityMul,s.alpha=s.baseAlpha,c.velocity&&(s.vx+=_t(c.velocity.min[0],c.velocity.max[0])*u,s.vy+=_t(c.velocity.min[1],c.velocity.max[1])*u,s.vz+=_t(c.velocity.min[2],c.velocity.max[2])*u),c.turbulentVelocity){const f=c.turbulentVelocity,h=f.audioMode?Rl(f.audioBounds,this._audioLevel||0):1,p=_t(f.speedMin,f.speedMax)*u*h,m=this.simTime*(f.timeScale||0),g=Fl(s.x*f.scale+f.offset,s.y*f.scale+f.offset,m+s.seed*(f.phaseMax||0),3);s.vx+=g[0]*p,s.vy+=g[1]*p,s.vz+=g[2]*p}c.rotation&&(s.rotX=Qr(c.rotation.min[0],c.rotation.max[0],c.rotation.exp),s.rotY=Qr(c.rotation.min[1],c.rotation.max[1],c.rotation.exp),s.rot=Qr(c.rotation.min[2],c.rotation.max[2],c.rotation.exp)),c.angularVelocity&&(s.rotVelX=Qr(c.angularVelocity.min[0],c.angularVelocity.max[0],c.angularVelocity.exp),s.rotVelY=Qr(c.angularVelocity.min[1],c.angularVelocity.max[1],c.angularVelocity.exp),s.rotVel=Qr(c.angularVelocity.min[2],c.angularVelocity.max[2],c.angularVelocity.exp)),s.rotVelX*=u,s.rotVelY*=u,s.rotVel*=u;const d=this.ops;if(d.oscPos)for(let f=0;f<3;f++)d.oscPos.mask[f]&&(s.oscPFreq[f]=_t(d.oscPos.freqMin,d.oscPos.freqMax),s.oscPAmp[f]=_t(d.oscPos.scaleMin,d.oscPos.scaleMax),s.oscPPhase[f]=_t(d.oscPos.phaseMin,d.oscPos.phaseMax+Gr));if(d.oscAlpha&&(s.oscAFreq=_t(d.oscAlpha.freqMin,d.oscAlpha.freqMax),s.oscAAmp=[d.oscAlpha.scaleMin,d.oscAlpha.scaleMax],s.oscAPhase=_t(d.oscAlpha.phaseMin,d.oscAlpha.phaseMax+Gr)),d.oscSize&&(s.oscSFreq=_t(d.oscSize.freqMin,d.oscSize.freqMax),s.oscSAmp=[d.oscSize.scaleMin,d.oscSize.scaleMax],s.oscSPhase=_t(d.oscSize.phaseMin,d.oscSize.phaseMax+Gr)),d.turbulence.length){const f=d.turbulence[0];s.turbSpeed=_t(f.speedMin,f.speedMax),s.turbPhase=_t(f.phaseMin,f.phaseMax)}if(this.frameCount>1&&(s.frame=this.animationMode==="randomframe"?Math.floor(Math.random()*this.frameCount):0),s.frameB=s.frame,s.frameMix=0,this.worldSpace){const f=Math.cos(this.angleZ),h=Math.sin(this.angleZ),p=s.x*this.scaleX,m=s.y*this.scaleY;s.x=this.originX+p*f-m*h,s.y=this.originY+p*h+m*f;const g=s.vx*this.scaleX,y=s.vy*this.scaleY;s.vx=g*f-y*h,s.vy=g*h+y*f,s.vz=s.vz*(this.scaleZ||1)}if(s.bx=s.x,s.by=s.y,s.bz=s.z,s.trail){for(let f=0;f<s.trail.length;f+=3)s.trail[f]=s.x,s.trail[f+1]=s.y,s.trail[f+2]=s.z;s.trailClock=0}return this._aliveCount++,this._eventChildren.length&&this._notifyChildren("spawn",s),s}updateParticle(e,n){if(e.age+=n,e.age>=e.life){this._eventChildren.length&&this._notifyChildren("death",e),e.alive=!1,this._aliveCount--;return}const r=e.age/e.life,i=this.ops;if(i.movement&&(e.vx+=i.movement.gravity[0]*n,e.vy+=i.movement.gravity[1]*n,e.vz+=i.movement.gravity[2]*n,i.movement.drag>0)){const o=Math.exp(-i.movement.drag*n);e.vx*=o,e.vy*=o,e.vz*=o}if(i.angularMovement){const o=i.angularMovement.force,c=i.angularMovement.drag||0;e.rotVelX+=(-e.rotVelX*c+(o[0]||0))*n,e.rotVelY+=(-e.rotVelY*c+(o[1]||0))*n,e.rotVel+=(-e.rotVel*c+(o[2]||0))*n}for(const o of i.turbulence){const c=o.timeScale||1,u=Fl(e.bx*o.scale,e.by*o.scale,this.simTime*o.scale*c+e.turbPhase,3);e.vx+=u[0]*e.turbSpeed*o.mask[0]*n,e.vy+=u[1]*e.turbSpeed*o.mask[1]*n,e.vz+=u[2]*e.turbSpeed*o.mask[2]*n}for(const o of i.attract){let c=this._cpPos(o.cp);if(!c)continue;if(this.worldSpace){const h=this.localToWorld(c[0]+(o.origin[0]||0),c[1]+(o.origin[1]||0));c=[h[0],h[1],c[2]];const p=c[0]-e.x,m=c[1]-e.y,g=Math.hypot(p,m);if(g<.001||o.threshold>0&&g>=o.threshold)continue;const y=o.scale*n/g;e.vx+=p*y,e.vy+=m*y;continue}const u=c[0]+o.origin[0]-e.x,l=c[1]+o.origin[1]-e.y,d=Math.hypot(u,l);if(d<.001||o.threshold>0&&d>=o.threshold)continue;const f=o.scale*n/d;e.vx+=u*f,e.vy+=l*f}for(const o of i.vortex){const c=this._cpPos(o.cp)||[0,0,0],u=e.x-(c[0]+o.offset[0]),l=e.y-(c[1]+o.offset[1]),d=Math.hypot(u,l);if(d<.001)continue;const f=o.distanceOuter-o.distanceInner,h=f>0?Math.min(1,Math.max(0,(d-o.distanceInner)/f)):0,p=o.audioMode?Rl(o.audioBounds,this._audioLevel||0):1,m=o.speedInner+(o.speedOuter-o.speedInner)*h;e.vx+=l/d*m*n*p,e.vy+=-u/d*m*n*p}for(const o of i.remap){const c=o.inputScale||1,u=Fl(e.bx*.01*c,e.by*.01*c,this.simTime*.1,o.fn==="fbmnoise"?4:2);if(o.output==="velocity")for(let l=0;l<3;l++){const d=(u[l]+1)/2,f=o.rangeMin[l]+(o.rangeMax[l]-o.rangeMin[l])*d;l===0?e.vx=f:l===1?e.vy=f:e.vz=f}else if(o.output==="speed"){const l=(u[0]+1)/2,d=o.rangeMin[0]+(o.rangeMax[0]-o.rangeMin[0])*l,f=Math.hypot(e.vx,e.vy)||1;e.vx=e.vx/f*d,e.vy=e.vy/f*d}}if(e.bx+=e.vx*n,e.by+=e.vy*n,e.bz+=e.vz*n,e.rotX+=e.rotVelX*n,e.rotY+=e.rotVelY*n,e.rot+=e.rotVel*n,e.x=e.bx,e.y=e.by,e.z=e.bz,i.oscPos){const o=i.oscPos.mask,c=e.age;for(let u=0;u<3;u++){if(!(o[u]>=.01))continue;const d=e.oscPFreq[u]*c+e.oscPPhase[u],f=e.oscPAmp[u]*(Math.cos(d)-Math.cos(e.oscPPhase[u]));u===0?e.x+=f:u===1?e.y+=f:e.z+=f}}let s=e.baseSize;if(i.sizeChange){const o=i.sizeChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0;s*=o.startValue+(o.endValue-o.startValue)*u}if(i.oscSize){const o=e.oscSFreq*e.age+e.oscSPhase;s*=e.oscSAmp[0]+(Math.cos(o)+1)*.5*(e.oscSAmp[1]-e.oscSAmp[0])}if(e.size=s,i.colorChange){const o=i.colorChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0,l=o.startValue||[e.baseR,e.baseG,e.baseB];e.r=l[0]+(o.endValue[0]-l[0])*u,e.g=l[1]+(o.endValue[1]-l[1])*u,e.b=l[2]+(o.endValue[2]-l[2])*u}let a=e.baseAlpha;if(i.alphaFade){const o=i.alphaFade.fadeIn,c=i.alphaFade.fadeOut;o>0&&r<o&&(a*=r/o),c<1&&r>c&&(a*=Math.max(0,(1-r)/(1-c)))}else!i.alphaChange&&!this.ropeRenderer&&(r<.1?a*=r/.1:r>.85&&(a*=(1-r)/.15));if(i.alphaChange){const o=i.alphaChange,c=o.endTime-o.startTime,u=c>0?Math.min(1,Math.max(0,(r-o.startTime)/c)):r>=o.startTime?1:0;a*=o.startValue+(o.endValue-o.startValue)*u}if(i.oscAlpha){const o=e.oscAFreq*e.age+e.oscAPhase;a*=e.oscAAmp[0]+(Math.cos(o)+1)*.5*(e.oscAAmp[1]-e.oscAAmp[0])}if(e.alpha=Math.max(0,a),this.frameCount>1&&this.animationMode!=="randomframe"){const o=r*this.frameCount,c=Math.min(this.frameCount-1,Math.floor(o));e.frame=c,e.frameB=Math.min(this.frameCount-1,c+1),e.frameMix=this.frameBlend?Math.min(1,Math.max(0,o-c)):0}if(e.trail){const o=e.trail,c=this.trailSampleDt;if(c>0){e.trailClock=(e.trailClock||0)+n;let u=0;const l=this.trailSegments||8;for(;e.trailClock>=c&&u<l;){e.trailClock-=c,u++;for(let d=o.length-3;d>=3;d-=3)o[d]=o[d-3],o[d+1]=o[d-2],o[d+2]=o[d-1]}}o[0]=e.x,o[1]=e.y,o[2]=e.z}}_cpPos(e){const n=this.controlPoints.find(r=>r.id===e);return n?n.lockToPointer?this.pointer?[this.pointer.x+n.offset[0],this.pointer.y+n.offset[1],n.offset[2]]:null:n.offset:null}advance(e,n){if(!(this.paused||!this.visible)){if(e=e*(this.timeScale===void 0?1:Math.max(0,this.timeScale)),this._syncFollow(),!this._warmed&&(this._warmed=!0,this.startTime>0)){const r=.03333333333333333,i=Math.min(900,Math.round(this.startTime/r)),a=Math.max(1,Math.floor(24e4/Math.max(1,this.maxCount))),o=Math.min(i,a);for(let c=0;c<o;c++)this._step(r)}this._step(e,n)}}_step(e,n){this.simTime+=e;const r=n&&Number.isFinite(n.level)?Math.max(0,Math.min(1,n.level)):0;if(this._audioLevel=r,this._eventParent)this._stepEventChild(e);else for(const s of this.emitters){if(s.instantaneous>0&&!s._burst){s._burst=!0;for(let c=0;c<Math.min(s.instantaneous,this.maxCount);c++)this.spawn(s)}if(s.fill){const c=Math.min(this.maxCount,Dl),u=this._aliveCount;let l=Math.min(c-u,512);for(;l-- >0;)this.spawn(s);continue}if(s.audioDriven){let c;if(n&&(n.left16||n.right16)?c=uw({left:n.left16,right:n.right16},s.audioMode,s.audioFreqStart,s.audioFreqEnd,s.audioBounds,s.audioExponent,1):c=Rl(s.audioBounds,r),s.rate>0){const u=s.rate*c*(this._ov.countMul!==void 0?this._ov.countMul:1);if(!(u>0))continue;s._accum=(s._accum||0)+u*e;let l=Math.floor(s._accum);if(l>0){s._accum-=l,l>this.maxCount&&(l=this.maxCount);for(let d=0;d<l;d++)this.spawn(s)}}else{const u=Math.round(Math.min(this.maxCount,Dl)*c),l=this._aliveCount;let d=Math.min(u-l,256);for(;d-- >0;)this.spawn(s)}continue}const a=s.rate*(this._ov.countMul!==void 0?this._ov.countMul:1);if(!(a>0))continue;s._accum=(s._accum||0)+a*e;let o=Math.floor(s._accum);if(o>0){s._accum-=o,o>this.maxCount&&(o=this.maxCount);for(let c=0;c<o;c++)this.spawn(s)}}const i=this.pool;for(let s=0;s<i.length;s++)i[s].alive&&this.updateParticle(i[s],e)}_stepEventChild(e){this._syncEventOrigin();const n=this._burstQueue;if(n.length){this._burstQueue=[];for(const i of n)this._burstAt(i)}if(!this._bound.length)return;const r=[];for(const i of this._bound){const s=i.particle;if(!s.alive||s.seq!==i.seq||i.parent._poolGen!==i.poolGen)continue;const a=i.parent.localToWorld(s.x,s.y),o=this.worldToLocal(a[0],a[1]);i.pos[0]=o[0],i.pos[1]=o[1],i.pos[2]=s.z,this._emitBound(i,e),r.push(i)}this._bound=r}_burstAt(e){for(const n of this.emitters){if(!(n.instantaneous>0))continue;const r=Math.min(n.instantaneous,this.maxCount);for(let i=0;i<r&&this.spawn(n,e);i++);}}_emitBound(e,n){const r=e.em;if(e.cap>0){let o=0;const c=[];for(const l of e.parts)l.p.alive&&l.p.seq===l.seq&&(o++,c.push(l));e.parts=c;let u=Math.min(e.cap-o,32);for(;u-- >0;){const l=this.spawn(r,e.pos);if(!l)break;e.parts.push({p:l,seq:l.seq})}return}const i=this._ov.countMul!==void 0?this._ov.countMul:1,s=r.rate*i;if(!(s>0))return;e.accum=(e.accum||0)+s*n;let a=Math.floor(e.accum);if(!(a<=0)){e.accum-=a,a>this.maxCount&&(a=this.maxCount);for(let o=0;o<a&&this.spawn(r,e.pos);o++);}}render(e,n,r,i,s){if(!this._ready||!this.visible||!this.renderers.length)return;const a=this.gl;this._prog||this._buildProgram(a);const o=this.trailCfg&&this.trailCfg.kind==="ropetrail"?this.trailCfg:null,c=this.trailCfg&&this.trailCfg.kind==="spritetrail"?this.trailCfg:null,u=this.ropeRenderer;um(this.trailCfg,this.trailSegments);const l=18,d=this.pool;let f=null;if(u){f=this._ropeOrder,f.length=0;for(let Y=0;Y<d.length;Y++)d[Y].alive&&f.push(d[Y]);f.sort((Y,oe)=>Y.seq-oe.seq)}let h=0;if(f)h=f.length;else for(let Y=0;Y<d.length;Y++)d[Y].alive&&h++;if(h===0||u&&h<2)return;const p=u?h-1:h,m=p*l;(!this._data||this._data.length<m)&&(this._data=new Float32Array(Math.max(m,1024)));const g=this._data;let y=0;const w=(this._ov.brightness||1)*(this.overbright??1),A=this.worldSpace,b=A?1:this.sysScale,v=Y=>Math.abs(Y)*b,x=(A?1:this.spriteStretchX)*(this.texAspectX||1),P=(A?1:this.spriteStretchY)*(this.texAspectY||1),S=A?1:Math.cos(this.angleZ),k=A?0:Math.sin(this.angleZ),_=A?this.parallaxX||0:this.originX+(this.parallaxX||0),I=A?this.parallaxY||0:this.originY+(this.parallaxY||0),B=A?1:this.scaleX,V=A?1:this.scaleY,O=(Y,oe)=>{const he=Y*B,Ae=oe*V;return[_+he*S-Ae*k,s-(I+he*k+Ae*S)]};if(u)for(let Y=0;Y+1<h;Y++){const oe=f[Y],he=f[Y+1],Ae=O(oe.x,oe.y),Pe=O(he.x,he.y),Ce=Pe[0]-Ae[0],Le=Pe[1]-Ae[1],Ne=Math.hypot(Ce,Le),De=(v(oe.size)+v(he.size))*.5;De>0&&(g[y++]=(Ae[0]+Pe[0])*.5,g[y++]=(Ae[1]+Pe[1])*.5,g[y++]=0,g[y++]=De,g[y++]=Math.atan2(-Ce,Le),g[y++]=(oe.r+he.r)*.5*w,g[y++]=(oe.g+he.g)*.5*w,g[y++]=(oe.b+he.b)*.5*w,g[y++]=(oe.alpha+he.alpha)*.5,g[y++]=1,g[y++]=Ne/De,g[y++]=0,g[y++]=Ul(oe),g[y++]=Ul(he),g[y++]=0,g[y++]=0,g[y++]=0,g[y++]=0)}const U=(Y,oe,he,Ae,Pe,Ce,Le,Ne,De)=>{g[y++]=Y,g[y++]=oe,g[y++]=0,g[y++]=Ae,g[y++]=he,g[y++]=Ne.r*w,g[y++]=Ne.g*w,g[y++]=Ne.b*w,g[y++]=Ne.alpha,g[y++]=x,g[y++]=Pe,g[y++]=De,g[y++]=Ce,g[y++]=Le,g[y++]=Ne.frameB===void 0?Ne.frame:Ne.frameB,g[y++]=Ne.frameMix||0,g[y++]=Ne.rotX||0,g[y++]=Ne.rotY||0};for(let Y=0;Y<d.length&&!u;Y++){const oe=d[Y];if(oe.alive)if(o||c){const he=o||c,Ae=O(oe.x,oe.y),Pe=O(oe.x+oe.vx,oe.y+oe.vy),Ce=Pe[0]-Ae[0],Le=Pe[1]-Ae[1],Ne=v(oe.size),De=lm(Ce,Le),Re=cm(Math.hypot(oe.vx,oe.vy),he.length,he.minLength,he.maxLength);U(Ae[0],Ae[1],De,Ne,Re,0,1,oe,oe.frame)}else{const he=O(oe.x,oe.y);U(he[0],he[1],oe.rot,v(oe.size),P,0,1,oe,oe.frame)}}const W=this._prog;am(a),a.useProgram(W.prog),a.bindVertexArray(this._vao),a.bindBuffer(a.ARRAY_BUFFER,this._vbuf),a.bufferData(a.ARRAY_BUFFER,g.subarray(0,y),a.DYNAMIC_DRAW),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),a.uniform1i(W.uniTex,0),a.uniformMatrix4fv(W.uniMvp,!1,e);const ie=this.refract&&this.normalTex&&this.normalTex.glTex;if(W.uniRefract&&a.uniform1i(W.uniRefract,ie?1:0),W.uniAlbedoR8&&a.uniform1i(W.uniAlbedoR8,this.albedoR8?1:0),ie){a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,this.normalTex.glTex),W.uniNormal&&a.uniform1i(W.uniNormal,1),W.uniNormalPacked&&a.uniform1i(W.uniNormalPacked,this.normalPacked?1:0),W.uniSampleScene&&a.uniform1i(W.uniSampleScene,1);{const Y=a.drawingBufferWidth||n,oe=a.drawingBufferHeight||r;if(a.activeTexture(a.TEXTURE2),Ll){const he=Ll(Y,oe);a.bindTexture(a.TEXTURE_2D,he||this.texture.glTex),am(a)}else a.bindFramebuffer(a.FRAMEBUFFER,null),this._sceneTex?a.bindTexture(a.TEXTURE_2D,this._sceneTex):(this._sceneTex=a.createTexture(),a.bindTexture(a.TEXTURE_2D,this._sceneTex),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE)),a.copyTexImage2D(a.TEXTURE_2D,0,a.RGB8,0,0,Y,oe,0);W.uniScene&&a.uniform1i(W.uniScene,2),W.uniResolution&&a.uniform2f(W.uniResolution,Y,oe),W.uniRefractScale&&a.uniform1f(W.uniRefractScale,Number.isFinite(this.refractAmount)?this.refractAmount:.05)}}else W.uniNormal&&(a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),a.uniform1i(W.uniNormal,1),a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,this.texture.glTex),W.uniScene&&a.uniform1i(W.uniScene,2),W.uniSampleScene&&a.uniform1i(W.uniSampleScene,0));const we=this._frameUniformData();we?(a.uniform1i(W.uniFrameCount,we.count),a.uniform4fv(W.uniFrames,we.arr)):a.uniform1i(W.uniFrameCount,0),a.enable(a.BLEND),this.blend==="additive"?a.blendFunc(a.SRC_ALPHA,a.ONE):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),a.depthMask(!1),a.drawArraysInstanced(a.TRIANGLE_STRIP,0,4,p),a.depthMask(!0),a.disable(a.BLEND),a.bindVertexArray(null)}_buildProgram(e){const n=iw(e);this._quadBuf=n.quadBuf,this._vbuf=n.vbuf,this._vao=n.vao,this._prog=n.prog}_frameUniformData(){if(this._frameData!==void 0)return this._frameData;let e=this.texFrames;if(!e&&this.sequenceMul>1){const i=this.sequenceMul;e=[];for(let s=0;s<i;s++)for(let a=0;a<i;a++)e.push({ou:a/i,ov:s/i,su:1/i,sv:1/i})}if(!e||e.length===0)return this._frameData=null,null;const n=Math.min(e.length,128),r=new Float32Array(n*4);for(let i=0;i<n;i++)r[i*4]=e[i].ou,r[i*4+1]=e[i].ov,r[i*4+2]=e[i].su,r[i*4+3]=e[i].sv;return this._frameData={count:n,arr:r},this._frameData}liveCount(){let e=0;for(const n of this.pool)n.alive&&e++;return e}dispose(){this.paused=!0;const e=this.gl;if(e){try{this._vbuf&&e.deleteBuffer(this._vbuf),this._quadBuf&&e.deleteBuffer(this._quadBuf),this._vao&&e.deleteVertexArray(this._vao),this._prog&&this._prog.prog&&e.deleteProgram(this._prog.prog),this._sceneTex&&e.deleteTexture(this._sceneTex)}catch{}this._prog=null,this._vbuf=null,this._quadBuf=null,this._vao=null,this._data=null,this._sceneTex=null}}}const kw=Object.freeze(Object.defineProperty({__proto__:null,ParticleSystem:xw,getParticleDensityTier:pw,getParticleQualityScale:dw,particleInstanceSegs:um,particlePassRefract:om,rgbaIsBlankWhite:vw,ropeParticleV:Ul,ropeTrailDuration:dm,ropeTrailHistoryCount:fm,setParticleDensityTier:mw,setParticleFrameTargetProvider:bw,setParticleQualityScale:fw,setParticleSceneCapture:ww,spriteTrailLengthFactor:cm,spriteTrailRotation:lm},Symbol.toStringTag,{value:"Module"})),Cn=new Map,Ol=new Map;let vo=null;function Tw(t,e){const n=String(t);Ol.set(n,e),Cn.delete(n)}function Sw(t){vo=typeof t=="function"?t:null}function Pw(){Ol.clear(),vo=null,Cn.clear()}function _w(){return Object.keys(oa)}function ft(t,e,n){t[e]=255,t[e+1]=255,t[e+2]=255,t[e+3]=Math.round(Math.min(1,Math.max(0,n))*255)}function ta(t,e){const{width:n,height:r,rgba:i}=t,s=Math.max(2,Math.round(Math.min(n,r)*.04));for(let a=0;a<r;a++)for(let o=0;o<n;o++){const c=Math.min(o,a,n-1-o,r-1-a);if(c>=s)continue;const u=c/s,l=(a*n+o)*4+3;i[l]=Math.round(i[l]*u)}if(e>0){let a=0;const o=n*r;for(let u=0;u<o;u++)a+=i[u*4+3];const c=a/o/255;if(c>e&&c>0){const u=e/c;for(let l=0;l<o;l++)i[l*4+3]=Math.round(i[l*4+3]*u)}}return t}function Yn(t){let e=t>>>0;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const Kn=t=>t*t*(3-2*t),na=t=>t*t*t*(t*(t*6-15)+10),Zn=(t,e,n)=>t+(e-t)*n,Me=(t,e)=>Math.exp(-(t*t)/(e*e));function Kr(t,e,n,r){const i=Math.min(t,e,n-1-t,n-1-e);return i>=r?1:i/r}function ra(t,e){const n=new Uint8Array(t*t*4),r=t/2;for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=Math.hypot((s+.5-r)/r,(i+.5-r)/r);let o=0;for(let c=0;c<e.length;c++)o+=e[c].w*Me(a,e[c].r);ft(n,(i*t+s)*4,o)}return{width:t,height:t,rgba:n}}function xi(t,e,n){return ra(t,[e,n])}function Ew(t,e){const n=new Uint8Array(t*t*4),r=t/2,i=e.length-1;for(let s=0;s<t;s++)for(let a=0;a<t;a++){const o=Math.hypot(a+.5-r,s+.5-r)/r;let c=0;if(o<1){const u=o*i,l=Math.min(i-1,Math.floor(u));c=e[l]+(e[l+1]-e[l])*(u-l)}ft(n,(s*t+a)*4,c)}return{width:t,height:t,rgba:n}}function Mw(t){const e=new Uint8Array(t*t*4),n=t/2;for(let r=0;r<t;r++)for(let i=0;i<t;i++){const s=Math.hypot(i+.5-n,r+.5-n)/n,a=Math.min(1,Math.max(0,(s-.6)/.4)),o=a*a*(3-2*a);ft(e,(r*t+i)*4,Math.pow(1-o,1.6))}return{width:t,height:t,rgba:e}}function Zr(t,e,n,r,i){const s=new Uint8Array(t*t*4),a=t/2,o=Math.max(2,Math.round(t*.03));for(let c=0;c<t;c++)for(let u=0;u<t;u++){const l=(u+.5-a)/a,d=(c+.5-a)/a,f=Math.hypot(l,d),h=Math.atan2(d,l),p=Math.pow(.5+.5*Math.cos(e*h),r);let m=Me(f,i)+p*Me(f,n);m*=Kr(u,c,t,o),ft(s,(c*t+u)*4,m)}return{width:t,height:t,rgba:s}}function Ao(t,e,n,r,i){const a=new Uint8Array(t*e*4);for(let o=0;o<e;o++){const c=o/(e-1),u=r?Me(c-.5,.27):Kn(Math.min(1,c/.06))*Math.pow(1-c,1.35);for(let l=0;l<t;l++){const d=l/(t-1)*2-1,f=Me(d,n);ft(a,(o*t+l)*4,f*f*f*u*.55)}}return{width:t,height:e,rgba:a}}function Cw(t){const e=t,n=new Uint8Array(e*e*4),r=15;for(let i=0;i<e;i++)for(let s=0;s<e;s++){const a=(i*e+s)*4;let o=0;s===r?o=255:(s===r-1||s===r+1)&&(o=50),n[a]=o,n[a+1]=o,n[a+2]=o,n[a+3]=255}return{width:e,height:e,rgba:n}}function Iw(t,e,n,r){const i=Math.round(t/Math.sqrt(e)),s=Math.round(t/i),a=new Uint8Array(t*t*4);for(let u=0;u<t*t;u++)a[u*4+3]=255;const o=Yn(r>>>0),c=[];for(let u=0;u<n;u++){const l=o()*Math.PI*2,d=Math.pow(o(),1.15)*.38*i;c.push({x:i/2+Math.cos(l)*d,y:i/2+Math.sin(l)*d,r:.5+o()*1.35,phase:o(),drift:(o()-.5)*.06,tint:[.55+o()*.45,.75+o()*.25,.85+o()*.15],bright:o()<.18?.75+o()*.6:.22+o()*.35})}for(let u=0;u<e;u++){const l=u%s*i,d=(u/s|0)*i,f=u/e;for(const h of c){const p=(f-h.phase+1)%1,m=Math.min(1,p*6),g=p>.75?Math.max(0,1-(p-.75)/.25):1,y=m*g*h.bright;if(y<=.02)continue;const w=h.r*(.6+.8*Math.min(1,p*3)),A=h.x+h.drift*i*p*3,b=h.y-p*i*.12;for(let v=Math.floor(b-w-1);v<=Math.ceil(b+w+1);v++)for(let x=Math.floor(A-w-1);x<=Math.ceil(A+w+1);x++){if(x<0||v<0||x>=i||v>=i)continue;const P=Math.hypot(x+.5-A,v+.5-b),S=Math.exp(-Math.pow((P-w)/.7,2)),k=Math.exp(-Math.pow(P/(w*.9),2))*.22,_=Math.min(1,(S+k)*y);if(_<=.01)continue;const I=((d+v)*t+l+x)*4,B=V=>Math.min(255,a[I+V]+Math.round(_*h.tint[V]*255*.42));a[I]=B(0),a[I+1]=B(1),a[I+2]=B(2),a[I+3]=255}}}return{width:t,height:t,rgba:a}}const hm={0:{w:256,h:512,p:.9,k:.996,grid:[[0,0,0,0,0,0,0,0,0],[0,0,.008,.122,.376,.247,.031,0,0],[0,0,.063,.314,.804,.698,.188,0,0],[0,.004,.129,.408,.741,.737,.22,0,0],[0,.008,.082,.278,.647,.639,.18,0,0],[0,.012,.075,.278,.541,.541,.125,0,0],[0,0,.027,.275,.451,.451,.098,0,0],[0,0,.027,.239,.361,.357,.067,0,0],[0,0,.031,.176,.278,.275,.031,0,0],[0,0,0,.137,.212,.188,.027,0,0],[0,0,0,.106,.153,.145,0,0,0],[0,0,0,.078,.106,.118,.027,0,0],[0,0,0,.067,.078,.086,0,0,0],[0,0,0,.055,.059,.071,.031,0,0],[0,0,0,.027,.031,.055,0,0,0],[0,0,0,.027,.027,.027,0,0,0],[0,0,0,0,0,0,0,0,0]]},1:{w:256,h:512,p:.75,k:1.137,grid:[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,.012,.027,0,.02,.02,0,0],[0,0,0,.09,0,.192,.035,0,0],[0,0,0,.024,.098,.075,.047,0,0],[0,0,0,.157,.208,.42,.031,0,0],[0,0,0,.059,.106,.157,0,0,0],[0,0,0,0,.031,0,0,0,0],[0,0,0,0,.016,.031,0,0,0],[0,0,0,0,.012,.039,0,0,0],[0,0,0,0,.012,.031,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,.075,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]},2:{w:256,h:256,p:3.15,k:2.941,grid:[[0,0,0,0,0,0,0,0,0],[0,0,.071,0,0,0,0,0,0],[0,0,.11,0,0,0,0,0,0],[0,0,.192,.02,0,.067,.008,0,0],[0,0,0,.098,.11,0,0,0,0],[0,0,0,.286,.427,.161,.012,0,0],[0,0,0,.902,1,.137,0,0,0],[0,0,0,.678,.965,0,0,0,0],[0,0,0,0,.973,0,0,0,0],[0,0,0,.212,.969,0,0,0,0],[0,0,0,.071,.894,.02,0,0,0],[0,0,0,.396,.757,.408,0,0,0],[0,0,0,.012,.514,0,.071,0,0],[0,0,.09,.102,.275,0,.02,0,0],[0,0,0,0,.106,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]},3:{w:128,h:512,p:3,k:5.021,grid:[[0,0,0,0,.141,0,0,0,0],[0,0,.035,.424,.455,.337,0,0,0],[0,0,.098,.231,.125,0,.039,0,0],[0,0,.031,.247,.592,.09,.196,0,0],[0,0,.071,0,.678,0,.012,0,0],[0,0,.122,0,.69,0,0,.004,0],[0,.004,0,0,.659,.039,0,0,0],[0,0,0,.047,.58,.008,0,0,0],[0,0,0,0,.467,0,0,0,0],[0,0,0,.016,.408,0,0,0,0],[0,0,0,.031,.392,0,0,0,0],[0,0,0,.027,.349,0,0,0,0],[0,0,0,.024,.255,0,0,0,0],[0,0,0,.02,.184,0,0,0,0],[0,0,0,0,.125,0,0,0,0],[0,0,0,0,.078,0,0,0,0],[0,0,0,0,0,0,0,0,0]]},4:{w:256,h:256,p:.8,k:.875,grid:[[0,0,0,0,.024,0,0,0,0],[0,0,.004,.114,.145,.09,.039,0,0],[0,.004,.286,0,.008,0,0,.063,0],[0,.149,0,0,.188,.169,.086,.086,0],[0,.247,.216,0,.514,.467,.22,0,0],[0,0,.122,.122,.604,.467,.086,.106,0],[0,0,0,.118,.494,.525,.306,.043,0],[0,.012,0,.263,.329,.416,.157,0,0],[0,0,0,.153,.192,.573,.102,.024,0],[0,0,0,.204,.122,.278,.082,.012,0],[0,0,.086,.169,.078,.259,.059,0,0],[0,0,.039,.075,.051,.208,.02,0,0],[0,0,.016,.02,.027,.145,.035,0,0],[0,0,.02,0,.012,.106,.016,0,0],[0,0,0,0,0,.075,0,0,0],[0,.012,0,0,0,.031,0,0,0],[0,0,0,0,0,0,0,0,0]]},5:{w:256,h:256,p:1.15,k:1.569,grid:[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,.008,0,0,0,0,0],[0,0,0,.094,.051,0,.067,0,0],[0,0,0,0,.137,.039,0,0,0],[0,0,0,.145,.031,.243,0,0,0],[0,0,0,.067,0,.016,0,0,0],[0,0,0,0,0,.008,0,0,0],[0,0,0,.094,.016,.125,.039,0,0],[0,0,0,.565,.231,.369,0,0,0],[0,0,0,.004,.557,.114,0,0,0],[0,0,0,.004,.184,0,.106,0,0],[0,0,0,.165,.035,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]},6:{w:128,h:512,p:.8,k:.838,grid:[[0,0,0,0,0,0,0,0,0],[0,0,.063,.09,.071,.137,.118,.008,0],[0,0,.129,.263,.176,.455,.365,.055,0],[0,0,.173,.376,.239,.655,.522,.067,0],[0,0,.157,.345,.22,.592,.471,.067,0],[0,0,.145,.306,.196,.486,.392,.051,0],[0,0,.133,.267,.165,.357,.282,.051,0],[0,0,.11,.208,.129,.231,.18,.02,0],[0,0,.086,.161,.098,.137,.106,.008,0],[0,0,.071,.118,.078,.078,.067,0,0],[0,0,.055,.082,.055,.031,.012,0,0],[0,0,.031,.063,.039,.012,0,0,0],[0,0,.02,.039,.02,.008,0,0,0],[0,0,.008,.012,.012,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]}};function ki(t){const e=hm[t]||hm[0],{w:n,h:r,p:i,k:s,grid:a}=e,o=a[0].length,c=a.length,u=new Uint8Array(n*r*4),l=(f,h)=>a[Math.min(c-1,Math.max(0,h))][Math.min(o-1,Math.max(0,f))],d=(f,h)=>{const p=Math.min(h-1-1e-6,Math.max(0,f*(h-1))),m=Math.floor(p);return[m,p-m]};for(let f=0;f<r;f++){const[h,p]=d(f/(r-1),c);for(let m=0;m<n;m++){const[g,y]=d(m/(n-1),o),w=l(g,h)*(1-y)+l(g+1,h)*y,A=l(g,h+1)*(1-y)+l(g+1,h+1)*y,b=w*(1-p)+A*p,v=Math.min(1,s*Math.pow(b,i)),x=Math.round(255*v),P=(f*n+m)*4;u[P]=x,u[P+1]=x,u[P+2]=x,u[P+3]=x}}return{width:n,height:r,rgba:u}}const mm=4,In=512,ia=In*2;function pm(t){const e=t||{},n=e.segments||89,r=e.peakMax||.37,i=e.peakPow||1.6,s=e.lean===void 0?-.019:e.lean,a=new Uint8Array(ia*ia*4);for(let o=0;o<mm;o++){const c=Yn((2654435769^o*2246822507)>>>0),u=o%2*In,l=(o/2|0)*In,d=3,f=(h,p,m)=>{if(h<d||p<d||h>=In-d||p>=In-d)return;const g=((l+p)*ia+u+h)*4,y=Math.round(Math.min(1,Math.max(0,m))*255);y*255>a[g+3]*255&&ft(a,g,y/255)};for(let h=0;h<n;h++){const p=c()*In,m=c()*In,g=16+430*Math.pow(c(),2.2),y=.04+(r-.04)*Math.pow(c(),i),w=.5+c()*.35;for(let A=0;A<g;A++){const b=Math.round(m+A),v=p+s*A,x=Math.min(1,Math.min(A,g-1-A)/5);if(!(x<=0))for(let P=Math.floor(v-3);P<=Math.ceil(v+3);P++){const S=P+.5-v,k=Math.exp(-(S*S)/(w*w))*y*x;k>.004&&f(P,b,k)}}}}return{width:ia,height:ia,rgba:a}}function Rw(t){if(t==="particle/nature/rain1"||t==="particle/nature/rain2"){const e=[];for(let n=0;n<mm;n++)e.push({x:n%2*In,y:(n/2|0)*In,width:In,height:In});return e}if(t==="particle/bubbles/bubble3"){const e=[];for(let n=0;n<64;n++)e.push({x:n%8*128,y:(n/8|0)*128,width:128,height:128});return e}{const e=gs[t];if(e)return _m(e.cols,e.fw,e.fh,e.frames);if(t==="particle/water/rain_drops_sheet")return _m(4,64,64,16)}if(t==="particle/fog/fog1"){const e=[];for(let n=0;n<Pm;n++)e.push({x:n%8*Jn,y:(n/8|0)*Jn,width:Jn,height:Jn});return e}if(t==="particle/smoke/smoke2"||t==="particle/smoke/smoke2light"){const e=[];for(let n=0;n<Ql;n++)e.push({x:n%8*Bn,y:(n/8|0)*Bn,width:Bn,height:Bn});return e}if(/^particle\/nature\/leaves\d*$/.test(t)){const e=[];for(let n=0;n<3;n++)for(let r=0;r<3;r++)e.push({x:r*sa,y:n*sa,width:sa,height:sa});return e}return null}function zl(t,e,n){const r=new Uint8Array(t*t*4),i=t/2;for(let s=0;s<t;s++)for(let a=0;a<t;a++){const o=Math.hypot((a-i)/i,(s-i)/i);ft(r,(s*t+a)*4,Me(o-e,n*.6)*Math.max(0,1-o))}return{width:t,height:t,rgba:r}}function gm(t,e){const n={1:{r:.78,t:.048,inner:.06,hi:[[-.28,-.32,.22,.9],[.32,.36,.12,.28]]},2:{r:.7,t:.07,inner:.14,hi:[[-.2,-.28,.3,.72],[.38,.2,.14,.4]]},3:{r:.84,t:.036,inner:.04,hi:[[-.34,-.18,.16,.95],[.2,.42,.1,.22],[.04,-.08,.07,.18]]}},r=n[e]||n[1],i=new Uint8Array(t*t*4),s=t/2;for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=(o+.5-s)/s,u=(a+.5-s)/s,l=Math.hypot(c,u);let d=Me(l-r.r,r.t*.85)*Math.max(0,1.05-l);l<r.r&&(d+=r.inner*Me(l,.5));for(let f=0;f<r.hi.length;f++){const h=r.hi[f];d+=h[3]*Me(Math.hypot(c-h[0],u-h[1]),h[2])}ft(i,(a*t+o)*4,d)}return ta({width:t,height:t,rgba:i},.05)}function xo(t,e){const n=t>>1,r=new Uint8Array(t*t*4),i=e===1?[1,2,1,3]:e===2?[2,1,2,3]:[3,1,2,3];for(let s=0;s<2;s++)for(let a=0;a<2;a++){const o=gm(n,i[s*2+a]);for(let c=0;c<n;c++){const u=(s*n+c)*t,l=c*n;for(let d=0;d<n;d++){const f=(u+a*n+d)*4,h=(l+d)*4;r[f]=o.rgba[h],r[f+1]=o.rgba[h+1],r[f+2]=o.rgba[h+2],r[f+3]=o.rgba[h+3]}}}return{width:t,height:t,rgba:r}}function ym(t){const e=new Uint8Array(t*t*4),n=t/2,r=[[.32,0],[1.1,.35],[2.2,-.3],[-.7,.2]];for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=s>=n?1:0,o=i>=n?1:0,c=o*2+a,u=a*n+n/2,l=o*n+n/2,d=r[c][0],f=r[c][1],h=(s+.5-u)/(n*.4),p=(i+.5-l)/(n*.4),m=Math.cos(d),g=Math.sin(d);let y=h*m+p*g;const w=-h*g+p*m;y+=f*w*.18;const A=1-Math.max(0,w)*.42,b=Math.hypot(y/(.52*A),w/.92);let v=b>=1.12?0:Me(b,.48);v=Math.min(1,v+Me(y,.07)*Me(w,.65)*v*.4),ft(e,(i*t+s)*4,v)}return ta({width:t,height:t,rgba:e},.11)}const sa=256,Ut=sa*3;function Ot(t,e){const n={0:{rx:.36,ry:.92,wave:0,folds:0,rgb:[196,66,32]},1:{rx:.48,ry:.86,wave:.05,folds:7,rgb:[188,58,30]},2:{rx:.4,ry:.88,wave:.08,folds:5,rgb:[206,82,36]},3:{rx:.58,ry:.72,wave:0,folds:0,rgb:[214,148,40]},5:{rx:.44,ry:.8,wave:.12,folds:9,rgb:[220,158,48]},6:{rx:.52,ry:.78,wave:.07,folds:4,rgb:[122,150,52]},7:{rx:.5,ry:.9,wave:.16,folds:3,rgb:[96,138,50]},8:{rx:.38,ry:.94,wave:.2,folds:2,rgb:[110,148,56]}},r=n[e]||n[0],i=Math.floor(t/3),s=new Uint8Array(i*3*i*3*4),a=i/2,o=Yn(7855+e*131);for(let c=0;c<9;c++){const u=c%3,l=c/3|0,d=c/9*Math.PI*2+(o()-.5)*.7,f=.9+o()*.16,h=.9+o()*.2,p=1+(o()-.5)*.12,m=Math.cos(d),g=Math.sin(d),y=c&1?-1:1;for(let w=0;w<i;w++)for(let A=0;A<i;A++){const b=(A+.5-a)/a*y,v=(w+.5-a)/a,x=(b*m+v*g)/f,P=(-b*g+v*m)/f,S=1-Math.pow(Math.min(1,Math.abs(P)),1.7)*.52,k=Math.atan2(x,P),_=r.wave?1+r.wave*Math.sin(k*r.folds):1,I=Math.hypot(x/(r.rx*_*S),P/r.ry),B=I>=1.08?0:Math.min(1,(1.08-I)/.14);if(B<=0)continue;const V=Me(x,.028)*Me(P,.72),O=(.8+.2*Math.max(0,1-I))*(1+V*.22)*h,U=((l*i+w)*i*3+u*i+A)*4;s[U]=Math.min(255,Math.round(r.rgb[0]*O*p)),s[U+1]=Math.min(255,Math.round(r.rgb[1]*O)),s[U+2]=Math.min(255,Math.round(r.rgb[2]*O*(2-p))),s[U+3]=Math.round(B*255)}}return ta({width:i*3,height:i*3,rgba:s},0)}function Rn(t,e){const n=t.width,r=t.height,i=t.rgba,s=e??2.8,a=new Uint8Array(n*r*4),o=(c,u)=>{const l=c<0?0:c>=n?n-1:c,d=u<0?0:u>=r?r-1:u;return i[(d*n+l)*4+3]/255};for(let c=0;c<r;c++)for(let u=0;u<n;u++){const l=(o(u-1,c)-o(u+1,c))*s,d=(o(u,c-1)-o(u,c+1))*s,f=1/Math.hypot(l,d,1),h=(c*n+u)*4;a[h]=Math.round((l*f*.5+.5)*255),a[h+1]=Math.round((d*f*.5+.5)*255),a[h+2]=Math.round((f*.5+.5)*255),a[h+3]=255}return{width:n,height:r,rgba:a}}function bm(t){const e=new Uint8Array(t*t*4),n=t/2;for(let r=0;r<t;r++)for(let i=0;i<t;i++){const s=(i+.5-n)/n,a=(r+.5-n)/n,o=Math.hypot(s,a),c=o>=1?0:Math.sqrt(Math.max(0,1-o*o)),u=Me(o-.62,.11)*.55;ft(e,(r*t+i)*4,Math.min(1,c*.85+u))}return{width:t,height:t,rgba:e}}function Bw(t){const e=new Uint8Array(t*t*4),n=t/2;for(let r=0;r<t;r++)for(let i=0;i<t;i++){const s=(i+.5-n)/n,a=(r+.5-n)/n,o=Math.hypot(s,a),c=Math.atan2(a,s),u=Me(o,.38)*(.55+.45*Math.cos(c*3+o*6));ft(e,(r*t+i)*4,u)}return{width:t,height:t,rgba:e}}function wm(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=Math.hypot(a,o),u=Math.atan2(o,a),l=Kn(Math.max(0,Math.cos(u)*.55+.45)),d=Me(c-.68,.07)*l+.35*Me(c-.78,.12)*Me(u-.9,.55);ft(e,(i*t+s)*4,Math.min(1,d)*Kr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Fw(t,e){if(!t||!t.rgba)return t;const n=Number(e);if(n!==8&&n!==9&&n!==10&&n!==11)return t;const r=t.width*t.height,i=new Uint8Array(r*4),s=t.rgba;if(n===9||n===11)for(let a=0;a<r;a++)i[a*4]=255,i[a*4+1]=255,i[a*4+2]=255,i[a*4+3]=s[a*4];else for(let a=0;a<r;a++){const o=s[a*4+3],c=s[a*4];i[a*4]=o,i[a*4+1]=o,i[a*4+2]=o,i[a*4+3]=c}return{width:t.width,height:t.height,rgba:i,format:n,frames:t.frames}}function Dw(t,e){if(!t||!t.rgba)return t;const n=Number(e);if(n!==8&&n!==10)return t;const r=t.width*t.height,i=new Uint8Array(r*4),s=t.rgba;for(let a=0;a<r;a++)i[a*4]=s[a*4+1],i[a*4+1]=s[a*4],i[a*4+2]=0,i[a*4+3]=255;return{width:t.width,height:t.height,rgba:i,format:n,frames:t.frames}}function vm(t){if(!t||t.length<16)return!1;const e=t.length/4,n=Math.max(1,e/48|0);let r=0;for(let i=0;i<e;i+=n){const s=i*4;if(t[s]<240||t[s+1]<240||t[s+2]<240)return!1;r++}return r>0}function Nw(t){if(!t||!t.rgba||!t.rgba.length)return!1;const e=t.rgba.length/4,n=Math.max(1,e/96|0);let r=0,i=0;for(let s=0;s<e;s+=n){const a=t.rgba[s*4+3];r++,a<250&&i++}return r>0&&i/r>.2}function Lw(t){return!t||!t.rgba?t:vm(t.rgba)?Rn(t,2.8):t}const Uw={"particle/drop":"particle/drop_normal","particle/water/rain_drops_sheet":"particle/water/rain_drops_sheet_normal","particle/bubbles/bubble1":"particle/bubbles/bubble1normal","particle/bubbles/bubble2":"particle/bubbles/bubble2_normal","particle/sharp_halo":"particle/sharp_halo_normal","particle/misc/wave":"particle/normal_splash","particle/halo":"particle/sharp_halo_normal"};function Ow(t){if(!t)return null;const e=String(t);return/normal/i.test(e)?e:Uw[e]||e+"_normal"}function zw(t){const e=String(t);return/(^|\/)normal_/.test(e)?null:/_normal$/i.test(e)?e.replace(/_normal$/i,""):/normal$/i.test(e)?e.replace(/normal$/i,""):null}function Hw(t){if(oa[t])return oa[t]();const e=String(t).toLowerCase();return/normal/.test(e)?xi(64,{r:.18,w:1},{r:.4,w:.2}):Mm(t)()}function Hl(t,e,n){const r=Yn(n*7919+17);let i=t;const s=[];for(let c=0;c<e;c++){const u=i*i,l=new Float32Array(u*2);for(let d=0;d<u;d++){const f=r()*Math.PI*2;l[d*2]=Math.cos(f),l[d*2+1]=Math.sin(f)}s.push({f:i,g:l,ox:c*7.31,oy:c*3.17}),i*=2}const a=(c,u,l,d,f)=>{const h=c.f,p=(u%h+h)%h,g=((l%h+h)%h*h+p)*2;return c.g[g]*d+c.g[g+1]*f},o=(c,u,l)=>{const d=(u+c.ox)*c.f,f=(l+c.oy)*c.f,h=Math.floor(d),p=Math.floor(f),m=d-h,g=f-p,y=na(m),w=na(g);return Zn(Zn(a(c,h,p,m,g),a(c,h+1,p,m-1,g),y),Zn(a(c,h,p+1,m,g-1),a(c,h+1,p+1,m-1,g-1),y),w)};return function(u,l,d){const f=d==null?s.length:Math.min(d,s.length);let h=1,p=0,m=0;for(let g=0;g<f;g++)p+=(o(s[g],u,l)*.5+.5)*h,m+=h,h*=.55;return p/m}}function Vl(t,e,n,r,i){const s=i===void 0?.55:i,a=Yn(n*7919+17),o=[];let c=t,u=r;for(let f=0;f<e;f++){const h=c*c*u,p=new Float32Array(h);for(let m=0;m<h;m++)p[m]=a();o.push({f:c,zf:u,g:p,ox:f*7.31,oy:f*3.17,oz:f*.379+.123}),c*=2,u*=2}const l=(f,h,p,m)=>{const g=(h%f.f+f.f)%f.f,y=(p%f.f+f.f)%f.f,w=(m%f.zf+f.zf)%f.zf;return f.g[(w*f.f+y)*f.f+g]},d=(f,h,p,m)=>{const g=(h+f.ox)*f.f,y=(p+f.oy)*f.f,w=m+f.oz,A=Math.floor(g),b=Math.floor(y),v=Math.floor(w),x=g-A,P=y-b,S=w-v,k=na(x),_=na(P),I=na(S),B=Zn(l(f,A,b,v),l(f,A+1,b,v),k),V=Zn(l(f,A,b+1,v),l(f,A+1,b+1,v),k),O=Zn(l(f,A,b,v+1),l(f,A+1,b,v+1),k),U=Zn(l(f,A,b+1,v+1),l(f,A+1,b+1,v+1),k);return Zn(Zn(B,V,_),Zn(O,U,_),I)};return function(h,p,m,g){const y=g==null?o.length:Math.min(g,o.length);let w=1,A=0,b=0;for(let v=0;v<y;v++)A+=d(o[v],h,p,m*o[v].zf)*w,b+=w,w*=s;return A/b}}function Wl(t,e,n){const{width:r,height:i,rgba:s}=t;if(r===e&&i===n)return t;const a=new Uint8Array(e*n*4);for(let o=0;o<n;o++){const c=(o+.5)/n*i-.5,u=Math.max(0,Math.min(i-1,Math.floor(c))),l=Math.max(0,Math.min(i-1,u+1)),d=c-Math.floor(c);for(let f=0;f<e;f++){const h=(f+.5)/e*r-.5,p=Math.max(0,Math.min(r-1,Math.floor(h))),m=Math.max(0,Math.min(r-1,p+1)),g=h-Math.floor(h),y=s[(u*r+p)*4+3],w=s[(u*r+m)*4+3],A=s[(l*r+p)*4+3],b=s[(l*r+m)*4+3],v=(y*(1-g)+w*g)*(1-d)+(A*(1-g)+b*g)*d;ft(a,(o*e+f)*4,v/255)}}return{width:e,height:n,rgba:a}}function jl(t,e,n,r,i,s,a){const o=s===void 0?1:s,c=a===void 0?200:a,u=256,l=Hl(e,n,r),d=new Uint8Array(u*u*4),f=u/2,h=u*u,p=new Float32Array(h);let m=1,g=0;for(let b=0;b<h;b++){const v=b%u,x=b/u|0,P=(v+.5)/u,S=(x+.5)/u,k=l(P+5.2,S+1.3,2)-.5,_=l(P+9.7,S+8.1,2)-.5,I=p[b]=l(P+k*.45,S+_*.45);I<m&&(m=I),I>g&&(g=I)}const y=g-m||1;for(let b=0;b<u;b++)for(let v=0;v<u;v++){const x=(p[b*u+v]-m)/y,P=Math.hypot((v+.5-f)/f,(b+.5-f)/f),S=Math.exp(-((P/.45)**2)),k=Math.pow(Math.max(0,1-P),o)*S;let _=Math.max(0,(x-(1-i))/(i||1));_=Kn(Math.min(1,_))*k,_=_<=.02?0:(_-.02)/.98,ft(d,(b*u+v)*4,_)}let w=0;for(let b=0;b<h;b++)w=Math.max(w,d[b*4+3]);if(w>0&&w<c){const b=c/w;for(let v=0;v<h;v++)d[v*4+3]=Math.round(Math.min(255,d[v*4+3]*b))}const A={width:u,height:u,rgba:d};return u===t?A:Wl(A,t,t)}function ql(t,e){const n=t,r=Hl(3,5,e??23),i=new Uint8Array(n*n*4),s=n*n,a=new Float32Array(s);let o=1,c=0;for(let f=0;f<s;f++){const h=f%n,p=f/n|0,m=(h+.5)/n,g=(p+.5)/n,y=r(m+2.1,g+4.7,2)-.5,w=r(m+6.3,g+1.9,2)-.5,A=a[f]=r(m+y*.28,g+w*.55);A<o&&(o=A),A>c&&(c=A)}const u=c-o||1;for(let f=0;f<n;f++)for(let h=0;h<n;h++){const p=(f+.5)/n,m=(h+.5)/n*2-1,g=.1+.52*Math.pow(p,1.25),y=(a[f*n+h]-o)/u,w=Me(m/(g||.01),.55)*Me(p-.58,.42);let A=Kn(Math.min(1,Math.max(0,(y-.18)/.72)))*w;A*=p<.06?p/.06:1,ft(i,(f*n+h)*4,A)}let l=0;for(let f=0;f<s;f++)l=Math.max(l,i[f*4+3]);if(l>0&&l<220){const f=220/l;for(let h=0;h<s;h++)i[h*4+3]=Math.round(Math.min(255,i[h*4+3]*f))}const d=ta({width:n,height:n,rgba:i},.08);return n===t?d:Wl(d,t,t)}function Vw(t,e,n,r){const i=new Uint8Array(t*e*4),s=t/n,a=e/r;for(let o=0;o<e;o++)for(let c=0;c<t;c++){const u=Math.floor(c/s),l=Math.floor(o/a),d=(c+.5-u*s)/s*2-1,f=(o+.5-l*a)/a*2-1,h=1-Math.max(0,f)*.45,p=Math.hypot(d/(.52*h),f/.8),m=p>=1.12?0:Me(p,.48);ft(i,(o*t+c)*4,m)}return{width:t,height:e,rgba:i}}function Am(t){const e=new Uint8Array(t*t*4),n=Yn(7),r=[];for(let i=0;i<11;i++)r.push({x:.14+n()*.72,y:.14+n()*.72,rx:.025+n()*.03,ry:.018+n()*.024,rot:n()*Math.PI});for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5)/t,o=(i+.5)/t;let c=0;for(const u of r){const l=a-u.x,d=o-u.y,f=Math.cos(u.rot),h=Math.sin(u.rot),p=(l*f+d*h)/u.rx,m=(-l*h+d*f)/u.ry,g=Me(Math.hypot(p,m),.55);g>c&&(c=g)}ft(e,(i*t+s)*4,c)}return{width:t,height:t,rgba:e}}function ko(t,e){const n=e??19,r=Yn(n),i=f=>Math.min(.86,Math.max(.14,f)),s=5+n%4,a=[];let o=i(.5+(r()-.5)*.16);for(let f=0;f<=s;f++){const h=.06+f/s*.86;f>0&&(o=i(o+(r()-.5)*.32)),a.push([o,h])}const c=[];for(let f=0;f<a.length-1;f++)c.push([a[f],a[f+1],1]);const u=1+n%2;for(let f=0;f<u;f++){const h=1+(n+f*3)%Math.max(1,a.length-2),p=a[h],m=[p];let g=p[0],y=p[1];const w=2+n%2;for(let A=0;A<w;A++)g=i(g+(r()-.5)*.36),y=Math.min(.92,y+.1+r()*.08),m.push([g,y]);for(let A=0;A<m.length-1;A++)c.push([m[A],m[A+1],.45+f*.1])}const l=new Uint8Array(t*t*4),d=Math.max(2,Math.round(t*.04));for(let f=0;f<t;f++)for(let h=0;h<t;h++){const p=(h+.5)/t,m=(f+.5)/t;let g=9,y=0;for(const[A,b,v]of c){const x=b[0]-A[0],P=b[1]-A[1],S=x*x+P*P||1e-8,k=Math.max(0,Math.min(1,((p-A[0])*x+(m-A[1])*P)/S)),_=Math.hypot(p-(A[0]+x*k),m-(A[1]+P*k));_/v<g&&(g=_/v,y=v)}const w=.95*Me(g,.012)+.3*Me(g,.05)*y;ft(l,(f*t+h)*4,Math.min(1,w)*Kr(h,f,t,d))}return{width:t,height:t,rgba:l}}function Xl(t,e){const n=new Uint8Array(t*e*4);for(let r=0;r<e;r++)for(let i=0;i<t;i++){const s=(i+.5-t/2)/(t/2),a=(r+.5-e/2)/(e/2),o=Me(s,.34)*Math.exp(-Math.max(0,-a-.05)*4.2)*(a<.1?1:Math.max(0,1-a*4)),c=Math.hypot(s/.34,(a-.42)/.3),u=c>=1?0:Me(c,.5);ft(n,(r*t+i)*4,Math.max(o,u))}return{width:t,height:e,rgba:n}}function Ww(t){return xi(t,{r:.1,w:1},{r:.3,w:.16})}function $l(t,e){const n=new Uint8Array(t*e*4);for(let r=0;r<e;r++){const i=(r+.5)/e,s=Kn(Math.min(1,Math.min(i/.08,(1-i)/.08))),a=Me(i-.46,.24)*s,o=.5*(1-Kn(Math.min(1,Math.max(0,(i-.42)/.5)))*.6);for(let c=0;c<t;c++){const u=(c+.5-t/2)/(t/2);ft(n,(r*t+c)*4,Me(Math.abs(u)/(o||.01),.5)*a)}}return{width:t,height:e,rgba:n}}function xm(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=Me(Math.hypot(a,o),.42),u=Me(Math.hypot(a-.34,o),.36),l=Math.max(0,c-u*1.08)*Kr(s,i,t,r);ft(e,(i*t+s)*4,l)}return{width:t,height:t,rgba:e}}function km(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.04));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n;let c=Me(Math.hypot(a,o),.08);for(let u=0;u<6;u++){const l=u*Math.PI/3,d=Math.cos(l),f=Math.sin(l),h=a*d+o*f,p=-a*f+o*d;if(h<0)continue;const m=Math.max(0,1.02-h/.72);c+=Me(p,.028)*Me(h,.5)*m,c+=.55*Me(p-(h-.28)*.65,.02)*Me(h-.28,.12)*m,c+=.55*Me(p+(h-.28)*.65,.02)*Me(h-.28,.12)*m,c+=.4*Me(p-(h-.48)*.7,.016)*Me(h-.48,.08)*m,c+=.4*Me(p+(h-.48)*.7,.016)*Me(h-.48,.08)*m}ft(e,(i*t+s)*4,Math.min(1,c)*Kr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Tm(t,e){const n=new Uint8Array(t*t*4),r=t/2,i=Math.max(2,Math.round(t*.04)),s=Math.abs(e|0)%3;for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=(o+.5-r)/r*1.55,u=(a+.5-r)/r*1.55,l=Math.abs(Math.abs(c)+Math.abs(u)-.55);let d=Me(l,.016);s===0?(d+=Me(c,.012)*Me(u,.38),d+=Me(u,.012)*Me(c,.38)):s===1?(d+=Me(c-u,.012)*Me(c+u,.36),d+=Me(c+u,.012)*Me(c-u,.36)):(d+=Me(Math.hypot(c,u)-.26,.014),d+=Me(c,.012)*Me(u,.22)),ft(n,(a*t+o)*4,Math.min(1,d)*Kr(o,a,t,i))}return ta({width:t,height:t,rgba:n},.03)}function Gl(t){let e=0;const n=String(t);for(let r=0;r<n.length;r++)e=e*31+n.charCodeAt(r)|0;return e}function jw(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.03)),i=1.6/t;for(let s=0;s<t;s++)for(let a=0;a<t;a++){const o=(a+.5-n)/n,c=(s+.5-n)/n,u=Math.hypot(o,c);let l=Me(u,.05)+.3*Me(u,.15);l+=.9*Me(c,i)*Math.exp(-Math.abs(o)/.3),l+=.9*Me(o,i)*Math.exp(-Math.abs(c)/.3),l*=Kr(a,s,t,r),ft(e,(s*t+a)*4,l)}return{width:t,height:t,rgba:e}}function Sm(t){const e=new Uint8Array(t*t*4),n=t/2,r=Math.max(2,Math.round(t*.03));for(let i=0;i<t;i++)for(let s=0;s<t;s++){const a=(s+.5-n)/n,o=(i+.5-n)/n,c=Math.hypot(a,o),u=Me(c,.07)+.85*Me(a,.62)*Me(o,.045)+.22*Me(a,.92)*Me(o,.018);ft(e,(i*t+s)*4,Math.min(1,u)*Kr(s,i,t,r))}return{width:t,height:t,rgba:e}}const qw=1024,Pm=64,Jn=128,Xw=[.02,.05,.09,.12,.14,.12,.09,.07,.03,.01,0];function $w(t){const e={},n=e.gen===void 0?Jn>>1:e.gen,r=e.frames===void 0?Pm:e.frames,i=e.seed===void 0?21:e.seed,s=e.freq===void 0?9:e.freq,a=e.oct===void 0?4:e.oct,o=e.ampFall===void 0?.8:e.ampFall,c=e.zCells===void 0?2:e.zCells,u=e.warp===void 0?.25:e.warp,l=e.thr===void 0?.62:e.thr,d=e.soft===void 0?.2:e.soft,f=e.gain===void 0?.85:e.gain,h=e.gamma===void 0?1.1:e.gamma,p=e.margin===void 0?.151:e.margin,m=e.envScale===void 0?.925:e.envScale,g=e.radial||Xw,y=Vl(s,a,i,c,o),w=Vl(Math.max(2,Math.round(s/2)),2,i+401,c,.55),A=Math.max(...g),b=g.map(k=>k/A),v=n/2,x=e.size===void 0?qw:e.size,P=Math.max(1,Math.round(Jn/n)),S={width:x,height:x,rgba:new Uint8Array(x*x*4),frames:[]};for(let k=0;k<r;k++){const _=k/r,I=k/8|0,V=k%8*Jn,O=I*Jn;for(let U=0;U<n;U++)for(let W=0;W<n;W++){const ie=(W+.5)/n,we=(U+.5)/n,Y=w(ie,we,_)-.5,oe=w(ie+.37,we+.11,_)-.5,he=y(ie+Y*u,we+oe*u,_),Ae=Math.hypot((W+.5-v)/v,(U+.5-v)/v),Pe=Math.min(10,Math.max(0,Ae*10)),Ce=Math.min(9,Math.floor(Pe)),Le=(b[Ce]+(b[Ce+1]-b[Ce])*(Pe-Ce))*m,Ne=Math.min(1,Math.max(0,(he-(l-d))/(2*d)));let De=Math.min(1,Math.max(0,f*Le*Ne));h!==1&&(De=Math.pow(De,h));const Re=Math.min(W,U,n-1-W,n-1-U)/n;Re<p&&(De*=Kn(Re/p));const Fe=Math.round(255*De);for(let Xe=0;Xe<P;Xe++)for(let $e=0;$e<P;$e++){const Ye=((O+U*P+Xe)*x+V+W*P+$e)*4;S.rgba[Ye]=255,S.rgba[Ye+1]=255,S.rgba[Ye+2]=255,S.rgba[Ye+3]=Fe}}S.frames.push({x:V,y:O,width:Jn,height:Jn})}return S}const Gw=[[.625,.3,.24,.476],[.618,.3,.24,.484],[.615,.3,.24,.492],[.613,.3,.24,.501],[.617,.3,.24,.54],[.626,.3,.24,.564],[.64,.3,.24,.557],[.669,.32,.22,.641],[.681,.32,.22,.611],[.699,.32,.22,.59],[.719,.32,.22,.568],[.735,.32,.22,.548],[.747,.32,.22,.54],[.743,.3,.24,.388],[.731,.3,.26,.272],[.74,.3,.26,.226],[.737,.28,.28,.118],[.73,.28,.3,.013],[.734,.28,.3,.026],[.735,.26,.32,0],[.735,.26,.32,.008],[.726,.26,.32,.045],[.707,.24,.34,.036],[.689,.24,.34,.064],[.685,.24,.34,.035],[.688,.24,.34,0],[.687,.24,.34,0],[.684,.26,.32,.009],[.703,.26,.3,0],[.7,.26,.3,0],[.706,.28,.28,0],[.707,.28,.28,0],[.692,.3,.28,0],[.686,.3,.28,0],[.68,.3,.28,0],[.674,.3,.28,0],[.669,.3,.28,0],[.664,.3,.28,0],[.661,.3,.28,0],[.649,.3,.3,0],[.641,.3,.32,0],[.673,.28,.3,0],[.662,.28,.32,0],[.684,.26,.32,0],[.694,.26,.32,0],[.705,.24,.34,0],[.717,.24,.34,.008],[.735,.24,.34,.021],[.754,.22,.36,.025],[.743,.24,.36,.135],[.748,.26,.34,.293],[.745,.26,.36,.328],[.733,.28,.34,.445],[.721,.28,.34,.464],[.705,.28,.34,.475],[.68,.26,.38,.407],[.684,.24,.38,.356],[.681,.22,.4,.266],[.703,.18,.42,.118],[.725,.14,.44,0],[.711,.16,.4,0],[.693,.18,.36,0],[.677,.2,.32,0],[.679,.22,.28,0]],Qw=[[.014,.1,.1,.004],[.018,.14,.08,.013],[.039,.16,.08,.02],[.055,.16,.06,.029],[.06,.18,.08,.038],[.073,.18,.1,.034],[.076,.18,.12,.035],[.084,.18,.12,.045],[.087,.18,.14,.049],[.096,.18,.14,.043],[.101,.2,.14,.064],[.113,.22,.12,.09],[.118,.22,.12,.098],[.119,.22,.14,.091],[.124,.22,.14,.102],[.122,.22,.16,.108],[.126,.22,.16,.129],[.129,.22,.16,.153],[.127,.22,.18,.159],[.126,.24,.18,.178],[.128,.24,.18,.183],[.123,.26,.18,.209],[.118,.26,.2,.207],[.115,.26,.22,.204],[.109,.24,.26,.188],[.109,.22,.3,.161],[.116,.16,.36,.104],[.124,.1,.42,.074],[.148,0,.48,.023],[.153,0,.48,.005],[.147,.02,.48,.002],[.135,.12,.4,0],[.136,.14,.38,0],[.139,.14,.36,0],[.141,.12,.38,.001],[.147,.12,.36,0],[.144,.16,.32,0],[.146,.16,.32,0],[.135,.22,.26,.072],[.136,.26,.22,.092],[.144,.28,.2,.053],[.139,.28,.22,.012],[.136,.3,.22,.036],[.134,.3,.22,.036],[.128,.3,.22,.027],[.113,.32,.22,.026],[.097,.32,.22,.015],[.077,.32,.24,.004],[.062,.32,.24,0],[.049,.32,.24,.001],[.038,.34,.24,.003],[.028,.34,.26,0],[.021,.34,.26,.002],[.016,.34,.26,.001],[.011,.34,.26,.001],[.007,.34,.3,0],[.007,.26,.14,.004],[.016,0,.06,.011],[.008,0,.06,.007],[.002,.28,.12,.001],[.001,.28,.1,0],[.001,.26,.08,0],[0,.26,.1,0],[0,.26,.08,0]],Yw=[[.489,.12,.06,.991],[.661,.08,.1,.651],[.714,.08,.12,.544],[.583,.14,.08,.978],[.568,.14,.1,.918],[.607,.14,.1,.876],[.616,.16,.1,.898],[.649,.16,.1,.849],[.663,.16,.1,.799],[.641,.16,.12,.658],[.657,.16,.12,.572],[.686,.14,.14,.321],[.664,.14,.16,.217],[.679,.14,.16,.12],[.695,.14,.16,.051],[.66,.14,.18,0],[.651,.14,.18,0],[.592,.16,.18,.036],[.591,.16,.18,0],[.542,.18,.18,.019],[.529,.18,.18,.016],[.528,.18,.18,0],[.513,.18,.18,0],[.48,.2,.18,.005],[.451,.2,.2,0],[.452,.2,.18,0],[.445,.2,.18,0],[.407,.22,.2,0],[.394,.22,.2,0],[.371,.22,.22,0],[.345,.24,.22,0],[.339,.24,.22,0],[.33,.24,.22,0],[.314,.26,.22,0],[.305,.26,.22,0],[.29,.26,.24,0],[.291,.26,.22,0],[.269,.28,.24,0],[.261,.28,.24,0],[.249,.28,.26,0],[.243,.28,.26,0],[.235,.3,.26,0],[.22,.3,.28,0],[.232,.3,.24,0],[.207,.32,.28,0],[.209,.32,.26,0],[.196,.32,.28,0],[.19,.34,.28,0],[.187,.34,.28,0],[.176,.34,.3,0],[.174,.34,.3,0],[.174,.36,.28,0],[.164,.36,.3,0],[.16,.36,.3,0],[.155,.38,.3,0],[.152,.38,.3,0],[.144,.38,.32,0],[.141,.38,.32,0],[.139,.4,.32,0],[.136,.4,.32,0],[.131,.4,.34,0],[.127,.42,.34,0],[.125,.42,.34,0],[.122,.42,.34,0]],Kw=[[.399,.12,.1,.755],[.782,.16,.1,.878],[.912,.24,.14,.852],[.704,.24,.24,.457],[.706,.38,.22,.173],[.586,.5,.16,0],[.444,.6,.12,.136],[.622,.16,.12,.759],[.887,.22,.16,.626],[.807,.36,.1,0],[.571,.48,.08,0],[.451,.56,.06,0],[.141,.64,.08,0],[.058,.72,.06,0]];function aa(t){const{fw:e,fh:n,cols:r,frames:i,noise:s=1,q:a=1,gate:o=0,gamma:c=1,power:u=1,seed:l=31,freq:d=5,oct:f=3,zCells:h=2,ampFall:p=.6,margin:m=.05,rgbOf:g,rows:y,gen:w}=t,A=Math.max(1,Math.ceil(i/r)),b={w:r*e,h:A*n},v=new Uint8Array(b.w*b.h*4),x=Vl(d,f,l,h,p),P=g||(()=>255),S={width:b.w,height:b.h,rgba:v,frames:[]},k=w===void 0?e>64?e>>1:e:w,_=n>64?n>>1:n,I=Math.max(1,Math.round(e/k)),B=Math.max(1,Math.round(n/_)),V=new Float32Array(k*_);for(let O=0;O<i;O++){const[U,W,ie,we]=y[O],Y=O/i;for(let Re=0;Re<_;Re++)for(let Fe=0;Fe<k;Fe++){const Xe=Math.max(0,x((Fe+.5)/k,(Re+.5)/_,Y));V[Re*k+Fe]=Xe}const oe=O%r*e,he=(O/r|0)*n,Ae=11,Pe=new Float64Array(Ae),Ce=new Float64Array(Ae),Le=new Float64Array(Ae),Ne=new Float32Array(k*_),De=Re=>Math.min(Ae-1,Math.round(Math.min(1.2,Re)*10));for(let Re=0;Re<_;Re++)for(let Fe=0;Fe<k;Fe++){const Xe=Re*k+Fe,$e=Math.hypot((Fe+.5-k/2)/(k/2),(Re+.5-_/2)/(_/2)),Ye=we*Math.exp(-(($e/.12)**2))+U*Math.exp(-((($e-W)/ie)**2)),nt=o*(1-Math.min(1,Ye)),dn=Math.pow(Math.max(0,(V[Xe]-nt)/(1-nt)),a),st=1-s+s*dn*2.2;let gt=Ye*st;u!==1&&(gt=Math.pow(Math.max(0,gt),u)),c!==1&&(gt=Math.pow(Math.min(1,Math.max(0,gt)),c)),gt=Math.min(1,Math.max(0,gt)),Ne[Xe]=gt;const Vt=De($e);Pe[Vt]+=Math.min(1,Ye),Ce[Vt]+=gt,Le[Vt]++}for(let Re=0;Re<Ae;Re++)Le[Re]>0&&(Pe[Re]/=Le[Re],Ce[Re]/=Le[Re]);for(let Re=0;Re<_;Re++)for(let Fe=0;Fe<k;Fe++){const Xe=Re*k+Fe,$e=Math.hypot((Fe+.5-k/2)/(k/2),(Re+.5-_/2)/(_/2)),Ye=De($e),nt=Math.abs(1.2-$e*10)<.001?Ae-1:Ye,dn=Pe[nt]||Pe[Ae-1],st=Ce[nt]||Ce[Ae-1];let gt=st>1e-6?Ne[Xe]*(dn/st):Ne[Xe];const Vt=Math.min(Fe,Re,k-1-Fe,_-1-Re)/k;Vt<m&&(gt*=Kn(Vt/m)),gt=Math.min(1,Math.max(0,gt));const xn=P(gt),Pt=Math.round(255*gt);for(let xt=0;xt<B;xt++)for(let tn=0;tn<I;tn++){const Mt=((he+Re*B+xt)*b.w+oe+Fe*I+tn)*4;v[Mt]=xn,v[Mt+1]=xn,v[Mt+2]=xn,v[Mt+3]=Pt}}S.frames.push({x:oe,y:he,width:e,height:n})}return S}const gs={"particle/water/ripple_single":{fw:32,fh:32,cols:7,frames:14,rows:Kw,noise:.35,q:.5,gate:.5,power:1,gamma:1,seed:31,freq:4,oct:3,zCells:4,ampFall:.6},"particle/water/splash_1":{fw:128,fh:128,cols:8,frames:64,rows:Yw,noise:1,q:.3,gate:.7,power:1,gamma:1,seed:53,freq:10,oct:4,zCells:6,ampFall:.78,gen:128},"particle/fog/fog2":{fw:128,fh:128,cols:8,frames:64,rows:Gw,noise:1,q:.8,gate:.7,power:1,gamma:1,seed:61,freq:5,oct:4,zCells:6,ampFall:.6,rgbOf:t=>Math.round(255*Math.min(1,.325+.246*t))},"particle/fog/fog3":{fw:128,fh:128,cols:8,frames:64,rows:Qw,noise:1,q:1.2,gate:.5,power:1,gamma:1,seed:71,freq:5,oct:4,zCells:12,ampFall:.6,rgbOf:t=>Math.round(255*Math.min(1,.116+1.274*t))}};function _m(t,e,n,r){const i=[];for(let s=0;s<r;s++)i.push({x:s%t*e,y:(s/t|0)*n,width:e,height:n});return i}function Em(t){const i=[23.27,11.11,14.31,18.68,6.93,15.33,8.42,10.38,17.43,4.3,16.92,13.45,16.58,8.28,22.31,13.33],s=Yn(47*7919+13),a=256,o=new Uint8Array(a*a*4),c={width:a,height:a,rgba:o,frames:[]};for(let u=0;u<16;u++){const l=5+(s()*3|0),d=s()*Math.PI*2,f=[];for(let b=0;b<l;b++)f.push(.78+.44*s());const h=b=>{let v=0;const x=f.map((S,k)=>{const _=d+k/l*Math.PI*2;return[Math.cos(_)*S*b,Math.sin(_)*S*b]}),P=(S,k)=>{let _=!1;for(let I=0,B=x.length-1;I<x.length;B=I++){const[V,O]=x[I],[U,W]=x[B];O>k!=W>k&&S<(U-V)*(k-O)/(W-O)+V&&(_=!_)}return _};for(let S=0;S<64;S++)for(let k=0;k<64;k++)P((k+.5-64/2)/(64/2),(S+.5-64/2)/(64/2))&&v++;return v/4096};let p=.05,m=1.2;for(let b=0;b<22;b++){const v=(p+m)/2;h(v)<i[u]/100?p=v:m=v}const g=(p+m)/2,y=u%4*64,w=(u/4|0)*64,A=f.map((b,v)=>{const x=d+v/l*Math.PI*2;return[Math.cos(x)*b*g,Math.sin(x)*b*g]});for(let b=0;b<64;b++)for(let v=0;v<64;v++){const x=(v+.5-32)/32,P=(b+.5-64/2)/(64/2);let S=!1;for(let _=0,I=A.length-1;_<A.length;I=_++){const[B,V]=A[_],[O,U]=A[I];V>P!=U>P&&x<(O-B)*(P-V)/(U-V)+B&&(S=!S)}const k=((w+b)*a+y+v)*4;o[k]=255,o[k+1]=255,o[k+2]=255,o[k+3]=S?255:0}c.frames.push({x:y,y:w,width:64,height:64})}return c}const Zw=1024,Ql=64,Bn=128;function Jw(t){const{gen:e=Bn>>1,frames:n=Ql,seed:r=11,puffs:i=81,spread:s=.73,sMin:a=.044,sMax:o=.15,ampMin:c=.4,ampMax:u=1,coreAmp:l=.64,coreS:d=.225,lobeBias:f=1.7,hazes:h=8,hazeAmp:p=.162,hazeSMin:m=.175,hazeSMax:g=.31,hazeSpread:y=.33,move:w=.06,pulse:A=.41,spin:b=0}=t,v=Yn(r*7919+101),x=e/2,P=[];for(let I=0;I<i+h;I++){const B=I>=i,V=(B?y:s)*Math.pow(v(),1/(2*(B?1:f))),O=v()*Math.PI*2,U=B?m+(g-m)*v():a+(o-a)*v(),W=B?p*(.6+.8*v()):c+(u-c)*v();P.push({cx:V*Math.cos(O),cy:V*Math.sin(O),s:U,amp:W,ph:v()*Math.PI*2,r1:1+(v()*2|0),r2:1+(v()*3|0),w:v()*Math.PI*2})}const S=new Float32Array(n*e*e),k=Math.PI*2,_=Math.round(b);for(let I=0;I<n;I++){const B=I/n,V=k*B,O=Math.cos(_*V),U=Math.sin(_*V),W=I*e*e;for(const ie of P){const we=x+(ie.cx*O-ie.cy*U+w*Math.cos(ie.r1*V+ie.ph))*x,Y=x+(ie.cx*U+ie.cy*O+w*Math.sin(ie.r1*V+ie.ph))*x,oe=ie.s*(1+A*.5*Math.sin(ie.r2*V+ie.w))*x,he=ie.amp*(1+A*.4*Math.sin(ie.r2*V+ie.w+1.7)),Ae=2.4*oe,Pe=Math.max(0,Math.floor(we-Ae)),Ce=Math.min(e-1,Math.ceil(we+Ae)),Le=Math.max(0,Math.floor(Y-Ae)),Ne=Math.min(e-1,Math.ceil(Y+Ae)),De=1/(oe*oe);for(let Re=Le;Re<=Ne;Re++)for(let Fe=Pe;Fe<=Ce;Fe++){const Xe=Fe+.5-we,$e=Re+.5-Y,Ye=(Xe*Xe+$e*$e)*De;Ye>5.76||(S[W+Re*e+Fe]+=he*Math.exp(-Ye))}}for(let ie=0;ie<e;ie++)for(let we=0;we<e;we++){const Y=(we+.5-x)/x,oe=(ie+.5-x)/x,he=Math.hypot(Y,oe);S[W+ie*e+we]+=l*Math.exp(-((he/d)**2))}}return{out:S,gen:e,frames:n}}function Yl(t,e){const n=e||{},r=n.gen===void 0?Bn>>1:n.gen,i=Ql,s=n.detail===void 0?.048:n.detail,a=5,o=3,c=.05,u=77,l=n.gamma===void 0?.838:n.gamma,d=n.gain===void 0?1.238:n.gain,f=n.margin===void 0?.038:n.margin,p=Jw({gen:r,frames:i,seed:11,...n}),m=Math.max(1,Math.round(Bn/r)),g=Hl(a,o,u),y=Zw,w=new Uint8Array(y*y*4),A={width:y,height:y,rgba:w,frames:[]},b=Math.PI*2,v=p.out;for(let x=0;x<i;x++){const P=x/i,S=c*Math.cos(b*P),k=c*Math.sin(b*P),_=Math.min(7,x/8|0),B=x%8*Bn,V=_*Bn,O=x*r*r;for(let U=0;U<r;U++)for(let W=0;W<r;W++){const ie=(W+.5)/r,we=(U+.5)/r,Y=v[O+U*r+W]+s*(g(ie+S,we+k)-.5)*2;let oe=Y<=0?0:Math.pow(Math.min(1,d*Y),l);const he=Math.min(W,U,r-1-W,r-1-U)/r;he<f&&(oe*=Kn(he/f));const Ae=t==="light"?Math.min(1,.8*Math.pow(oe,1.25)):.865+.108*oe,Pe=Math.round(255*Ae),Ce=Math.round(255*oe);for(let Le=0;Le<m;Le++)for(let Ne=0;Ne<m;Ne++){const De=((V+U*m+Le)*y+B+W*m+Ne)*4;w[De]=Pe,w[De+1]=Pe,w[De+2]=Pe,w[De+3]=Ce}}A.frames.push({x:B,y:V,width:Bn,height:Bn})}return A}const oa={"particle/halo_6":()=>Mw(128),"particle/normal_splash":()=>Rn(bm(256),3.2),"particle/drop_normal":()=>Rn($l(128,512),3.4),"particle/normal_ring_smooth":()=>Rn(zl(256,.55,.12),3.1),"particle/normal_pinch_rotate":()=>Rn(Bw(256),2.8),"particle/water/rain_drops_sheet_normal":()=>Rn(Em(),3.6),"particle/bubbles/bubble1normal":()=>Rn(xo(256,1),3.2),"particle/bubbles/bubble2_normal":()=>Rn(xo(256,2),3.2),"particle/sharp_halo_normal":()=>Rn(ra(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),3.4),"particle/beam/beam_0":()=>Ao(128,512,.46,!0),"particle/beam/beam_1":()=>Cw(32),"particle/beam/beam_2":()=>Ao(128,512,.22,!0),"particle/beam/beam_2_fade":()=>Ao(128,512,.24,!1),"particle/light/light_shafts_0":()=>ki(0),"particle/light/light_shafts_1":()=>ki(1),"particle/light/light_shafts_2":()=>ki(2),"particle/light/light_shafts_3":()=>ki(3),"particle/light/light_shafts_4":()=>ki(4),"particle/light/light_shafts_5":()=>ki(5),"particle/light/light_shafts_6":()=>ki(6),"particle/nature/rosepetals":()=>ym(256),"particle/nature/leaves":()=>Ot(Ut,0),"particle/nature/leaves1":()=>Ot(Ut,1),"particle/nature/leaves2":()=>Ot(Ut,2),"particle/nature/leaves3":()=>Ot(Ut,3),"particle/nature/leaves5":()=>Ot(Ut,5),"particle/nature/leaves6":()=>Ot(Ut,6),"particle/nature/leaves7":()=>Ot(Ut,7),"particle/nature/leaves8":()=>Ot(Ut,8),"particle/nature/snow":()=>km(256),"particle/halo":()=>Ew(256,[234,225,201,164,119,75,41,19,8,3,1].map(t=>t/255)),"particle/halo_1":()=>xi(256,{r:.1,w:1},{r:.3,w:.13}),"particle/halo_2":()=>xi(256,{r:.2,w:.9},{r:.44,w:.2}),"particle/halo_3":()=>ra(256,[{r:.045,w:1},{r:.13,w:.85},{r:.36,w:.15}]),"particle/halo_4":()=>xi(256,{r:.085,w:1},{r:.28,w:.12}),"particle/halo_5":()=>ra(256,[{r:.04,w:1},{r:.11,w:.8},{r:.34,w:.17}]),"particle/sharp_halo":()=>ra(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),"particle/chromaticdot":()=>Ww(128),"particle/light/flare_0":()=>Zr(256,6,.58,10,.08),"particle/light/flare_1":()=>jw(512),"particle/light/flare_2":()=>Sm(256),"particle/drop":()=>$l(128,512),"particle/nature/rain1":()=>pm({segments:120,peakMax:.42,peakPow:2.4}),"particle/nature/rain2":()=>pm({segments:120,peakMax:.55,peakPow:2.2}),"particle/water/rain_drops_sheet":()=>Em(),"particle/water/splash_1":()=>aa(gs["particle/water/splash_1"]),"particle/water/ripple_single":()=>aa(gs["particle/water/ripple_single"]),"particle/fog/fog1":()=>$w(),"particle/fog/fog2":()=>aa(gs["particle/fog/fog2"]),"particle/fog/fog3":()=>aa(gs["particle/fog/fog3"]),"particle/smoke/smoke2":()=>Yl("smoke2"),"particle/smoke/smoke2light":()=>Yl("light"),"particle/smoke/smoke1":()=>jl(512,3,5,7,.55,1.5,185),"particle/misc/wave":()=>zl(512,.72,.085),"particle/misc/star_0":()=>Zr(256,5,.62,8,.1),"particle/bubbles/bubble1":()=>xo(256,1),"particle/bubbles/bubble2":()=>xo(256,2),"particle/bubbles/bubble3":()=>Iw(1024,64,58,11776798),"particle/debris/debris1":()=>Am(128),"particle/lightning/lightning1":()=>ko(256,3),"particle/lightning/lightning2":()=>ko(256,11),"particle/lightning/lightning3":()=>ko(256,19),"particle/fire/fire1":()=>ql(256,23),"particle/fire/fire2":()=>ql(256,41),"particle/star":()=>Zr(256,4,.58,12,.09),"particle/shape/circle_wind":()=>wm(256),"particle/sickle":()=>xm(256),"particle/magic/glyph_4":()=>Tm(256,4),"@sparkle":()=>Zr(256,4,.6,16,.08),"@star":()=>Zr(256,5,.62,8,.1),"@trail":()=>Xl(128,256)};function Mm(t){const e=String(t).toLowerCase();if(/normal/.test(e)){const n=zw(t);return n?()=>Rn(Hw(n),2.8):()=>Rn(bm(128),2.6)}return/rosepetal|petal|sakura|blossom/.test(e)?()=>ym(256):/leaf|leaves|foliage/.test(e)?/leaves8/.test(e)?()=>Ot(Ut,8):/leaves7/.test(e)?()=>Ot(Ut,7):/leaves6/.test(e)?()=>Ot(Ut,6):/leaves5/.test(e)?()=>Ot(Ut,5):/leaves3/.test(e)?()=>Ot(Ut,3):/leaves2/.test(e)?()=>Ot(Ut,2):/leaves1/.test(e)?()=>Ot(Ut,1):()=>Ot(Ut,0):/circle_wind|windcircle/.test(e)?()=>wm(256):/fog|cloud|mist|vapor/.test(e)?()=>jl(512,4,5,5,.4,.9,210):/smoke/.test(e)?()=>jl(512,3,5,8,.55,1.5,185):/beam|shaft|ray|godray/.test(e)?()=>Ao(128,512,.3,!0):/flare/.test(e)?()=>Sm(256):/bubble/.test(e)?()=>gm(256,1):/ring|wave/.test(e)?()=>zl(512,.72,.085):/fire|flame|ember|ash/.test(e)?()=>ql(256,Gl(e)):/sickle|crescent|moon/.test(e)?()=>xm(256):/glyph|magic|rune/.test(e)?()=>Tm(256,Gl(e)):/snowflake|雪花|snow/.test(e)?()=>km(256):/流星|meteor|shooting/.test(e)?()=>Xl(128,256):/star|星/.test(e)?()=>Zr(256,5,.62,8,.1):/sparkle|glint|twinkle/.test(e)?()=>Zr(256,4,.6,16,.08):/rain_drops_sheet|drops_sheet/.test(e)?()=>Vw(256,512,2,4):/drop|rain/.test(e)?()=>$l(128,512):/debris|dirt|rock/.test(e)?()=>Am(128):/lightning|bolt|arc/.test(e)?()=>ko(256,Gl(e)):/note|music/.test(e)?()=>Zr(256,4,.55,8,.12):/trail|streak/.test(e)?()=>Xl(128,256):()=>xi(256,{r:.12,w:1},{r:.3,w:.15})}function ev(t){if(Cn.has(t))return Cn.get(t);let e=null;const n=Ol.get(t);if(n)try{e=n()}catch{e=null}if(!e&&vo)try{e=vo(t)}catch{e=null}if(!e&&oa[t])try{e=oa[t]()}catch{e=null}if(!e)try{e=Mm(t)()}catch{e=null}e||(e=xi(256,{r:.12,w:1},{r:.3,w:.15}));for(const r of tv)if(r.re.test(t)){nv(e,r.band);break}return Cn.set(t,e),e}const tv=[{re:/^particle\/(light|beam|fire)\/(?!beam_1)/,band:.18},{re:/^particle\/bubbles\/(?!.*normal)(?!bubble3)/,band:.18},{re:/^particle\/(misc|shape)\//,band:.18},{re:/^particle\/(star|sickle)/,band:.18},{re:/^particle\/drop$/,band:.08},{re:/^@(star|sparkle|trail)$/,band:.18}];function nv(t,e){if(!t||!t.rgba)return t;const n=t.width,r=t.height,i=Math.max(2,Math.round(Math.min(n,r)*e)),s=t.rgba;for(let a=0;a<r;a++)for(let o=0;o<n;o++){const c=Math.min(o,a,n-1-o,r-1-a);if(c>=i)continue;const u=Kn(c/i),l=(a*n+o)*4+3;s[l]=Math.round(s[l]*u)}return t}function rv(t){return typeof t=="string"&&t.indexOf("particle/")===0}function iv(t,e,n){const r=Yn(n),i=new Float32Array(e*e);for(let o=0;o<i.length;o++)i[o]=r();const s=new Float32Array(t*t),a=t/e;for(let o=0;o<t;o++){const c=o/a,u=Math.floor(c),l=c-u,d=l*l*(3-2*l),f=u%e*e,h=(u+1)%e*e;for(let p=0;p<t;p++){const m=p/a,g=Math.floor(m),y=m-g,w=y*y*(3-2*y),A=g%e,b=(g+1)%e,v=i[f+A],x=i[f+b],P=i[h+A],S=i[h+b],k=v+(x-v)*w,_=P+(S-P)*w;s[o*t+p]=k+(_-k)*d}}return s}function sv(t=256){const e=[[4,.5,2654435761],[8,.25,2246822507],[16,.125,3266489909],[32,.0625,668265263],[64,.03125,374761393]],n=new Float32Array(t*t);let r=0;for(const[s,a,o]of e){const c=iv(t,s,o);for(let u=0;u<n.length;u++)n[u]+=c[u]*a;r+=a}const i=new Uint8Array(t*t*4);for(let s=0;s<n.length;s++){let a=n[s]/r;a=Math.min(1,Math.max(0,(a-.3)/.52)),a=a*a*(3-2*a);const o=Math.round(a*255),c=s*4;i[c]=o,i[c+1]=o,i[c+2]=o,i[c+3]=255}return{width:t,height:t,rgba:i}}function av(t){return t==="util/clouds_256"?(Cn.has(t)||Cn.set(t,sv(256)),Cn.get(t)):t==="util/black"?(Cn.has(t)||Cn.set(t,{width:1,height:1,rgba:new Uint8Array([0,0,0,255])}),Cn.get(t)):null}const ov=Object.freeze(Object.defineProperty({__proto__:null,RING_SHEETS:gs,bilinearResize:Wl,buildBuiltinParticleTexture:ev,buildBuiltinUtilTexture:av,builtinParticleFrames:Rw,convertParticleNormalFormat:Dw,convertParticleTexFormat:Fw,isBuiltinParticleTextureName:rv,isPackedNormalTexture:Nw,listBuiltinParticleTextureNames:_w,particleNormalNameForAlbedo:Ow,prepareParticleNormalTexture:Lw,resetParticleTextureFactories:Pw,rgbaLooksLikeAlbedo:vm,ringSheetAtlas:aa,setParticleTextureFactory:Tw,setParticleTextureProvider:Sw,smokePuffAtlas:Yl},Symbol.toStringTag,{value:"Module"})),cv=["util/white","util/black","util/noflow","util/flatnormal","util/noise","util/perlin_256","util/uniform_256","util/fur","util/clouds_256"],lv=new Set(["util/flatnormal","util/fur","util/noflow","util/noise"]);function uv(t){return lv.has(t)}function To(t){let e=t>>>0;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function fv(t,e,n,r){const i=To((n^Math.imul(r|0,2654435761))>>>0),s=new Float32Array(e*e);for(let c=0;c<s.length;c++)s[c]=i();const a=new Float32Array(t*t),o=t/e;for(let c=0;c<t;c++){const u=c/o,l=Math.floor(u),d=u-l,f=d*d*d*(d*(d*6-15)+10),h=l%e*e,p=(l+1)%e*e;for(let m=0;m<t;m++){const g=m/o,y=Math.floor(g),w=g-y,A=w*w*w*(w*(w*6-15)+10),b=y%e,v=(y+1)%e,x=s[h+b],P=s[h+v],S=s[p+b],k=s[p+v],_=x+(P-x)*A,I=S+(k-S)*A;a[c*t+m]=_+(I-_)*f}}return a}function Cm(t,e,n){const r=new Float32Array(t*t);let i=0;for(const[s,a]of e){const o=fv(t,s,s*2654435761^2246822507,n);for(let c=0;c<r.length;c++)r[c]+=o[c]*a;i+=a}for(let s=0;s<r.length;s++)r[s]/=i;return r}function Im(t,e,n){let r=0,i=0;for(let l=0;l<t.length;l++)r+=t[l],i+=t[l]*t[l];const s=t.length,a=r/s,o=Math.sqrt(Math.max(1e-9,i/s-a*a)),c=n/o,u=new Uint8ClampedArray(s);for(let l=0;l<s;l++)u[l]=e+(t[l]-a)*c;return u}function Rm(t,e){const n=new Uint8Array(e*e*4);for(let r=0;r<e*e;r++)n[r*4]=t[0][r],n[r*4+1]=t[1][r],n[r*4+2]=t[2][r],n[r*4+3]=t[3][r];return n}function So(t,e,n,r,i){const s=new Uint8Array(t*t*4);for(let a=0;a<t*t;a++)s[a*4]=e,s[a*4+1]=n,s[a*4+2]=r,s[a*4+3]=i;return s}const Kl=new Map;function dv(){const e=To(1852795251),n=new Uint8Array(256*256*4);for(let r=0;r<256*256;r++)n[r*4]=e()*256,n[r*4+1]=e()*256,n[r*4+2]=e()*256,n[r*4+3]=e()*256;return{width:256,height:256,rgba:n}}function hv(){const e=[[4,.55],[8,.27],[16,.13],[32,.05]],r=[[94.8,21.5,1],[108.4,26.2,2],[145.2,23.6,3],[112,32,4]].map(([i,s,a])=>Im(Cm(256,e,a),i,s));return Rm(r,256)}function mv(){const e=To(1970170214),n=new Uint8Array(256*256*4);for(let r=0;r<256*256;r++)for(let i=0;i<4;i++)n[r*4+i]=e()<.5?0:1+Math.floor(e()*254);return{width:256,height:256,rgba:n}}function pv(){const e=To(1718972961),n=new Uint8Array(16384*4);for(let r=0;r<16384;r++){const i=e()<.413?0:Math.floor(21+Math.pow(e(),.62)*234);n[r*4]=i,n[r*4+1]=i,n[r*4+2]=i,n[r*4+3]=255}return{width:128,height:128,rgba:n}}function gv(){const n=Im(Cm(256,[[4,.42],[8,.24],[16,.16],[32,.11],[64,.07]],5),126,52.7);return{width:256,height:256,rgba:Rm([n,n,n,n],256)}}let Zl=null;function yv(t){Zl=typeof t=="function"?t:null}function bv(t){if(Zl)try{const n=Zl(t);if(n&&n.rgba)return n}catch{}if(Kl.has(t))return Kl.get(t);let e=null;switch(t){case"util/white":e={width:32,height:32,rgba:So(32,255,255,255,255)};break;case"util/black":e={width:32,height:32,rgba:So(32,0,0,0,255)};break;case"util/noflow":e={width:32,height:32,rgba:So(32,127,127,0,255)};break;case"util/flatnormal":e={width:16,height:16,rgba:So(16,255,127,0,127)};break;case"util/noise":e=dv();break;case"util/perlin_256":e={width:256,height:256,rgba:hv()};break;case"util/uniform_256":e=mv();break;case"util/fur":e=pv();break;case"util/clouds_256":e=gv();break}return e&&Kl.set(t,e),e}const wv=Object.freeze(Object.defineProperty({__proto__:null,SYSTEM_UTIL_TEXTURES:cv,buildSystemUtilTexture:bv,isNomipSystemTexture:uv,setSystemTextureProvider:yv},Symbol.toStringTag,{value:"Module"})),Po=64,Jl=2,vv=256,eu={ferro_fluid:{r8:!1,stops:[[0,0,0,0],[4,0,0,1],[8,0,0,0],[12,0,0,0],[16,0,0,0],[20,0,0,0],[24,0,0,0],[28,0,0,0],[32,0,0,5],[36,0,0,12],[40,9,3,23],[41,234,233,235],[42,243,242,243],[44,159,156,165],[46,74,69,85],[48,14,8,28],[52,0,0,9],[56,0,0,0],[60,0,0,0],[63,0,0,1]]},fire:{r8:!1,stops:[[0,130,14,14],[4,142,11,12],[8,160,5,10],[12,180,0,7],[16,202,0,4],[20,223,0,1],[24,241,0,0],[28,254,0,0],[32,255,23,3],[36,255,63,10],[40,255,105,17],[44,255,126,20],[48,255,146,24],[52,254,164,27],[56,252,180,30],[60,251,194,32],[63,250,202,34]]},fire_2:{r8:!1,stops:[[0,255,255,255],[2,255,255,255],[3,0,0,0],[4,0,0,0],[8,0,0,0],[12,0,0,0],[16,0,0,0],[20,0,0,0],[21,0,0,0],[22,52,33,16],[24,233,149,71],[26,248,152,72],[28,194,108,50],[30,142,66,28],[32,135,60,24],[36,135,60,22],[40,144,60,22],[44,155,62,22],[48,166,66,23],[52,166,66,23],[56,166,66,22],[60,118,47,15],[62,79,31,10],[63,32,12,4]]},fire_3:{r8:!1,stops:[[0,18,10,10],[4,21,8,8],[8,26,6,6],[12,42,5,5],[16,102,10,10],[20,134,17,17],[24,130,23,23],[26,145,20,21],[28,182,5,13],[32,253,0,0],[36,255,39,2],[40,255,103,8],[44,254,167,19],[47,250,202,32],[48,248,219,56],[50,243,225,145],[51,241,225,169],[52,244,215,108],[53,250,204,34],[56,252,212,64],[60,254,231,147],[63,255,243,200]]},ghost_flame:{r8:!1,stops:[[0,0,0,0],[4,0,0,0],[8,0,0,0],[12,2,0,1],[16,209,28,126],[17,183,24,110],[18,191,25,115],[20,74,10,44],[22,0,0,0],[24,0,0,0],[28,0,0,0],[32,0,0,0],[36,0,0,0],[40,19,2,20],[43,201,26,207],[44,231,60,235],[47,255,216,253],[48,223,226,252],[49,216,255,255],[52,25,244,255],[53,0,220,247],[56,0,103,117],[60,0,42,47],[63,0,8,9]]},ice:{r8:!1,stops:[[0,114,190,255],[4,117,191,255],[8,121,193,255],[12,126,196,255],[16,132,199,255],[20,138,202,255],[24,145,205,255],[28,152,208,255],[32,158,211,255],[36,164,214,255],[40,170,216,255],[44,175,218,255],[48,178,220,255],[52,181,220,255],[56,182,220,255],[58,181,219,255],[60,146,194,255],[63,107,168,255]]},iridescent:{r8:!1,stops:[[0,254,164,142],[4,254,164,139],[8,239,174,149],[12,210,187,172],[16,177,196,198],[20,134,189,226],[24,90,183,254],[28,75,175,254],[32,70,170,255],[36,80,159,255],[40,104,142,255],[44,139,126,255],[48,179,126,255],[52,164,130,253],[56,119,135,255],[60,102,162,255],[63,93,175,255]]},neon:{r8:!1,stops:[[0,0,186,255],[4,0,186,255],[8,10,178,255],[12,40,153,255],[16,79,120,255],[20,122,83,255],[24,165,49,255],[28,205,21,255],[32,238,3,255],[36,255,1,248],[40,255,17,221],[44,255,47,184],[48,255,86,142],[52,255,129,99],[56,255,170,58],[60,255,205,24],[63,255,224,5]]},rainbow:{r8:!1,stops:[[0,255,0,0],[4,255,0,94],[8,255,0,213],[10,255,0,253],[12,224,0,255],[16,117,0,255],[20,16,0,255],[22,0,13,255],[24,0,57,255],[28,0,170,255],[32,0,255,255],[36,0,255,165],[40,0,255,49],[42,0,255,7],[44,26,255,0],[48,144,255,0],[52,248,255,0],[54,255,232,0],[56,255,187,0],[60,255,80,0],[63,255,14,0]]},swamp:{r8:!1,stops:[[0,60,36,50],[4,60,36,50],[8,60,36,50],[12,60,36,50],[16,58,46,61],[20,54,65,82],[24,50,87,108],[28,45,112,135],[32,42,135,159],[36,40,154,176],[40,41,167,182],[44,45,175,180],[48,51,179,171],[52,59,181,157],[56,66,181,141],[60,73,181,128],[63,76,182,121]]},swipe_dual:{r8:!1,stops:[[0,0,0,0],[2,0,0,0],[4,76,76,76],[7,224,224,224],[8,255,255,255],[9,255,255,255],[10,0,0,0],[11,0,0,0],[12,245,245,245],[16,218,218,218],[20,183,183,183],[24,143,143,143],[28,102,102,102],[32,63,63,63],[36,29,29,30],[40,4,4,5],[44,0,0,0],[48,0,0,0],[52,0,0,0],[56,0,0,0],[60,0,0,0],[63,0,0,0]]},swipe_wide:{r8:!1,stops:[[0,0,0,0],[2,0,0,0],[3,255,255,255],[4,255,255,255],[8,233,233,233],[12,201,201,201],[16,163,163,163],[20,122,122,122],[24,82,82,82],[28,45,45,45],[32,16,16,16],[36,0,0,0],[40,0,0,0],[44,0,0,0],[48,0,0,0],[52,0,0,0],[56,0,0,0],[60,0,0,0],[63,0,0,0]]},toon:{r8:!0,stops:[[0,0,0,0],[4,0,0,0],[8,0,0,0],[12,0,0,0],[16,0,0,0],[20,0,0,0],[24,0,0,0],[28,0,0,0],[32,0,0,0],[36,0,0,0],[39,0,0,0],[40,255,255,255],[44,255,255,255],[48,255,255,255],[52,255,255,255],[56,255,255,255],[60,255,255,255],[63,255,255,255]]},toon_smooth:{r8:!0,stops:[[0,0,0,0],[4,0,0,0],[8,0,0,0],[12,0,0,0],[16,1,1,1],[20,3,3,3],[24,6,6,6],[28,11,11,11],[32,17,17,17],[36,28,28,28],[38,34,34,34],[39,77,77,77],[40,165,165,165],[41,184,184,184],[44,197,197,197],[48,213,213,213],[52,227,227,227],[56,238,238,238],[60,248,248,248],[63,253,253,253]]}},tu={blend_gradient:{invert:!1,stops:[[0,0],[8,6],[16,14],[24,23],[32,33],[40,44],[48,56],[56,68],[64,81],[72,95],[80,109],[88,123],[96,137],[104,151],[112,165],[120,178],[128,191],[136,203],[144,215],[152,226],[160,235],[168,244],[176,251],[181,254]]},blend_gradient_reverse:{invert:!0,stops:[[0,0],[8,6],[16,14],[24,23],[32,33],[40,44],[48,56],[56,68],[64,81],[72,95],[80,109],[88,123],[96,137],[104,151],[112,165],[120,178],[128,191],[136,203],[144,215],[152,226],[160,235],[168,244],[176,251],[181,254]]}},nu=new Map;let ru=null;function Av(t){ru=typeof t=="function"?t:null}function xv(){return[...Object.keys(eu).map(t=>"gradient/gradient_"+t),...Object.keys(tu).map(t=>"gradient/"+t)]}function kv(t){return Bm(t)!==null}function Bm(t){if(typeof t!="string")return null;let e=/^gradient\/gradient_([a-z0-9_]+)$/.exec(t);return e&&eu[e[1]]?{kind:"ramp",spec:eu[e[1]]}:(e=/^gradient\/(blend_gradient(?:_reverse)?)$/.exec(t),e&&tu[e[1]]?{kind:"radial",spec:tu[e[1]]}:null)}function _o(t){return t<0?0:t>255?255:t}function Tv(t,e){if(e<=t[0][0])return[t[0][1],t[0][2],t[0][3]];const n=t[t.length-1];if(e>=n[0])return[n[1],n[2],n[3]];for(let r=0;r<t.length-1;r++){const i=t[r],s=t[r+1];if(e>=i[0]&&e<=s[0]){const a=s[0]===i[0]?0:(e-i[0])/(s[0]-i[0]);return[i[1]+(s[1]-i[1])*a,i[2]+(s[2]-i[2])*a,i[3]+(s[3]-i[3])*a]}}return[n[1],n[2],n[3]]}function Sv(t,e){if(e<=t[0][0])return t[0][1];const n=t[t.length-1];if(e>=n[0])return n[1];for(let r=0;r<t.length-1;r++){const i=t[r],s=t[r+1];if(e>=i[0]&&e<=s[0]){const a=s[0]===i[0]?0:(e-i[0])/(s[0]-i[0]);return i[1]+(s[1]-i[1])*a}}return n[1]}function Pv(t){const e=new Uint8Array(Po*Jl*4);for(let n=0;n<Jl;n++){const r=n*Po;for(let i=0;i<Po;i++){const[s,a,o]=Tv(t.stops,i),c=(r+i)*4;e[c]=_o(Math.round(s)),e[c+1]=_o(Math.round(a)),e[c+2]=_o(Math.round(o)),e[c+3]=255}}return{width:Po,height:Jl,rgba:e}}function _v(t){const e=vv,n=new Uint8Array(e*e*4),r=(e-1)/2;for(let i=0;i<e;i++)for(let s=0;s<e;s++){const a=Math.sqrt((s-r)*(s-r)+(i-r)*(i-r));let o=Sv(t.stops,a);t.invert&&(o=255-o);const c=(i*e+s)*4;n[c]=n[c+1]=n[c+2]=_o(Math.round(o)),n[c+3]=255}return{width:e,height:e,rgba:n}}function Ev(t){const e=Bm(t);if(!e)return null;const n=nu.get(t);if(n)return n;if(ru)try{const i=ru(t);if(i&&i.rgba)return nu.set(t,i),i}catch{}const r=e.kind==="radial"?_v(e.spec):Pv(e.spec);return nu.set(t,r),r}const Mv=Object.freeze(Object.defineProperty({__proto__:null,buildBuiltinGradientTexture:Ev,isBuiltinGradientTextureName:kv,listBuiltinGradientTextureNames:xv,setGradientTextureProvider:Av},Symbol.toStringTag,{value:"Module"})),Fm=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Jr(t,e,n){const r=n||new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)r[i*4+s]=t[s]*e[i*4]+t[4+s]*e[i*4+1]+t[8+s]*e[i*4+2]+t[12+s]*e[i*4+3];return r}function Dm(t){const e=[];for(let r=0;r<4;r++)e.push([t[r],t[4+r],t[8+r],t[12+r],0,0,0,0]),e[r][4+r]=1;for(let r=0;r<4;r++){let i=r;for(let o=r+1;o<4;o++)Math.abs(e[o][r])>Math.abs(e[i][r])&&(i=o);const s=e[r];e[r]=e[i],e[i]=s;const a=e[r][r];if(Math.abs(a)<1e-12)return Float32Array.from(Fm);for(let o=0;o<8;o++)e[r][o]/=a;for(let o=0;o<4;o++){if(o===r)continue;const c=e[o][r];if(c!==0)for(let u=0;u<8;u++)e[o][u]-=c*e[r][u]}}const n=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i][4+r];return n}function iu(t,e,n,r,i,s,a,o,c,u){const l=u||new Float32Array(16),d=Math.cos(r),f=Math.sin(r),h=Math.cos(i),p=Math.sin(i),m=Math.cos(s),g=Math.sin(s);return l[0]=m*h*a,l[1]=g*h*a,l[2]=-p*a,l[3]=0,l[4]=(m*p*f-g*d)*o,l[5]=(g*p*f+m*d)*o,l[6]=h*f*o,l[7]=0,l[8]=(m*p*d+g*f)*c,l[9]=(g*p*d-m*f)*c,l[10]=h*d*c,l[11]=0,l[12]=t,l[13]=e,l[14]=n,l[15]=1,l}function Pr(t,e){const n=[];for(;e<t.byteLength;){const i=t.getUint8(e++);if(i===0)break;n.push(i)}let r="";try{r=new TextDecoder("utf-8").decode(new Uint8Array(n))}catch{r=String.fromCharCode.apply(null,n)}return{value:r,next:e}}function Eo(t,e,n=0){const r=[];for(let i=0;i<e.length;i++)r.push(e.charCodeAt(i));e:for(let i=n;i<=t.length-r.length;i++){for(let s=0;s<r.length;s++)if(t[i+s]!==r[s])continue e;return i}return-1}function Cv(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=String.fromCharCode.apply(null,Array.from(t.subarray(0,8)));if(!n.startsWith("MDLV"))throw new Error("\u4E0D\u662F MDL: "+n);const r=Pr(e,21),s=parseInt(n.slice(4),10)>=23?[{lenOff:32,stride:80,uv:72,bone:40,weight:56},{lenOff:32,stride:84,uv:76,bone:44,weight:60,formatMarker:25231374},{lenOff:32,stride:48,uv:40,bone:-1,weight:-1}]:[{lenOff:8,stride:52,uv:44,bone:12,weight:28},{lenOff:4,stride:52,uv:44,bone:12,weight:28},{lenOff:32,stride:80,uv:72,bone:40,weight:56}];let a=null,o=0,c=0;for(const Y of s){const oe=r.next+Y.lenOff;if(oe+4>t.byteLength)continue;const he=e.getUint32(oe,!0);if((Y.formatMarker===void 0||e.getUint32(r.next+28,!0)===Y.formatMarker)&&he>0&&he%Y.stride===0&&oe+4+he<=t.byteLength){a=Y,o=he,c=oe;break}}if(!a)throw new Error("\u9876\u70B9\u533A\u957F\u5EA6\u5F02\u5E38\uFF08"+n+"\uFF0C\u5DF2\u8BD5 stride "+s.map(Y=>Y.stride).join("/")+"\uFF09");const u=c+4,l=o/a.stride,d=new Float32Array(l*3),f=new Float32Array(l*2),h=new Float32Array(l*4),p=new Float32Array(l*4);for(let Y=0;Y<l;Y++){const oe=u+Y*a.stride;if(d[Y*3]=e.getFloat32(oe,!0),d[Y*3+1]=e.getFloat32(oe+4,!0),d[Y*3+2]=e.getFloat32(oe+8,!0),f[Y*2]=e.getFloat32(oe+a.uv,!0),f[Y*2+1]=e.getFloat32(oe+a.uv+4,!0),a.bone>=0&&a.weight>=0)for(let he=0;he<4;he++)h[Y*4+he]=e.getUint32(oe+a.bone+he*4,!0),p[Y*4+he]=e.getFloat32(oe+a.weight+he*4,!0);else h[Y*4]=0,p[Y*4]=1}const m=e.getUint32(u+o,!0),g=u+o+4,y=l>65535&&m%4===0,w=y?m/4:m/2,A=y?new Uint32Array(w):new Uint16Array(w);if(y)for(let Y=0;Y<w;Y++)A[Y]=e.getUint32(g+Y*4,!0);else for(let Y=0;Y<w;Y++)A[Y]=e.getUint16(g+Y*2,!0);const b=Rv(t,e),v=b.bones,x=Bv(e,b,v.length),P=Nv(t,e,v.length),S=Uv(t,e,v),k=Iv(t,e,v.length),_=[],I=[],B=[];if(v.length>0){const Y=v.map((he,Ae)=>{const Pe=he.matrix,Ce=Math.hypot(Pe[0],Pe[1]),Le=Math.hypot(Pe[4],Pe[5]);return B[Ae]=Float32Array.from([Pe[12],Pe[13],Pe[14],0,0,Math.atan2(Pe[1],Pe[0]),Ce||1,Le||1,Pe[10]||1]),Float32Array.from(Pe)});for(let he=0;he<v.length;he++){const Ae=B[he],Pe=v[he].matrix;Math.hypot(Ae[0]-Pe[12],Ae[1]-Pe[13])>.001&&(Y[he]=iu(Ae[0],Ae[1],Ae[2],Ae[3],Ae[4],Ae[5],Ae[6],Ae[7],Ae[8],new Float32Array(16)))}const oe=[];for(let he=0;he<v.length;he++){const Ae=v[he].parent;oe[he]=Ae>=0&&Ae<he?Jr(oe[Ae],Y[he]):Float32Array.from(Y[he])}for(let he=0;he<v.length;he++)_[he]=Float64Array.from(Dm(oe[he]));if(S){const he=[];for(let Ae=0;Ae<v.length;Ae++){const Pe=v[Ae].parent;he[Ae]=Pe>=0&&Pe<Ae?Jr(he[Pe],S[Ae]):Float32Array.from(S[Ae])}for(let Ae=0;Ae<v.length;Ae++)I[Ae]=Jr(he[Ae],_[Ae])}}let V=1/0,O=-1/0,U=1/0,W=-1/0;for(let Y=0;Y<l;Y++){const oe=d[Y*3],he=d[Y*3+1];oe<V&&(V=oe),oe>O&&(O=oe),he<U&&(U=he),he>W&&(W=he)}let ie=null,we=null;return x&&x.local.length===v.length&&(ie=x.local.map(Y=>Float32Array.from([Y[12],Y[13],Y[14],0,0,Math.atan2(Y[1],Y[0]),Math.hypot(Y[0],Y[1])||1,Math.hypot(Y[4],Y[5])||1,Y[10]||1])),x.permutationIdentity||(we=x.permutation)),{magic:n,materialPath:r.value,vertexCount:l,positions:d,uvs:f,boneIdx:h,weights:p,indexCount:w,indexType:y?"u32":"u16",indices:A,bones:v,staticPoseTRS:ie,staticPoseLocal:x?x.local:null,staticPosePermutation:we,staticPoseAt:x?x.at:-1,animations:P,animBound:Lv(P,v),invBindWorld:_,bindTRS:B.length>0?B:null,attachments:k.length>0?k:null,restCorrection:I.length>0?I:null,bounds:{minX:V,maxX:O,minY:U,maxY:W}}}function Iv(t,e,n){const r=Eo(t,"MDAT");if(r<0)return[];const i=e.getUint16(r+13,!0);if(i<=0||i>256)return[];const s=[];let a=r+15;for(let o=0;o<i&&!(a+2>t.length);o++){const c=e.getUint16(a,!0),u=Pr(e,a+2);if(u.next+64>t.length)break;const l=new Float32Array(16);for(let d=0;d<16;d++)l[d]=e.getFloat32(u.next+d*4,!0);c<n&&s.push({bone:c,name:u.value,matrix:l}),a=u.next+64}return s}function Rv(t,e){const n=Eo(t,"MDLS");if(n<0)return{bones:[],sectionStart:-1,recordsEnd:-1,nextOff:-1,permutation:null};const r=e.getUint32(n+13,!0);if(r<=0||r>1024)return{bones:[],sectionStart:n,recordsEnd:-1,nextOff:-1,permutation:null};const i=h=>Number.isFinite(h[12])&&Number.isFinite(h[13])&&Number.isFinite(h[14])&&Math.abs(Math.hypot(h[0],h[1])-1)<.05&&Math.abs(Math.hypot(h[4],h[5])-1)<.05,s=()=>{const h=[];let p=n+17,m=!0;for(let g=0;g<r;g++){if(p+77>e.byteLength)return{bones:h,ok:!1,end:-1};const y=e.getUint32(p+1,!0),w=e.getInt32(p+5,!0),A=new Float32Array(16);for(let v=0;v<16;v++)A[v]=e.getFloat32(p+13+v*4,!0);const b=Pr(e,p+77);(!(w===-1||w>=0&&w<r)||!i(A))&&(m=!1),h.push({id:y,name:"",parent:w>=0&&w<r?w:-1,matrix:A}),p=b.next}return{bones:h,ok:m,end:p}},a=(h,p)=>({bones:h,sectionStart:n,recordsEnd:p,nextOff:e.getUint32(n+9,!0),permutation:null}),o=s();if(o.ok)return a(o.bones,o.end);const c=h=>{const p=Math.min(h+80,e.byteLength-76);for(let m=h;m<=p;m++){const g=e.getUint32(m,!0),y=e.getInt32(m+4,!0),w=e.getUint32(m+8,!0);if(g>=1e5||!(y===-1||y>=0&&y<r)||w!==64)continue;const A=new Float32Array(16);for(let b=0;b<16;b++)A[b]=e.getFloat32(m+12+b*4,!0);if(i(A)&&!(m<=h||t[m-1]!==0))return{id:g,parent:y,matrix:A,head:m,nameStart:h}}return null},u=[];let l=n+17,d=!0;for(let h=0;h<r;h++){const p=c(l);if(!p){d=!1;break}let m="",g=p.nameStart,y=p.head-1;for(;g<y&&t[g]===0;)g++;for(;y>g&&t[y-1]===0;)y--;if(y>g){const A=new TextDecoder("utf-8",{fatal:!1}).decode(t.subarray(g,y));/^[\x20-\x7e\u3000-\u9fff\uff00-\uffefA-Za-z0-9 _.-]*$/.test(A)&&(m=A)}u.push({id:p.id,name:m,parent:p.parent,matrix:p.matrix});const w=p.head+12+64;l=w<e.byteLength&&t[w]===123?Pr(e,w).next:w}return d&&u.length===r&&u.every(h=>h.parent===-1||h.parent>=0&&h.parent<r)&&u.every(h=>i(h.matrix))?a(u,l):a(o.bones,o.end)}function Bv(t,e,n){if(!e||n<=0||!(e.recordsEnd>0&&e.nextOff>e.recordsEnd))return null;const r=1+4*n,i=76*n,s=64*n,a=[],o=e.nextOff-r-i-9-s;o>=e.recordsEnd&&a.push(o);for(let u=e.recordsEnd;u<Math.min(e.recordsEnd+32,e.nextOff-s);u++)a.includes(u)||a.push(u);const c=u=>{if(!(Number.isFinite(u[12])&&Number.isFinite(u[13]))||Math.abs(u[15]-1)>.001||Math.abs(u[3])>.001||Math.abs(u[7])>.001||Math.abs(u[11])>.001)return!1;const l=(d,f,h)=>Math.hypot(u[d],u[f],u[h]);return Math.abs(l(0,1,2)-1)<.05&&Math.abs(l(4,5,6)-1)<.05&&Math.abs(l(8,9,10)-1)<.05};for(const u of a){if(u<0||u+s>e.nextOff)continue;const l=[];let d=!0;for(let m=0;m<n;m++){const g=new Float32Array(16);for(let y=0;y<16;y++)g[y]=t.getFloat32(u+m*64+y*4,!0);if(!c(g)){d=!1;break}l.push(g)}if(!d)continue;const f=[],h=e.nextOff-r;if(h>=u+s)for(let m=0;m<n;m++)f.push(t.getUint32(h+1+m*4,!0));const p=f.length===n&&f.every((m,g)=>m===g);return{local:l,permutation:f.length===n?f:null,permutationIdentity:p,at:u}}return null}function Fv(t,e,n){const r=Math.min(t.byteLength-24,n);for(let i=e;i<r;i++){if(t.getUint32(i+4,!0)!==0)continue;const s=Pr(t,i+8);if(!s.value||s.value.length>64)continue;const a=Pr(t,s.next);if(!a.value||a.value.length>16)continue;const o=t.getFloat32(a.next,!0);if(!(o>0&&o<=240))continue;const c=t.getUint32(a.next+4,!0);if(c<=0||c>1e5)continue;const u=t.getUint32(a.next+12,!0);if(!(u<=0||u>1024))return i}return-1}function Dv(t,e,n){const r=[],i=Math.min(t.byteLength,n,e+64);let s=e,a=0;for(;s<i&&t.getUint8(s)!==123&&a++<64;)s++;if(s>=i||t.getUint8(s)!==123)return{events:r,next:e};const o=Math.min(t.byteLength,n,e+8192);for(let c=0;c<64&&s<o&&t.getUint8(s)===123;c++){const u=Pr(t,s);let l=null;try{l=JSON.parse(u.value)}catch{l=null}if(!l||typeof l!="object"||!Number.isFinite(Number(l.frame))||typeof l.name!="string")break;r.push({frame:Number(l.frame),name:l.name}),s=u.next;let d=s,f=0;for(;d<o&&t.getUint8(d)!==123&&f<8;)d++,f++;if(f<8&&d<o&&t.getUint8(d)===123){s=d;continue}break}return{events:r,next:s}}function Nv(t,e,n){const r=Eo(t,"MDLA");if(r<0)return[];let i=r+9;const s=e.getUint32(i,!0);i+=4;const a=e.getUint32(i,!0);if(i+=4,a<=0||a>256)return[];const o=[];for(let c=0;c<a&&!(i+16>e.byteLength);c++){const u=e.getUint32(i,!0);i+=8;const l=Pr(e,i);i=l.next;const d=Pr(e,i);if(i=d.next,i+16>e.byteLength)break;const f=e.getFloat32(i,!0);i+=4;const h=e.getUint32(i,!0);i+=8;const p=e.getUint32(i,!0);if(i+=4,p>1024)break;const m=[];for(let A=0;A<p&&!(i+8>e.byteLength);A++){i+=4;const b=e.getUint32(i,!0);i+=4;const v=Math.floor(b/36);if(i+b>e.byteLength)break;const x=new Float32Array(v*9);for(let P=0;P<v;P++){const S=i+P*36;for(let k=0;k<9;k++)x[P*9+k]=e.getFloat32(S+k*4,!0)}i+=b,m.push({frameCount:v,keyframes:x})}const g=s>0&&s<=e.byteLength?s:e.byteLength,y=Dv(e,i,g);m.length>0&&h>0&&f>0&&o.push({id:u,name:l.value,mode:d.value,fps:f,frameCount:h,duration:h/f,tracks:m,events:y.events});const w=Fv(e,y.next,g);if(w<0)break;i=w}return o}function Lv(t,e){let n=0,r=0;for(const i of t)for(let s=0;s<i.tracks.length;s++){const a=i.tracks[s];if(!a)continue;const o=e[s],c=o?o.matrix[12]:0,u=o?o.matrix[13]:0,l=a.keyframes;for(let d=0;d<a.frameCount;d++){const f=Math.abs(l[d*9]-c),h=Math.abs(l[d*9+1]-u);f>n&&(n=f),h>r&&(r=h)}}return{x:n,y:r}}function Uv(t,e,n){if(n.length===0)return null;const r=Eo(t,"MDLE");if(r<0)return null;const i=r+8+1+4+4;if(i+n.length*64>e.byteLength)return null;const s=[];for(let a=0;a<n.length;a++){const o=new Float32Array(16);for(let c=0;c<16;c++)o[c]=e.getFloat32(i+a*64+c*4,!0);s.push(o)}return s}function Ov(t,e,n,r){const i=t.frameCount;if(i===0)return r[0]=0,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=0,r[6]=1,r[7]=1,r[8]=1,r;const s=n*e.fps;let a,o,c;if(e.mode==="loop"){const h=Math.max(1,i-1),p=(s%h+h)%h;a=Math.floor(p),o=(a+1)%i,c=p-a}else if(e.mode==="mirror"){const h=Math.max(1,i-1),p=h*2;let m=(s%p+p)%p;m>h&&(m=p-m),a=Math.floor(m),o=Math.min(a+1,i-1),c=m-a}else{const h=Math.min(Math.max(s,0),i-1);a=Math.floor(h),o=Math.min(a+1,i-1),c=h-a}const u=t.keyframes,l=a*9,d=o*9,f=1-c;for(let h=0;h<9;h++)if(h>=3&&h<=5){let p=u[d+h]-u[l+h];p>Math.PI?p-=2*Math.PI:p<-Math.PI&&(p+=2*Math.PI),r[h]=u[l+h]+p*c}else r[h]=u[l+h]*f+u[d+h]*c;return r}function Nm(t,e,n){const r=t.bindTRS&&t.bindTRS[e];if(r)return n.set(r),n;const i=t.bones[e].matrix;return n[0]=i[12],n[1]=i[13],n[2]=i[14],n[3]=0,n[4]=0,n[5]=Math.atan2(i[1],i[0]),n[6]=Math.hypot(i[0],i[1])||1,n[7]=Math.hypot(i[4],i[5])||1,n[8]=i[10]||1,n}function zv(t,e,n){const r=t.staticPoseTRS&&t.staticPoseTRS[e];return r?(n.set(r),n):Nm(t,e,n)}function su(t,e,n,r){const i=t.bones,s=i.length;if(s===0)return null;const a=!!(r&&r.size>0);if(!t._skin||t._skin.length!==s*16){t._skin=new Float32Array(s*16),t._local=[],t._world=[],t._tmp=new Float32Array(16),t._tmp2=new Float32Array(16);for(let p=0;p<s;p++)t._local.push(new Float32Array(16)),t._world.push(new Float32Array(16))}const o=Array.isArray(n)&&n.length>0,c=[];if(o)for(const p of n){if(p.visible===!1||p.visible===0||p.playing===!1)continue;const m=t.animations.find(g=>g.id===p.animation);m&&c.push({anim:m,additive:!!p.additive,blend:typeof p.blend=="number"?p.blend:1,rate:typeof p.rate=="number"?p.rate:1})}const u=!(t.animations&&t.animations.length)&&!!(t.staticPoseTRS&&t.staticPoseTRS.length===s);let l=!1;if(c.length===0&&!o){const p=t.animations[0];p?c.push({anim:p,additive:!1,blend:1,rate:1}):l=!a&&!u}const d=t._trsBase||(t._trsBase=new Float32Array(9)),f=t._trsAcc||(t._trsAcc=new Float32Array(9)),h=t._trsSmp||(t._trsSmp=new Float32Array(9));for(let p=0;p<s;p++){u?zv(t,p,d):Nm(t,p,d),f.set(d);let m=!1,g=0,y=!1,w=!1;const A=t._addDelta||(t._addDelta=new Float32Array(9));A.fill(0);for(const v of c){const x=v.anim.tracks[p];if(!x||!x.keyframes.length)continue;Ov(x,v.anim,e*v.rate,h);const P=v.blend;if(v.additive){const S=x.keyframes;if(!y&&!w){for(let k=0;k<9;k++)f[k]=S[k];w=!0}for(let k=0;k<9;k++){let _=h[k]-S[k];if(k>=3&&k<=5)_>Math.PI?_-=2*Math.PI:_<-Math.PI&&(_+=2*Math.PI);else if(k>=6&&(!(Math.abs(S[k])>.001)||Math.abs(h[k])>3&&Math.abs(S[k])<1.5))continue;A[k]+=_*P}g+=P}else{y=!0;for(let S=0;S<9;S++)f[S]=f[S]*(1-P)+h[S]*P}m=!0}if(g>1)for(let v=0;v<9;v++)A[v]/=g;if(g>0)for(let v=0;v<9;v++)f[v]+=A[v];const b=a?r.get(p):void 0;b&&(f[0]=b[0],f[1]=b[1],f[2]=b[2],m=!0),m?iu(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],t._local[p]):iu(d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8],t._local[p])}for(let p=0;p<s;p++){const m=i[p].parent;m>=0&&m<p?Jr(t._world[m],t._local[p],t._world[p]):t._world[p].set(t._local[p])}for(let p=0;p<s;p++)Jr(t._world[p],t.invBindWorld[p],t._tmp),t._skin.set(t._tmp,p*16);return l?null:t._skin}function Lm(t,e){return!t||!t.invBindWorld||!(e>=0&&e<t.invBindWorld.length)?null:Dm(t.invBindWorld[e])}function Hv(t,e){return Jr(t,e)}function Um(t,e){if(!t||!t.attachments||typeof e!="string"||e===""||!t._world)return null;for(const n of t.attachments)if(n.name===e)return n.bone<0||n.bone>=t._world.length?null:Jr(t._world[n.bone],n.matrix);return null}function Om(t,e){if(!t||!t.attachments||typeof e!="string"||e==="")return null;for(const n of t.attachments){if(n.name!==e)continue;const r=Lm(t,n.bone);return r?Jr(r,n.matrix):null}return null}function Vv(t,e){if(!t||!t.uvs||!t.positions||!e)return!1;const n=e[0],r=e[1];if(!(n>0&&r>0)||t.vertexCount<3)return!1;const i=Math.min(t.vertexCount,48),s=Math.max(1,t.vertexCount/i|0);let a=0,o=0;for(let c=0;c<t.vertexCount;c+=s){const u=t.positions[c*3],l=t.positions[c*3+1],d=Math.abs(t.uvs[c*2]-(u+n/2)/n),f=Math.abs(t.uvs[c*2+1]-(r/2-l)/r);a+=Math.max(d,f),o++}return o>0&&a/o<.001}function au(t,e,n){const r=t&&t.angles&&t.angles[2]||0,i=t&&t.scale?t.scale[0]:1,s=t&&t.scale?t.scale[1]:1,a=r,o=Math.cos(a),c=Math.sin(a),u=e*i,l=n*s;return[u*o-l*c,u*c+l*o]}function Wv(t){const e=new Map,n=new Map;for(const s of t){if(!s||s.id===void 0||s.id===null||(e.set(s.id,s),s.parentId===void 0||s.parentId===null))continue;const a=n.get(s.parentId);a?a.push(s):n.set(s.parentId,[s])}const r=(s,a)=>{const o=n.get(s.id);if(o)for(const c of o)a.push(c),r(c,a)},i=[];for(const s of t){const a=s&&s.attachment;if(typeof a!="string"||a==="")continue;const o=e.get(s.parentId);if(!o||!o.puppet)continue;const c=Om(o.puppet,a);if(!c)continue;const u=c[12],l=c[13],f=!(o.puppet.animations&&o.puppet.animations.length)&&!o.puppet.staticPoseTRS&&o.puppet.magic==="MDLV0019"&&Vv(o.puppet,o.size)?[0,0]:au(o,u,l),h=[];r(s,h),s.origin[0]+=f[0],s.origin[1]+=f[1];for(const p of h)p.origin[0]+=f[0],p.origin[1]+=f[1];s.parallaxDepth=o.parallaxDepth?o.parallaxDepth.slice():null;for(const p of h)p.parallaxDepth=s.parallaxDepth?s.parallaxDepth.slice():null;s.attachBindDelta=[f[0],f[1]],i.push({layer:s,parent:o,name:a,bindX:u,bindY:l,desc:h})}for(const s of i){s.baseX=s.layer.origin[0],s.baseY=s.layer.origin[1],s.subtree=[{layer:s.layer,x:s.layer.origin[0],y:s.layer.origin[1]}];for(const a of s.desc)s.subtree.push({layer:a,x:a.origin[0],y:a.origin[1]});for(const a of s.subtree)a.layer.attachBase||(a.layer.attachBase=[a.x,a.y])}return i}function jv(t,e,n){if(!t||t.length===0)return;const r=new Set,i=[];for(const o of t){const c=o.parent&&o.parent.puppet;if(!c){i.push(null);continue}if(!r.has(c)){r.add(c);const l=typeof n=="function"?n(o.parent):null;su(c,e,o.parent.animationLayers,l)}const u=Um(c,o.name);if(!u){i.push(null);continue}i.push(au(o.parent,u[12]-o.bindX,u[13]-o.bindY))}const s=o=>{const c=o.layer.attachBase;return c||[o.x,o.y]},a=new Set;for(const o of t){const c=o.subtree||[{layer:o.layer,x:o.baseX,y:o.baseY}];for(const u of c){if(a.has(u.layer))continue;a.add(u.layer);const l=s(u);u.layer.origin[0]=l[0],u.layer.origin[1]=l[1]}}for(let o=0;o<t.length;o++){const c=t[o],u=i[o],l=c.subtree||[{layer:c.layer,x:c.baseX,y:c.baseY}];if(u)for(const d of l)d.layer.origin[0]+=u[0],d.layer.origin[1]+=u[1]}}const qv=128,Mo=24;function Xv(t){const e=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS)||256,n=Math.floor((e-32)/4);return Math.max(Mo,Math.min(qv,n))}const $v=t=>`#version 300 es
425
532
  in vec3 a_pos;
426
533
  in vec2 a_uv;
427
534
  in vec4 a_bone;
@@ -429,6 +536,7 @@ in vec4 a_weight;
429
536
  uniform mat4 u_mvp;
430
537
  uniform mat4 u_skin[${t}];
431
538
  uniform int u_boneCount;
539
+ uniform float u_keepZ;
432
540
  out vec2 v_uv;
433
541
  void main() {
434
542
  vec4 p = vec4(a_pos, 1.0);
@@ -445,9 +553,9 @@ void main() {
445
553
  }
446
554
  }
447
555
  vec4 local = total > 0.0 ? skinned / total : p;
448
- gl_Position = u_mvp * vec4(local.xy, 0.0, 1.0);
556
+ gl_Position = u_mvp * vec4(local.xy, local.z * u_keepZ, 1.0);
449
557
  v_uv = a_uv;
450
- }`,vb=`#version 300 es
558
+ }`,Gv=`#version 300 es
451
559
  precision mediump float;
452
560
  in vec2 v_uv;
453
561
  uniform sampler2D u_tex;
@@ -456,7 +564,7 @@ out vec4 fragColor;
456
564
  void main() {
457
565
  vec4 t = texture(u_tex, v_uv);
458
566
  fragColor = t * u_color;
459
- }`;function kb(t){const e=(u,l)=>{const f=t.createShader(u);if(t.shaderSource(f,l),t.compileShader(f),!t.getShaderParameter(f,t.COMPILE_STATUS))throw new Error("MDL \u7740\u8272\u5668\u7F16\u8BD1\u5931\u8D25: "+t.getShaderInfoLog(f));return f};let n=bb(t),r=null;for(;;){const u=t.createProgram();let l=!1;try{t.attachShader(u,e(t.VERTEX_SHADER,wb(n))),t.attachShader(u,e(t.FRAGMENT_SHADER,vb)),t.bindAttribLocation(u,0,"a_pos"),t.bindAttribLocation(u,1,"a_uv"),t.bindAttribLocation(u,2,"a_bone"),t.bindAttribLocation(u,3,"a_weight"),t.linkProgram(u),l=!!t.getProgramParameter(u,t.LINK_STATUS)}catch{l=!1}if(l){r=u;break}if(t.deleteProgram(u),n<=Pa)throw new Error("MDL \u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25\uFF08\u9AA8\u6570\u5DF2\u964D\u5230 "+Pa+"\uFF09");n=Math.max(Pa,n>>1)}const i=n,s={mvp:t.getUniformLocation(r,"u_mvp"),tex:t.getUniformLocation(r,"u_tex"),skin:t.getUniformLocation(r,"u_skin"),boneCount:t.getUniformLocation(r,"u_boneCount"),color:t.getUniformLocation(r,"u_color")},a=new Float32Array(i*16);for(let u=0;u<i;u++)a.set(Ld,u*16);const o=new WeakMap;function c(u){let l=o.get(u);if(l)return l;const f=t.createVertexArray();t.bindVertexArray(f);const d=u.vertexCount,h=new Float32Array(d*13);for(let w=0;w<d;w++){const y=w*13;h[y]=u.positions[w*3],h[y+1]=u.positions[w*3+1],h[y+2]=u.positions[w*3+2],h[y+3]=u.uvs[w*2],h[y+4]=u.uvs[w*2+1];for(let b=0;b<4;b++)h[y+5+b]=u.boneIdx[w*4+b],h[y+9+b]=u.weights[w*4+b]}const p=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,p),t.bufferData(t.ARRAY_BUFFER,h,t.STATIC_DRAW);const m=52;t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,t.FLOAT,!1,m,0),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,t.FLOAT,!1,m,12),t.enableVertexAttribArray(2),t.vertexAttribPointer(2,4,t.FLOAT,!1,m,20),t.enableVertexAttribArray(3),t.vertexAttribPointer(3,4,t.FLOAT,!1,m,36);const g=t.createBuffer();return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,g),t.bufferData(t.ELEMENT_ARRAY_BUFFER,u.indices,t.STATIC_DRAW),t.bindVertexArray(null),l={vao:f,vbuf:p,ibuf:g},o.set(u,l),l}return{gl:t,prog:r,maxBones:i,upload(u){c(u)},draw(u,l,f,d){const h=c(l);t.useProgram(r),t.bindVertexArray(h.vao),t.activeTexture(t.TEXTURE0);const p=f.overrideTex||(d&&d.glTex?d.glTex:d);t.bindTexture(t.TEXTURE_2D,p),t.uniform1i(s.tex,0),t.uniformMatrix4fv(s.mvp,!1,u);const m=f.color||[1,1,1,1];t.uniform4f(s.color,m[0],m[1],m[2],m[3]);const g=Lc(l,f.time||0,f.animLayers,f.boneOverrides),w=Math.min(l.bones.length,i);g&&w>0?(t.uniformMatrix4fv(s.skin,!1,g.subarray(0,w*16)),t.uniform1i(s.boneCount,w)):(t.uniformMatrix4fv(s.skin,!1,a),t.uniform1i(s.boneCount,0)),f.blending==="additive"?(t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE)):f.blending==="normal"?t.disable(t.BLEND):(t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA));const y=l.indexType==="u32"?t.UNSIGNED_INT:t.UNSIGNED_SHORT;t.drawElements(t.TRIANGLES,l.indexCount,y,0),t.bindVertexArray(null)}}}const Ab=Object.freeze(Object.defineProperty({__proto__:null,applyAttachmentBindOrigins:pb,attachmentBind:Hd,attachmentWorld:zd,bindWorldOf:Od,computeSkinMatrices:Lc,createMDLRenderer:kb,followAttachments:gb,mat4MulOut:mb,parentMeshToWorldDelta:Uc,parseMDL:ib},Symbol.toStringTag,{value:"Module"}));function xb(t={},e={}){const n=typeof t.setTimeout=="function"?t.setTimeout:null,r=typeof t.clearTimeout=="function"?t.clearTimeout:null,i=typeof t.setInterval=="function"?t.setInterval:null,s=typeof t.clearInterval=="function"?t.clearInterval:null,a=typeof e.onError=="function"?e.onError:null,o=new Set,c=g=>{const w=Number(g);return Number.isFinite(w)&&w>0?w:0},u=g=>()=>{try{g()}catch(w){a&&a(w,"timer")}},l=(g,w)=>{const y=()=>{g.fired||(g.fired=!0,o.delete(y),w&&g.handle!=null&&w(g.handle))};return y.handle=null,y.valueOf=()=>typeof g.handle=="number"?g.handle:0,y};function f(g,w){if(typeof g!="function")return l({fired:!0,handle:null},null);const y={fired:!1,handle:null},b=l(y,r);return o.add(b),y.handle=n?n(u(()=>{y.fired=!0,o.delete(b),g()}),c(w)):null,b.handle=y.handle,b}function d(g,w){if(typeof g!="function")return l({fired:!0,handle:null},null);const y={fired:!1,handle:null},b=l(y,s);return o.add(b),y.handle=i?i(u(g),c(w)):null,b.handle=y.handle,b}function h(g){if(typeof g=="function"){g();return}r&&g!=null&&r(g)}function p(g){if(typeof g=="function"){g();return}s&&g!=null&&s(g)}function m(){for(const g of[...o])g();o.clear()}return{setTimeout:f,setInterval:d,clearTimeout:h,clearInterval:p,dispose:m,pendingCount:()=>o.size}}const Tb=Object.freeze(Object.defineProperty({__proto__:null,createEngineTimers:xb},Symbol.toStringTag,{value:"Module"}));function Sb(t){let e=t>>>0;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function _a(t,e){const n=Math.floor(t),r=t-n,i=a=>{const o=Math.sin((a*127.1+e*311.7)*43758.5453)*43758.5453;return(o-Math.floor(o))*2-1},s=r*r*(3-2*r);return i(n)*(1-s)+i(n+1)*s}const Pb=32,_b=112,Vd=60/_b,Wd=3.2;function Eb(t){const e=new Float32Array(16),n=new Float32Array(16),r=new Float32Array(16);for(let i=0;i<16;i++)e[i]=i%4===0?1:i%4===2?.38+t()*.15:t()<.08?.5:0,n[i]=i%8===4?1:t()<.06?.6:0,r[i]=i%2===1?.5+t()*.4:i%4===0?.25:t()<.3?.3:0;return{kick:e,snare:n,hat:r}}function jd(t=20260830){const e=Sb(t),n=Eb(e),r=new Float32Array(64);for(let y=0;y<64;y++)r[y]=e()*64;const i=64,s=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),c=new Float32Array(i),u=new Float32Array(i),l=new Float32Array(i),f=new Float32Array(32),d=new Float32Array(32),h=new Float32Array(16),p=new Float32Array(16),m={left64:u,right64:l,left32:f,right32:d,left16:h,right16:p,preL64:o,preR64:c,level:0,silent:!1};function g(y,b){const v=b.length/y.length;for(let k=0;k<y.length;k++){let A=0;const T=Math.floor(k*v),S=Math.floor((k+1)*v);for(let P=T;P<Math.max(T+1,S);P++)A+=b[P];y[k]=A/Math.max(1,S-T)}}function w(y){const b=y/Vd,v=b*4,k=(Math.floor(v)%16+16)%16,A=v-Math.floor(v),T=Math.exp(-A*Vd*14),S=y%Pb,P=S>=27&&S<29,M=S>=29?(S-29)/3:0,B=S>=24&&S<27?1-(S-24)/3:0,N=P?0:M>0?M*M:B>0?0:1,O=P?0:B>0?.35:1,q=n.kick[k]*T*N,H=(n.snare[k]*T+n.hat[k]*T*.7)*N,G=n.hat[k]*T*N,Y=M>0?Math.pow(M,3)*(.4+.6*Math.abs(_a(v*2,7))):0;let J=0;for(let ne=0;ne<i;ne++){const fe=ne/i,Ne=Math.pow(1-fe*.85,1.6),Qe=O*(.5+.3*_a(b*.5+r[ne]*.05,ne%8)),Ve=O*(.5+.3*_a(b*.53+r[ne]*.05+31.7,ne%8+16));let Fe=Qe*(.35+.65*fe),Le=Ve*(.35+.65*fe);if(fe<.2){const ve=q*(1-fe/.2);Fe+=ve,Le+=ve}if(fe>=.12&&fe<.62){const ve=1-Math.abs(fe-.34)/.28;ve>0&&(Fe+=H*.55*ve,Le+=H*.35*ve)}if(fe>=.45){const ve=(fe-.45)/.55;Le+=G*.5*ve,Fe+=G*.3*ve}Fe+=Y*.5,Le+=Y*.5,Fe*=Ne,Le*=Ne;const Tt=Fe,Xe=Le;Fe=Math.min(1,Fe*Wd),Le=Math.min(1,Le*Wd);const It=.06+fe*.2,Ue=_a(b*.13+ne*.35,11)*It;let We=Math.min(1,Math.max(0,Fe*(1-Ue))),Oe=Math.min(1,Math.max(0,Le*(1+Ue)));const it=P?.012:0;s[ne]=Math.max(it,We),a[ne]=Math.max(it,Oe),o[ne]=Math.max(it,Math.max(0,Tt*(1-Ue))),c[ne]=Math.max(it,Math.max(0,Xe*(1+Ue))),ne<48&&(J+=(s[ne]+a[ne])*.5)}return u.set(s),l.set(a),g(f,s),g(d,a),g(h,s),g(p,a),m.level=Math.min(1,J/(48*1.2)),m.silent=P,m}return{update:w,snapshot:m,bands:i}}function Cb(t,e){for(const n of t.values()){qd(n.left,e.left64),qd(n.right,e.right64);for(let r=0;r<n.average.length;r++)n.average[r]=(n.left[r]+n.right[r])*.5}}function qd(t,e){const n=e.length/t.length;for(let r=0;r<t.length;r++){let i=0;const s=Math.floor(r*n),a=Math.max(s+1,Math.floor((r+1)*n));for(let o=s;o<a;o++)i+=e[o];t[r]=i/(a-s)}}const Ea="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAA7J0lEQVR42u2d2XIcSZZY412mqYUbiIVYSBY3cKni1kWyyCKLxTZTd9u0pBlNz9L9JzMvmv4NfYn6s/ScsgQIEEBmRPhy7/Xr7ufhvIxNkwlWIs7x6+ERw3/9ZnMBAAAAfTHwjwAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAFBtAGwtAAAAoC8IAAAAAAIAAAAACAAAAABoNAC+3VoAAABAXxAAAAAABAAAAAAQAAAAAEAAAAAAQCMB8Hffbi0AAACgLwgAAAAAAgAAAAAIAAAAAGg1ALYXAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAoB8Cl7QUAAAD0xfB3l3YWAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAACAcAF9durEAAACAviAAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAAqg2AyzcWAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAFQXA7gIAAAD6ggAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAO0A2FsAAABAXxAAAAAAXQbAlb0FAAAA9AUBAAAAQAAAAABAFwHw9ZW9BQAAAPQFAQAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAngNgfwEAAAB9QQAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAngLg6v4CAAAA+oIAAAAAIAAAAACAAAAAAIBWA+BgAQAAAH1BAAAAABAAAAAAQAAAAAAAAQAAAAAEAAAAABAAAAAAQAAAAAAAAQAAAACOAuCbqwcLAAAA6AsCAAAAgAAAAAAAAgAAAABaDYCbCwAAAOgLAgAAAIAAAAAAAAIAAAAAGg2AazcXAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAOAqAG4tAAAAoC8IAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAAbANg49YCAAAA+mL4ZuP2AgAAAPqCAAAAAOgxAL7duL0AAACAviAAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAwDoDvFgAAANAXBAAAQCL/+183zsG/CRAAAAANyf3//Z//ksz//fdvT/+c373a5d8WCAAAAI/Cz5F9DEwNgAAAACjAcjX+n4bCn5sS/CcxAAQAAIAeS9EuhetB/MQAEAAAAJ2s9mMgBEA3AK5/twAAaJGl+D2v9sND4Dr/PUEcAgAAED8hAAQAAEDdLCXZmvgJASAAAAAmVv2ti//izYJHzxXgvz0QAADQKy2O+5kGAAEAADC66t/rVvyr04A9vhMQGwB3FgAAtdHDXn8sxxHAdwPCIAAAoDp6HvmHTAP4jgABAADInwgAIAAAoF7Y7ycCgAAAAOQPRAAQAACA/IEIgOgAuHT9zgIAwCPIXy4C+D7BRQgAAHALN/wRAUAAAADyByIACAAAQP6Q9Ojgf7vOdwwIAADwx1JQiFr/iYF814AAAAA/N/295qY/K/i+AQEAAG5AzNwPAKYBcHcBAFAa9v1L3Q/Ad69XhkubdxcAACVh9F/wfoDXe3wHO4UAAIDiIOLCWwF8BwkAAABruOvfwxRgn+8iAQAAwOq/y1MBfBcJAAAAK7jxz9kNgXwnCQAAAP0b//YRL1MAIAAAoL+9/02k624KsMl3kwAAAGDvnykAEAAAAKz+mQIAAQAAwOq/Tf7GcwEIAAAAVv998nueC0AAAABI8zeO/rENAF4C4N4CAMAKBFvLzYB8V1uHAAAAMxj/17YNwHeWAAAAEIDxf23bAHxnCQAAAMb/bAMAAQAAEMvvefQvAQAEAACw/w9sAwABAABd7P9fQqoEABAAAMD+P7ANAAQAADS+/3+ATAkAcBcAW/cWAACasP9f8/MADvgON8pweeveAgBAEwKg7vsA+A63CQEAAAQAEAB9BsD9BQCAJoi09gDgO9wiBAAAEAAwyvL4Jt9hAgAAgADoEL7DBAAAAAFAAAABAABAABAAQAAAABAABAAQAAAABAABAAQAABAAQAAAAQAABAAQAEAAAAABAAQAEAAAQAAAAQAEAAAQAEAAAAEAAAQAmL0L4M9bfIfbDYAHCwAATZbPk0emdfLXowDgO9wiBAAAqLOUCDIlAIAAAAACAAgAIAAAgAAAvzcA8v1tNwC2HywAALRBppUGAN/dZiEAAIAAgLUsb97ku0sAAABkwUmASvf/+e4SAAAAOXAfQH38/s1NvrsEAABAHkuZIFX2/4EAAADuAwD2/4EAAAC2AYD9fyAAAKBJ/sA2AON/IAAAgG0AYPwPRQPgcAEAYAXbALWM//mutg4BAACm/OEntgH8j//5nnYRAFe2DxcAAJb87T94KJDn1T/f0T4gAADAHLYB/PKHn27xHSUAAAD0QLYOb/77j0t8NwkAAACmAKz+gQAAAGAKwOofCAAAAJkpwDbyZfUPBAAAcCIAWP0DAQAAXbBceSJhVv9AAAAAUwAwPfe/zXeQAAAA4IZARv/QTwDsHC4AAErDVkCh0T/fvW4Zruw8XAAAeICtAOPRP9+5riEAAIAI6HH0z3eNAOAfAQA8wVaAPnzPgAAAACKgy31/vmNAAACAU3hKIPIHAgAAuB8AkD8QAADQVwRcRuDZN/1d5rsEBAAAEAHIH4AAAAAigLP+QAAAABABrez53+Y7AwQAALR0RPA2gkf+QAAAABEAyB8IAADoKgLYEuBmP8gKgEcLAIBa+etfeGDQ8t+A7wLEQgAAQPX0uiWwXPUfj/z5DgABAABMA1j1AxAAANDdNOBt2/cGHO/1898ZCAAAgC5C4Gjc/5ZxPxAAAABdhADiB7UAuHrj0QIAoHWWEv3rX3Yq2uPf4b8bqEIAAEB3LOXqcSqw/EyIHwgAAIAOYgDpAwEAAOBkm0AzCJZ//pLl38W/uQzXD54ttu+8PmXvwfvFzSe/zeLsn7eEAAAA6C4KvjuV9gmhkv8i++/4txQR/fNTIecKPpVlXLQSBQQAAAC4pLTsY6cFFQbA4wUAAEBpahF+yISghn9vAgAAACoX/qdVHmey8me2FwMEAAAAmHCyh59+k1644A8yCI+DuG2C5c9PAAAAQFfSzxK+guRF4yAiCJbx4yUECACAikenMfDvBv5H++uFf+CclBjwsD1AAAA4F7zEmeaQI01HI8qbz/n3h+TvbPx3tU7hS8dAqRAgAACcyF5T9LlxQBiAjPTbE35cDMxsDRj/nhEAANZ7ojc/3wh1+L7KY05EAdKP++72Jf3ZGJiZCliGAAEAYCh9GQl/ykBhUnD4niBA+rPSt5Ptr8KUmQos/70JAIAupS94njnqrPMn4Sej8T1A+jVIvkwYhISA5u8RAQAgzE609D8VO+6k/SCUE5b/JjsEQRXfXX/SDxTyI2UUg2AuBJb/TTQmbAQAgNBqP1z847J3ewPTaBgQBC18b31Jv7DoRaJAJwSkf2cIAIDMC2jYxbONG6EIgt5i1UL6lcg+OQjktwWkpgHD1RtPFgAQR5j4S94IVc+T0aaDgO+aBCf/nu6lnyngfQVKxUDYNCDvezFc3X2yAIAwgsXf8XGnA80g4DsY/D3dSX0Sn8qUSlb4+w7IiwGZEDi9NyDxe0IAAARdUF/MiP/8aukATIJg+d+F7+fx93Mn6dkSn9xLP0/UHxNRCoLcEBj5nUmNAAIAYIbplZS2+Os50lQyCJbi62lKcPKzpj1Myrf0bQT/UTUO4mNAZhpAAABYiV/04pkgbdEjTGXjQDoILkZBzZOCk9X9TtaDpIz381WE/9EpmTGQGgKj04AXBACAzrhf6iLq9KiTkyjQCIJ1YeBpYnD2M+U/Jlr71Im29AXE/DADpSCQDIEvvxvpEUAAACSs+j3d+ewjDEoFwSeVRxuflfEJmwlThM0zq/eLyH7uT66lryb8hwUQiAHxEEjcEiAAAD5fqHXE38j5ZmdRcFN5SuCfT0bPlnAi/YfOSYyB0hFAAED3hIz7sy+cFRx30o+COp9a6Fn2ZjeeinxfGxJ+VgzohMDUlsDY9IoAgK5X/evln3px1VwtVXLe2UkQHBR4AZL4Wx5NHxVdWPoPG6VUCKz5Tq+LAAIAOt3rfyO46o+/cO67OO7k5elotkcR096QmBILM3/OzOco8srcaqX/SxR7n4n739nFgFYELK975wLg2u6TBUBPyK364y6e9R11MogCR88mOHis/Orl4i9/Kix9RdnvGSAWBbkTgcDfkbEtgeX17+RaSABAN4zf6Kcn/nrPNudHQQtBUDe/NiB9e9HnRYFEDNhFwHBt9/sFQOvs3H0jsOqXEL+z406GUUAQ+F/ll5e+b+HHBYFlCMRvCSwjgACA5pka+UuKv7m7n6sLgl8RfnXSFxT+oSJWMZASAjHTgAsRQABAs4yO/FNX/Rrib+6Ik7cg+LUP2Zd4Ep+A9N2JXikKokJAcRpwMQIIAOhI/jEj/1Txd3jcyVMQPPL7AiTR90KoPFNCS/oZwj+sCOkYyJoGhN0XQAAAI39t8auI95cE6npcqt3zCKwjQfnFT9KnTiylLyLjD4LoBYFUCKRsCZxEAAEA7ctfaNUfdQFVFLz8USaDSPAWBGJvShRE4GfZL3pG31L6HwrjIQTytwQIAGhj5H9r3VP9Qkf+pcX/i6u7n03CwNPRQ4tQUPg84g+RspJ+dbIXjILcEBDeEiAAoAH5v1Qb+euIv86jTqpR8KjSKDDEh/AtpP+hAXJDQHAaMBEBBAAgfxPxKwlf6QhT8SgweKxx/aK3PGaqKX0dCe9m4CEGcqYBoREwXNv7fgFQI2sf7pM58pcVf2XHnZoKgo9+3pAo/tKnjz6lX2CVPyvzB4moxEH879++cggQAFAly1+oLPmnrvojLpxNHXdqIgjkwsCGEk+N9Cl9ccE/kI0DsRgwngYQANCA/A1W/dLiP2yAZoKgZBwIfOaHXqUvLPxkab+PJC8IioVAQgQQANCP/GdX/SkXV23pOzzWVEMQPPxY4YuWrJ4c6W8/P0/2740JDwKNENiPCoHpCBiu7f2wAKgBSfnnr/oDL6DV3/3cUBDUFgZKD45yKX2XohcIgugYiA2BuGnAxesgAQDuSb/TP0T+CuLv4riTTRSYP82waskLHDVV/O7Gr/LfV8p0DCT/filsCRAA0KD8f02Tf8BFNe/i+aFhGpoQVIv2k/i0pf++QXKnAvO/N5O/CzMRQABAXfJ/HCj/2JG/mvjLn2m2O+9sHwT9RsEvRi/Z0Rztv++M1BCQngZ8uQ4SANCZ/AXH/RY3Q2kedzKPA7vnErQVBb8YCh/p1xwCsRFAAEA18j8wln/8xdT67ucazjv7mBLseXlLYsILoPZMHiSlJX1jud5XwjAEVKcBFyKAAADkbyh+X8edvEVBmacX7qm/Unn+zzV7LHQL0h8V9c+LGwrsHqEZBTohEBIBBAA4ln/anf6p4t9XEn+ddz6XjoKyjzSWiAX1FzQZPVOiuPSNRJ8dBuYhkB8BBABUKn+DVX/GhbTdPdGSUwK/UeBP9hVL36Hso4OgZAhE3BdAAADyD77gVrov6ujJaG6CwGsYZP9MH+qTfqXC148B/WkAAQBty99a/Nz5XHcQaIaCymf7YPD4XYRfNgb0pgEEABSU/2+E5W+/6kf8noPgQxsvXRJ8pgTSLx0DqSGw+jsjEQEEAFQr//iR/8jNWaLiLyRZ0+NLNQdBLWHwQechUg/KSP9Gx9JXC4HJ342wCBiu7T1dAFhSSv4Sq35T8c+eT/45glJnnWsJAutI0Pvcuy6kX1qy775wL5Kz/1ur7QGLLYE1EUAAQDvyjxn5exP/iNyLHmsqFgba72Bvi+LP2y8m/UTB56IQBhIhkLIlMGzsPV0AWFCj/NXEf7+eEenaMOjm6KFz2Zd6toS59AuIvkAQxIdA3pbAsLH/dAGgjb38Q0f+MxdbyYtpQ3uiZaMg710HVcu+5MOkzKSvv7Lf+YzXIIj/nQqZBqxGAAEAfcg/e9WP9IMvWl6nBAEvQXIj+cOSj4guJH0BoWtSIgbifpfiI4AAAH/yzzrml77qFxM/dz8rPSq1zLsOVEl6UdP7Bp7C51f0alFgsi0Qd18AAQDIX2rczzln50Hw3tfbFh84eTeEY+nvVIbmVCBpGjBzXwABADryv11Y/oEjf5FVP6v9ioPAQxyUfm6E4n9nN8J/G4hhDOSEgNA0gAAAcba05O9t1W8mfqWboozOOtcbBI1hsjVVQvhvDVGIgYTfwfDfkekIIAAA+bsR/zs/x50cxAFB0N5oX130dxUQjgLxEIjcEiAAoFv5Z438xcXv+Gyz4UNQ6nkeQU3Cf+/mrn0V4d91QGYQSP2O5UQAAQB9yb+4+OXOMJsdZXIaBd0HwX3rl+xof0cdyz45CHJCQOOkwPmbA4eN/WcLgByKyl975C8h/sqOOzElqEH27909ga874UfFgFUIxEUAAQBNy3915B9zwa1hX7SCMPB2L4HnOJh48dMNh4/dFZH+3caJjIHc36GYCCAAoG35x676c1dXDZ5t9vZ0NJMw0IqEgDc8Fnt7XmPS387AJgZSQkByS4AAgGT5/9ik/LUunjvujjwRBOEX0ohYmHl1s6+fz1D6JpL/SRHhOAj8XdSeBhAA0Lj8NVf9Be5+dn7eufUgqBvN+1B0V/l2ojeOgqwQyI8AAgCcyn/uTn+h/f7i4n/r57iTQRQQBEg/TvhCsr4TiEAQmIZA4O/GWAQQANCO/GNG/kmr/jpWS7ZhUCoIiIIyT+LT+e5mCf+OIZFBoBECqdOAdfcFEADQpfylbu7ztidaexTcYErg8AU7TqR/xykak4GUEAj4HbgYAQQAJMj/t/3IP+si2vtxp4JB0GQUvDN8ja689JsRflYQpP5O6WwJEADQiPylR/6pF9LOpF9TEFS1fZD3XoidGqV/p0EkpgIzvzvpWwIEAHQi/9xVf2nxj59Zjrtb2ey8s1EQ7Ki8AOmdneCF3gexU6P0VeX7RgCvIRA6DZj/HhIAgPyzVv1a+6Jvix5r2q44CHbuVfiSJdNHRbci/TcF0YmB3BCI3RIYNg6eLQDOkiT/xwLynznjv6sp/0Li93e2WeGIk4Mg2OlW9to38VmN9t84RyoEbKcBw8bB8wXACa7lH3qzX9QjVW3Fny38IseZCkWB4VMM65d8a9JPE/GWAuoxYDYNIACgA/nrrPrTL6RV3v3s4XGpBYNAIhZsP5f2Q3l8CX9S2t8JkxUGBiGQEQEEAHQo/8RVf3U3QpWOglJB8LapFy5FPT2yGulnyv47B0QHgWIIJEYAAQCVyF9ovz9l1e9utVRrFLwtuG1QaxjYPSbai/Rdyj4yCERiQHMa8PnmQAIA+Xcrf8lx/+zF805HeAqCu+XfkCj28ie1o6VlpW8n/NcTlIoBhRCIiAACAPnXK//gm/30Vv2TF9Bqjjt1FgTRYWDMXYvX5zqSvqrYpdGKgTIRQAAg/2rlLzvyFxJ/c0edOgoCi0go8DPY3Llvtcp/7ZD4GLANgfEIGK4fPF9AX2zdftWl/CVW/bLif1MpHQdBBWx7lH4zsheKgZwQEJoGEADIv3P5lxB/+XPNcuedrR+bWugBRS0J37X0XzdGbgjE/Z6kRAAB0JP8v+tB/rIjfxnxZ4i+0JGm/DBo+KSBC9n7EH510r89QukYSA2BmGnAmgggALqV/6fm5Z+/6s+5mFZ6tjkwDuoJgnrDIOu9EG6lbyj1CTY/E/2/1Y4BkRAIjwACAPm3IX/tVb/AxbPa880qUeDlscZvi8bBttQLoO50Iv0ZoWsiHwUpISC5JUAANM9SxMg/TP55436L405vyh1lqikI7ui+JTEdoc9jeLy0qPSTRP9KgYgoUAiBqN+XyAgYrh+8WECbFJP/Q4fyV1n1B1w4q7z7udSjUg2eTXC3Mu7Yv0K3mPSjhP/KATNBIPV7lz0NGL/uEQDIP1P+Hx3LP3HVb77ab+yIU01B4CEOVH+uN1VJ36/s44MgPQaEQiAgAggA5F+h/BVH/gkX1PgLZ2dHnWoNgiqxeN4+wreJgZhtgbQIGJYXbaSZzt3n/y2K/cOf1T7L8ma/+uX/s5H8rcX/uhNKBcEbhO/1uF4Xwk+IAfFpQPx9AcNSEsuL91IeCH1e9E/e/sPiN7/9ixhSYbD2jH+v8hdd9eeI38eRJ/szz0JR4O15BDUL35X0X3WMfAikTAPOBcAJRMCq8Ocl/uf1fBr5v8/8ecvAWP69yN9gv9+r+APPMIseZfL0UBTVIKglDNJ+ri0n+/lFpX9LkBpCIGNLYLgojqMtgZsvumO5Ap8W/hmxf/rz4mUmvznLRBicTgdGPveNe2/XPt1PS/770vK/byX/9FV/2MXU+rhTyAXWy3lnmyDYquXtiELvgtgqvcovLf1Zgf+YgVUYpISA3JbAcLRSXBMBR9OArqUvJ/voKFgTBKeTgTOff3W/H/mrrPqlL6BujzolhIHz+wi2qn3hkubTIyuUvorkBePAUQgEBe1pAHwWxuoI+bdHF9wWxT++l28r/KAgWBMDy88ff7Mf8pdd9fd0I5T2g1Bsjx96DwP590K8rkv6QqK/nkF2FEiFgHIEDCdyOI6A9dOAtlf7KdL/NyHiY+Dp+z8l7Pd/WhF/E/IXGfkrir/pG6FKTgn0X4CkFQlBb2b08sTIotLXl7xeHEjEQOY0IHBLYDgribEIWLJd6ZbAUvyrq/0Y6a8R96+CRETBD0ny/xX5x8hfUPy9H3eqLggSAiEJlc/72uChPOWEf905QTGgHgIh04CJADiNgAamAffWrfZThD8i7heZxAbB3ee/707+scf8wkf+Cqv+0QsnR56qu4+gCl43Lf3rFaMTA6HbAnERMIzJY3oa8Loi8Yes9qeFHyb1fw0gPgp++Pmf1sv/MfIXk7+A+JG+9yB43bfoS9yP0onw42MgNQQypgEj9wUMU/vGUxFwfIPgSzfEi39c+nmST2X171vKP3m/vyn5vxWX//Sq35H4bxnQbRB4igPFn41V/io3f3OMlxiwmAasiYDhWBYzETA7DSgn/uUef5L4Z6U/I+yPAkz8+Wkjf4fyf+BB/m/k5K8p/lsljjt5igNPQZATDg4+l0PpmwhdE1chEDoNmL45cDgVxoxYpiJg/+jeAGvxv79wc1+8+IOk/9GW79/9r7X/xvnH/FqUv+TIv4D43ZxrjowDgsAf1i/ZKSV9C9EbRoFECERHwJlpwHAkipgIKDwNiBO/pvT/ZfE8gxdHnP8z16/6Q/b7kb/qyF/qQnrL33EnPw9C8X70sHPhl5K+N+ErBUHePQLpWwLDqTAeR4bAxDRAKwTkxB8n/OeZsp8jb9WP/NPlH7vql7hw1nPcyX8QdBAFUe+DeFW/9GsTvnAMpE8D0rYEhot7xVLTgOWb29Ru8FMWf7C8f8ng858xuuoX2e9vS/7J+/2xq34J8Td697P9k9EUn1roKQ6SXv70qn7ptyR8oRjYlAqBgAgY9h+tCiQ0AuamAbkhsDLulxB/ivSDxf7PI6z+/x6++uOk+JF/OflnXWRL3gjlOgp83VyY9JbE0HBI+HPSXvZUofSVRbuhQKkYWPs7JBwBw4ksxiMgfxqQsi1wcdwfL/751X688P85mydv/3FxJ2vVLyP/vYblnzTyz1n1z1w4r3eI7yDIe2OinNQLvxfCakpViejNw0B1WyAsAoaz0jhQngaEhMC9578L3+dPEH+c9Kdl/iyCZdDcef67zFV/5DG/RwGrfjH5v/cj/6xVv8wF1O2RJ4LAJBI2Pb706Vad0o+X80thlIMgNQQETgkMX2QxEQKC04CxEIga98+JP3S1Hyj8Sbl/mOfwxz+O/ltEr/qRv5z8U1f9FuKv+GhT+0FQERVKX0TyB0IkhoHW7530NGA4Lw3haUBgCKSM+9fu8SeJP1D4a+X+p0lCxK8y8m9N/ndS5S+86tcSf+NHnFSCgCjw8SQ+E+ErS14sDIRiQGUasD4ChhVxBEeAXAgsefj6f4ys+oXEP7Panxb+n4J58tM/LO48+52Q+JVu9kP+GfIXuIh2ftSJINB+VHTt0ncm+6QgEIgB8WnAagQMp5KICYHICIgNgeUz8C+O+0Pv6o9Z7UsI/4QHP/79jPgTV/3IX+5mv3Mjf2Pxc9zJPghu9SB7o2dLIPyMIMgIgajfjfAtgZMIGM7JwmoaEBACZ2PARvzx0n/80/88Ev/czyG16kf+efKPWvVLiL8X6bsMgh+dvgBJV/ae7kOJkv5Bw0zEgNo0IDAChhVpTESA+DQgMASOYuDVfz96Yl6q+HOk//SE9zHSzxB/9n7/3Bl/j/LXvdkvXv4+xF/VsSb3QRD4AqRbJQVf+DHRat/XjoRfKARSImBYLw/9aUBqCCxZPj3v8CgI/lFF/Ceyf/r+n06FPz/ePyP9aPEj/zz5C43811x4fayWKj/v7PbGwoxAECPus3l8uY5v6b9IxCoGEn7XBLcEhqUsUiJAMgRW7xEIj4ETlk/WO+LHP54Xf4T0l6I/IfbvPyt9KfHHj/yRv/mqX134L41wEgWuHmdcFs+vzvUj/TTBX/tM8ThQCoHQacCwdxQAMRHwUS0CcqYCZfiUIX7pVT/yT5J/6qrf4kYoq4to6QehOHpwUTOSb1L680LXRDUIUkMgMwKGs8LwMg0Yj4FPDUg/Y9WffLMf8g9Z9WtcSKu/8zkjCloIgmpRvwdF+3sbKfp9A4KjQDYENCNguCgO8WmAQAiMx8AnO+FnSz9W/Mg/Xf4Kq36RC2cjN0IlRsF1osC98MtJP1D4+86YDQJvIXD+voDhSBAxEZA6DRAKgZUYWBsFn/JE/2T933EgIX6xVX/8Mb9m5X87Xf6SF9eu7372FAQ9RIHZy3Vspe9e+BFBkB0DKdsCkREwnMriYWQIPJLYFsgLgckgECD/s/2qtOpH/iYjfynxd3/kyUEQ1BwF5m/T0/ruNij8pBgoNw24GAHDyri4yDRAJgRCQ0H/75oX/+yqH/nLyT925J98Ee1c+rUFgac4MPgZPUi/aeFHx4ByCATcFzAcCyIkAhSmAQVjwI/4JVf9Lcr/taj8JS7EZcT/QgGCQDUWCn/Ock/iKyH95wY4mAoIR8DwRRTTEZA2DeghBH6VEz/yV7jZT27VP3oRNRa9zlGmwoFQcxA4wqX0qxO9URTkTAQu/I6kButwXhi/mEwD4kPAWxCES3+9+GNW/b7kf6ND+euKP1HyQseY4iPBbxBsIHvjo6YW0n9eGYYhIDANGNaJw2oaMBsCrmLgVx3xz6z665X/2zLyjxn5R19kJS6igbJ3cqzJ7EEoSkGw0ZXwLU6daEtfUMZ7mVjHQFYIpEXASADERIBRCEzGgHQUzPw9j7TFn7nqR/7Cq/7ci2kDN0IdGD0IxeABRd7DIOsx0Qe1SV9P8FczkI8D5RBI3BIYToQRFAGp04CIEAiOgaAgECLw8wSL32TV34j8b8fIP3/kLzvut9gT9RUF/rYNXrp6EVLei5leFnvsbnHpK0heNA6UQiAnAjYCImA4lcVoBGhPA4RiQCIMEv6ufTHxj6z6kb+c/E1W/Y1LP/vJaC+cPLXwpeM3MJZ6L4SW9POFf9U5ajGQPA0Ii4DhnDRiIkB8GjAdAskxoMC+gvjDVv19yX8zUv4yq35B8avKttAxptqDIPgFSJqREPD3FnpdbjHpiwr/mSAWMaAQAoFbAsOxGM5HgMk0ICME9muR/qz481b9UTf7Hcn/Z+QvLv8KbobyFAlegyA5EDIo8rNp3o9iKfxnhdGIAfsIGM5LQmMaEBACmTEgHQVhf9/HbPFnj/wjbvZrSv6hN/tVI/5Gjze1FARVU7v0n1VCYAyIhkDclsBMAMhHgGwIxAWBPB+NxY/8/clfYsz/vBFKBQFRkHXUdL+M9NsTfloMhE8FBG8SHLkvYFgvjowtAakQCI6Bj2WF/+hj+M/zcPzfJm3kn7nfX6X8f5SVv5n4C55nVj3rrBwFBIGTl+xoSv9Z4+RMBXQjYJjeNw6dBiiHQFQMxARCxp/5ME78uat+5J8n//RVf474/R930o+DUkcPX3Qje71nS1Qm/V1lvIZAzL0BF+4LGGZvHMudBkiHQHYMWElfWPxRN/sh/7Kr/nTZuz3aJBYGJR9QVFsYvDAWfiXS33WEcAxM/44JTQPORMBwtEf8IASdaUBWCGgHQernmRK/5qq/cfnnjfwtVv3tnW+WfQhKmfsI4l6E5Efydo+K1pK+F9k/jcQyCDSnAfNbAsNSCKkRIDkNOB8CGTEQEgoaf/ac9CPFj/xLyD9F/Fo3Qlnvj3qJAm/vObBB/MVPSmf01b+vmXK/okByIJQKgYgIGE7EkBQBqdOAmRDY0w4BF+KPGfnLy3+nYfmnjfxj5d/L3c9CUeD1uQT7eq9Ujn5ds5cHR+0ZSj9R9lccEBUEaiGQtyUwnBXErto0ID0E/MXAL2HSTxB/6qp/9pifS/m/ciJ/HfG3f/dzw0EgGAvlPuvzBqTvR/ZiQZAbAsIRMKyThd40YCIEomPgF5/SzxE/8heSf8LIP/eiGnTh7POoU9NB4IbnDUi/LuHbxIDANGBiS2AYk8axXLSmAfkhsD4IcsNg9c/ay5b+L7P/FtHiDx35I/9J+Wev+oMunorSNT3CpBsF7m8sbEH4lnfudyb8rBiwmAaMRMAwJY+4LQGFEIiMgfkwGCf178kWv5r83/Upf9GRf0HxV3esyXMQ1B4Gcg+R6kr6NzJQjQGZEBj/3QjZEggIgPgtgfXbAiIhkBED4hzmiX/9qj905F+r/OVv+Mva789c9dtfOGs97+w5CLyFgdDP40r6ysK/UYCiISAzDTi5Fg5HsgiKAItpQEQMHHoSfqT4E1f9Qfv9yD9z5G8kfpPzzIrnnXedBcGe1/cfGHwm65fslJB+kJx/UEY+CkZ/D1OmAQkRMByJIjAC4qcBRiEgGQUpf6em+BP3+5uQv8id/qGrfmXxOzrXHHbe2UMUlH5qoUP2Cr1Vz1r6RUWfGQVmIZC5JXAaACfERIDJtkBmDKjyIUP8yD9f/i915W8mfv83QmWFgaeTBrVFgcijoiuRfhWyTwiCUiEQGAHDRXGERkD2NOBMCMTHwAe3wpcU/27ofwvkLzvyH73YSlw427jzOTkKPD6kqFQgzHyOqyWeHFlc+jaivvwZrzGw9vdKYUtg2LkYAClbAkVDQCMK0j9DtvhjVv29yl9kv99S/Bx38hwEUXEgTP5nflaP9BWFf9kAsRgwCoGQLYHhrCxspwFrQkA0BuzYFRR/uPznxP9uVPztyj9v5J98gZ24cF7pmPJBIBcGPrB8hoRP6V92hsVUQDMChovSyJsG6ITAbnXS/xD/byC66kf+Jqt+y9W+4yNN9QWB9zAo9dAof9K/XBmaU4G4EAi7L2BYJ48bEtOApBDwHQPz0k8TP/IvJ/+kC7Dmaj9K4EJHmArFgb8gsAoEo89fVPoFhL9zlu+F+PznqcZAbAhkTAMuXAOH4z3i9SLJiYD0bYGJEDAOgl0t6aes+jP3+1uWf/R+f+qqX0P87u5+LhcF/oPAObulb+IzEr645BPDQDwG9KcBFyNgOJLDiTiCIiB2GpAbAjMxsCYIxhgV+xhzf2+G+HejYuqdgPx/alf++7nyNxR/tUedSj029amzxxnXJHt/0q9T9rJBIBsCiRGwdzYAYiMgaRogEQKBQRAaCLF/Tu7nvq+x6teW/5tK5R868jcQfxPnm8tHQdZDihB+HdKvQvYyQSC1LbDyOxERAcM5WUxEgMQ0IP/+AKEgsBJ+jviDVv3IX23knyt+ReGXO8qUEQVen1y4W6vk1z89Euk7xCAEwrcEzl8Dh7XiUJ4G6IVAShwo/t1J4v957b+xF/lvFZX/CyH5+xd/XUebfATBFel3HUiGguhnsTppovSdbV34iVMBiW2B2C2BYUwe0dOA5BCwjAEjUsUfLP9p8SN/qZF/6sWzzaNONQaBehSo89T4aCnSLz0VEJ8GTETAMCWRtAjoOARyxC828leQ/3fe5Z+5328sflEx7wTgOgrKPZ/gqps4MHwBVEfSv3SOJ4Ec//97mArkTANCI2A4FsX0atJqGrCyPXC/HunvZvy8ciN/5J878tcSv+/jTnKhUHMQhEVCHkV+DivpFxD+rNy3E5kIBMsQyJ8GTG8JDF+EoRABmSHgNgbu5672Y8WP/MXln7rqj7iItnEjVF4ctBYEVXDD8Iy+0fd2VPTbBdCMAuNpwHBOGnd/mo4A422ByRi4X0b42dIfGfenrvpl5P/apfyvRco/deRfRPxV74laPB2NICjxMCkv3921wt92yoXPaR8C6REwHMnh7kW0pgEyIbByz4BkFKz7M4U+c5z4pW7261H+gqv+wAsqN0I5C4Ibvcle+Ul8yt/dFeFvV4xkDAhOA9ZFwHBOFDER4CQEVqNgJAyC+FlQ9vPjfv2Rf8Xy39eVf9zFNuMCypEnPycNaguDGzqPivYj/UaEHxQDVvcHxEXAsCIM4S2BEiHginsaq37kny5/A/Fz5Els28DsHQel4kDlxU8+pX+pF+nPxID+NCD85sBhrTjuyk8DuguBaPEr7vcj/zD5B1xwEX8LEwKBNyWqUOhpkUi/oqlA5JbATAQM46vHnAhIDIF7tYfA9M+WI/6V/X5J+d+uSP6hd/rHjvyzxG95pvmJENbnnXWC4LKnNyXeKPd2x8uupF9K+I8VcRYCQtOA4YswQiJAbhowHwLvql/tq636hY/5tS1/xVV/7ceddkqcd9YPgstNvGipHuHbS/+xE0qHQH4EDGelIRoBUiHgNgbeqYtfbr+/RvlbjvzLid/1USdXUfBDt1GQ95TI2qUfKeUtJSyCIPUegaDv+voIGLbOBcBEBGRPAwRC4DQG3rkU/rz0353/9xAZ+SN/aflrir/6PVFvUeDyBUiFXv5kcj5f+7ubJ/lvFUiPAssQiJgGnAuA746lsR0aAtnTgLcBkgyMAdUJQdxnkBW/vvw3G5a/+Ko/88J6TvpN39RUOgr0331w2dNLnsyewldY+kaizw4DDyEQGQHDqShiIsAwBKJjYHRiMELGn70jLP7UkX/X8t+Vkb/0BbZ56Xe0deAC4xMmutKPE/63laAWA7G/QxH3BQznhHFnXQgoREBiCGTHgAA7VuL3Kv+RACgv/5CRf8yqn4ebtBkEzsNgp9xx0mLSr1T4eTGgPQ0Iuy9gWBWH4TRgJQTiYmDHlfDTxJ898kf+0/I3WvWXk36hI0zNBcFIIEiGwk5Zwdvfj1JS+I8EcBgDUb8v8xEwHAtCIwJsQyA3DHay0RZ/yH4/8s+TvzfxV3qsqckgaIO2pP+oIJkxIBACElsCw3lZrEaAeQgoxIAeb5PEv/YOf42Rf+PyF9vvT1iRyV9AM+WddXzJWRwQBM2N9uuWvXwQjP9+Kk0DRiJgWJWGwDTgjkAEuI2BdOnnrvrT5f+qQ/nrrPrlLqQFzzSLxQJBwCpfS/qCct6MxDAIskMg5t6ANREwrJfHGz/TgMkYeGsv/Htpn307etWfsd/fq/wVV/0yF9N42Rc91hQdBqWmBAi/6FE9ke+roeBzcRoCKfcFDKMCUZ0GZIbAaAykxkHAn3W3jPij9/uRf4D8LcVf/53PxZ6MxpQg7FHR2zVKvwLRiweBcggEf+/PBsDtqQAQnAZMhEB2DERFgZ7s88WP/MflH7/ff1lC/krSb+qYk/aT0UTfdVC57HcKniqxlr6itL/5TLkgSAkB4WnAMgA2b395LGxUBIxOA1JD4Ce5ECiIqPgjR/7IX2bkn36hbVv6ck9G83bqoFwcTL7h0cNRUkvpCwh9moczTP/vdWJAKQQCI2A4FsOxOEynATMhsF2d9FPFL7nqb0T+Ucf85Eb+l5JX/drS93mkqZkgCH5DogLFflbNrSk94aeJXZKMKEj8HdSMgOGLIDIiIGcaMBkCfmNgUvo54kf+heTvQfz1H29qLgia4XGV0i8r+/gocBcCM5Ot4bwozkSA6DQgMAScx8Cs9BPFn7TqR/7T8g8c+aet+tdfQNs722z4hLStx3U+1bBb6VsI/2GFRMRATggITQOG9dLInwbohoBNEAQJP0r8Qqv+0Jv9WpO/8H5/GfE7Ou7kLAoIAruX7HhZ5dcvfIEYMJwGBAZATASkTAMiQiA4Bs5HwTpWxb6OiL/rTrr4p1f9Ujf79Sh/jZF/rvgrPO5UbRA8RviOR/vqI/3rCljFgMU04EIEDLMryJwtAekQiI4BBe4IiV995G/wSt+D+uQfd/NVjvgrP9ssHgYln0fwuH3Ziz5bQlP6jkVvFgayIZATAcORKAIiIGsaoBECVkGQ+rmixS+/34/8hVb90uLftDjyJHiUSSUKSgeB1zDIe/9Dk9K/XgkmISC0JfD55sDhdLUYEwEeQyAnDsT+zjcq4vck/w1v8hff71+9yGZfPEUlL3+USTwSPN1YuOXpZUiyL3syO15qLf0sER8qoRkDwiEQEQHDF2GERIDQNCAoBIRjQJVU8cfI/xXyT5D/pVT5B11kK9kXFQqEGoPgW/EXICmzpf1eCIfSdyV6hSiQCAGlCBjOSsN8GhAcAm+qkb6I+GNG/hl3+rcv/wLib+Zsc1gY1BgEQWGgFQkBf5/sz/moAemnCfrrDNSCwCgEVr+7IwFwIoj4CIidBoSFgO8YeGMiftGb/VTl/6KQ/L9Xk3/yBbXb407tBEFWJGyVkLvdiZPs76+S8L8ugEgMBP5uyU4DJgLgfAQkbglIhEB0DGhFQdjfuyUl/qRVf4vy/8FI/kKr/m7POHsLgkfNv2vB+oipnfR9il4uCnJCIGYaEL8lMFwUxqbENEAhBOJiQJdw6YeLP3Xk37L8Y+/0v5Qofz3xV3bcycujUkWfSdC58JOlr/l9LSD8jUBKxUBqCMRsCayJgGFMHnYREBACDmIgTvpvwn/2GPEjf7mR/+yqP+5iajsirT0MSgZBLWFg88TIb5xI30TuEojFQHoIpE4D1t0XMBoA6VsCyiEwEgRbWrKPkn6c+FVG/shfZ9UvvWISF7XA0aViUVDqpEHpOBD6vJudSD9a2A8ykY0CuRAInQbMR8BwJIeYCDAJgcgYmIiCJFL+bi3xI39D+SuL3/1RJy9RIPRMgq1G2axT+jrCf1CAvCCQDIHcLYHhnCgUpwHpIZAYAya8zhC/9ci/c/lvycg/+iJa1blm4TDwFgSbfcje/qE8QtJ3J3qBKIiOAYEIiJgGDCvSUJ4G5IXA67qkf0b8uat+5B8rf9lVv7z4D10cdzKNAk8nDTzFwabG46ErkH7Vwo+MgRIhEBABw1p5zIyZ06cBkiFgFQSJnytV/Bojf+QvIH8b6ddztMn6cakGDyiqiG+KPG9fU/oPGiUuBvJCID4ChjGB6E4DNEIgNw6E/s4c8ceM/L3Jf09A/jNP97skJn/hVX+pu5/dR4GPGwtrjwKVJ0deR/rFYyDnHoGsGwTPBMDGVACkTAMkQkAlBpRJ3eNPGfn3Kn+R/f55+eeLX1H4hY4zyUSBn+OH3uJA9+VPBe7cLyT8rxTwEwLy04DhRBhlI6DSGLjtR/zhd/rPvdLXo/zjbvYLHvmnjvsjL56uzzUrBUIdQRD+hsSUWIh7VbPCz3TdUPrGq/xJaV+b4/4FZv7/VcNAIAQyImA4XikGREChEHAXA6PSfx3/cyJ/AfnLjPyDLsQRF1B52Rc60iQUBfUFQWo8FP4sDUo/TPL3DZgOA9sQkImA4XRUfEYichGQGwIzMXDbVvgi0k8RP/KXk3/Kql9a/NXc/awXBf5PGlSA8HMlvEh/Wvb3nbE+CLRCIG0asGZydRoAJ3KIiYAiIfBqjXzXBEFqGIz8OZtS0h8Rf478N1Lkv4/881f9CRfPpm6Cko+COp5H0KHwDaQ/Lvz7FSIVAzEhkDgNOBcApxEgtyUwui2QHQLjQTAbBlGizxS+yaq/Y/lv5cpfWfzd3PlcKggOnb78qNQLoA7rlH7VwteMAf0IGFZkcVN+GqAfAmFREIbw5xFe9cfd6d+2/FVG/rni57jTfBR4DQKLSFB//4NP6X/VjfTDYqBsCEwFgNKWwOS2gEoIFOSWjviRv/LIP+AiG37xfAAuguDQ95sWFR4V/bVH6Xcn/JkYyAkBwQgYJgVy0yoEGomBHPGLjvyRv/Sqv5T4vzKknyDwHAeH+o+JZrRfcQiM/56kRMAwLxKdCGgqBBTFn7LfH/yAH1H5P21E/mXEH3emWfAo08xZ568qDYKvPb0lUfClT7IPj0L61YdAzDRgzfVvOBFGWATohECVMTAh/c2In1t65I/8A0f+qat+oYvoV66PO83HQY1BIB8Guug8MRLptxMCCdOAiwFw7TQAlCJAJAQuxMCt0sJ/Nfo5r2ut+pH/tPy1V/0CF9L6b4QqGQXeHmvsQPIlz+cjfX8hkLAlMBzJ4bM4giLAKASiYkAjCm4pSD9A/Fn7/d3IX2fkH3Zx5aI5d9SpeBBs1PeSJdlHRSP9lkJAMwKGU0mciwDFaUBCCEzHwEwUZPGjjPTVVv1O5X/DofyzV/2JF85ejztdcxYEtYZBgcdEI/1apwHxWwLDijBiIqBACITFgA7XlcSfLf/9VuT/2Fz+kuJfvXByASsXBA+KviFR7+VPBi/XQfpthEBABAxrxSGwJWARAtpBkPu5NMWP/JVG/jni58LpPAgSw6AYhq/N5bvb2LZAWAQMowI5MJ4GCIRAaCio/j0RPy/yt5T/zMg/4cLLar+VICgVCLY/F8LvbRowHwHDsSQmZBIbARIhYBAD9Yk/ZL8f+Vus+hF/b0FQJ6zymQaMhcCFAJiPAIlpQFIIeI6ByJ9jQ2LV36v8Nfb7I1djiJ8gQPrQ0pbAsCINg2lAcgh4iIGEz7yRuepPGflryf+KtPy3Sssf8bcSBF/1LnuEz5ZAZASsCQCFaYBGCFgFQcZnyxM/8k+Xv/CqnwsqUYDwoYlpwPkIGE6EERUBqdMAzRDIDQPBv3tU/CmrfumRP/IPkj+r/raj4KvaRO/qUdHQSgQMJ7JYHwFK04CJEFCJASPyxR+66s/d729E/gojf8TfSRRcK/OGxKA3M15D9pDJ7Pf3+Ho4nJVGUgTkTANmQmCjSukLiB/5l5M/F1ziICIQkriG5MHHNGA4FsSFCLCeBpwLAf8xsCEq/oxVf+Pyj73ZL3Xkz6ofxF6rjNShoggYvoji+UJ+GqATAhtNSD9/1Y/8WfUDAKRGwHBeGKERoDwNWBsD00GwYSL7NdK/mfizBa/6Q0b+yD9W/qz6AaC3+wJmAmA1BK5lTgNEQiAhBuSRkH7mqr9G+W97lj8XBQDo9+bAYfSomNQ0QDoERoPgpZ7sbwp83ijxZ+z3X5D/lSLyf2Iv/5j9flb9AMCWwGI4EkVMBKROA7RCYDIIMhD7bC/yxv0x+/3dy5+RPwBAaAQMp8LYiwyBfckQEI4BF7xQWvUjf0b+AAD5ETCc3ys2nAY0GwJC4k/e729X/sn7/az6AQBWGJZiCI8AhWlAEyGwRvoHgT+74Mh/9Ga/3fXiR/4AAJ0HwHEEPM2LAMEQqCMGXsiLP2PkHyv/yw3Ln5E/AEBEAKyNgIgtgflpQEQITMbAi4qlPy1+5C8kf1b9AABxAfAlBJ4pTgPSQ2B9DLwwE3669AVX/d3Ln5E/AIBaAMRPAwxCICoIQiNh/n93LVv6Wqv+iZv9WpM/+/0AAHYBIBEBqiGwJgbSwmBE9NnSFxR/9Kof+QMAwFwAnAgjJgT2nIVARBjoiD5Q/MhfVP7c7AcAkBUAPyySIiBnGjAbAoIxYMZzZfEjf+QPACAeAGEREH+DYOsh8DxD/HHyv5Ir/x2P8j9Mlz8jfwAAqQAID4GrRULASxA81xV/zMg/+AE/yB8AAGYDIGMakBgCV5NC4Llb6cuIP23kj/wBACAoAC6vDYCYCEiZBgSEQHQMSIRB4t+XK/6kVT/yBwCAzAA4wVMIyMWAErPSTxF/uvxjbvZD/gAA8P8BH8l/mUKxpUMAAAAASUVORK5CYII=",vr={STOPPED:0,PLAYING:1,PAUSED:2};class rt{constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new rt(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new rt(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){if(e!==null&&typeof e=="object")return new rt(this.x*e.x,this.y*e.y,this.z*e.z);const n=Number(e)||0;return new rt(this.x*n,this.y*n,this.z*n)}divide(e){const n=Number(e)||1;return new rt(this.x/n,this.y/n,this.z/n)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}copy(){return new rt(this.x,this.y,this.z)}toArray(){return[this.x,this.y,this.z]}}function Ib(t,e,n){return new rt(t,e,n)}const Ca={primary:[.96,.65,.14],secondary:[.08,.11,.18],tertiary:[.66,.74,.88],text:[.96,.97,1]},Mb=[{title:"WebWallGL",artist:"oneincase",album:"Scene",albumArtist:"oneincase",duration:212,colors:Ca,thumbnail:Ea,lyrics:[[0,"\u573A\u666F\u4E00\u5C42\u5C42\u4EAE\u8D77"],[12,"\u9AA8\u9ABC\u4E0E\u7C92\u5B50\u5404\u5C31\u5404\u4F4D"],[26,"\u811A\u672C\u5728\u6C99\u7BB1\u91CC\u82CF\u9192"],[41,"\u628A\u6BCF\u4E00\u5E27\u4EA4\u7ED9\u65F6\u95F4"],[58,"WebWallGL"],[72,"\u573A\u666F\u6B63\u5728\u547C\u5438"],[95,"\uFF08\u95F4\u594F\uFF09"],[126,"\u56FE\u5C42\u6392\u6210\u661F\u8F68"],[140,"\u6548\u679C\u94FE\u4E00\u5BF8\u5BF8\u70B9\u4EAE"],[158,"\u6211\u4EEC\u4E0D\u6E32\u67D3\u9ED1\u6697"],[176,"\u53EA\u6E32\u67D3\u5149"],[198,"\u2026\u2026"]]},{title:"WebWallGL",artist:"oneincase",album:"Web",albumArtist:"oneincase",duration:187,colors:Ca,thumbnail:Ea,lyrics:[[0,"iframe \u91CC\u6709\u4E00\u5EA7\u57CE"],[14,"shim \u4E3A\u5B83\u70B9\u4EAE\u8DEF\u706F"],[30,"\u6307\u9488\u7FFB\u8FC7\u5C71\u810A"],[46,"\u4E8B\u4EF6\u6309\u65F6\u5230\u8FBE"],[63,"WebWallGL\uFF0C\u7F51\u9875\u6B63\u5728\u64AD\u653E"],[88,"(instrumental)"],[118,"\u6BCF\u4E00\u5E27\u90FD\u662F\u540C\u6E90"],[134,"\u6BCF\u4E00\u6B21\u70B9\u51FB\u90FD\u6709\u56DE\u58F0"],[152,"\u7F51\u9875\u6B63\u5728\u64AD\u653E"],[170,"\u4E0D\u505C\u6B47"]]},{title:"WebWallGL",artist:"oneincase",album:"Video",albumArtist:"oneincase",duration:241,colors:Ca,thumbnail:Ea,lyrics:[[0,"\u89E3\u7801\u5668\u63A8\u5F00\u7B2C\u4E00\u5E27"],[16,"\u5FAA\u73AF\u70B9\u6CA1\u6709\u7F1D\u9699"],[33,"\u5E27\u7387\u8D34\u7740\u5FC3\u8DF3\u8D70"],[52,"\u753B\u9762\u4E0D\u65E7"],[70,"\u65F6\u95F4\u4E00\u76F4\u65B0"],[92,"\uFF08\u95F4\u594F\uFF09"],[130,"\u628A\u50CF\u7D20\u4EA4\u7ED9\u786C\u4EF6"],[148,"\u628A\u6D41\u7545\u7559\u7ED9\u773C\u775B"],[172,"\u4E00\u5708\u4E00\u5708"],[200,"\u90FD\u662F\u7B2C\u4E00\u5708"],[226,"\u2026\u2026"]]},{title:"WebWallGL",artist:"oneincase",album:"Live",albumArtist:"oneincase",duration:168,colors:Ca,thumbnail:Ea,lyrics:[[0,"\u9EA6\u514B\u98CE\u542C\u89C1\u623F\u95F4"],[11,"\u9891\u8C31\u5F00\u51FA\u516D\u5341\u56DB\u4E2A\u7A97\u53E3"],[24,"\u6B63\u5728\u64AD\u653E\u7684\u6B4C"],[38,"\u6709\u540D\u5B57\u4E5F\u6709\u5C01\u9762"],[55,"WebWallGL \u5B9E\u51B5"],[76,"(drop)"],[104,"\u7CFB\u7EDF\u5728\u8BF4\u5B83\u5728\u542C"],[122,"\u58C1\u7EB8\u5728\u8DDF\u7740\u5531"],[146,"\u2026"]]}],Ia=3;function Xd(t=20260901){const e=Mb,n=e.reduce((w,y)=>w+y.duration+Ia,0),r={hasMedia:!1,state:vr.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,thumbnail:"",primaryColor:new rt(0,0,0),secondaryColor:new rt(0,0,0),tertiaryColor:new rt(0,0,0),textColor:new rt(1,1,1),highContrastColor:new rt(1,1,1),trackIndex:-1,lyrics:[],lyricLine:"",lyricIndex:-1};let i=0,s=!1,a=0,o=0;function c(w){let y=0;const b=(w%e.length+e.length)%e.length;for(let v=0;v<b;v++)y+=e[v].duration+Ia;return y}function u(w){let y=n>0?w%n:0;y<0&&(y+=n);let b=-1,v=0,k=!1;for(let B=0;B<e.length;B++){const N=e[B].duration;if(y<N){b=B,v=y;break}if(y-=N,y<Ia){b=B,v=N,k=!0;break}y-=Ia}b<0&&(b=e.length-1,v=e[b].duration,k=!0);const A=e[b];r.hasMedia=!0,r.trackIndex=b,r.title=A.title,r.artist=A.artist,r.album=A.album,r.albumArtist=A.albumArtist,r.duration=A.duration,r.position=v;const T=A.duration>0?v/A.duration:0;s?r.state=vr.PAUSED:k?r.state=vr.STOPPED:T>.7&&T<.76?r.state=vr.PAUSED:r.state=vr.PLAYING,r.hasThumbnail=!k,r.thumbnail=k?"":A.thumbnail||"";const S=A.colors;r.primaryColor=new rt(S.primary[0],S.primary[1],S.primary[2]),r.secondaryColor=new rt(S.secondary[0],S.secondary[1],S.secondary[2]),r.tertiaryColor=new rt(S.tertiary[0],S.tertiary[1],S.tertiary[2]),r.textColor=new rt(S.text[0],S.text[1],S.text[2]);const P=.2126*S.primary[0]+.7152*S.primary[1]+.0722*S.primary[2];r.highContrastColor=P>.5?new rt(0,0,0):new rt(1,1,1),r.lyrics=A.lyrics;let M=-1;for(let B=0;B<A.lyrics.length;B++)v>=A.lyrics[B][0]&&(M=B);return r.lyricIndex=M,r.lyricLine=M>=0?A.lyrics[M][1]:"",r}function l(w){o=Number(w)||0;const y=s?a:o+i;return u(y)}function f(w){s=!1;const y=c(w);return i=y-o,u(y)}function d(){const w=r.trackIndex<0?0:r.trackIndex+1;return f(w)}function h(){const w=r.trackIndex<0?e.length-1:r.trackIndex-1;return f(w)}function p(){return s||(a=o+i,s=!0,r.state=vr.PAUSED),r}function m(){return s?(s=!1,i=a-o,u(a)):r}function g(){return s?m():p()}return{update:l,snapshot:r,tracks:e,cycle:n,MEDIA_PLAYBACK:vr,skipNext:d,skipPrevious:h,play:m,pause:p,playPause:g}}function Bb(t,e=512){const n=Math.max(8,e|0),r=new Uint8Array(n*n*4),i=t&&t.colors?t.colors:{primary:[.5,.5,.5],secondary:[.1,.1,.1],tertiary:[.8,.8,.8]},[s,a,o]=i.primary,[c,u,l]=i.secondary,[f,d,h]=i.tertiary;for(let p=0;p<n;p++)for(let m=0;m<n;m++){const g=m/(n-1),w=p/(n-1),y=g-.5,b=w-.5,v=Math.sqrt(y*y+b*b)*2,k=.5+.5*Math.sin(v*18-1.2),A=.5+.5*Math.sin((g+w)*6),T=Math.min(1,Math.max(0,v));let S=s*(1-T)+c*T,P=a*(1-T)+u*T,M=o*(1-T)+l*T;S=S*(.72+.28*k)+f*.18*A,P=P*(.72+.28*k)+d*.18*A,M=M*(.72+.28*k)+h*.18*A;const B=1-.35*Math.min(1,v*v),N=(p*n+m)*4;r[N]=Math.max(0,Math.min(255,Math.round(S*B*255))),r[N+1]=Math.max(0,Math.min(255,Math.round(P*B*255))),r[N+2]=Math.max(0,Math.min(255,Math.round(M*B*255))),r[N+3]=255}return{width:n,height:n,rgba:r}}function Rb(t,e){const n=[];if(!e)return n;const r=!t;return(r||t.hasMedia!==e.hasMedia)&&n.push({name:"mediaStatusChanged",event:{enabled:e.hasMedia}}),(r||t.title!==e.title||t.artist!==e.artist||t.album!==e.album||t.albumArtist!==e.albumArtist)&&n.push({name:"mediaPropertiesChanged",event:{title:e.title,artist:e.artist,album:e.album,albumArtist:e.albumArtist,albumTitle:e.album,subTitle:"",trackType:"music"}}),(r||t.hasThumbnail!==e.hasThumbnail||t.trackIndex!==e.trackIndex||t.thumbnail!==e.thumbnail)&&n.push({name:"mediaThumbnailChanged",event:{hasThumbnail:e.hasThumbnail,thumbnail:e.thumbnail,primaryColor:e.primaryColor,secondaryColor:e.secondaryColor,tertiaryColor:e.tertiaryColor,textColor:e.textColor,highContrastColor:e.highContrastColor}}),(r||t.state!==e.state)&&n.push({name:"mediaPlaybackChanged",event:{state:e.state}}),(r||Math.floor(t.position)!==Math.floor(e.position)||t.duration!==e.duration)&&n.push({name:"mediaTimelineChanged",event:{position:e.position,duration:e.duration}}),(r||t.lyricIndex!==e.lyricIndex||t.trackIndex!==e.trackIndex)&&n.push({name:"mediaLyricsChanged",event:{line:e.lyricLine,index:e.lyricIndex,lines:e.lyrics}}),n}function Fb(t){return t?{hasMedia:t.hasMedia,state:t.state,title:t.title,artist:t.artist,album:t.album,albumArtist:t.albumArtist,position:t.position,duration:t.duration,hasThumbnail:t.hasThumbnail,thumbnail:t.thumbnail,trackIndex:t.trackIndex,lyricIndex:t.lyricIndex,lyricLine:t.lyricLine}:null}const Db=Object.freeze(Object.defineProperty({__proto__:null,MEDIA_PLAYBACK:vr,cloneMediaSnapshot:Fb,createSimulatedMedia:Xd,diffMediaEvents:Rb,mediaVec3:Ib,renderThumbnail:Bb},Symbol.toStringTag,{value:"Module"})),Gd=14,ks=[{app:"Safari",title:"GitHub \xB7 we-scene-renderer",url:"https://github.com/oneincase/we-scene-renderer"},{app:"Google Chrome",title:"YouTube",url:"https://www.youtube.com/watch?v=dQw4w9WgXcQ"},{app:"Google Chrome",title:"Wallpaper Engine - Workshop",url:"https://steamcommunity.com/app/431960/workshop/"},{app:"Safari",title:"MDN Web Docs",url:"https://developer.mozilla.org/en-US/docs/Web/API"},{app:"Music",title:"\u591C\u822A\u661F \u2014 \u76F8\u4F4D\u8FC1\u79FB",url:""},{app:"Code",title:"we-scene-renderer \u2014 text.js",url:""}];function $d(){const t={app:"",title:"",url:"",index:-1};function e(n){const r=Number(n)||0,i=ks.length?Math.floor(r/Gd)%ks.length:0,s=ks[i]||ks[0];return t.app=s.app,t.title=s.title,t.url=s.url,t.index=i,t}return e(0),{update:e,snapshot:t,tabs:ks,hold:Gd}}function Qd(t){const e={name:"",at:0};function n(r){return e.name=String(r||""),e.at=Date.now(),typeof t=="function"&&t(e.name),e.name}return{openUserShortcut:n,last:e}}function Nb(t){const e=Xd(t),n=$d(),r=Qd(null);return{media:e,windowTitle:n,shortcuts:r}}const Lb=Object.freeze(Object.defineProperty({__proto__:null,createShortcutHandler:Qd,createSimulatedSystem:Nb,createSimulatedWindowTitle:$d},Symbol.toStringTag,{value:"Module"}));function Ub(t={}){const e=t.target||(typeof window<"u"?window:null),n=t.viewport||(typeof window<"u"?()=>({w:window.innerWidth||1,h:window.innerHeight||1}):null),r={u:.5,v:.5,screenX:0,screenY:0,wx:0,wy:0,originY:null,lastU:.5,lastV:.5,lastScreenX:0,lastScreenY:0,lastWx:0,lastWy:0,lastOriginY:null,leftDown:!1,has:!1,moveCount:0,downCount:0,upCount:0,lastEventTime:0,screenW:1,screenH:1};function i(){if(!n)return;const d=n();r.screenW=d.w||1,r.screenH=d.h||1}i();function s(d,h){const p=d/r.screenW,m=h/r.screenH;r.has||(r.lastU=p,r.lastV=m,r.lastScreenX=d,r.lastScreenY=h),r.screenX=d,r.screenY=h,r.u=p,r.v=m,r.has=!0,r.moveCount++,r.lastEventTime=Date.now()}function a(d){const h=(d&1)!==0;h!==r.leftDown&&(r.leftDown=h,h?r.downCount++:r.upCount++,r.lastEventTime=Date.now())}function o(d){i();let h=d.clientX,p=d.clientY;if(e&&typeof e.getBoundingClientRect=="function"){const m=e.getBoundingClientRect();h-=m.left,p-=m.top}s(h,p)}function c(d){d.button!==void 0&&d.button!==0||a(1)}function u(d){d.button!==void 0&&d.button!==0||a(0)}function l(){a(0)}let f=!1;return e&&e.addEventListener&&(f=!0,e.addEventListener("mousemove",o,{passive:!0}),e.addEventListener("mousedown",c,{passive:!0}),e.addEventListener("mouseup",u,{passive:!0}),e.addEventListener("blur",l,{passive:!0}),typeof document<"u"&&document.addEventListener&&document.addEventListener("mouseleave",l,{passive:!0})),{state:r,pushExternal(d){if(!d)return;i();const h=Number(d.u),p=Number(d.v);Number.isFinite(h)&&Number.isFinite(p)&&s(h*r.screenW,p*r.screenH),a(Number(d.buttons)||0)},pushExternalLeave(){a(0)},beginFrame(){i(),r.lastU=r.u,r.lastV=r.v,r.lastScreenX=r.screenX,r.lastScreenY=r.screenY,r.lastWx=r.wx,r.lastWy=r.wy,r.lastOriginY=r.originY},syncWorld(d,h=0,p=0){if(!d)return;r.wx=d.offX+r.u*d.viewW-h,r.wy=d.offY+r.v*d.viewH-p;const m=Number(d.projH);r.originY=Number.isFinite(m)?m-r.wy:r.wy,r.lastWx===0&&r.lastWy===0&&(r.lastWx=r.wx,r.lastWy=r.wy,r.lastOriginY=r.originY)},normalizedDelta(){const d=r.u-r.lastU,h=r.v-r.lastV;return Math.hypot(d,h)},dispose(){!f||!e||!e.removeEventListener||(f=!1,e.removeEventListener("mousemove",o),e.removeEventListener("mousedown",c),e.removeEventListener("mouseup",u),e.removeEventListener("blur",l),typeof document<"u"&&document.removeEventListener&&document.removeEventListener("mouseleave",l))}}}const Ob=Object.freeze(Object.defineProperty({__proto__:null,createPointerSource:Ub},Symbol.toStringTag,{value:"Module"}));function Yd(t,e,n,r,i,s,a){const o=t.size||[0,0],c=t.scale||[1,1,1],u=o[0]*c[0],l=o[1]*c[1];if(!(u>0)||!(l>0))return null;const f=t.origin||[0,0,0];let d=f[0],h=r-f[1];if(t.parallaxDepth&&(i!==0||s!==0)){const y=t.parallaxDepth,b=ei(y[0]),v=ei(y[1]);d+=b*i,h+=v*s}let p=e-d,m=n-h;const g=t.angles?t.angles[2]:0;if(g){const y=Math.cos(-g),b=Math.sin(-g),v=p*y+m*b,k=-p*b+m*y;p=v,m=k}const w=a&&a[t.alignment]||[.5,.5];return(w[0]!==.5||w[1]!==.5)&&(p-=(.5-w[0])*u,m-=(.5-w[1])*l),{lx:p/u,ly:m/l,w:u,h:l}}function zb(t,e,n,r,i={}){if(!t||t.length===0)return null;const s=i.parOffX||0,a=i.parOffY||0,o=i.alignTable,c=i.filter;for(let u=t.length-1;u>=0;u--){const l=t[u];if(!l||!l.visible||l.destroyed||c&&!c(l))continue;const f=Yd(l,e,n,r,s,a,o);if(f&&Math.abs(f.lx)<=.5&&Math.abs(f.ly)<=.5)return l}return null}const Hb=Object.freeze(Object.defineProperty({__proto__:null,hitTestLayers:zb,worldToLayerLocal:Yd},Symbol.toStringTag,{value:"Module"})),kt=t=>t,Ye=kt(Gg),Ma=kt(l0),At=kt(X0),Pn=kt(K0),ht=kt(By),Vb=kt(Fy),Wb=kt(zy),Vr=kt(rb),As=kt(Ab),Ke=kt(F0),jb=kt(Tb),Pe=kt(Db),Kd=kt(Lb),xs=kt(ky),qb=kt(Ob),Xb=kt(Hb);function Gb(t,e,n){return{camera:null,general:{orthogonalprojection:{width:t,height:e},clearenabled:!0,clearcolor:"0 0 0"},layers:[{id:0,name:"media",visible:!0,image:n,textureName:n,particle:null,puppet:null,solid:!1,isContainer:!1,isPostProcess:!1,isText:!1,isSound:!1,isComponent:!1,sound:[],origin:[t/2,e/2,0],scale:[1,1,1],angles:[0,0,0],size:[t,e],alignment:"center",color:[1,1,1],alpha:1,brightness:1,colorBlendMode:0,copybackground:!1,parallaxDepth:null,animationLayers:[],effects:[]}],properties:{}}}async function $b(t){const e=await fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status}`);const n=new window.ImageDecoder({data:await e.arrayBuffer(),type:"image/gif"});await n.tracks.ready,await n.completed;const r=n.tracks.selectedTrack;if(!r||!r.frameCount)return null;const i=Math.min(r.frameCount,300),s=[];let a=0,o=0;for(let c=0;c<i;c++){const{image:u}=await n.decode({frameIndex:c});a=u.displayWidth,o=u.displayHeight,s.push({bitmap:await createImageBitmap(u,{premultiplyAlpha:"none"}),durationMs:u.duration?u.duration/1e3:100}),u.close()}return n.close?.(),{width:a,height:o,frames:s}}function Qb(t,e,n){if(t.audioBridge)return;const r=window.AudioContext||window.webkitAudioContext;if(!r)return;let i,s;try{i=new r;const l=i.createMediaElementSource(n);s=i.createAnalyser(),s.fftSize=256,s.smoothingTimeConstant=.75,l.connect(s),s.connect(i.destination)}catch(l){ce(t,e,`media \u9891\u8C31\u63A5\u7BA1\u8DF3\u8FC7: ${l?.message??l}`);return}const a=new Uint8Array(s.frequencyBinCount),o=new Float32Array(64),c=new Float32Array(64),u=()=>{if(i.state!=="running")return null;s.getByteFrequencyData(a);const l=Math.min(64,a.length);for(let f=0;f<l;f++){const d=a[f]/255;o[f]=d,c[f]=d}for(let f=l;f<64;f++)o[f]=0,c[f]=0;return{left:o,right:c}};if(t.audioBridge=u,i.state==="suspended"){const l=()=>{i.resume().catch(()=>{}),window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",l)};window.addEventListener("pointerdown",l,{once:!0}),window.addEventListener("keydown",l,{once:!0}),(t.wallpaperDisposers??=[]).push(()=>{window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",l)})}(t.wallpaperDisposers??=[]).push(()=>{t.audioBridge===u&&(t.audioBridge=null),i.close().catch(()=>{})})}function Yb(t,e,n,r){if(t.audioBridge)return;const i=window.AudioContext||window.webkitAudioContext;if(!i)return;let s;const a=new Map;try{s=new i;for(const d of[n,r]){const h=s.createMediaElementSource(d),p=s.createAnalyser();p.fftSize=256,p.smoothingTimeConstant=.75,h.connect(p),p.connect(s.destination),a.set(d,p)}}catch(d){ce(t,e,`media \u9891\u8C31\u63A5\u7BA1\u8DF3\u8FC7: ${d?.message??d}`);return}let o=a.get(n);const c=new Uint8Array(o.frequencyBinCount),u=new Float32Array(64),l=new Float32Array(64),f=()=>{if(s.state!=="running")return null;o.getByteFrequencyData(c);const d=Math.min(64,c.length);for(let h=0;h<d;h++){const p=c[h]/255;u[h]=p,l[h]=p}for(let h=d;h<64;h++)u[h]=0,l[h]=0;return{left:u,right:l}};if(t.audioBridge=f,s.state==="suspended"){const d=()=>{s.resume().catch(()=>{}),window.removeEventListener("pointerdown",d),window.removeEventListener("keydown",d)};window.addEventListener("pointerdown",d,{once:!0}),window.addEventListener("keydown",d,{once:!0}),(t.wallpaperDisposers??=[]).push(()=>{window.removeEventListener("pointerdown",d),window.removeEventListener("keydown",d)})}return(t.wallpaperDisposers??=[]).push(()=>{t.audioBridge===f&&(t.audioBridge=null),s.close().catch(()=>{})}),d=>{const h=a.get(d);h&&(o=h)}}function Kb(t,e){rr(t);const n=g=>{ce(t,e,`media ${e.type} \u5931\u8D25: ${g}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08${e.type}\uFF09${g}`)),t.fallbackPage?.()};if(!e.src){n("\u7F3A\u5C11\u8D44\u6E90 URL\uFF08cfg.src \u4E3A\u7A7A\uFF09");return}const r=e.type==="video",i=e.type==="gif";if(r){Jb(t,e);return}const s=e.canvas instanceof HTMLCanvasElement,a=s?e.canvas:document.createElement("canvas"),o=Ns(t,e),c=a.clientWidth||window.innerWidth||1,u=a.clientHeight||window.innerHeight||1;if(a.width=Math.max(1,Math.round(c*o)),a.height=Math.max(1,Math.round(u*o)),s||(a.style.cssText="position:absolute;inset:0;width:100%;height:100%;"),!a.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0})){if(ce(t,e,`media ${e.type}: WEBGL2_UNAVAILABLE`),s){t.onError?.(new Error("WEBGL2_UNAVAILABLE"));return}t1(t,e);return}if(s||t.wrap?.appendChild(a),a.setAttribute("data-webwallgl-gl","1"),t.canvas=a,t.onSceneInfo){const g=t.onSceneInfo;t.onSceneInfo=void 0;try{g({width:c,height:u,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}}let f=!1;t.sceneCleanup=()=>{f=!0,t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0)};let d,h,p=!1;t.sceneAudio={setVolume(g){const w=t.video;if(!w)return;const y=Math.max(0,Math.min(1,Number(g)||0));w.volume=y,w.muted=y<=0,y>0&&w.paused&&!t.paused&&w.play().catch(b=>{ce(t,e,`media \u53D6\u6D88\u9759\u97F3\u540E\u81EA\u52A8\u64AD\u653E\u88AB\u62D2\u7EDD: ${b?.message??b}`)})},audios:[]},t.sceneCtl={pause(){d?.()},resume(){h?.()},applyUserProperties(){}};const m=g=>{f||(f=!0,n(g))};(async()=>{try{const g=ht.createRenderer(a,{diag:O=>ce(t,e,`renderer: ${O}`),fboCapFactor:0});if(t.renderer=g,f)return;const w="__media",y=new Map;let b,v=0,k=0;{let O=!1;if(i&&typeof window.ImageDecoder=="function")try{const q=await $b(e.src);if(q&&q.frames.length>1){v=q.width,k=q.height;const H=g.gl,G={glTex:ht.makeTexture(H,null,0,0,q.frames[0].bitmap),width:v,height:k,rg88:!1};y.set(w,G);let Y=0,J=performance.now()+q.frames[0].durationMs;b=()=>{const fe=performance.now();if(!(fe<J)){Y=(Y+1)%q.frames.length,J=fe+q.frames[Y].durationMs,H.bindTexture(H.TEXTURE_2D,G.glTex);try{H.texImage2D(H.TEXTURE_2D,0,H.RGBA,H.RGBA,H.UNSIGNED_BYTE,q.frames[Y].bitmap)}catch{}}};const ne=t.sceneCleanup;t.sceneCleanup=()=>{ne?.();for(const fe of q.frames)fe.bitmap.close()},O=!0,ce(t,e,`media gif ${v}x${k} ${q.frames.length} \u5E27 \u2192 scene \u6E32\u67D3`)}}catch(q){ce(t,e,`gif \u89E3\u7801\u5931\u8D25\uFF0C\u56DE\u9000\u9759\u6001\u9996\u5E27: ${String(q.message).slice(0,80)}`)}if(!O){const q=new Image;if(q.crossOrigin="anonymous",q.src=e.src,await new Promise((H,G)=>{q.addEventListener("load",()=>H(),{once:!0}),q.addEventListener("error",()=>G(new Error("image load error")),{once:!0})}),f)return;v=q.naturalWidth||1,k=q.naturalHeight||1,t.img=q,y.set(w,{glTex:ht.makeTexture(g.gl,null,0,0,q),width:v,height:k,rg88:!1}),ce(t,e,`media ${e.type} ${v}x${k} \u2192 scene \u6E32\u67D3`)}}if(f)return;const A=Gb(v,k,w),T=performance.now();let S=0,P=0,M=-1/0;const B=O=>{if(f||t.paused)return;const q=t.cfg.sceneFps||60;if(O-M>=1e3/q){M=O,ir(t,O),tl(t,a,t.cfg),b?.();const H=t.coverAlign;g.render(A,y,a.width,a.height,(O-T-S)/1e3,Mr(t.cfg.fit),H.x,H.y).then(()=>{if(t.onFirstFrame){const G=t.onFirstFrame;t.onFirstFrame=void 0;try{G()}catch{}}f||t.paused||(t.raf=requestAnimationFrame(B))}).catch(G=>m(String(G.message||G).slice(0,200)))}else t.paused||(t.raf=requestAnimationFrame(B))},N=()=>{f||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(B))};d=()=>{t.raf!==void 0&&(cancelAnimationFrame(t.raf),t.raf=void 0),P||(P=performance.now());const O=t.video;p=!!(O&&!O.paused&&!O.ended),O?.pause()},h=()=>{P&&(S+=performance.now()-P,P=0),p&&t.video?.play().catch(()=>{}),p=!1,N()},N()}catch(g){m(String(g.message||g).slice(0,200))}})()}function Zb(t,e){if(t.wrap)return t.wrap;const n=e.canvas;return n?n instanceof HTMLCanvasElement?n.parentElement:n:null}function Jb(t,e){if(rr(t),!e.src){t.fallbackPage?.(),t.onError?.(new Error("\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09\u7F3A\u5C11\u8D44\u6E90 URL\uFF08cfg.src \u4E3A\u7A7A\uFF09"));return}const n=Zb(t,e);if(!n){const d="\u89C6\u9891\u58C1\u7EB8\u9700\u8981\u4E00\u4E2A\u5BB9\u5668\u5143\u7D20\uFF08\u4F20\u5165\u7684 canvas \u6CA1\u6709\u7236\u8282\u70B9\uFF09";ce(t,e,`media video \u5931\u8D25: ${d}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09${d}`));return}const r=Va(e.fit),i=`position:absolute;inset:0;width:100%;height:100%;object-fit:${r.objectFit};object-position:50% 50%;background:${r.background};`;!t.wrap&&getComputedStyle(n).position==="static"&&(n.style.position="relative");let s=!1;const a=d=>{if(s)return;s=!0;const h=`\u89E3\u7801/\u52A0\u8F7D\u5931\u8D25\uFF08code ${d??"?"}\uFF09`;ce(t,e,`media video \u5931\u8D25: ${h}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09${h}`)),t.fallbackPage?.()},o=e.loop!==!1,c=e.muted!==!1,u=()=>{ir(t,performance.now());const d=t.onFirstFrame;if(d){if(t.onFirstFrame=void 0,t.onSceneInfo){const h=t.onSceneInfo;t.onSceneInfo=void 0;try{h({width:t.video?.videoWidth||0,height:t.video?.videoHeight||0,layerCount:1,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}}try{d()}catch{}}},l=d=>{let h=!1,p=0,m=-1;const g=v=>{if(t.paused||v.paused||v.readyState<2)return;const k=v.currentTime;m>=0&&k===m||(m=k,ir(t,performance.now()))};let w;const y=()=>{h||!w||(g(w),w.requestVideoFrameCallback(y))},b=()=>{if(h)return;p=requestAnimationFrame(b);const v=d();v&&(v!==w&&typeof v.requestVideoFrameCallback=="function"&&(w=v,v.requestVideoFrameCallback(y)),g(v))};p=requestAnimationFrame(b),(t.wallpaperDisposers??=[]).push(()=>{h=!0,w=void 0,p&&cancelAnimationFrame(p)})};if(!o){const d=document.createElement("video");d.autoplay=!0,d.loop=!1,d.muted=c,d.playsInline=!0,d.preload="metadata",e1(d,t,e),d.style.cssText=i,d.src=e.src,d.addEventListener("error",()=>a(d.error?.code)),n.appendChild(d),t.video=d,(t.videoTextures??=[]).push(d),d.addEventListener("canplay",()=>{d.play().catch(()=>{})},{once:!0}),d.addEventListener("loadeddata",u,{once:!0}),d.readyState>=2&&u(),Qb(t,e,d),l(()=>d),ce(t,e,"media video \u2192 DOM \u76F4\u663E\uFF08\u5355\u5143\u7D20\uFF0C\u4E0D\u5FAA\u73AF\uFF09");return}const f=()=>{const d=il(e.src,{muted:c,renderDpr:e.renderDpr,maxW:n.clientWidth||window.innerWidth,maxH:n.clientHeight||window.innerHeight,onRecover:m=>ce(t,e,`media video \u81EA\u6108: ${m}`)});for(const m of[d.active,d.standby])m.style.cssText=i,n.appendChild(m),(t.videoTextures??=[]).push(m),m.addEventListener("error",()=>a(m.error?.code));const h=()=>{d.active.style.zIndex="1",d.standby.style.zIndex="0",t.video=d.active};h(),d.onSwap=()=>{h(),p?.(d.active)},d.onFallback=()=>ce(t,e,"media video: \u65E0\u7F1D\u5FAA\u73AF\u515C\u5E95\uFF08\u9000\u56DE\u539F\u751F loop\uFF09"),(t.videoPairs??=[]).push(d),t.webcodecsPreferred=mf();const p=Yb(t,e,d.active,d.standby);d.active.addEventListener("loadeddata",u,{once:!0}),d.active.readyState>=2&&u(),l(()=>d.active),t.paused||d.resume(),ce(t,e,"media video \u2192 DOM \u76F4\u663E\uFF08A/B \u65E0\u7F1D\u5FAA\u73AF\uFF09")};if(o&&c&&mf()){let d=!0,h=null;const p=(m,g=!0)=>{d&&(d=!1,h?.destroy(),h=null,ce(t,e,`media video: ${m}\uFF0C\u56DE\u9000 A/B <video>`),f(),g||(t.webcodecsPreferred=!1))};h=Wg({src:e.src,container:n,cssText:i,fit:()=>Mr(t.cfg.fit),fps:()=>t.cfg.sceneFps||60,paused:()=>!!t.paused,renderDpr:e.renderDpr,onFirstFrame:u,onFrame:()=>ir(t,performance.now()),onDiag:m=>ce(t,e,`media video(webcodecs): ${m}`),onFatal:m=>p(`WebCodecs \u8DEF\u5F84\u5931\u8D25\uFF08${m}\uFF09`,!1)}),t.sceneCtl={pause:()=>h?.pause(),resume:()=>h?.resume(),applyUserProperties(){}},t.sceneAudio={setVolume:m=>{m>0&&p("\u53D6\u6D88\u9759\u97F3\uFF08\u9700\u8981\u97F3\u8F68\uFF09")},audios:[]},(t.wallpaperDisposers??=[]).push(()=>{d=!1,h?.destroy(),h=null}),t.canvas=h.canvas,ce(t,e,"media video \u2192 WebCodecs \u9010\u5E27\u8C03\u5EA6\uFF08\u9759\u97F3\u5FAA\u73AF\uFF09");return}f()}function e1(t,e,n){const r=Math.min(window.devicePixelRatio||1,n.renderDpr??e.cfg?.renderDpr??1),i=n.canvas?.clientWidth||window.innerWidth,s=n.canvas?.clientHeight||window.innerHeight;t.width=Math.max(1,Math.round(i*r)),t.height=Math.max(1,Math.round(s*r))}function t1(t,e){rr(t);const n=document.createElement("img"),r=Va(e.fit);n.style.cssText=`position:absolute;inset:0;width:100%;height:100%;object-fit:${r.objectFit};object-position:50% 50%;background:${r.background};`,n.src=e.src??"",n.addEventListener("error",()=>t.fallbackPage?.()),t.wrap?.appendChild(n),t.img=n}const n1=["scene.pkg","scenes/scene.pkg","gifscene.pkg"],r1={mp4:"video",webm:"video",mov:"video",m4v:"video",ogv:"video",gif:"gif",png:"image",jpg:"image",jpeg:"image",webp:"image",avif:"image",bmp:"image"};function Zd(t){const e=t.toLowerCase().split(";")[0].trim();return e==="image/gif"?"gif":e.startsWith("video/")?"video":e.startsWith("image/")?"image":null}function Oc(t){if(typeof t!="string"||!t)return null;let e=t;const n=e.indexOf("#");n>=0&&(e=e.slice(0,n));const r=e.indexOf("?");r>=0&&(e=e.slice(0,r));const i=e.split("/").pop()||"",s=i.lastIndexOf(".");return s<0?null:r1[i.slice(s+1).toLowerCase()]??null}async function i1(t,e,n){try{const r=await fetch(t,{...e,method:"HEAD",signal:n});return r.ok?Zd(r.headers.get("content-type")||""):null}catch{return null}}function Jd(t,e){const n=t.replace(/\/+$/,"");return{key:n,async scenePkg(r){let i=null,s=null;for(const o of n1){let c;try{c=await fetch(`${n}/${o}`,{...e,signal:r})}catch(u){if(r?.aborted)throw u;s=u;continue}if(!c.ok){i=c.status;continue}try{return await c.arrayBuffer()}catch(u){if(r?.aborted)throw u;const l=u instanceof Error?u.message:String(u);throw new Error(`\u8BFB\u53D6 scene.pkg \u4F53\u5931\u8D25\uFF08${l}\uFF09`)}}if(i!=null)throw new Error(`scene.pkg \u52A0\u8F7D\u5931\u8D25\uFF08HTTP ${i}\uFF09`);const a=s instanceof Error?s.message:"Failed to fetch";throw new Error(`scene.pkg \u52A0\u8F7D\u5931\u8D25\uFF08${a}\uFF09`)},async project(r){try{const i=await fetch(`${n}/project.json`,{...e,signal:r});return i.ok?await i.json():null}catch{return null}},async webEntry(r){let i="index.html";try{const s=await fetch(`${n}/project.json`,{...e,signal:r});if(s.ok){const a=await s.json();a&&typeof a.file=="string"&&a.file.trim()&&(i=a.file.trim().replace(/^\/+/,""))}}catch{if(r?.aborted)throw new Error("aborted")}return{url:`${n}/${i}`}},async mediaEntry(r){let i="";try{const s=await fetch(`${n}/project.json`,{...e,signal:r});if(s.ok){const a=await s.json();a&&typeof a.file=="string"&&a.file.trim()&&(i=a.file.trim().replace(/^\/+/,""))}}catch{if(r?.aborted)throw new Error("aborted")}return i?{url:`${n}/${i}`}:null}}}function s1(t,e){const n=t;return{key:typeof n.name=="string"?`file:${n.name}:${n.size}:${n.lastModified??0}`:void 0,scenePkg:()=>t.arrayBuffer(),project:async()=>e??null}}function a1(t,e,n){return{key:n,scenePkg:async()=>t,project:async()=>e??null}}function o1(t,e){const n=typeof t!="string",r=t;let i=e?.type??(n?Zd(t.type||""):null)??Oc(n?String(r.name??""):t),s=!1,a=null;const o=()=>n?(a||(a=URL.createObjectURL(t)),a):t;return{key:e?.key??(n?typeof r.name=="string"?`media:${r.name}:${r.size}:${r.lastModified??0}`:void 0:`media:${t}`),async scenePkg(){throw new Error("mediaSource \u662F\u7EAF\u5A92\u4F53\u6765\u6E90\uFF0C\u6CA1\u6709 scene.pkg\uFF08\u8BF7\u6539\u7528 httpSource/fileSource/bytesSource\uFF09")},async project(){return i?{type:i}:null},async mediaEntry(u){return!i&&!n&&!s&&(s=!0,i=await i1(t,void 0,u)),{url:o(),type:i??void 0}},dispose(){a&&(URL.revokeObjectURL(a),a=null)}}}const eh=!1,th=!0,nh=!1,c1=!1,l1=!1,rh=4,Ts=64,ih={STOPPED:0};function u1(){return{left64:new Float32Array(Ts),right64:new Float32Array(Ts),left32:new Float32Array(32),right32:new Float32Array(32),left16:new Float32Array(16),right16:new Float32Array(16),level:0,silent:!0}}function Ba(t,e){const n=e.length/t.length;for(let r=0;r<t.length;r++){let i=0;const s=Math.floor(r*n),a=Math.max(s+1,Math.floor((r+1)*n));for(let o=s;o<a;o++)i+=e[o];t[r]=i/(a-s)}}function f1(t,e,n){const r=e.length,i=n*.5,s=20,a=Math.min(2e4,i);let o=0;for(let c=0;c<Ts;c++){const u=c/Ts,l=(c+1)/Ts,f=s*Math.pow(a/s,u),d=s*Math.pow(a/s,l),h=Math.max(0,Math.floor(f/i*r)),p=Math.min(r,Math.max(h+1,Math.ceil(d/i*r)));let m=0;for(let w=h;w<p;w++)m+=e[w]/255;const g=Math.min(1,m/(p-h)*1.35);t.left64[c]=g,t.right64[c]=g,c<48&&(o+=g)}Ba(t.left32,t.left64),Ba(t.right32,t.right64),Ba(t.left16,t.left64),Ba(t.right16,t.right64),t.level=Math.min(1,o/(48*1.2)),t.silent=t.level<.02}function d1(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0)%360}function zc(t,e,n){const r=e/100,i=n/100,s=(1-Math.abs(2*i-1))*r,a=t/60,o=s*(1-Math.abs(a%2-1));let c=0,u=0,l=0;a<1?[c,u,l]=[s,o,0]:a<2?[c,u,l]=[o,s,0]:a<3?[c,u,l]=[0,s,o]:a<4?[c,u,l]=[0,o,s]:a<5?[c,u,l]=[o,0,s]:[c,u,l]=[s,0,o];const f=i-s/2;return[c+f,u+f,l+f]}function h1(t,e){const n=d1(e||"empty"),[r,i,s]=zc(n,72,48),[a,o,c]=zc((n+40)%360,55,28),[u,l,f]=zc((n+20)%360,70,72);t.primaryColor=Pe.mediaVec3(r,i,s),t.secondaryColor=Pe.mediaVec3(a,o,c),t.tertiaryColor=Pe.mediaVec3(u,l,f),t.textColor=Pe.mediaVec3(.98,.98,1),t.highContrastColor=Pe.mediaVec3(1,1,1),t.hasThumbnail=!!e}function m1(t,e,n){const r=document.createElement("canvas");r.width=32,r.height=32;const i=r.getContext("2d",{willReadFrequently:!0});if(!i)return null;i.drawImage(t,0,0,e,n,0,0,32,32);const s=i.getImageData(0,0,32,32).data;let a=0,o=0,c=0,u=0,l=0,f=0,d=0,h=-1;for(let w=0;w<s.length;w+=4){const y=s[w]/255,b=s[w+1]/255,v=s[w+2]/255;a+=y,o+=b,c+=v,u++;const k=Math.max(y,b,v),A=Math.min(y,b,v),T=k-A,S=.2126*y+.7152*b+.0722*v,P=T*1.4+(S>.15&&S<.85?.3:0);P>h&&(h=P,l=y,f=b,d=v)}if(!u)return null;const p=[l,f,d],m=[a/u*.55,o/u*.55,c/u*.55],g=[Math.min(1,p[0]*.45+.55),Math.min(1,p[1]*.45+.55),Math.min(1,p[2]*.45+.55)];return{primary:p,secondary:m,tertiary:g}}function p1(t,e,n,r=512){const i=document.createElement("canvas");i.width=r,i.height=r;const s=i.getContext("2d"),a=Math.max(r/Math.max(1,e),r/Math.max(1,n)),o=e*a,c=n*a;s.fillStyle="#000",s.fillRect(0,0,r,r),s.drawImage(t,(r-o)/2,(r-c)/2,o,c);const u=s.getImageData(0,0,r,r);return{width:r,height:r,rgba:new Uint8Array(u.data)}}function g1(){return{hasMedia:!1,state:ih.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,primaryColor:Pe.mediaVec3(0,0,0),secondaryColor:Pe.mediaVec3(0,0,0),tertiaryColor:Pe.mediaVec3(0,0,0),textColor:Pe.mediaVec3(1,1,1),highContrastColor:Pe.mediaVec3(1,1,1),trackIndex:-1,lyrics:[],lyricLine:"",lyricIndex:-1}}async function y1(){if(!navigator.mediaDevices?.getUserMedia)return null;try{const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1},video:!1}),e=new AudioContext,n=e.createMediaStreamSource(t),r=e.createAnalyser();return r.fftSize=2048,r.smoothingTimeConstant=.8,n.connect(r),e.state==="suspended"&&await e.resume().catch(()=>{}),{ctx:e,stream:t,analyser:r,buf:new Uint8Array(r.frequencyBinCount)}}catch{return null}}async function sh(t){const e=t?.origin??(typeof location<"u"?location.origin:""),n=t?.onArtwork,r=u1(),i=g1(),s={app:"",title:"",url:"",index:0};let a="off",o="offline",c="offline",u="",l=!1,f="";const d=await y1();d?a="mic":navigator.mediaDevices?.getUserMedia?a="denied":a="unavailable";let h=null,p=null,m=!1;const g=(k,A,T)=>{!e||!n||!l||f!==k&&(f=k,n({url:`${e}/api/system/artwork?k=${encodeURIComponent(k)}&_=${Date.now()}`,trackKey:k,title:A,artist:T}))},w=k=>{if(!k||!k.hasMedia){i.hasMedia=!1,i.state=ih.STOPPED,i.title="",i.artist="",i.album="",i.albumArtist="",i.position=0,i.duration=0,i.hasThumbnail=!1,i.trackIndex=-1,o=k?"empty":"offline",u="",l=!1,f="";return}o="live",i.hasMedia=!0,i.state=Number(k.state)===2?2:Number(k.state)===1?1:0,i.title=String(k.title??""),i.artist=String(k.artist??""),i.album=String(k.album??""),i.albumArtist=String(k.albumArtist??k.artist??""),i.position=Number(k.position)||0,i.duration=Number(k.duration)||0,l=k.hasArtwork===!0;const A=`${i.title}|${i.artist}|${i.album}`;A!==u&&(u=A,f="",i.trackIndex=i.trackIndex+1|0,h1(i,A)),g(A,i.title,i.artist)},y=k=>{if(!k){c="offline";return}s.app=String(k.app??""),s.title=String(k.title??""),s.url=String(k.url??""),c=s.app||s.title?"live":"empty"},b=async()=>{if(!(!e||m))try{const[k,A]=await Promise.all([fetch(`${e}/api/system/media`,{cache:"no-store"}),fetch(`${e}/api/system/window`,{cache:"no-store"})]);if(k.ok){const T=await k.json();w(T)}else o="offline";A.ok&&y(await A.json())}catch{o=o==="live"?"live":"offline",c=c==="live"?"live":"offline"}};if(e){await b(),p=setInterval(()=>{b()},1e3);try{h=new EventSource(`${e}/api/system/stream`),h.onmessage=k=>{if(!m)try{const A=JSON.parse(k.data);w(A.media),y(A.window)}catch{}}}catch{}}const v=k=>{!e||m||fetch(`${e}/api/system/media-control`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:k})}).then(async A=>A.ok?A.json():null).then(A=>{A&&typeof A=="object"&&w(A),b()}).catch(()=>{b()})};return{audio:{snapshot:r,pump:()=>{if(!d||m){r.level=0,r.silent=!0;return}d.analyser.getByteFrequencyData(d.buf),f1(r,d.buf,d.ctx.sampleRate||48e3)}},media:{snapshot:i,pump:()=>{},skipNext:()=>v("skipNext"),skipPrevious:()=>v("skipPrevious"),play:()=>v("play"),pause:()=>v("pause"),playPause:()=>v("playPause")},windowTitle:{snapshot:s,pump:()=>{}},status:()=>({audio:a,media:o,window:c,title:i.title,artist:i.artist,app:s.app,windowTitle:s.title,hasArtwork:l}),dispose:()=>{m=!0,p&&(clearInterval(p),p=null);try{h?.close()}catch{}if(h=null,d)try{d.stream.getTracks().forEach(k=>k.stop()),d.ctx.close()}catch{}}}}const b1={"common.h":`// WE common.h\uFF08\u91CD\u5EFA\u5B50\u96C6\uFF0C\u4F9B we-scene \u6D4F\u89C8\u5668\u6E32\u67D3\uFF09
567
+ }`;function Qv(t){const e=(u,l)=>{const d=t.createShader(u);if(t.shaderSource(d,l),t.compileShader(d),!t.getShaderParameter(d,t.COMPILE_STATUS))throw new Error("MDL \u7740\u8272\u5668\u7F16\u8BD1\u5931\u8D25: "+t.getShaderInfoLog(d));return d};let n=Xv(t),r=null;for(;;){const u=t.createProgram();let l=!1;try{t.attachShader(u,e(t.VERTEX_SHADER,$v(n))),t.attachShader(u,e(t.FRAGMENT_SHADER,Gv)),t.bindAttribLocation(u,0,"a_pos"),t.bindAttribLocation(u,1,"a_uv"),t.bindAttribLocation(u,2,"a_bone"),t.bindAttribLocation(u,3,"a_weight"),t.linkProgram(u),l=!!t.getProgramParameter(u,t.LINK_STATUS)}catch{l=!1}if(l){r=u;break}if(t.deleteProgram(u),n<=Mo)throw new Error("MDL \u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25\uFF08\u9AA8\u6570\u5DF2\u964D\u5230 "+Mo+"\uFF09");n=Math.max(Mo,n>>1)}const i=n,s={mvp:t.getUniformLocation(r,"u_mvp"),tex:t.getUniformLocation(r,"u_tex"),skin:t.getUniformLocation(r,"u_skin"),boneCount:t.getUniformLocation(r,"u_boneCount"),color:t.getUniformLocation(r,"u_color"),keepZ:t.getUniformLocation(r,"u_keepZ")},a=new Float32Array(i*16);for(let u=0;u<i;u++)a.set(Fm,u*16);const o=new WeakMap;function c(u){let l=o.get(u);if(l)return l;const d=t.createVertexArray();t.bindVertexArray(d);const f=u.vertexCount,h=new Float32Array(f*13);for(let y=0;y<f;y++){const w=y*13;h[w]=u.positions[y*3],h[w+1]=u.positions[y*3+1],h[w+2]=u.positions[y*3+2],h[w+3]=u.uvs[y*2],h[w+4]=u.uvs[y*2+1];for(let A=0;A<4;A++)h[w+5+A]=u.boneIdx[y*4+A],h[w+9+A]=u.weights[y*4+A]}const p=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,p),t.bufferData(t.ARRAY_BUFFER,h,t.STATIC_DRAW);const m=52;t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,t.FLOAT,!1,m,0),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,t.FLOAT,!1,m,12),t.enableVertexAttribArray(2),t.vertexAttribPointer(2,4,t.FLOAT,!1,m,20),t.enableVertexAttribArray(3),t.vertexAttribPointer(3,4,t.FLOAT,!1,m,36);const g=t.createBuffer();return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,g),t.bufferData(t.ELEMENT_ARRAY_BUFFER,u.indices,t.STATIC_DRAW),t.bindVertexArray(null),l={vao:d,vbuf:p,ibuf:g},o.set(u,l),l}return{gl:t,prog:r,maxBones:i,upload(u){c(u)},draw(u,l,d,f){const h=c(l);t.useProgram(r),t.bindVertexArray(h.vao),t.activeTexture(t.TEXTURE0);const p=d.overrideTex||(f&&f.glTex?f.glTex:f);t.bindTexture(t.TEXTURE_2D,p),t.uniform1i(s.tex,0),t.uniformMatrix4fv(s.mvp,!1,u),t.uniform1f(s.keepZ,d.keepZ?1:0);const m=d.color||[1,1,1,1];t.uniform4f(s.color,m[0],m[1],m[2],m[3]);const g=su(l,d.time||0,d.animLayers,d.boneOverrides),y=Math.min(l.bones.length,i);g&&y>0?(t.uniformMatrix4fv(s.skin,!1,g.subarray(0,y*16)),t.uniform1i(s.boneCount,y)):(t.uniformMatrix4fv(s.skin,!1,a),t.uniform1i(s.boneCount,0)),d.blending==="additive"?(t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE)):d.blending==="normal"?t.disable(t.BLEND):(t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA));const w=l.indexType==="u32"?t.UNSIGNED_INT:t.UNSIGNED_SHORT;t.drawElements(t.TRIANGLES,l.indexCount,w,0),t.bindVertexArray(null)}}}const Yv=Object.freeze(Object.defineProperty({__proto__:null,applyAttachmentBindOrigins:Wv,attachmentBind:Om,attachmentWorld:Um,bindWorldOf:Lm,computeSkinMatrices:su,createMDLRenderer:Qv,followAttachments:jv,mat4MulOut:Hv,parentMeshToWorldDelta:au,parseMDL:Cv},Symbol.toStringTag,{value:"Module"}));function Kv(t={},e={}){const n=typeof t.setTimeout=="function"?t.setTimeout:null,r=typeof t.clearTimeout=="function"?t.clearTimeout:null,i=typeof t.setInterval=="function"?t.setInterval:null,s=typeof t.clearInterval=="function"?t.clearInterval:null,a=typeof e.onError=="function"?e.onError:null,o=new Set,c=g=>{const y=Number(g);return Number.isFinite(y)&&y>0?y:0},u=g=>()=>{try{g()}catch(y){a&&a(y,"timer")}},l=(g,y)=>{const w=()=>{g.fired||(g.fired=!0,o.delete(w),y&&g.handle!=null&&y(g.handle))};return w.handle=null,w.valueOf=()=>typeof g.handle=="number"?g.handle:0,w};function d(g,y){if(typeof g!="function")return l({fired:!0,handle:null},null);const w={fired:!1,handle:null},A=l(w,r);return o.add(A),w.handle=n?n(u(()=>{w.fired=!0,o.delete(A),g()}),c(y)):null,A.handle=w.handle,A}function f(g,y){if(typeof g!="function")return l({fired:!0,handle:null},null);const w={fired:!1,handle:null},A=l(w,s);return o.add(A),w.handle=i?i(u(g),c(y)):null,A.handle=w.handle,A}function h(g){if(typeof g=="function"){g();return}r&&g!=null&&r(g)}function p(g){if(typeof g=="function"){g();return}s&&g!=null&&s(g)}function m(){for(const g of[...o])g();o.clear()}return{setTimeout:d,setInterval:f,clearTimeout:h,clearInterval:p,dispose:m,pendingCount:()=>o.size}}const Zv=Object.freeze(Object.defineProperty({__proto__:null,createEngineTimers:Kv},Symbol.toStringTag,{value:"Module"})),Co="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAA7J0lEQVR42u2d2XIcSZZY412mqYUbiIVYSBY3cKni1kWyyCKLxTZTd9u0pBlNz9L9JzMvmv4NfYn6s/ScsgQIEEBmRPhy7/Xr7ufhvIxNkwlWIs7x6+ERw3/9ZnMBAAAAfTHwjwAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAFBtAGwtAAAAoC8IAAAAAAIAAAAACAAAAABoNAC+3VoAAABAXxAAAAAABAAAAAAQAAAAAEAAAAAAQCMB8Hffbi0AAACgLwgAAAAAAgAAAAAIAAAAAGg1ALYXAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAoB8Cl7QUAAAD0xfB3l3YWAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAACAcAF9durEAAACAviAAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAAqg2AyzcWAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAFQXA7gIAAAD6ggAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAO0A2FsAAABAXxAAAAAAXQbAlb0FAAAA9AUBAAAAQAAAAABAFwHw9ZW9BQAAAPQFAQAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAngNgfwEAAAB9QQAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAAngLg6v4CAAAA+oIAAAAAIAAAAACAAAAAAIBWA+BgAQAAAH1BAAAAABAAAAAAQAAAAAAAAQAAAAAEAAAAABAAAAAAQAAAAAAAAQAAAACOAuCbqwcLAAAA6AsCAAAAgAAAAAAAAgAAAABaDYCbCwAAAOgLAgAAAIAAAAAAAAIAAAAAGg2AazcXAAAA0BcEAAAAAAEAAAAABAAAAAAQAAAAAEAAAAAAAAEAAAAABAAAAAAQAAAAAOAqAG4tAAAAoC8IAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAAbANg49YCAAAA+mL4ZuP2AgAAAPqCAAAAAOgxAL7duL0AAACAviAAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAgAAAAAIAAAAAAAAIAAAAACAAAAAAwDoDvFgAAANAXBAAAQCL/+183zsG/CRAAAAANyf3//Z//ksz//fdvT/+c373a5d8WCAAAAI/Cz5F9DEwNgAAAACjAcjX+n4bCn5sS/CcxAAQAAIAeS9EuhetB/MQAEAAAAJ2s9mMgBEA3AK5/twAAaJGl+D2v9sND4Dr/PUEcAgAAED8hAAQAAEDdLCXZmvgJASAAAAAmVv2ti//izYJHzxXgvz0QAADQKy2O+5kGAAEAADC66t/rVvyr04A9vhMQGwB3FgAAtdHDXn8sxxHAdwPCIAAAoDp6HvmHTAP4jgABAADInwgAIAAAoF7Y7ycCgAAAAOQPRAAQAACA/IEIgOgAuHT9zgIAwCPIXy4C+D7BRQgAAHALN/wRAUAAAADyByIACAAAQP6Q9Ojgf7vOdwwIAADwx1JQiFr/iYF814AAAAA/N/295qY/K/i+AQEAAG5AzNwPAKYBcHcBAFAa9v1L3Q/Ad69XhkubdxcAACVh9F/wfoDXe3wHO4UAAIDiIOLCWwF8BwkAAABruOvfwxRgn+8iAQAAwOq/y1MBfBcJAAAAK7jxz9kNgXwnCQAAAP0b//YRL1MAIAAAoL+9/02k624KsMl3kwAAAGDvnykAEAAAAKz+mQIAAQAAwOq/Tf7GcwEIAAAAVv998nueC0AAAABI8zeO/rENAF4C4N4CAMAKBFvLzYB8V1uHAAAAMxj/17YNwHeWAAAAEIDxf23bAHxnCQAAAMb/bAMAAQAAEMvvefQvAQAEAACw/w9sAwABAABd7P9fQqoEABAAAMD+P7ANAAQAADS+/3+ATAkAcBcAW/cWAACasP9f8/MADvgON8pweeveAgBAEwKg7vsA+A63CQEAAAQAEAB9BsD9BQCAJoi09gDgO9wiBAAAEAAwyvL4Jt9hAgAAgADoEL7DBAAAAAFAAAABAABAABAAQAAAABAABAAQAAAABAABAAQAABAAQAAAAQAABAAQAEAAAAABAAQAEAAAQAAAAQAEAAAQAEAAAAEAAAQAmL0L4M9bfIfbDYAHCwAATZbPk0emdfLXowDgO9wiBAAAqLOUCDIlAIAAAAACAAgAIAAAgAAAvzcA8v1tNwC2HywAALRBppUGAN/dZiEAAIAAgLUsb97ku0sAAABkwUmASvf/+e4SAAAAOXAfQH38/s1NvrsEAABAHkuZIFX2/4EAAADuAwD2/4EAAAC2AYD9fyAAAKBJ/sA2AON/IAAAgG0AYPwPRQPgcAEAYAXbALWM//mutg4BAACm/OEntgH8j//5nnYRAFe2DxcAAJb87T94KJDn1T/f0T4gAADAHLYB/PKHn27xHSUAAAD0QLYOb/77j0t8NwkAAACmAKz+gQAAAGAKwOofCAAAAJkpwDbyZfUPBAAAcCIAWP0DAQAAXbBceSJhVv9AAAAAUwAwPfe/zXeQAAAA4IZARv/QTwDsHC4AAErDVkCh0T/fvW4Zruw8XAAAeICtAOPRP9+5riEAAIAI6HH0z3eNAOAfAQA8wVaAPnzPgAAAACKgy31/vmNAAACAU3hKIPIHAgAAuB8AkD8QAADQVwRcRuDZN/1d5rsEBAAAEAHIH4AAAAAigLP+QAAAABABrez53+Y7AwQAALR0RPA2gkf+QAAAABEAyB8IAADoKgLYEuBmP8gKgEcLAIBa+etfeGDQ8t+A7wLEQgAAQPX0uiWwXPUfj/z5DgABAABMA1j1AxAAANDdNOBt2/cGHO/1898ZCAAAgC5C4Gjc/5ZxPxAAAABdhADiB7UAuHrj0QIAoHWWEv3rX3Yq2uPf4b8bqEIAAEB3LOXqcSqw/EyIHwgAAIAOYgDpAwEAAOBkm0AzCJZ//pLl38W/uQzXD54ttu+8PmXvwfvFzSe/zeLsn7eEAAAA6C4KvjuV9gmhkv8i++/4txQR/fNTIecKPpVlXLQSBQQAAAC4pLTsY6cFFQbA4wUAAEBpahF+yISghn9vAgAAACoX/qdVHmey8me2FwMEAAAAmHCyh59+k1644A8yCI+DuG2C5c9PAAAAQFfSzxK+guRF4yAiCJbx4yUECACAikenMfDvBv5H++uFf+CclBjwsD1AAAA4F7zEmeaQI01HI8qbz/n3h+TvbPx3tU7hS8dAqRAgAACcyF5T9LlxQBiAjPTbE35cDMxsDRj/nhEAANZ7ojc/3wh1+L7KY05EAdKP++72Jf3ZGJiZCliGAAEAYCh9GQl/ykBhUnD4niBA+rPSt5Ptr8KUmQos/70JAIAupS94njnqrPMn4Sej8T1A+jVIvkwYhISA5u8RAQAgzE609D8VO+6k/SCUE5b/JjsEQRXfXX/SDxTyI2UUg2AuBJb/TTQmbAQAgNBqP1z847J3ewPTaBgQBC18b31Jv7DoRaJAJwSkf2cIAIDMC2jYxbONG6EIgt5i1UL6lcg+OQjktwWkpgHD1RtPFgAQR5j4S94IVc+T0aaDgO+aBCf/nu6lnyngfQVKxUDYNCDvezFc3X2yAIAwgsXf8XGnA80g4DsY/D3dSX0Sn8qUSlb4+w7IiwGZEDi9NyDxe0IAAARdUF/MiP/8aukATIJg+d+F7+fx93Mn6dkSn9xLP0/UHxNRCoLcEBj5nUmNAAIAYIbplZS2+Os50lQyCJbi62lKcPKzpj1Myrf0bQT/UTUO4mNAZhpAAABYiV/04pkgbdEjTGXjQDoILkZBzZOCk9X9TtaDpIz381WE/9EpmTGQGgKj04AXBACAzrhf6iLq9KiTkyjQCIJ1YeBpYnD2M+U/Jlr71Im29AXE/DADpSCQDIEvvxvpEUAAACSs+j3d+ewjDEoFwSeVRxuflfEJmwlThM0zq/eLyH7uT66lryb8hwUQiAHxEEjcEiAAAD5fqHXE38j5ZmdRcFN5SuCfT0bPlnAi/YfOSYyB0hFAAED3hIz7sy+cFRx30o+COp9a6Fn2ZjeeinxfGxJ+VgzohMDUlsDY9IoAgK5X/evln3px1VwtVXLe2UkQHBR4AZL4Wx5NHxVdWPoPG6VUCKz5Tq+LAAIAOt3rfyO46o+/cO67OO7k5elotkcR096QmBILM3/OzOco8srcaqX/SxR7n4n739nFgFYELK975wLg2u6TBUBPyK364y6e9R11MogCR88mOHis/Orl4i9/Kix9RdnvGSAWBbkTgcDfkbEtgeX17+RaSABAN4zf6Kcn/nrPNudHQQtBUDe/NiB9e9HnRYFEDNhFwHBt9/sFQOvs3H0jsOqXEL+z406GUUAQ+F/ll5e+b+HHBYFlCMRvCSwjgACA5pka+UuKv7m7n6sLgl8RfnXSFxT+oSJWMZASAjHTgAsRQABAs4yO/FNX/Rrib+6Ik7cg+LUP2Zd4Ep+A9N2JXikKokJAcRpwMQIIAOhI/jEj/1Txd3jcyVMQPPL7AiTR90KoPFNCS/oZwj+sCOkYyJoGhN0XQAAAI39t8auI95cE6npcqt3zCKwjQfnFT9KnTiylLyLjD4LoBYFUCKRsCZxEAAEA7ctfaNUfdQFVFLz8USaDSPAWBGJvShRE4GfZL3pG31L6HwrjIQTytwQIAGhj5H9r3VP9Qkf+pcX/i6u7n03CwNPRQ4tQUPg84g+RspJ+dbIXjILcEBDeEiAAoAH5v1Qb+euIv86jTqpR8KjSKDDEh/AtpP+hAXJDQHAaMBEBBAAgfxPxKwlf6QhT8SgweKxx/aK3PGaqKX0dCe9m4CEGcqYBoREwXNv7fgFQI2sf7pM58pcVf2XHnZoKgo9+3pAo/tKnjz6lX2CVPyvzB4moxEH879++cggQAFAly1+oLPmnrvojLpxNHXdqIgjkwsCGEk+N9Cl9ccE/kI0DsRgwngYQANCA/A1W/dLiP2yAZoKgZBwIfOaHXqUvLPxkab+PJC8IioVAQgQQANCP/GdX/SkXV23pOzzWVEMQPPxY4YuWrJ4c6W8/P0/2740JDwKNENiPCoHpCBiu7f2wAKgBSfnnr/oDL6DV3/3cUBDUFgZKD45yKX2XohcIgugYiA2BuGnAxesgAQDuSb/TP0T+CuLv4riTTRSYP82waskLHDVV/O7Gr/LfV8p0DCT/filsCRAA0KD8f02Tf8BFNe/i+aFhGpoQVIv2k/i0pf++QXKnAvO/N5O/CzMRQABAXfJ/HCj/2JG/mvjLn2m2O+9sHwT9RsEvRi/Z0Rztv++M1BCQngZ8uQ4SANCZ/AXH/RY3Q2kedzKPA7vnErQVBb8YCh/p1xwCsRFAAEA18j8wln/8xdT67ucazjv7mBLseXlLYsILoPZMHiSlJX1jud5XwjAEVKcBFyKAAADkbyh+X8edvEVBmacX7qm/Unn+zzV7LHQL0h8V9c+LGwrsHqEZBTohEBIBBAA4ln/anf6p4t9XEn+ddz6XjoKyjzSWiAX1FzQZPVOiuPSNRJ8dBuYhkB8BBABUKn+DVX/GhbTdPdGSUwK/UeBP9hVL36Hso4OgZAhE3BdAAADyD77gVrov6ujJaG6CwGsYZP9MH+qTfqXC148B/WkAAQBty99a/Nz5XHcQaIaCymf7YPD4XYRfNgb0pgEEABSU/2+E5W+/6kf8noPgQxsvXRJ8pgTSLx0DqSGw+jsjEQEEAFQr//iR/8jNWaLiLyRZ0+NLNQdBLWHwQechUg/KSP9Gx9JXC4HJ342wCBiu7T1dAFhSSv4Sq35T8c+eT/45glJnnWsJAutI0Pvcuy6kX1qy775wL5Kz/1ur7QGLLYE1EUAAQDvyjxn5exP/iNyLHmsqFgba72Bvi+LP2y8m/UTB56IQBhIhkLIlMGzsPV0AWFCj/NXEf7+eEenaMOjm6KFz2Zd6toS59AuIvkAQxIdA3pbAsLH/dAGgjb38Q0f+MxdbyYtpQ3uiZaMg710HVcu+5MOkzKSvv7Lf+YzXIIj/nQqZBqxGAAEAfcg/e9WP9IMvWl6nBAEvQXIj+cOSj4guJH0BoWtSIgbifpfiI4AAAH/yzzrml77qFxM/dz8rPSq1zLsOVEl6UdP7Bp7C51f0alFgsi0Qd18AAQDIX2rczzln50Hw3tfbFh84eTeEY+nvVIbmVCBpGjBzXwABADryv11Y/oEjf5FVP6v9ioPAQxyUfm6E4n9nN8J/G4hhDOSEgNA0gAAAcba05O9t1W8mfqWboozOOtcbBI1hsjVVQvhvDVGIgYTfwfDfkekIIAAA+bsR/zs/x50cxAFB0N5oX130dxUQjgLxEIjcEiAAoFv5Z438xcXv+Gyz4UNQ6nkeQU3Cf+/mrn0V4d91QGYQSP2O5UQAAQB9yb+4+OXOMJsdZXIaBd0HwX3rl+xof0cdyz45CHJCQOOkwPmbA4eN/WcLgByKyl975C8h/sqOOzElqEH27909ga874UfFgFUIxEUAAQBNy3915B9zwa1hX7SCMPB2L4HnOJh48dMNh4/dFZH+3caJjIHc36GYCCAAoG35x676c1dXDZ5t9vZ0NJMw0IqEgDc8Fnt7XmPS387AJgZSQkByS4AAgGT5/9ik/LUunjvujjwRBOEX0ohYmHl1s6+fz1D6JpL/SRHhOAj8XdSeBhAA0Lj8NVf9Be5+dn7eufUgqBvN+1B0V/l2ojeOgqwQyI8AAgCcyn/uTn+h/f7i4n/r57iTQRQQBEg/TvhCsr4TiEAQmIZA4O/GWAQQANCO/GNG/kmr/jpWS7ZhUCoIiIIyT+LT+e5mCf+OIZFBoBECqdOAdfcFEADQpfylbu7ztidaexTcYErg8AU7TqR/xykak4GUEAj4HbgYAQQAJMj/t/3IP+si2vtxp4JB0GQUvDN8ja689JsRflYQpP5O6WwJEADQiPylR/6pF9LOpF9TEFS1fZD3XoidGqV/p0EkpgIzvzvpWwIEAHQi/9xVf2nxj59Zjrtb2ey8s1EQ7Ki8AOmdneCF3gexU6P0VeX7RgCvIRA6DZj/HhIAgPyzVv1a+6Jvix5r2q44CHbuVfiSJdNHRbci/TcF0YmB3BCI3RIYNg6eLQDOkiT/xwLynznjv6sp/0Li93e2WeGIk4Mg2OlW9to38VmN9t84RyoEbKcBw8bB8wXACa7lH3qzX9QjVW3Fny38IseZCkWB4VMM65d8a9JPE/GWAuoxYDYNIACgA/nrrPrTL6RV3v3s4XGpBYNAIhZsP5f2Q3l8CX9S2t8JkxUGBiGQEQEEAHQo/8RVf3U3QpWOglJB8LapFy5FPT2yGulnyv47B0QHgWIIJEYAAQCVyF9ovz9l1e9utVRrFLwtuG1QaxjYPSbai/Rdyj4yCERiQHMa8PnmQAIA+Xcrf8lx/+zF805HeAqCu+XfkCj28ie1o6VlpW8n/NcTlIoBhRCIiAACAPnXK//gm/30Vv2TF9Bqjjt1FgTRYWDMXYvX5zqSvqrYpdGKgTIRQAAg/2rlLzvyFxJ/c0edOgoCi0go8DPY3Llvtcp/7ZD4GLANgfEIGK4fPF9AX2zdftWl/CVW/bLif1MpHQdBBWx7lH4zsheKgZwQEJoGEADIv3P5lxB/+XPNcuedrR+bWugBRS0J37X0XzdGbgjE/Z6kRAAB0JP8v+tB/rIjfxnxZ4i+0JGm/DBo+KSBC9n7EH510r89QukYSA2BmGnAmgggALqV/6fm5Z+/6s+5mFZ6tjkwDuoJgnrDIOu9EG6lbyj1CTY/E/2/1Y4BkRAIjwACAPm3IX/tVb/AxbPa880qUeDlscZvi8bBttQLoO50Iv0ZoWsiHwUpISC5JUAANM9SxMg/TP55436L405vyh1lqikI7ui+JTEdoc9jeLy0qPSTRP9KgYgoUAiBqN+XyAgYrh+8WECbFJP/Q4fyV1n1B1w4q7z7udSjUg2eTXC3Mu7Yv0K3mPSjhP/KATNBIPV7lz0NGL/uEQDIP1P+Hx3LP3HVb77ab+yIU01B4CEOVH+uN1VJ36/s44MgPQaEQiAgAggA5F+h/BVH/gkX1PgLZ2dHnWoNgiqxeN4+wreJgZhtgbQIGJYXbaSZzt3n/y2K/cOf1T7L8ma/+uX/s5H8rcX/uhNKBcEbhO/1uF4Xwk+IAfFpQPx9AcNSEsuL91IeCH1e9E/e/sPiN7/9ixhSYbD2jH+v8hdd9eeI38eRJ/szz0JR4O15BDUL35X0X3WMfAikTAPOBcAJRMCq8Ocl/uf1fBr5v8/8ecvAWP69yN9gv9+r+APPMIseZfL0UBTVIKglDNJ+ri0n+/lFpX9LkBpCIGNLYLgojqMtgZsvumO5Ap8W/hmxf/rz4mUmvznLRBicTgdGPveNe2/XPt1PS/770vK/byX/9FV/2MXU+rhTyAXWy3lnmyDYquXtiELvgtgqvcovLf1Zgf+YgVUYpISA3JbAcLRSXBMBR9OArqUvJ/voKFgTBKeTgTOff3W/H/mrrPqlL6BujzolhIHz+wi2qn3hkubTIyuUvorkBePAUQgEBe1pAHwWxuoI+bdHF9wWxT++l28r/KAgWBMDy88ff7Mf8pdd9fd0I5T2g1Bsjx96DwP590K8rkv6QqK/nkF2FEiFgHIEDCdyOI6A9dOAtlf7KdL/NyHiY+Dp+z8l7Pd/WhF/E/IXGfkrir/pG6FKTgn0X4CkFQlBb2b08sTIotLXl7xeHEjEQOY0IHBLYDgribEIWLJd6ZbAUvyrq/0Y6a8R96+CRETBD0ny/xX5x8hfUPy9H3eqLggSAiEJlc/72uChPOWEf905QTGgHgIh04CJADiNgAamAffWrfZThD8i7heZxAbB3ee/707+scf8wkf+Cqv+0QsnR56qu4+gCl43Lf3rFaMTA6HbAnERMIzJY3oa8Loi8Yes9qeFHyb1fw0gPgp++Pmf1sv/MfIXk7+A+JG+9yB43bfoS9yP0onw42MgNQQypgEj9wUMU/vGUxFwfIPgSzfEi39c+nmST2X171vKP3m/vyn5vxWX//Sq35H4bxnQbRB4igPFn41V/io3f3OMlxiwmAasiYDhWBYzETA7DSgn/uUef5L4Z6U/I+yPAkz8+Wkjf4fyf+BB/m/k5K8p/lsljjt5igNPQZATDg4+l0PpmwhdE1chEDoNmL45cDgVxoxYpiJg/+jeAGvxv79wc1+8+IOk/9GW79/9r7X/xvnH/FqUv+TIv4D43ZxrjowDgsAf1i/ZKSV9C9EbRoFECERHwJlpwHAkipgIKDwNiBO/pvT/ZfE8gxdHnP8z16/6Q/b7kb/qyF/qQnrL33EnPw9C8X70sHPhl5K+N+ErBUHePQLpWwLDqTAeR4bAxDRAKwTkxB8n/OeZsp8jb9WP/NPlH7vql7hw1nPcyX8QdBAFUe+DeFW/9GsTvnAMpE8D0rYEhot7xVLTgOWb29Ru8FMWf7C8f8ng858xuuoX2e9vS/7J+/2xq34J8Td697P9k9EUn1roKQ6SXv70qn7ptyR8oRjYlAqBgAgY9h+tCiQ0AuamAbkhsDLulxB/ivSDxf7PI6z+/x6++uOk+JF/OflnXWRL3gjlOgp83VyY9JbE0HBI+HPSXvZUofSVRbuhQKkYWPs7JBwBw4ksxiMgfxqQsi1wcdwfL/751X688P85mydv/3FxJ2vVLyP/vYblnzTyz1n1z1w4r3eI7yDIe2OinNQLvxfCakpViejNw0B1WyAsAoaz0jhQngaEhMC9578L3+dPEH+c9Kdl/iyCZdDcef67zFV/5DG/RwGrfjH5v/cj/6xVv8wF1O2RJ4LAJBI2Pb706Vad0o+X80thlIMgNQQETgkMX2QxEQKC04CxEIga98+JP3S1Hyj8Sbl/mOfwxz+O/ltEr/qRv5z8U1f9FuKv+GhT+0FQERVKX0TyB0IkhoHW7530NGA4Lw3haUBgCKSM+9fu8SeJP1D4a+X+p0lCxK8y8m9N/ndS5S+86tcSf+NHnFSCgCjw8SQ+E+ErS14sDIRiQGUasD4ChhVxBEeAXAgsefj6f4ys+oXEP7Panxb+n4J58tM/LO48+52Q+JVu9kP+GfIXuIh2ftSJINB+VHTt0ncm+6QgEIgB8WnAagQMp5KICYHICIgNgeUz8C+O+0Pv6o9Z7UsI/4QHP/79jPgTV/3IX+5mv3Mjf2Pxc9zJPghu9SB7o2dLIPyMIMgIgajfjfAtgZMIGM7JwmoaEBACZ2PARvzx0n/80/88Ev/czyG16kf+efKPWvVLiL8X6bsMgh+dvgBJV/ae7kOJkv5Bw0zEgNo0IDAChhVpTESA+DQgMASOYuDVfz96Yl6q+HOk//SE9zHSzxB/9n7/3Bl/j/LXvdkvXv4+xF/VsSb3QRD4AqRbJQVf+DHRat/XjoRfKARSImBYLw/9aUBqCCxZPj3v8CgI/lFF/Ceyf/r+n06FPz/ePyP9aPEj/zz5C43811x4fayWKj/v7PbGwoxAECPus3l8uY5v6b9IxCoGEn7XBLcEhqUsUiJAMgRW7xEIj4ETlk/WO+LHP54Xf4T0l6I/IfbvPyt9KfHHj/yRv/mqX134L41wEgWuHmdcFs+vzvUj/TTBX/tM8ThQCoHQacCwdxQAMRHwUS0CcqYCZfiUIX7pVT/yT5J/6qrf4kYoq4to6QehOHpwUTOSb1L680LXRDUIUkMgMwKGs8LwMg0Yj4FPDUg/Y9WffLMf8g9Z9WtcSKu/8zkjCloIgmpRvwdF+3sbKfp9A4KjQDYENCNguCgO8WmAQAiMx8AnO+FnSz9W/Mg/Xf4Kq36RC2cjN0IlRsF1osC98MtJP1D4+86YDQJvIXD+voDhSBAxEZA6DRAKgZUYWBsFn/JE/2T933EgIX6xVX/8Mb9m5X87Xf6SF9eu7372FAQ9RIHZy3Vspe9e+BFBkB0DKdsCkREwnMriYWQIPJLYFsgLgckgECD/s/2qtOpH/iYjfynxd3/kyUEQ1BwF5m/T0/ruNij8pBgoNw24GAHDyri4yDRAJgRCQ0H/75oX/+yqH/nLyT925J98Ee1c+rUFgac4MPgZPUi/aeFHx4ByCATcFzAcCyIkAhSmAQVjwI/4JVf9Lcr/taj8JS7EZcT/QgGCQDUWCn/Ock/iKyH95wY4mAoIR8DwRRTTEZA2DeghBH6VEz/yV7jZT27VP3oRNRa9zlGmwoFQcxA4wqX0qxO9URTkTAQu/I6kButwXhi/mEwD4kPAWxCES3+9+GNW/b7kf6ND+euKP1HyQseY4iPBbxBsIHvjo6YW0n9eGYYhIDANGNaJw2oaMBsCrmLgVx3xz6z665X/2zLyjxn5R19kJS6igbJ3cqzJ7EEoSkGw0ZXwLU6daEtfUMZ7mVjHQFYIpEXASADERIBRCEzGgHQUzPw9j7TFn7nqR/7Cq/7ci2kDN0IdGD0IxeABRd7DIOsx0Qe1SV9P8FczkI8D5RBI3BIYToQRFAGp04CIEAiOgaAgECLw8wSL32TV34j8b8fIP3/kLzvut9gT9RUF/rYNXrp6EVLei5leFnvsbnHpK0heNA6UQiAnAjYCImA4lcVoBGhPA4RiQCIMEv6ufTHxj6z6kb+c/E1W/Y1LP/vJaC+cPLXwpeM3MJZ6L4SW9POFf9U5ajGQPA0Ii4DhnDRiIkB8GjAdAskxoMC+gvjDVv19yX8zUv4yq35B8avKttAxptqDIPgFSJqREPD3FnpdbjHpiwr/mSAWMaAQAoFbAsOxGM5HgMk0ICME9muR/qz481b9UTf7Hcn/Z+QvLv8KbobyFAlegyA5EDIo8rNp3o9iKfxnhdGIAfsIGM5LQmMaEBACmTEgHQVhf9/HbPFnj/wjbvZrSv6hN/tVI/5Gjze1FARVU7v0n1VCYAyIhkDclsBMAMhHgGwIxAWBPB+NxY/8/clfYsz/vBFKBQFRkHXUdL+M9NsTfloMhE8FBG8SHLkvYFgvjowtAakQCI6Bj2WF/+hj+M/zcPzfJm3kn7nfX6X8f5SVv5n4C55nVj3rrBwFBIGTl+xoSv9Z4+RMBXQjYJjeNw6dBiiHQFQMxARCxp/5ME78uat+5J8n//RVf474/R930o+DUkcPX3Qje71nS1Qm/V1lvIZAzL0BF+4LGGZvHMudBkiHQHYMWElfWPxRN/sh/7Kr/nTZuz3aJBYGJR9QVFsYvDAWfiXS33WEcAxM/44JTQPORMBwtEf8IASdaUBWCGgHQernmRK/5qq/cfnnjfwtVv3tnW+WfQhKmfsI4l6E5Efydo+K1pK+F9k/jcQyCDSnAfNbAsNSCKkRIDkNOB8CGTEQEgoaf/ac9CPFj/xLyD9F/Fo3Qlnvj3qJAm/vObBB/MVPSmf01b+vmXK/okByIJQKgYgIGE7EkBQBqdOAmRDY0w4BF+KPGfnLy3+nYfmnjfxj5d/L3c9CUeD1uQT7eq9Ujn5ds5cHR+0ZSj9R9lccEBUEaiGQtyUwnBXErto0ID0E/MXAL2HSTxB/6qp/9pifS/m/ciJ/HfG3f/dzw0EgGAvlPuvzBqTvR/ZiQZAbAsIRMKyThd40YCIEomPgF5/SzxE/8heSf8LIP/eiGnTh7POoU9NB4IbnDUi/LuHbxIDANGBiS2AYk8axXLSmAfkhsD4IcsNg9c/ay5b+L7P/FtHiDx35I/9J+Wev+oMunorSNT3CpBsF7m8sbEH4lnfudyb8rBiwmAaMRMAwJY+4LQGFEIiMgfkwGCf178kWv5r83/Upf9GRf0HxV3esyXMQ1B4Gcg+R6kr6NzJQjQGZEBj/3QjZEggIgPgtgfXbAiIhkBED4hzmiX/9qj905F+r/OVv+Mva789c9dtfOGs97+w5CLyFgdDP40r6ysK/UYCiISAzDTi5Fg5HsgiKAItpQEQMHHoSfqT4E1f9Qfv9yD9z5G8kfpPzzIrnnXedBcGe1/cfGHwm65fslJB+kJx/UEY+CkZ/D1OmAQkRMByJIjAC4qcBRiEgGQUpf6em+BP3+5uQv8id/qGrfmXxOzrXHHbe2UMUlH5qoUP2Cr1Vz1r6RUWfGQVmIZC5JXAaACfERIDJtkBmDKjyIUP8yD9f/i915W8mfv83QmWFgaeTBrVFgcijoiuRfhWyTwiCUiEQGAHDRXGERkD2NOBMCMTHwAe3wpcU/27ofwvkLzvyH73YSlw427jzOTkKPD6kqFQgzHyOqyWeHFlc+jaivvwZrzGw9vdKYUtg2LkYAClbAkVDQCMK0j9DtvhjVv29yl9kv99S/Bx38hwEUXEgTP5nflaP9BWFf9kAsRgwCoGQLYHhrCxspwFrQkA0BuzYFRR/uPznxP9uVPztyj9v5J98gZ24cF7pmPJBIBcGPrB8hoRP6V92hsVUQDMChovSyJsG6ITAbnXS/xD/byC66kf+Jqt+y9W+4yNN9QWB9zAo9dAof9K/XBmaU4G4EAi7L2BYJ48bEtOApBDwHQPz0k8TP/IvJ/+kC7Dmaj9K4EJHmArFgb8gsAoEo89fVPoFhL9zlu+F+PznqcZAbAhkTAMuXAOH4z3i9SLJiYD0bYGJEDAOgl0t6aes+jP3+1uWf/R+f+qqX0P87u5+LhcF/oPAObulb+IzEr645BPDQDwG9KcBFyNgOJLDiTiCIiB2GpAbAjMxsCYIxhgV+xhzf2+G+HejYuqdgPx/alf++7nyNxR/tUedSj029amzxxnXJHt/0q9T9rJBIBsCiRGwdzYAYiMgaRogEQKBQRAaCLF/Tu7nvq+x6teW/5tK5R868jcQfxPnm8tHQdZDihB+HdKvQvYyQSC1LbDyOxERAcM5WUxEgMQ0IP/+AKEgsBJ+jviDVv3IX23knyt+ReGXO8qUEQVen1y4W6vk1z89Euk7xCAEwrcEzl8Dh7XiUJ4G6IVAShwo/t1J4v957b+xF/lvFZX/CyH5+xd/XUebfATBFel3HUiGguhnsTppovSdbV34iVMBiW2B2C2BYUwe0dOA5BCwjAEjUsUfLP9p8SN/qZF/6sWzzaNONQaBehSo89T4aCnSLz0VEJ8GTETAMCWRtAjoOARyxC828leQ/3fe5Z+5328sflEx7wTgOgrKPZ/gqps4MHwBVEfSv3SOJ4Ec//97mArkTANCI2A4FsX0atJqGrCyPXC/HunvZvy8ciN/5J878tcSv+/jTnKhUHMQhEVCHkV+DivpFxD+rNy3E5kIBMsQyJ8GTG8JDF+EoRABmSHgNgbu5672Y8WP/MXln7rqj7iItnEjVF4ctBYEVXDD8Iy+0fd2VPTbBdCMAuNpwHBOGnd/mo4A422ByRi4X0b42dIfGfenrvpl5P/apfyvRco/deRfRPxV74laPB2NICjxMCkv3921wt92yoXPaR8C6REwHMnh7kW0pgEyIbByz4BkFKz7M4U+c5z4pW7261H+gqv+wAsqN0I5C4Ibvcle+Ul8yt/dFeFvV4xkDAhOA9ZFwHBOFDER4CQEVqNgJAyC+FlQ9vPjfv2Rf8Xy39eVf9zFNuMCypEnPycNaguDGzqPivYj/UaEHxQDVvcHxEXAsCIM4S2BEiHginsaq37kny5/A/Fz5Els28DsHQel4kDlxU8+pX+pF+nPxID+NCD85sBhrTjuyk8DuguBaPEr7vcj/zD5B1xwEX8LEwKBNyWqUOhpkUi/oqlA5JbATAQM46vHnAhIDIF7tYfA9M+WI/6V/X5J+d+uSP6hd/rHjvyzxG95pvmJENbnnXWC4LKnNyXeKPd2x8uupF9K+I8VcRYCQtOA4YswQiJAbhowHwLvql/tq636hY/5tS1/xVV/7ceddkqcd9YPgstNvGipHuHbS/+xE0qHQH4EDGelIRoBUiHgNgbeqYtfbr+/RvlbjvzLid/1USdXUfBDt1GQ95TI2qUfKeUtJSyCIPUegaDv+voIGLbOBcBEBGRPAwRC4DQG3rkU/rz0353/9xAZ+SN/aflrir/6PVFvUeDyBUiFXv5kcj5f+7ubJ/lvFUiPAssQiJgGnAuA746lsR0aAtnTgLcBkgyMAdUJQdxnkBW/vvw3G5a/+Ko/88J6TvpN39RUOgr0331w2dNLnsyewldY+kaizw4DDyEQGQHDqShiIsAwBKJjYHRiMELGn70jLP7UkX/X8t+Vkb/0BbZ56Xe0deAC4xMmutKPE/63laAWA7G/QxH3BQznhHFnXQgoREBiCGTHgAA7VuL3Kv+RACgv/5CRf8yqn4ebtBkEzsNgp9xx0mLSr1T4eTGgPQ0Iuy9gWBWH4TRgJQTiYmDHlfDTxJ898kf+0/I3WvWXk36hI0zNBcFIIEiGwk5Zwdvfj1JS+I8EcBgDUb8v8xEwHAtCIwJsQyA3DHay0RZ/yH4/8s+TvzfxV3qsqckgaIO2pP+oIJkxIBACElsCw3lZrEaAeQgoxIAeb5PEv/YOf42Rf+PyF9vvT1iRyV9AM+WddXzJWRwQBM2N9uuWvXwQjP9+Kk0DRiJgWJWGwDTgjkAEuI2BdOnnrvrT5f+qQ/nrrPrlLqQFzzSLxQJBwCpfS/qCct6MxDAIskMg5t6ANREwrJfHGz/TgMkYeGsv/Htpn307etWfsd/fq/wVV/0yF9N42Rc91hQdBqWmBAi/6FE9ke+roeBzcRoCKfcFDKMCUZ0GZIbAaAykxkHAn3W3jPij9/uRf4D8LcVf/53PxZ6MxpQg7FHR2zVKvwLRiweBcggEf+/PBsDtqQAQnAZMhEB2DERFgZ7s88WP/MflH7/ff1lC/krSb+qYk/aT0UTfdVC57HcKniqxlr6itL/5TLkgSAkB4WnAMgA2b395LGxUBIxOA1JD4Ce5ECiIqPgjR/7IX2bkn36hbVv6ck9G83bqoFwcTL7h0cNRUkvpCwh9moczTP/vdWJAKQQCI2A4FsOxOEynATMhsF2d9FPFL7nqb0T+Ucf85Eb+l5JX/drS93mkqZkgCH5DogLFflbNrSk94aeJXZKMKEj8HdSMgOGLIDIiIGcaMBkCfmNgUvo54kf+heTvQfz1H29qLgia4XGV0i8r+/gocBcCM5Ot4bwozkSA6DQgMAScx8Cs9BPFn7TqR/7T8g8c+aet+tdfQNs722z4hLStx3U+1bBb6VsI/2GFRMRATggITQOG9dLInwbohoBNEAQJP0r8Qqv+0Jv9WpO/8H5/GfE7Ou7kLAoIAruX7HhZ5dcvfIEYMJwGBAZATASkTAMiQiA4Bs5HwTpWxb6OiL/rTrr4p1f9Ujf79Sh/jZF/rvgrPO5UbRA8RviOR/vqI/3rCljFgMU04EIEDLMryJwtAekQiI4BBe4IiV995G/wSt+D+uQfd/NVjvgrP9ssHgYln0fwuH3Ziz5bQlP6jkVvFgayIZATAcORKAIiIGsaoBECVkGQ+rmixS+/34/8hVb90uLftDjyJHiUSSUKSgeB1zDIe/9Dk9K/XgkmISC0JfD55sDhdLUYEwEeQyAnDsT+zjcq4vck/w1v8hff71+9yGZfPEUlL3+USTwSPN1YuOXpZUiyL3syO15qLf0sER8qoRkDwiEQEQHDF2GERIDQNCAoBIRjQJVU8cfI/xXyT5D/pVT5B11kK9kXFQqEGoPgW/EXICmzpf1eCIfSdyV6hSiQCAGlCBjOSsN8GhAcAm+qkb6I+GNG/hl3+rcv/wLib+Zsc1gY1BgEQWGgFQkBf5/sz/moAemnCfrrDNSCwCgEVr+7IwFwIoj4CIidBoSFgO8YeGMiftGb/VTl/6KQ/L9Xk3/yBbXb407tBEFWJGyVkLvdiZPs76+S8L8ugEgMBP5uyU4DJgLgfAQkbglIhEB0DGhFQdjfuyUl/qRVf4vy/8FI/kKr/m7POHsLgkfNv2vB+oipnfR9il4uCnJCIGYaEL8lMFwUxqbENEAhBOJiQJdw6YeLP3Xk37L8Y+/0v5Qofz3xV3bcycujUkWfSdC58JOlr/l9LSD8jUBKxUBqCMRsCayJgGFMHnYREBACDmIgTvpvwn/2GPEjf7mR/+yqP+5iajsirT0MSgZBLWFg88TIb5xI30TuEojFQHoIpE4D1t0XMBoA6VsCyiEwEgRbWrKPkn6c+FVG/shfZ9UvvWISF7XA0aViUVDqpEHpOBD6vJudSD9a2A8ykY0CuRAInQbMR8BwJIeYCDAJgcgYmIiCJFL+bi3xI39D+SuL3/1RJy9RIPRMgq1G2axT+jrCf1CAvCCQDIHcLYHhnCgUpwHpIZAYAya8zhC/9ci/c/lvycg/+iJa1blm4TDwFgSbfcje/qE8QtJ3J3qBKIiOAYEIiJgGDCvSUJ4G5IXA67qkf0b8uat+5B8rf9lVv7z4D10cdzKNAk8nDTzFwabG46ErkH7Vwo+MgRIhEBABw1p5zIyZ06cBkiFgFQSJnytV/Bojf+QvIH8b6ddztMn6cakGDyiqiG+KPG9fU/oPGiUuBvJCID4ChjGB6E4DNEIgNw6E/s4c8ceM/L3Jf09A/jNP97skJn/hVX+pu5/dR4GPGwtrjwKVJ0deR/rFYyDnHoGsGwTPBMDGVACkTAMkQkAlBpRJ3eNPGfn3Kn+R/f55+eeLX1H4hY4zyUSBn+OH3uJA9+VPBe7cLyT8rxTwEwLy04DhRBhlI6DSGLjtR/zhd/rPvdLXo/zjbvYLHvmnjvsjL56uzzUrBUIdQRD+hsSUWIh7VbPCz3TdUPrGq/xJaV+b4/4FZv7/VcNAIAQyImA4XikGREChEHAXA6PSfx3/cyJ/AfnLjPyDLsQRF1B52Rc60iQUBfUFQWo8FP4sDUo/TPL3DZgOA9sQkImA4XRUfEYichGQGwIzMXDbVvgi0k8RP/KXk3/Kql9a/NXc/awXBf5PGlSA8HMlvEh/Wvb3nbE+CLRCIG0asGZydRoAJ3KIiYAiIfBqjXzXBEFqGIz8OZtS0h8Rf478N1Lkv4/881f9CRfPpm6Cko+COp5H0KHwDaQ/Lvz7FSIVAzEhkDgNOBcApxEgtyUwui2QHQLjQTAbBlGizxS+yaq/Y/lv5cpfWfzd3PlcKggOnb78qNQLoA7rlH7VwteMAf0IGFZkcVN+GqAfAmFREIbw5xFe9cfd6d+2/FVG/rni57jTfBR4DQKLSFB//4NP6X/VjfTDYqBsCEwFgNKWwOS2gEoIFOSWjviRv/LIP+AiG37xfAAuguDQ95sWFR4V/bVH6Xcn/JkYyAkBwQgYJgVy0yoEGomBHPGLjvyRv/Sqv5T4vzKknyDwHAeH+o+JZrRfcQiM/56kRMAwLxKdCGgqBBTFn7LfH/yAH1H5P21E/mXEH3emWfAo08xZ568qDYKvPb0lUfClT7IPj0L61YdAzDRgzfVvOBFGWATohECVMTAh/c2In1t65I/8A0f+qat+oYvoV66PO83HQY1BIB8Guug8MRLptxMCCdOAiwFw7TQAlCJAJAQuxMCt0sJ/Nfo5r2ut+pH/tPy1V/0CF9L6b4QqGQXeHmvsQPIlz+cjfX8hkLAlMBzJ4bM4giLAKASiYkAjCm4pSD9A/Fn7/d3IX2fkH3Zx5aI5d9SpeBBs1PeSJdlHRSP9lkJAMwKGU0mciwDFaUBCCEzHwEwUZPGjjPTVVv1O5X/DofyzV/2JF85ejztdcxYEtYZBgcdEI/1apwHxWwLDijBiIqBACITFgA7XlcSfLf/9VuT/2Fz+kuJfvXByASsXBA+KviFR7+VPBi/XQfpthEBABAxrxSGwJWARAtpBkPu5NMWP/JVG/jni58LpPAgSw6AYhq/N5bvb2LZAWAQMowI5MJ4GCIRAaCio/j0RPy/yt5T/zMg/4cLLar+VICgVCLY/F8LvbRowHwHDsSQmZBIbARIhYBAD9Yk/ZL8f+Vus+hF/b0FQJ6zymQaMhcCFAJiPAIlpQFIIeI6ByJ9jQ2LV36v8Nfb7I1djiJ8gQPrQ0pbAsCINg2lAcgh4iIGEz7yRuepPGflryf+KtPy3Sssf8bcSBF/1LnuEz5ZAZASsCQCFaYBGCFgFQcZnyxM/8k+Xv/CqnwsqUYDwoYlpwPkIGE6EERUBqdMAzRDIDQPBv3tU/CmrfumRP/IPkj+r/raj4KvaRO/qUdHQSgQMJ7JYHwFK04CJEFCJASPyxR+66s/d729E/gojf8TfSRRcK/OGxKA3M15D9pDJ7Pf3+Ho4nJVGUgTkTANmQmCjSukLiB/5l5M/F1ziICIQkriG5MHHNGA4FsSFCLCeBpwLAf8xsCEq/oxVf+Pyj73ZL3Xkz6ofxF6rjNShoggYvoji+UJ+GqATAhtNSD9/1Y/8WfUDAKRGwHBeGKERoDwNWBsD00GwYSL7NdK/mfizBa/6Q0b+yD9W/qz6AaC3+wJmAmA1BK5lTgNEQiAhBuSRkH7mqr9G+W97lj8XBQDo9+bAYfSomNQ0QDoERoPgpZ7sbwp83ijxZ+z3X5D/lSLyf2Iv/5j9flb9AMCWwGI4EkVMBKROA7RCYDIIMhD7bC/yxv0x+/3dy5+RPwBAaAQMp8LYiwyBfckQEI4BF7xQWvUjf0b+AAD5ETCc3ys2nAY0GwJC4k/e729X/sn7/az6AQBWGJZiCI8AhWlAEyGwRvoHgT+74Mh/9Ga/3fXiR/4AAJ0HwHEEPM2LAMEQqCMGXsiLP2PkHyv/yw3Ln5E/AEBEAKyNgIgtgflpQEQITMbAi4qlPy1+5C8kf1b9AABxAfAlBJ4pTgPSQ2B9DLwwE3669AVX/d3Ln5E/AIBaAMRPAwxCICoIQiNh/n93LVv6Wqv+iZv9WpM/+/0AAHYBIBEBqiGwJgbSwmBE9NnSFxR/9Kof+QMAwFwAnAgjJgT2nIVARBjoiD5Q/MhfVP7c7AcAkBUAPyySIiBnGjAbAoIxYMZzZfEjf+QPACAeAGEREH+DYOsh8DxD/HHyv5Ir/x2P8j9Mlz8jfwAAqQAID4GrRULASxA81xV/zMg/+AE/yB8AAGYDIGMakBgCV5NC4Llb6cuIP23kj/wBACAoAC6vDYCYCEiZBgSEQHQMSIRB4t+XK/6kVT/yBwCAzAA4wVMIyMWAErPSTxF/uvxjbvZD/gAA8P8BH8l/mUKxpUMAAAAASUVORK5CYII=",ei={STOPPED:0,PLAYING:1,PAUSED:2};class St{constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new St(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new St(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){if(e!==null&&typeof e=="object")return new St(this.x*e.x,this.y*e.y,this.z*e.z);const n=Number(e)||0;return new St(this.x*n,this.y*n,this.z*n)}divide(e){const n=Number(e)||1;return new St(this.x/n,this.y/n,this.z/n)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}copy(){return new St(this.x,this.y,this.z)}toArray(){return[this.x,this.y,this.z]}}function Jv(t,e,n){return new St(t,e,n)}const Io={primary:[.96,.65,.14],secondary:[.08,.11,.18],tertiary:[.66,.74,.88],text:[.96,.97,1]},eA=[{title:"WebWallGL",artist:"oneincase",album:"Scene",albumArtist:"oneincase",duration:212,colors:Io,thumbnail:Co,lyrics:[[0,"\u573A\u666F\u4E00\u5C42\u5C42\u4EAE\u8D77"],[12,"\u9AA8\u9ABC\u4E0E\u7C92\u5B50\u5404\u5C31\u5404\u4F4D"],[26,"\u811A\u672C\u5728\u6C99\u7BB1\u91CC\u82CF\u9192"],[41,"\u628A\u6BCF\u4E00\u5E27\u4EA4\u7ED9\u65F6\u95F4"],[58,"WebWallGL"],[72,"\u573A\u666F\u6B63\u5728\u547C\u5438"],[95,"\uFF08\u95F4\u594F\uFF09"],[126,"\u56FE\u5C42\u6392\u6210\u661F\u8F68"],[140,"\u6548\u679C\u94FE\u4E00\u5BF8\u5BF8\u70B9\u4EAE"],[158,"\u6211\u4EEC\u4E0D\u6E32\u67D3\u9ED1\u6697"],[176,"\u53EA\u6E32\u67D3\u5149"],[198,"\u2026\u2026"]]},{title:"WebWallGL",artist:"oneincase",album:"Web",albumArtist:"oneincase",duration:187,colors:Io,thumbnail:Co,lyrics:[[0,"iframe \u91CC\u6709\u4E00\u5EA7\u57CE"],[14,"shim \u4E3A\u5B83\u70B9\u4EAE\u8DEF\u706F"],[30,"\u6307\u9488\u7FFB\u8FC7\u5C71\u810A"],[46,"\u4E8B\u4EF6\u6309\u65F6\u5230\u8FBE"],[63,"WebWallGL\uFF0C\u7F51\u9875\u6B63\u5728\u64AD\u653E"],[88,"(instrumental)"],[118,"\u6BCF\u4E00\u5E27\u90FD\u662F\u540C\u6E90"],[134,"\u6BCF\u4E00\u6B21\u70B9\u51FB\u90FD\u6709\u56DE\u58F0"],[152,"\u7F51\u9875\u6B63\u5728\u64AD\u653E"],[170,"\u4E0D\u505C\u6B47"]]},{title:"WebWallGL",artist:"oneincase",album:"Video",albumArtist:"oneincase",duration:241,colors:Io,thumbnail:Co,lyrics:[[0,"\u89E3\u7801\u5668\u63A8\u5F00\u7B2C\u4E00\u5E27"],[16,"\u5FAA\u73AF\u70B9\u6CA1\u6709\u7F1D\u9699"],[33,"\u5E27\u7387\u8D34\u7740\u5FC3\u8DF3\u8D70"],[52,"\u753B\u9762\u4E0D\u65E7"],[70,"\u65F6\u95F4\u4E00\u76F4\u65B0"],[92,"\uFF08\u95F4\u594F\uFF09"],[130,"\u628A\u50CF\u7D20\u4EA4\u7ED9\u786C\u4EF6"],[148,"\u628A\u6D41\u7545\u7559\u7ED9\u773C\u775B"],[172,"\u4E00\u5708\u4E00\u5708"],[200,"\u90FD\u662F\u7B2C\u4E00\u5708"],[226,"\u2026\u2026"]]},{title:"WebWallGL",artist:"oneincase",album:"Live",albumArtist:"oneincase",duration:168,colors:Io,thumbnail:Co,lyrics:[[0,"\u9EA6\u514B\u98CE\u542C\u89C1\u623F\u95F4"],[11,"\u9891\u8C31\u5F00\u51FA\u516D\u5341\u56DB\u4E2A\u7A97\u53E3"],[24,"\u6B63\u5728\u64AD\u653E\u7684\u6B4C"],[38,"\u6709\u540D\u5B57\u4E5F\u6709\u5C01\u9762"],[55,"WebWallGL \u5B9E\u51B5"],[76,"(drop)"],[104,"\u7CFB\u7EDF\u5728\u8BF4\u5B83\u5728\u542C"],[122,"\u58C1\u7EB8\u5728\u8DDF\u7740\u5531"],[146,"\u2026"]]}],Ro=3;function zm(t=20260901){const e=eA,n=e.reduce((y,w)=>y+w.duration+Ro,0),r={hasMedia:!1,state:ei.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,thumbnail:"",primaryColor:new St(0,0,0),secondaryColor:new St(0,0,0),tertiaryColor:new St(0,0,0),textColor:new St(1,1,1),highContrastColor:new St(1,1,1),trackIndex:-1,lyrics:[],lyricLine:"",lyricIndex:-1};let i=0,s=!1,a=0,o=0;function c(y){let w=0;const A=(y%e.length+e.length)%e.length;for(let b=0;b<A;b++)w+=e[b].duration+Ro;return w}function u(y){let w=n>0?y%n:0;w<0&&(w+=n);let A=-1,b=0,v=!1;for(let I=0;I<e.length;I++){const B=e[I].duration;if(w<B){A=I,b=w;break}if(w-=B,w<Ro){A=I,b=B,v=!0;break}w-=Ro}A<0&&(A=e.length-1,b=e[A].duration,v=!0);const x=e[A];r.hasMedia=!0,r.trackIndex=A,r.title=x.title,r.artist=x.artist,r.album=x.album,r.albumArtist=x.albumArtist,r.duration=x.duration,r.position=b;const P=x.duration>0?b/x.duration:0;s?r.state=ei.PAUSED:v?r.state=ei.STOPPED:P>.7&&P<.76?r.state=ei.PAUSED:r.state=ei.PLAYING,r.hasThumbnail=!v,r.thumbnail=v?"":x.thumbnail||"";const S=x.colors;r.primaryColor=new St(S.primary[0],S.primary[1],S.primary[2]),r.secondaryColor=new St(S.secondary[0],S.secondary[1],S.secondary[2]),r.tertiaryColor=new St(S.tertiary[0],S.tertiary[1],S.tertiary[2]),r.textColor=new St(S.text[0],S.text[1],S.text[2]);const k=.2126*S.primary[0]+.7152*S.primary[1]+.0722*S.primary[2];r.highContrastColor=k>.5?new St(0,0,0):new St(1,1,1),r.lyrics=x.lyrics;let _=-1;for(let I=0;I<x.lyrics.length;I++)b>=x.lyrics[I][0]&&(_=I);return r.lyricIndex=_,r.lyricLine=_>=0?x.lyrics[_][1]:"",r}function l(y){o=Number(y)||0;const w=s?a:o+i;return u(w)}function d(y){s=!1;const w=c(y);return i=w-o,u(w)}function f(){const y=r.trackIndex<0?0:r.trackIndex+1;return d(y)}function h(){const y=r.trackIndex<0?e.length-1:r.trackIndex-1;return d(y)}function p(){return s||(a=o+i,s=!0,r.state=ei.PAUSED),r}function m(){return s?(s=!1,i=a-o,u(a)):r}function g(){return s?m():p()}return{update:l,snapshot:r,tracks:e,cycle:n,MEDIA_PLAYBACK:ei,skipNext:f,skipPrevious:h,play:m,pause:p,playPause:g}}function tA(t,e=512){const n=Math.max(8,e|0),r=new Uint8Array(n*n*4),i=t&&t.colors?t.colors:{primary:[.5,.5,.5],secondary:[.1,.1,.1],tertiary:[.8,.8,.8]},[s,a,o]=i.primary,[c,u,l]=i.secondary,[d,f,h]=i.tertiary;for(let p=0;p<n;p++)for(let m=0;m<n;m++){const g=m/(n-1),y=p/(n-1),w=g-.5,A=y-.5,b=Math.sqrt(w*w+A*A)*2,v=.5+.5*Math.sin(b*18-1.2),x=.5+.5*Math.sin((g+y)*6),P=Math.min(1,Math.max(0,b));let S=s*(1-P)+c*P,k=a*(1-P)+u*P,_=o*(1-P)+l*P;S=S*(.72+.28*v)+d*.18*x,k=k*(.72+.28*v)+f*.18*x,_=_*(.72+.28*v)+h*.18*x;const I=1-.35*Math.min(1,b*b),B=(p*n+m)*4;r[B]=Math.max(0,Math.min(255,Math.round(S*I*255))),r[B+1]=Math.max(0,Math.min(255,Math.round(k*I*255))),r[B+2]=Math.max(0,Math.min(255,Math.round(_*I*255))),r[B+3]=255}return{width:n,height:n,rgba:r}}function nA(t,e){const n=[];if(!e)return n;const r=!t;return(r||t.hasMedia!==e.hasMedia)&&n.push({name:"mediaStatusChanged",event:{enabled:e.hasMedia}}),(r||t.title!==e.title||t.artist!==e.artist||t.album!==e.album||t.albumArtist!==e.albumArtist)&&n.push({name:"mediaPropertiesChanged",event:{title:e.title,artist:e.artist,album:e.album,albumArtist:e.albumArtist,albumTitle:e.album,subTitle:"",trackType:"music"}}),(r||t.hasThumbnail!==e.hasThumbnail||t.trackIndex!==e.trackIndex||t.thumbnail!==e.thumbnail)&&n.push({name:"mediaThumbnailChanged",event:{hasThumbnail:e.hasThumbnail,thumbnail:e.thumbnail,primaryColor:e.primaryColor,secondaryColor:e.secondaryColor,tertiaryColor:e.tertiaryColor,textColor:e.textColor,highContrastColor:e.highContrastColor}}),(r||t.state!==e.state)&&n.push({name:"mediaPlaybackChanged",event:{state:e.state}}),(r||Math.floor(t.position)!==Math.floor(e.position)||t.duration!==e.duration)&&n.push({name:"mediaTimelineChanged",event:{position:e.position,duration:e.duration}}),(r||t.lyricIndex!==e.lyricIndex||t.trackIndex!==e.trackIndex)&&n.push({name:"mediaLyricsChanged",event:{line:e.lyricLine,index:e.lyricIndex,lines:e.lyrics}}),n}function rA(t){return t?{hasMedia:t.hasMedia,state:t.state,title:t.title,artist:t.artist,album:t.album,albumArtist:t.albumArtist,position:t.position,duration:t.duration,hasThumbnail:t.hasThumbnail,thumbnail:t.thumbnail,trackIndex:t.trackIndex,lyricIndex:t.lyricIndex,lyricLine:t.lyricLine}:null}function Hm(t){let e=String(t||"");return e=e.replace(/\.(ogg|oga|mp3|wav|flac|m4a)$/i,""),e=e.replace(/^\s*\d{1,3}\s*[.\-_]\s*\d{0,3}\s*[.\-_\)]?\s+/,""),e=e.replace(/^\s*\d{1,3}\s*[.\-_\)]\s+/,""),e.trim()}function iA(t,e){const n=[],r=new Map;let i=null,s=0;const a={primaryColor:new e(.18,.22,.3),secondaryColor:new e(.08,.1,.16),tertiaryColor:new e(.6,.66,.76),textColor:new e(.96,.97,1),highContrastColor:new e(1,1,1)};function o(h,p){if(!h||r.has(h))return;const m=Hm(p),g={au:h,title:m,key:`wa:${n.length}:${m}`};return n.push(g),r.set(h,g),g}function c(h){const p=r.get(h);!p||i===p||(i=p,s++)}function u(h){i&&i.au===h&&(i=null,s++)}function l(){return i?n.indexOf(i):-1}const d={get hasMedia(){return i!=null},get state(){if(!i)return t.STOPPED;const h=i.au;return!h.paused&&!h.ended?t.PLAYING:h.ended?t.STOPPED:t.PAUSED},get title(){return i?i.title:""},get artist(){return""},get album(){return""},get albumArtist(){return""},get position(){return i&&Number(i.au.currentTime)||0},get duration(){const h=i?Number(i.au.duration):0;return Number.isFinite(h)?h:0},get hasThumbnail(){return!1},get thumbnail(){return""},get trackIndex(){return l()},get lyrics(){return[]},get lyricIndex(){return-1},get lyricLine(){return""},primaryColor:a.primaryColor,secondaryColor:a.secondaryColor,tertiaryColor:a.tertiaryColor,textColor:a.textColor,highContrastColor:a.highContrastColor};function f(h){const p=(h%n.length+n.length)%n.length,m=n[p];if(m){for(const{au:g}of n)if(g!==m.au){g.pause();try{g.currentTime=0}catch{}}Promise.resolve(m.au.play()).catch(()=>{}),c(m.au)}}return{snapshot:d,register:o,markPlayed:c,markStopped:u,hasCurrent:()=>i!=null,_changeSeq:()=>s,skipNext(){n.length&&f(l()+1)},skipPrevious(){n.length&&f(l()-1)},play(){i&&Promise.resolve(i.au.play()).catch(()=>{})},pause(){i&&i.au.pause()},playPause(){i&&(i.au.paused?this.play():this.pause())}}}const sA=Object.freeze(Object.defineProperty({__proto__:null,MEDIA_PLAYBACK:ei,cloneMediaSnapshot:rA,createSimulatedMedia:zm,createWallpaperAudioMedia:iA,diffMediaEvents:nA,mediaVec3:Jv,renderThumbnail:tA,songTitleFromLayerName:Hm},Symbol.toStringTag,{value:"Module"})),Vm=14,ca=[{app:"Safari",title:"GitHub \xB7 we-scene-renderer",url:"https://github.com/oneincase/we-scene-renderer"},{app:"Google Chrome",title:"YouTube",url:"https://www.youtube.com/watch?v=dQw4w9WgXcQ"},{app:"Google Chrome",title:"Wallpaper Engine - Workshop",url:"https://steamcommunity.com/app/431960/workshop/"},{app:"Safari",title:"MDN Web Docs",url:"https://developer.mozilla.org/en-US/docs/Web/API"},{app:"Music",title:"\u591C\u822A\u661F \u2014 \u76F8\u4F4D\u8FC1\u79FB",url:""},{app:"Code",title:"we-scene-renderer \u2014 text.js",url:""}];function Wm(){const t={app:"",title:"",url:"",index:-1};function e(n){const r=Number(n)||0,i=ca.length?Math.floor(r/Vm)%ca.length:0,s=ca[i]||ca[0];return t.app=s.app,t.title=s.title,t.url=s.url,t.index=i,t}return e(0),{update:e,snapshot:t,tabs:ca,hold:Vm}}function jm(t){const e={name:"",at:0};function n(r){return e.name=String(r||""),e.at=Date.now(),typeof t=="function"&&t(e.name),e.name}return{openUserShortcut:n,last:e}}function aA(t){const e=zm(t),n=Wm(),r=jm(null);return{media:e,windowTitle:n,shortcuts:r}}const oA=Object.freeze(Object.defineProperty({__proto__:null,createShortcutHandler:jm,createSimulatedSystem:aA,createSimulatedWindowTitle:Wm},Symbol.toStringTag,{value:"Module"}));function cA(t={}){const e=t.target||(typeof window<"u"?window:null),n=t.viewport||(typeof window<"u"?()=>({w:window.innerWidth||1,h:window.innerHeight||1}):null),r={u:.5,v:.5,screenX:0,screenY:0,wx:0,wy:0,originY:null,lastU:.5,lastV:.5,lastScreenX:0,lastScreenY:0,lastWx:0,lastWy:0,lastOriginY:null,leftDown:!1,has:!1,moveCount:0,downCount:0,upCount:0,lastEventTime:0,screenW:1,screenH:1};function i(){if(!n)return;const f=n();r.screenW=f.w||1,r.screenH=f.h||1}i();function s(f,h){const p=f/r.screenW,m=h/r.screenH;r.has||(r.lastU=p,r.lastV=m,r.lastScreenX=f,r.lastScreenY=h),r.screenX=f,r.screenY=h,r.u=p,r.v=m,r.has=!0,r.moveCount++,r.lastEventTime=Date.now()}function a(f){const h=(f&1)!==0;h!==r.leftDown&&(r.leftDown=h,h?r.downCount++:r.upCount++,r.lastEventTime=Date.now())}function o(f){i();let h=f.clientX,p=f.clientY;if(e&&typeof e.getBoundingClientRect=="function"){const m=e.getBoundingClientRect();h-=m.left,p-=m.top}s(h,p)}function c(f){f.button!==void 0&&f.button!==0||a(1)}function u(f){f.button!==void 0&&f.button!==0||a(0)}function l(){a(0)}let d=!1;return e&&e.addEventListener&&(d=!0,e.addEventListener("mousemove",o,{passive:!0}),e.addEventListener("mousedown",c,{passive:!0}),e.addEventListener("mouseup",u,{passive:!0}),e.addEventListener("blur",l,{passive:!0}),typeof document<"u"&&document.addEventListener&&document.addEventListener("mouseleave",l,{passive:!0})),{state:r,pushExternal(f){if(!f)return;i();const h=Number(f.u),p=Number(f.v);Number.isFinite(h)&&Number.isFinite(p)&&s(h*r.screenW,p*r.screenH),a(Number(f.buttons)||0)},pushExternalLeave(){a(0)},beginFrame(){i(),r.lastU=r.u,r.lastV=r.v,r.lastScreenX=r.screenX,r.lastScreenY=r.screenY,r.lastWx=r.wx,r.lastWy=r.wy,r.lastOriginY=r.originY},syncWorld(f,h=0,p=0){if(!f)return;r.wx=f.offX+r.u*f.viewW-h,r.wy=f.offY+r.v*f.viewH-p;const m=Number(f.projH);r.originY=Number.isFinite(m)?m-r.wy:r.wy,r.lastWx===0&&r.lastWy===0&&(r.lastWx=r.wx,r.lastWy=r.wy,r.lastOriginY=r.originY)},normalizedDelta(){const f=r.u-r.lastU,h=r.v-r.lastV;return Math.hypot(f,h)},dispose(){!d||!e||!e.removeEventListener||(d=!1,e.removeEventListener("mousemove",o),e.removeEventListener("mousedown",c),e.removeEventListener("mouseup",u),e.removeEventListener("blur",l),typeof document<"u"&&document.removeEventListener&&document.removeEventListener("mouseleave",l))}}}const lA=Object.freeze(Object.defineProperty({__proto__:null,createPointerSource:cA},Symbol.toStringTag,{value:"Module"}));function qm(t,e,n,r,i,s,a,o,c){const u=t.size||[0,0],l=t.scale||[1,1,1],d=u[0]*l[0],f=u[1]*l[1];if(!(d>0)||!(f>0))return null;const h=t.origin||[0,0,0];let p=h[0],m=r-h[1];if(t.parallaxDepth&&c){const b=Ko(t,c);p+=b[0],m+=b[1]}else if(t.parallaxDepth&&(i!==0||s!==0)){const b=t.parallaxDepth;p+=b[0]*.5*i,m+=b[1]*.5*s}if(t.perspective&&o)return hA(t,e,n,p,m,d,f,a,o);let g=e-p,y=n-m;const w=t.angles?t.angles[2]:0;if(w){const b=Math.cos(-w),v=Math.sin(-w),x=g*b+y*v,P=-g*v+y*b;g=x,y=P}const A=a&&a[t.alignment]||[.5,.5];return(A[0]!==.5||A[1]!==.5)&&(g-=(.5-A[0])*d,y-=(.5-A[1])*f),{lx:g/d,ly:y/f,w:d,h:f}}function uA(t){const e=Math.cos(t),n=Math.sin(t);return[e,n,0,-n,e,0,0,0,1]}function fA(t){const e=Math.cos(t),n=Math.sin(t);return[e,0,-n,0,1,0,n,0,e]}function dA(t){const e=Math.cos(t),n=Math.sin(t);return[1,0,0,0,e,n,0,-n,e]}function Xm(t,e){const n=new Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[r*3+i]=t[i]*e[r*3]+t[3+i]*e[r*3+1]+t[6+i]*e[r*3+2];return n}function hA(t,e,n,r,i,s,a,o,c){const u=(t.origin||[0,0,0])[2]||0,l=t.angles||[0,0,0];let d=uA(-(l[2]||0));d=Xm(d,fA(-(l[1]||0))),d=Xm(d,dA(l[0]||0));const f=d[6],h=d[7],p=d[8],m=e-c[0],g=n-c[1],y=-c[2],w=f*m+h*g+p*y;if(Math.abs(w)<1e-9)return null;const A=r-c[0],b=i-c[1],v=u-c[2],x=(f*A+h*b+p*v)/w,P=c[0]+m*x-r,S=c[1]+g*x-i,k=c[2]+y*x-u;let _=d[0]*P+d[1]*S+d[2]*k,I=d[3]*P+d[4]*S+d[5]*k;const B=o&&o[t.alignment]||[.5,.5];return(B[0]!==.5||B[1]!==.5)&&(_-=(.5-B[0])*s,I-=(.5-B[1])*a),{lx:_/s,ly:I/a,w:s,h:a}}function $m(t,e,n,r,i={}){if(!t||t.length===0)return[];const s=i.parOffX||0,a=i.parOffY||0,o=i.parallaxCtx,c=i.alignTable,u=i.filter,l=[];for(let d=t.length-1;d>=0;d--){const f=t[d];if(!f||!f.visible||f.destroyed||u&&!u(f))continue;const h=qm(f,e,n,r,s,a,c,i.perspEye,o);h&&Math.abs(h.lx)<=.5&&Math.abs(h.ly)<=.5&&l.push(f)}return l}function mA(t,e,n,r,i={}){const s=$m(t,e,n,r,i);return s.length?s[0]:null}const pA=Object.freeze(Object.defineProperty({__proto__:null,hitTestLayers:mA,hitTestLayersAll:$m,worldToLayerLocal:qm},Symbol.toStringTag,{value:"Module"}));function gA(t,e,n){const r=t&&t.hovered||[],i=t&&t.pressed||[],s=!!(t&&t.lastLeftDown),a=Array.isArray(e)?e:[],o=new Set(a),c=[],u=[],l=[],d=[],f=[],h=[];for(const m of r)o.has(m)||c.push(m);for(const m of a)r.includes(m)||u.push(m);for(const m of a)l.push(m);let p=i;if(n&&!s){p=a.slice();for(const m of a)d.push(m)}else if(!n&&s){for(const m of i)f.push(m);for(const m of i)o.has(m)&&h.push(m);p=[]}return{leave:c,enter:u,move:l,down:d,up:f,click:h,next:{hovered:a,pressed:p,lastLeftDown:n}}}const yA=Object.freeze(Object.defineProperty({__proto__:null,planCursorDispatch:gA},Symbol.toStringTag,{value:"Module"})),Et=t=>t,at=Et(oy),er=Et(_y),zt=Et(ub),An=Et(pb),pt=Et(nw),Ti=Et(kw),en=Et(ov),Bo=Et(wv),ou=Et(Mv),la=Et(Yv),ot=Et(Zy),bA=Et(Zv),We=Et(sA),Gm=Et(oA),ua=Et(qb),wA=Et(lA),vA=Et(pA),AA=Et(yA);function xA(t,e,n){return{camera:null,general:{orthogonalprojection:{width:t,height:e},clearenabled:!0,clearcolor:"0 0 0"},layers:[{id:0,name:"media",visible:!0,image:n,textureName:n,particle:null,puppet:null,solid:!1,isContainer:!1,isPostProcess:!1,isText:!1,isSound:!1,isComponent:!1,sound:[],origin:[t/2,e/2,0],scale:[1,1,1],angles:[0,0,0],size:[t,e],alignment:"center",color:[1,1,1],alpha:1,brightness:1,colorBlendMode:0,copybackground:!1,parallaxDepth:null,animationLayers:[],effects:[]}],properties:{}}}async function kA(t){const e=await fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status}`);const n=new window.ImageDecoder({data:await e.arrayBuffer(),type:"image/gif"});await n.tracks.ready,await n.completed;const r=n.tracks.selectedTrack;if(!r||!r.frameCount)return null;const i=Math.min(r.frameCount,300),s=[];let a=0,o=0;for(let c=0;c<i;c++){const{image:u}=await n.decode({frameIndex:c});a=u.displayWidth,o=u.displayHeight,s.push({bitmap:await createImageBitmap(u,{premultiplyAlpha:"none"}),durationMs:u.duration?u.duration/1e3:100}),u.close()}return n.close?.(),{width:a,height:o,frames:s}}function TA(t,e,n){if(t.audioBridge)return;const r=window.AudioContext||window.webkitAudioContext;if(!r)return;let i,s;try{i=new r;const l=i.createMediaElementSource(n);s=i.createAnalyser(),s.fftSize=256,s.smoothingTimeConstant=.75,l.connect(s),s.connect(i.destination)}catch(l){be(t,e,`media \u9891\u8C31\u63A5\u7BA1\u8DF3\u8FC7: ${l?.message??l}`);return}const a=new Uint8Array(s.frequencyBinCount),o=new Float32Array(64),c=new Float32Array(64),u=()=>{if(i.state!=="running")return null;s.getByteFrequencyData(a);const l=Math.min(64,a.length);for(let d=0;d<l;d++){const f=a[d]/255;o[d]=f,c[d]=f}for(let d=l;d<64;d++)o[d]=0,c[d]=0;return{left:o,right:c}};if(t.audioBridge=u,i.state==="suspended"){const l=()=>{i.resume().catch(()=>{}),window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",l)};window.addEventListener("pointerdown",l,{once:!0}),window.addEventListener("keydown",l,{once:!0}),(t.wallpaperDisposers??=[]).push(()=>{window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",l)})}(t.wallpaperDisposers??=[]).push(()=>{t.audioBridge===u&&(t.audioBridge=null),i.close().catch(()=>{})})}function SA(t,e,n,r){if(t.audioBridge)return;const i=window.AudioContext||window.webkitAudioContext;if(!i)return;let s;const a=new Map;try{s=new i;for(const f of[n,r]){const h=s.createMediaElementSource(f),p=s.createAnalyser();p.fftSize=256,p.smoothingTimeConstant=.75,h.connect(p),p.connect(s.destination),a.set(f,p)}}catch(f){be(t,e,`media \u9891\u8C31\u63A5\u7BA1\u8DF3\u8FC7: ${f?.message??f}`);return}let o=a.get(n);const c=new Uint8Array(o.frequencyBinCount),u=new Float32Array(64),l=new Float32Array(64),d=()=>{if(s.state!=="running")return null;o.getByteFrequencyData(c);const f=Math.min(64,c.length);for(let h=0;h<f;h++){const p=c[h]/255;u[h]=p,l[h]=p}for(let h=f;h<64;h++)u[h]=0,l[h]=0;return{left:u,right:l}};if(t.audioBridge=d,s.state==="suspended"){const f=()=>{s.resume().catch(()=>{}),window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",f)};window.addEventListener("pointerdown",f,{once:!0}),window.addEventListener("keydown",f,{once:!0}),(t.wallpaperDisposers??=[]).push(()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",f)})}return(t.wallpaperDisposers??=[]).push(()=>{t.audioBridge===d&&(t.audioBridge=null),s.close().catch(()=>{})}),f=>{const h=a.get(f);h&&(o=h)}}function PA(t,e){Or(t);const n=g=>{be(t,e,`media ${e.type} \u5931\u8D25: ${g}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08${e.type}\uFF09${g}`)),t.fallbackPage?.()};if(!e.src){n("\u7F3A\u5C11\u8D44\u6E90 URL\uFF08cfg.src \u4E3A\u7A7A\uFF09");return}const r=e.type==="video",i=e.type==="gif";if(r){EA(t,e),Ru(t);return}const s=e.canvas instanceof HTMLCanvasElement,a=s?e.canvas:document.createElement("canvas"),o=Vi(t,e),c=a.clientWidth||window.innerWidth||1,u=a.clientHeight||window.innerHeight||1;if(a.width=Math.max(1,Math.round(c*o)),a.height=Math.max(1,Math.round(u*o)),s||(a.style.cssText="position:absolute;inset:0;width:100%;height:100%;"),!a.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0})){if(be(t,e,`media ${e.type}: WEBGL2_UNAVAILABLE`),s){t.onError?.(new Error("WEBGL2_UNAVAILABLE"));return}CA(t,e);return}if(s||t.wrap?.appendChild(a),a.setAttribute("data-webwallgl-gl","1"),t.canvas=a,t.onSceneInfo){const g=t.onSceneInfo;t.onSceneInfo=void 0;try{g({width:c,height:u,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}}let d=!1;t.sceneCleanup=()=>{d=!0,t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0)};let f,h,p=!1;t.sceneAudio={setVolume(g){const y=t.video;if(!y)return;const w=Math.max(0,Math.min(1,Number(g)||0));y.volume=w,y.muted=w<=0,w>0&&y.paused&&!t.paused&&y.play().catch(A=>{be(t,e,`media \u53D6\u6D88\u9759\u97F3\u540E\u81EA\u52A8\u64AD\u653E\u88AB\u62D2\u7EDD: ${A?.message??A}`)})},audios:[]},t.sceneCtl={pause(){f?.()},resume(){h?.()},applyUserProperties(){}};const m=g=>{d||(d=!0,n(g))};(async()=>{try{const g=pt.createRenderer(a,{diag:O=>be(t,e,`renderer: ${O}`),fboCapFactor:0});if(t.renderer=g,d)return;const y="__media",w=new Map;let A,b=0,v=0;{let O=!1;if(i&&typeof window.ImageDecoder=="function")try{const U=await kA(e.src);if(U&&U.frames.length>1){b=U.width,v=U.height;const W=g.gl,ie={glTex:pt.makeTexture(W,null,0,0,U.frames[0].bitmap),width:b,height:v,rg88:!1};w.set(y,ie);let we=0,Y=performance.now()+U.frames[0].durationMs;A=()=>{const he=performance.now();if(!(he<Y)){we=(we+1)%U.frames.length,Y=he+U.frames[we].durationMs,W.bindTexture(W.TEXTURE_2D,ie.glTex);try{W.texImage2D(W.TEXTURE_2D,0,W.RGBA,W.RGBA,W.UNSIGNED_BYTE,U.frames[we].bitmap)}catch{}}};const oe=t.sceneCleanup;t.sceneCleanup=()=>{oe?.();for(const he of U.frames)he.bitmap.close()},O=!0,be(t,e,`media gif ${b}x${v} ${U.frames.length} \u5E27 \u2192 scene \u6E32\u67D3`)}}catch(U){be(t,e,`gif \u89E3\u7801\u5931\u8D25\uFF0C\u56DE\u9000\u9759\u6001\u9996\u5E27: ${String(U.message).slice(0,80)}`)}if(!O){const U=new Image;if(U.crossOrigin="anonymous",U.src=e.src,await new Promise((W,ie)=>{U.addEventListener("load",()=>W(),{once:!0}),U.addEventListener("error",()=>ie(new Error("image load error")),{once:!0})}),d)return;b=U.naturalWidth||1,v=U.naturalHeight||1,t.img=U,w.set(y,{glTex:pt.makeTexture(g.gl,null,0,0,U),width:b,height:v,rg88:!1}),be(t,e,`media ${e.type} ${b}x${v} \u2192 scene \u6E32\u67D3`)}}if(d)return;const x=xA(b,v,y),P=performance.now();let S=0,k=0;const _=new ys(t.cfg.sceneFps||60);let I=t.cfg.sceneFps||60;const B=O=>{if(d||t.paused)return;const U=t.cfg.sceneFps||60;if(U!==I&&(I=U,_.setFps(U)),_.shouldRender(O)){zr(t,O),Du(t,a,t.cfg),A?.();const W=t.coverAlign;g.render(x,w,a.width,a.height,(O-P-S)/1e3,Ur(t.cfg.fit),W.x,W.y).then(()=>{if(t.onFirstFrame){const ie=t.onFirstFrame;t.onFirstFrame=void 0;try{ie()}catch{}}d||t.paused||(t.raf=requestAnimationFrame(B))}).catch(ie=>m(String(ie.message||ie).slice(0,200)))}else t.paused||(t.raf=requestAnimationFrame(B))},V=()=>{d||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(B))};f=()=>{t.raf!==void 0&&(cancelAnimationFrame(t.raf),t.raf=void 0),k||(k=performance.now());const O=t.video;p=!!(O&&!O.paused&&!O.ended),O?.pause()},h=()=>{k&&(S+=performance.now()-k,k=0),p&&t.video?.play().catch(()=>{}),p=!1,_.reset(),V()},V()}catch(g){m(String(g.message||g).slice(0,200))}})()}function _A(t,e){if(t.wrap)return t.wrap;const n=e.canvas;return n?n instanceof HTMLCanvasElement?n.parentElement:n:null}function EA(t,e){if(Or(t),!e.src){t.fallbackPage?.(),t.onError?.(new Error("\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09\u7F3A\u5C11\u8D44\u6E90 URL\uFF08cfg.src \u4E3A\u7A7A\uFF09"));return}const n=_A(t,e);if(!n){const f="\u89C6\u9891\u58C1\u7EB8\u9700\u8981\u4E00\u4E2A\u5BB9\u5668\u5143\u7D20\uFF08\u4F20\u5165\u7684 canvas \u6CA1\u6709\u7236\u8282\u70B9\uFF09";be(t,e,`media video \u5931\u8D25: ${f}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09${f}`));return}const r=Zo(e.fit),i=`position:absolute;inset:0;width:100%;height:100%;object-fit:${r.objectFit};object-position:50% 50%;background:${r.background};`;!t.wrap&&getComputedStyle(n).position==="static"&&(n.style.position="relative");let s=!1;const a=f=>{if(s)return;s=!0;const h=`\u89E3\u7801/\u52A0\u8F7D\u5931\u8D25\uFF08code ${f??"?"}\uFF09`;be(t,e,`media video \u5931\u8D25: ${h}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09${h}`)),t.fallbackPage?.()},o=e.loop!==!1,c=e.muted!==!1,u=()=>{zr(t,performance.now());const f=t.onFirstFrame;if(f){if(t.onFirstFrame=void 0,t.onSceneInfo){const h=t.onSceneInfo;t.onSceneInfo=void 0;try{h({width:t.video?.videoWidth||0,height:t.video?.videoHeight||0,layerCount:1,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}}try{f()}catch{}}},l=f=>{let h=!1,p=0,m=-1;const g=b=>{if(t.paused||b.paused||b.readyState<2)return;const v=b.currentTime;m>=0&&v===m||(m=v,zr(t,performance.now()))};let y;const w=()=>{h||!y||(g(y),y.requestVideoFrameCallback(w))},A=()=>{if(h)return;p=requestAnimationFrame(A);const b=f();b&&(b!==y&&typeof b.requestVideoFrameCallback=="function"&&(y=b,b.requestVideoFrameCallback(w)),g(b))};p=requestAnimationFrame(A),(t.wallpaperDisposers??=[]).push(()=>{h=!0,y=void 0,p&&cancelAnimationFrame(p)})};if(!o){const f=document.createElement("video");f.autoplay=!0,f.loop=!1,f.muted=c,f.playsInline=!0,f.preload="metadata",MA(f,t,e),f.style.cssText=i,f.src=e.src,f.addEventListener("error",()=>a(f.error?.code)),n.appendChild(f),t.video=f,(t.videoTextures??=[]).push(f),f.addEventListener("canplay",()=>{f.play().catch(()=>{})},{once:!0}),f.addEventListener("loadeddata",u,{once:!0}),f.readyState>=2&&u(),TA(t,e,f),l(()=>f),be(t,e,"media video \u2192 DOM \u76F4\u663E\uFF08\u5355\u5143\u7D20\uFF0C\u4E0D\u5FAA\u73AF\uFF09");return}const d=()=>{const f=Uu(e.src,{muted:c,renderDpr:e.renderDpr,maxW:n.clientWidth||window.innerWidth,maxH:n.clientHeight||window.innerHeight,onRecover:m=>be(t,e,`media video \u81EA\u6108: ${m}`)});for(const m of[f.active,f.standby])m.style.cssText=i,n.appendChild(m),(t.videoTextures??=[]).push(m),m.addEventListener("error",()=>a(m.error?.code));const h=()=>{f.active.style.zIndex="1",f.standby.style.zIndex="0",t.video=f.active};h(),f.onSwap=()=>{h(),p?.(f.active)},f.onFallback=()=>be(t,e,"media video: \u65E0\u7F1D\u5FAA\u73AF\u515C\u5E95\uFF08\u9000\u56DE\u539F\u751F loop\uFF09"),(t.videoPairs??=[]).push(f),t.webcodecsPreferred=Gd();const p=SA(t,e,f.active,f.standby);f.active.addEventListener("loadeddata",u,{once:!0}),f.active.readyState>=2&&u(),l(()=>f.active),t.paused||f.resume(),be(t,e,"media video \u2192 DOM \u76F4\u663E\uFF08A/B \u65E0\u7F1D\u5FAA\u73AF\uFF09")};if(o&&c&&Gd()){let f=!0,h=null;const p=(m,g=!0)=>{f&&(f=!1,h?.destroy(),h=null,be(t,e,`media video: ${m}\uFF0C\u56DE\u9000 A/B <video>`),d(),g||(t.webcodecsPreferred=!1))};h=ry({src:e.src,container:n,cssText:i,fit:()=>Ur(t.cfg.fit),fps:()=>t.cfg.sceneFps||60,paused:()=>!!t.paused,renderDpr:e.renderDpr,onFirstFrame:u,onFrame:()=>zr(t,performance.now()),onDiag:m=>be(t,e,`media video(webcodecs): ${m}`),onFatal:m=>p(`WebCodecs \u8DEF\u5F84\u5931\u8D25\uFF08${m}\uFF09`,!1)}),t.sceneCtl={pause:()=>h?.pause(),resume:()=>h?.resume(),applyUserProperties(){}},t.sceneAudio={setVolume:m=>{m>0&&p("\u53D6\u6D88\u9759\u97F3\uFF08\u9700\u8981\u97F3\u8F68\uFF09")},audios:[]},(t.wallpaperDisposers??=[]).push(()=>{f=!1,h?.destroy(),h=null}),t.canvas=h.canvas,be(t,e,"media video \u2192 WebCodecs \u9010\u5E27\u8C03\u5EA6\uFF08\u9759\u97F3\u5FAA\u73AF\uFF09");return}d()}function MA(t,e,n){const r=n.renderDpr??e.cfg?.renderDpr??0,i=Math.min(window.devicePixelRatio||1,!r||r<=0?window.devicePixelRatio||1:r),s=n.canvas?.clientWidth||window.innerWidth,a=n.canvas?.clientHeight||window.innerHeight;t.width=Math.max(1,Math.round(s*i)),t.height=Math.max(1,Math.round(a*i))}function CA(t,e){Or(t);const n=document.createElement("img"),r=Zo(e.fit);n.style.cssText=`position:absolute;inset:0;width:100%;height:100%;object-fit:${r.objectFit};object-position:50% 50%;background:${r.background};`,n.src=e.src??"",n.addEventListener("error",()=>t.fallbackPage?.()),t.wrap?.appendChild(n),t.img=n}const IA=["scene.pkg","scenes/scene.pkg","gifscene.pkg"],RA={mp4:"video",webm:"video",mov:"video",m4v:"video",ogv:"video",gif:"gif",png:"image",jpg:"image",jpeg:"image",webp:"image",avif:"image",bmp:"image"};function Qm(t){const e=t.toLowerCase().split(";")[0].trim();return e==="image/gif"?"gif":e.startsWith("video/")?"video":e.startsWith("image/")?"image":null}function cu(t){if(typeof t!="string"||!t)return;const e=t.replace(/[?#].*$/,"").replace(/\/+$/,"").split(/[/\\]/).pop()??"";return/^\d+$/.test(e)?e:void 0}function lu(t){if(typeof t!="string"||!t)return null;let e=t;const n=e.indexOf("#");n>=0&&(e=e.slice(0,n));const r=e.indexOf("?");r>=0&&(e=e.slice(0,r));const i=e.split("/").pop()||"",s=i.lastIndexOf(".");return s<0?null:RA[i.slice(s+1).toLowerCase()]??null}async function BA(t,e,n){try{const r=await fetch(t,{...e,method:"HEAD",signal:n});return r.ok?Qm(r.headers.get("content-type")||""):null}catch{return null}}function Ym(t,e){const n=t.replace(/\/+$/,"");return{key:n,async scenePkg(r){let i=null,s=null;for(const o of IA){let c;try{c=await fetch(`${n}/${o}`,{...e,signal:r})}catch(u){if(r?.aborted)throw u;s=u;continue}if(!c.ok){i=c.status;continue}try{return await c.arrayBuffer()}catch(u){if(r?.aborted)throw u;const l=u instanceof Error?u.message:String(u);throw new Error(`\u8BFB\u53D6 scene.pkg \u4F53\u5931\u8D25\uFF08${l}\uFF09`)}}if(i!=null)throw new Error(`scene.pkg \u52A0\u8F7D\u5931\u8D25\uFF08HTTP ${i}\uFF09`);const a=s instanceof Error?s.message:"Failed to fetch";throw new Error(`scene.pkg \u52A0\u8F7D\u5931\u8D25\uFF08${a}\uFF09`)},async project(r){try{const i=await fetch(`${n}/project.json`,{...e,signal:r});return i.ok?await i.json():null}catch{return null}},async webEntry(r){let i="index.html";try{const s=await fetch(`${n}/project.json`,{...e,signal:r});if(s.ok){const a=await s.json();a&&typeof a.file=="string"&&a.file.trim()&&(i=a.file.trim().replace(/^\/+/,""))}}catch{if(r?.aborted)throw new Error("aborted")}return{url:`${n}/${i}`}},async mediaEntry(r){let i="";try{const s=await fetch(`${n}/project.json`,{...e,signal:r});if(s.ok){const a=await s.json();a&&typeof a.file=="string"&&a.file.trim()&&(i=a.file.trim().replace(/^\/+/,""))}}catch{if(r?.aborted)throw new Error("aborted")}return i?{url:`${n}/${i}`}:null}}}function FA(t,e){const n=t;return{key:typeof n.name=="string"?`file:${n.name}:${n.size}:${n.lastModified??0}`:void 0,scenePkg:()=>t.arrayBuffer(),project:async()=>e??null}}function DA(t,e,n){return{key:n,scenePkg:async()=>t,project:async()=>e??null}}function NA(t,e){const n=typeof t!="string",r=t;let i=e?.type??(n?Qm(t.type||""):null)??lu(n?String(r.name??""):t),s=!1,a=null;const o=()=>n?(a||(a=URL.createObjectURL(t)),a):t;return{key:e?.key??(n?typeof r.name=="string"?`media:${r.name}:${r.size}:${r.lastModified??0}`:void 0:`media:${t}`),async scenePkg(){throw new Error("mediaSource \u662F\u7EAF\u5A92\u4F53\u6765\u6E90\uFF0C\u6CA1\u6709 scene.pkg\uFF08\u8BF7\u6539\u7528 httpSource/fileSource/bytesSource\uFF09")},async project(){return i?{type:i}:null},async mediaEntry(u){return!i&&!n&&!s&&(s=!0,i=await BA(t,void 0,u)),{url:o(),type:i??void 0}},dispose(){a&&(URL.revokeObjectURL(a),a=null)}}}const Km=!1,Zm=!0,Jm=!1,LA=!1,UA=!1,ep=4,uu={antiAliasing:"off",particles:"high",postProcessing:"high"},OA={low:.4,medium:.7,high:1},zA={low:.5,medium:1,high:0},HA=["off","fxaa","msaa2","msaa4"],VA=["off","low","medium","high"],WA=["off","low","medium","high"];function fu(t,e,n){return typeof t=="string"&&e.includes(t)?t:n}function fa(t){const e=t??{};return{antiAliasing:fu(e.antiAliasing,HA,uu.antiAliasing),particles:fu(e.particles,VA,uu.particles),postProcessing:fu(e.postProcessing,WA,uu.postProcessing)}}function jA(t){return t==="off"?0:OA[t]}function qA(t){return t==="off"?0:zA[t]}const da=64,tp={STOPPED:0};function XA(){return{left64:new Float32Array(da),right64:new Float32Array(da),left32:new Float32Array(32),right32:new Float32Array(32),left16:new Float32Array(16),right16:new Float32Array(16),level:0,silent:!0}}function Fo(t,e){const n=e.length/t.length;for(let r=0;r<t.length;r++){let i=0;const s=Math.floor(r*n),a=Math.max(s+1,Math.floor((r+1)*n));for(let o=s;o<a;o++)i+=e[o];t[r]=i/(a-s)}}function $A(t,e,n){const r=e.length,i=n*.5,s=20,a=Math.min(2e4,i);let o=0;for(let c=0;c<da;c++){const u=c/da,l=(c+1)/da,d=s*Math.pow(a/s,u),f=s*Math.pow(a/s,l),h=Math.max(0,Math.floor(d/i*r)),p=Math.min(r,Math.max(h+1,Math.ceil(f/i*r)));let m=0;for(let y=h;y<p;y++)m+=e[y]/255;const g=Math.min(1,m/(p-h)*1.35);t.left64[c]=g,t.right64[c]=g,c<48&&(o+=g)}Fo(t.left32,t.left64),Fo(t.right32,t.right64),Fo(t.left16,t.left64),Fo(t.right16,t.right64),t.level=Math.min(1,o/(48*1.2)),t.silent=t.level<.02}function GA(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0)%360}function du(t,e,n){const r=e/100,i=n/100,s=(1-Math.abs(2*i-1))*r,a=t/60,o=s*(1-Math.abs(a%2-1));let c=0,u=0,l=0;a<1?[c,u,l]=[s,o,0]:a<2?[c,u,l]=[o,s,0]:a<3?[c,u,l]=[0,s,o]:a<4?[c,u,l]=[0,o,s]:a<5?[c,u,l]=[o,0,s]:[c,u,l]=[s,0,o];const d=i-s/2;return[c+d,u+d,l+d]}function QA(t,e){const n=GA(e||"empty"),[r,i,s]=du(n,72,48),[a,o,c]=du((n+40)%360,55,28),[u,l,d]=du((n+20)%360,70,72);t.primaryColor=We.mediaVec3(r,i,s),t.secondaryColor=We.mediaVec3(a,o,c),t.tertiaryColor=We.mediaVec3(u,l,d),t.textColor=We.mediaVec3(.98,.98,1),t.highContrastColor=We.mediaVec3(1,1,1),t.hasThumbnail=!!e}function YA(t,e,n){const r=document.createElement("canvas");r.width=32,r.height=32;const i=r.getContext("2d",{willReadFrequently:!0});if(!i)return null;i.drawImage(t,0,0,e,n,0,0,32,32);const s=i.getImageData(0,0,32,32).data;let a=0,o=0,c=0,u=0,l=0,d=0,f=0,h=-1;for(let y=0;y<s.length;y+=4){const w=s[y]/255,A=s[y+1]/255,b=s[y+2]/255;a+=w,o+=A,c+=b,u++;const v=Math.max(w,A,b),x=Math.min(w,A,b),P=v-x,S=.2126*w+.7152*A+.0722*b,k=P*1.4+(S>.15&&S<.85?.3:0);k>h&&(h=k,l=w,d=A,f=b)}if(!u)return null;const p=[l,d,f],m=[a/u*.55,o/u*.55,c/u*.55],g=[Math.min(1,p[0]*.45+.55),Math.min(1,p[1]*.45+.55),Math.min(1,p[2]*.45+.55)];return{primary:p,secondary:m,tertiary:g}}function KA(t,e,n,r=512){const i=document.createElement("canvas");i.width=r,i.height=r;const s=i.getContext("2d"),a=Math.max(r/Math.max(1,e),r/Math.max(1,n)),o=e*a,c=n*a;s.fillStyle="#000",s.fillRect(0,0,r,r),s.drawImage(t,(r-o)/2,(r-c)/2,o,c);const u=s.getImageData(0,0,r,r);return{width:r,height:r,rgba:new Uint8Array(u.data)}}function ZA(){return{hasMedia:!1,state:tp.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,primaryColor:We.mediaVec3(0,0,0),secondaryColor:We.mediaVec3(0,0,0),tertiaryColor:We.mediaVec3(0,0,0),textColor:We.mediaVec3(1,1,1),highContrastColor:We.mediaVec3(1,1,1),trackIndex:-1,lyrics:[],lyricLine:"",lyricIndex:-1}}async function JA(){if(!navigator.mediaDevices?.getUserMedia)return null;try{const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1},video:!1}),e=new AudioContext,n=e.createMediaStreamSource(t),r=e.createAnalyser();return r.fftSize=2048,r.smoothingTimeConstant=.8,n.connect(r),e.state==="suspended"&&await e.resume().catch(()=>{}),{ctx:e,stream:t,analyser:r,buf:new Uint8Array(r.frequencyBinCount)}}catch{return null}}async function np(t){const e=t?.origin??(typeof location<"u"?location.origin:""),n=t?.onArtwork,r=XA(),i=ZA(),s={app:"",title:"",url:"",index:0};let a="off",o="offline",c="offline",u="",l=!1,d="";const f=await JA();f?a="mic":navigator.mediaDevices?.getUserMedia?a="denied":a="unavailable";let h=null,p=null,m=!1;const g=(v,x,P)=>{!e||!n||!l||d!==v&&(d=v,n({url:`${e}/api/system/artwork?k=${encodeURIComponent(v)}&_=${Date.now()}`,trackKey:v,title:x,artist:P}))},y=v=>{if(!v||!v.hasMedia){i.hasMedia=!1,i.state=tp.STOPPED,i.title="",i.artist="",i.album="",i.albumArtist="",i.position=0,i.duration=0,i.hasThumbnail=!1,i.trackIndex=-1,o=v?"empty":"offline",u="",l=!1,d="";return}o="live",i.hasMedia=!0,i.state=Number(v.state)===2?2:Number(v.state)===1?1:0,i.title=String(v.title??""),i.artist=String(v.artist??""),i.album=String(v.album??""),i.albumArtist=String(v.albumArtist??v.artist??""),i.position=Number(v.position)||0,i.duration=Number(v.duration)||0,l=v.hasArtwork===!0;const x=`${i.title}|${i.artist}|${i.album}`;x!==u&&(u=x,d="",i.trackIndex=i.trackIndex+1|0,QA(i,x)),g(x,i.title,i.artist)},w=v=>{if(!v){c="offline";return}s.app=String(v.app??""),s.title=String(v.title??""),s.url=String(v.url??""),c=s.app||s.title?"live":"empty"},A=async()=>{if(!(!e||m))try{const[v,x]=await Promise.all([fetch(`${e}/api/system/media`,{cache:"no-store"}),fetch(`${e}/api/system/window`,{cache:"no-store"})]);if(v.ok){const P=await v.json();y(P)}else o="offline";x.ok&&w(await x.json())}catch{o=o==="live"?"live":"offline",c=c==="live"?"live":"offline"}};if(e){await A(),p=setInterval(()=>{A()},1e3);try{h=new EventSource(`${e}/api/system/stream`),h.onmessage=v=>{if(!m)try{const x=JSON.parse(v.data);y(x.media),w(x.window)}catch{}}}catch{}}const b=v=>{!e||m||fetch(`${e}/api/system/media-control`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:v})}).then(async x=>x.ok?x.json():null).then(x=>{x&&typeof x=="object"&&y(x),A()}).catch(()=>{A()})};return{audio:{snapshot:r,pump:()=>{if(!f||m){r.level=0,r.silent=!0;return}f.analyser.getByteFrequencyData(f.buf),$A(r,f.buf,f.ctx.sampleRate||48e3)}},media:{snapshot:i,pump:()=>{},skipNext:()=>b("skipNext"),skipPrevious:()=>b("skipPrevious"),play:()=>b("play"),pause:()=>b("pause"),playPause:()=>b("playPause")},windowTitle:{snapshot:s,pump:()=>{}},status:()=>({audio:a,media:o,window:c,title:i.title,artist:i.artist,app:s.app,windowTitle:s.title,hasArtwork:l}),dispose:()=>{m=!0,p&&(clearInterval(p),p=null);try{h?.close()}catch{}if(h=null,f)try{f.stream.getTracks().forEach(v=>v.stop()),f.ctx.close()}catch{}}}}const e2=2048,Do=64;function t2(){let t=null,e=null,n=null,r=1,i=null;const s=new WeakSet,a=new WeakSet,o=[],c=()=>{if(t)return!0;try{const m=globalThis.AudioContext??globalThis.webkitAudioContext;return m?(t=new m,e=t.createAnalyser(),e.fftSize=e2,e.smoothingTimeConstant=.8,e.maxDecibels=-25,n=t.createGain(),n.gain.value=r,n.connect(t.destination),i=new Uint8Array(e.frequencyBinCount),!0):!1}catch{return t=null,e=null,n=null,!1}};return{attach:m=>{if(!(!m||s.has(m))&&!(!c()||!t||!e))try{const g=t.createMediaElementSource(m);g.connect(e),n&&g.connect(n),s.add(m),a.add(m),o.push(m)}catch{s.add(m)}},routes:m=>a.has(m),readBands:()=>{if(!e||!i||!t||!o.some(A=>!A.paused&&!A.ended&&!A.muted&&A.volume>0))return null;e.getByteFrequencyData(i);const g=new Float32Array(Do),y=i.length*.72,w=2;for(let A=0;A<Do;A++){const b=w+Math.floor(y*(A/Do)**2),v=Math.max(b+1,w+Math.floor(y*((A+1)/Do)**2));let x=0;for(let P=b;P<v&&P<i.length;P++){const S=i[P];S>x&&(x=S)}g[A]=x/255}return g},resume:()=>{t&&t.state==="suspended"&&t.resume().catch(()=>{})},setVolume:m=>{r=Math.max(0,Math.min(1,Number(m)||0)),n&&(n.gain.value=r)},dispose:()=>{try{t?.close()}catch{}t=null,e=null,n=null,i=null,o.length=0}}}function n2(t,e,n){for(let r=0;r<64;r++){const i=Math.min(1,e[r]*n);i>t.left64[r]&&(t.left64[r]=i),i>t.right64[r]&&(t.right64[r]=i)}No(t.left64,t.left32),No(t.right64,t.right32),No(t.left64,t.left16),No(t.right64,t.right16)}function No(t,e){if(!e)return;const n=t.length/e.length;for(let r=0;r<e.length;r++){const i=Math.floor(r*n),s=Math.max(i+1,Math.floor((r+1)*n));let a=0;for(let o=i;o<s;o++)t[o]>a&&(a=t[o]);e[r]=a}}const _r=new Map;let Fn=null,rp=!1,ha=null,hu=null;const mu=new Map,Lo="/api/local-assets";function r2(){if(typeof location>"u")return"off";const t=new URLSearchParams(location.search).get("localAssets");return t==="0"||t==="off"||t==="false"?"off":t==="all"?"all":t==="1"||t==="on"||t==="true"||typeof import.meta<"u"&&!1?"lazy":"off"}async function i2(t){if(t&&t.rgba)return{width:t.width,height:t.height,rgba:t.rgba};const e=t&&(t.png||t.image);if(!e)return null;const n=!!t.png;if(!n&&t.fif!==er.FIF?.JPEG&&t.fif!==er.FIF?.PNG)return null;const r=new Blob([e],{type:n?"image/png":"image/jpeg"}),i=await createImageBitmap(r,{premultiplyAlpha:"none"}),s=i.width,a=i.height,o=document.createElement("canvas");o.width=s,o.height=a;const c=o.getContext("2d",{willReadFrequently:!0});if(!c)return null;c.drawImage(i,0,0),typeof i.close=="function"&&i.close();const u=c.getImageData(0,0,s,a),l=new Uint8Array(s*a*4);return l.set(u.data),{width:s,height:a,rgba:l}}async function s2(t){const e=await fetch(t,{cache:"force-cache"});if(!e.ok)return null;const n=new Uint8Array(await e.arrayBuffer()),r=er.parseTex(n),i=er.decodeMips(r);if(!i.length)return null;const s=await i2(i[0]);if(!s)return null;s.format=r.format;const a=r.frames?.list;return a&&a.length&&(a.atlasWidth=s.width,a.atlasHeight=s.height,s.frames=a),s}async function a2(t,e,n){const r=new Array(t.length);let i=0;const s=new Array(Math.min(e,Math.max(1,t.length))).fill(0).map(async()=>{for(;;){const a=i++;if(a>=t.length)return;r[a]=await n(t[a])}});return await Promise.all(s),r}async function ip(t){const e=_r.get(t);if(e)return e;if(!Fn||!Fn.names.has(t))return null;const n=mu.get(t);if(n)return n;const r=`${Lo}/${encodeURIComponent(Fn.id)}/materials/${t.split("/").map(encodeURIComponent).join("/")}.tex`,i=(async()=>{try{const s=await s2(r);return s&&_r.set(t,s),s}catch{return null}finally{mu.delete(t)}})();return mu.set(t,i),i}async function o2(){const t=r2();if(t==="off")return null;if(rp)return hu;if(ha)return ha;ha=(async()=>{const e=typeof performance<"u"?performance.now():Date.now();try{const u=await fetch(Lo,{cache:"no-store"});if(!u.ok)return null;const l=await u.json();if(!l?.ok||!l.roots?.length)return null;const d=l.roots[0],f=await fetch(`${Lo}/${encodeURIComponent(d.id)}/materials/index.json`,{cache:"force-cache"});if(!f.ok)return null;const h=await f.json();if(!Array.isArray(h.names)||!h.names.length)return null;Fn={id:d.id,names:new Set(h.names)}}catch{return null}Bo.setSystemTextureProvider(u=>_r.get(u)??null),en.setParticleTextureProvider(u=>_r.get(u)??null),ou.setGradientTextureProvider(u=>_r.get(u)??null);const n=[...Fn.names].filter(u=>u.startsWith("util/")),r=t==="all"?[...Fn.names]:n;let i=0;await a2(r,8,async u=>{await ip(u)||i++}),rp=!0;let s=0,a=0,o=0;for(const[u,l]of _r)o+=l.rgba.byteLength,u.startsWith("util/")?s++:u.startsWith("particle/")&&a++;const c={source:Fn.id,available:Fn.names.size,requested:r.length,loaded:_r.size,failed:i,bytes:o,ms:Math.round((typeof performance<"u"?performance.now():Date.now())-e),mode:t==="all"?"all":"lazy",util:s,particle:a};return hu=c,globalThis.__localAssets=c,c})();try{return await ha}finally{ha=null}}async function sp(t){if(typeof t!="string"||!t)return!1;if(_r.has(t))return!0;if(!Fn)return!1;const e=await ip(t);if(!e)return!1;const n=hu;return n&&(n.loaded=_r.size,n.bytes+=e.rgba.byteLength,t.startsWith("util/")?n.util++:t.startsWith("particle/")&&n.particle++,globalThis.__localAssets=n),!0}const ap=new Map;async function c2(t){if(!Fn||!t||t.includes(".."))return null;const e=ap.get(t);if(e)return e;try{const n=`${Lo}/${encodeURIComponent(Fn.id)}/${t.split("/").map(encodeURIComponent).join("/")}`,r=await fetch(n,{cache:"force-cache"});if(!r.ok)return null;const i=new Uint8Array(await r.arrayBuffer());return ap.set(t,i),i}catch{return null}}const l2={"common.h":`// WE common.h\uFF08\u91CD\u5EFA\u5B50\u96C6\uFF0C\u4F9B we-scene \u6D4F\u89C8\u5668\u6E32\u67D3\uFF09
460
568
  #define M_PI 3.14159265359
461
569
  // M_PI_2 \u662F\u300CPI \xD7 2\u300D\u800C\u4E0D\u662F\u300CPI \xF7 2\u300D\u2014\u2014 \u540D\u5B57\u6781\u6613\u8BFB\u53CD\uFF0C\u6B64\u524D\u8BEF\u5199\u6210 1.5708\uFF0C
462
570
  // \u5F71\u54CD\u5168\u5E93 142 \u4E2A\u6587\u4EF6\uFF0864 \u4E2A\u58C1\u7EB8\uFF09\u3002\u4E09\u6761\u72EC\u7ACB\u8BC1\u636E\uFF1A
@@ -480,6 +588,14 @@ vec2 rotateVec2(vec2 v, float a) {
480
588
  float s = sin(a);
481
589
  return vec2(v.x * c - v.y * s, v.x * s + v.y * c);
482
590
  }
591
+ // [we-scene patch 3351179520] HLSL \u5141\u8BB8\u628A vec4 \u9690\u5F0F\u622A\u65AD\u6210 float2 \u4F20\u53C2\uFF0CGLSL \u4E0D\u5141\u8BB8 \u2014\u2014
592
+ // multistage_wave.vert\uFF08GLOBAL_ROTATION=1 \u65F6 v_DirectionN \u662F vec4\uFF09\u5199
593
+ // \`v_DirectionN.zw = rotateVec2(v_DirectionN, g_DirectionOffset)\`\uFF0C\u6CA1\u6709\u8FD9\u4E2A\u91CD\u8F7D
594
+ // \u6574\u6761 pass \u7F16\u8BD1\u5931\u8D25\u3001\u6548\u679C\u88AB\u9759\u9ED8\u8DF3\u8FC7\uFF08\u98D8\u5E26/\u5934\u53D1\u7684\u591A\u5C42\u6CE2\u52A8\u5168\u6D88\u5931\uFF09\u3002
595
+ // \u8BED\u4E49 = \u53D6 xy \u5206\u91CF\u65CB\u8F6C\uFF0C\u4E0E WE \u539F\u751F\u622A\u65AD\u4E00\u81F4\u3002
596
+ vec2 rotateVec2(vec4 v, float a) {
597
+ return rotateVec2(v.xy, a);
598
+ }
483
599
  float rand(vec2 n) { return fract(sin(dot(n, vec2(12.9898, 78.233))) * 43758.5453); }
484
600
  float rand(vec2 n, float m) { return 0.5 + 0.5 * rand(n * m); }
485
601
  float smoothstep01(float x) { return smoothstep(0.0, 1.0, x); }
@@ -504,13 +620,12 @@ vec3 hsv2rgb(vec3 c) {
504
620
  vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
505
621
  return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
506
622
  }
507
- `,"common_blending.h":`${ed}
623
+ `,"common_blending.h":`${Fh}
508
624
  // greyscale \u5FC5\u987B\u8FD4\u56DE **float** \u800C\u4E0D\u662F vec3 \u2014\u2014 \u8C03\u7528\u70B9\u51E0\u4E4E\u5168\u662F
509
625
  // \`noise = CAST3(greyscale(noise))\`\uFF08filmgrain/vhs\uFF09\uFF0CCAST3 \u53EA\u80FD\u4F5C\u7528\u4E8E\u6807\u91CF\uFF1B
510
626
  // \u82E5\u58F0\u660E\u6210 vec3 \u7248\u672C\uFF0C\u8FD9\u4E9B\u70B9\u4F1A\u53D8\u6210\u975E\u6CD5\u7684 vec3(vec3)\u3002
511
627
  // \u552F\u4E00\u7684 \`albedo.rgb = greyscale(albedo.rgb)\`\uFF08color_grading\uFF09\u5728 HLSL \u91CC\u9760\u6807\u91CF
512
628
  // \u81EA\u52A8\u5E7F\u64AD\u6210\u7ACB\uFF0C\u8F6C\u8BD1\u5230 GLSL \u540E\u7531\u8D4B\u503C\u7AEF\u7684 vec3 = float \u5E7F\u64AD\u627F\u63A5\u3002
513
- //
514
629
  // \u6743\u91CD\u662F **vec3(0.11, 0.59, 0.3)**\uFF0C\u5373 Rec.601 (0.30,0.59,0.11) \u7684**\u9006\u5E8F**\u2014\u2014
515
630
  // WE \u7B2C\u4E00\u65B9 shader \u91CC\u7684\u5386\u53F2\u9057\u7559\uFF08BGR \u65F6\u4EE3\uFF09\u3002\u4F9D\u636E\u662F 4 \u4E2A\u7B2C\u4E00\u65B9\u6587\u4EF6\u628A\u5B83\u5185\u8054\u5199\u6B7B\uFF1A
516
631
  // localcontrast_combine.frag\uFF08\u6B63\u662F blur_combine \u7684\u514D\u5934\u6587\u4EF6\u7248\uFF0C#if GREYSCALE \u4E0B
@@ -643,11 +758,11 @@ vec3 DecompressNormal(vec4 tex) {
643
758
  return vec3(xy, sqrt(clamp(1.0 - dot(xy, xy), 0.0, 1.0)));
644
759
  }
645
760
  `,"common_vertex.h":`// WE common_vertex.h\uFF08\u91CD\u5EFA\uFF1A\u7A7A\u5360\u4F4D\uFF0C\u89C1 headers.ts \u6CE8\u91CA\uFF09
646
- `};function w1(t){if(!t||t.length<12)return t;const e=t[0],n=t[1],r=t[2],i=t[3];if(!(e===0&&n===1&&r===0&&i===0)&&!(e===79&&n===84&&r===84&&i===79))return t;const o=Uint8Array.from(t),c=new DataView(o.buffer,o.byteOffset,o.byteLength),u=c.getUint16(4);if(u<=0||12+u*16>o.length)return t;let l=-1,f=0,d=0;for(let w=0;w<u;w++){const y=12+w*16;if(String.fromCharCode(o[y],o[y+1],o[y+2],o[y+3])==="cmap"){l=y,f=c.getUint32(y+8),d=c.getUint32(y+12);break}}if(l<0||f+d>o.length)return t;let h=!1;const p=c.getUint16(f+2);for(let w=0;w<p;w++){const y=f+4+w*8,b=c.getUint32(y+4),v=f+b;if(v+14>o.length||c.getUint16(v)!==4)continue;const k=c.getUint16(v+6),A=k>>>1;if(A<1)continue;const T=2*Math.pow(2,Math.floor(Math.log2(A))),S=Math.floor(Math.log2(A)),P=k-T,M=c.getUint16(v+8),B=c.getUint16(v+10),N=c.getUint16(v+12);M===T&&B===S&&N===P||(c.setUint16(v+8,T),c.setUint16(v+10,S),c.setUint16(v+12,P),h=!0)}if(!h)return t;let m=0;const g=f+d;for(let w=f;w<g;w+=4){const y=o[w]||0,b=w+1<g?o[w+1]:0,v=w+2<g?o[w+2]:0,k=w+3<g?o[w+3]:0;m=m+(y<<24|b<<16|v<<8|k)>>>0}return c.setUint32(l+4,m),o}function v1(t,e,n,r,i){if(e===r&&n===i)return"keep";if(e===i&&n===r&&r>0&&i>0){if(t===6||t===5)return"rot-ccw";if(t===8||t===7)return"rot-cw"}return"keep"}function k1(t){if(t.length<4||t[0]!==255||t[1]!==216)return 1;const e=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=2;for(;n+4<=t.length;){if(t[n]!==255){n++;continue}const r=t[n+1];if(r===216||r===1||r>=208&&r<=215){n+=2;continue}if(r===218)break;const i=e.getUint16(n+2);if(r===225&&n+10<=t.length&&t[n+4]===69&&t[n+5]===120&&t[n+6]===105&&t[n+7]===102&&t[n+8]===0&&t[n+9]===0){const s=n+10,a=t[s]===77&&t[s+1]===77,o=t[s]===73&&t[s+1]===73;if(a||o){const c=f=>e.getUint16(f,o),u=f=>e.getUint32(f,o),l=s+u(s+4);if(l>=0&&l+2<=e.byteLength){const f=c(l);for(let d=0;d<f;d++){const h=l+2+d*12;if(h+12>e.byteLength)break;if(c(h)===274)return c(h+2)===3&&u(h+4)===1?c(h+8):1}}}}n+=2+i}return 1}async function A1(t,e,n,r){let i;try{i=await createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none"})}catch{i=await createImageBitmap(t,{premultiplyAlpha:"none"})}const s=v1(e?k1(e):1,i.width,i.height,n,r);if(s==="keep")return i;const a=document.createElement("canvas");a.width=n,a.height=r;const o=a.getContext("2d");if(!o)return i;s==="rot-cw"?(o.translate(n,0),o.rotate(Math.PI/2)):(o.translate(0,r),o.rotate(-Math.PI/2)),o.drawImage(i,0,0);const c=await createImageBitmap(a);return i.close?.(),c}const x1={systemfont_segoe:"'Segoe UI', 'Helvetica Neue', Arial, sans-serif",systemfont_arial:"Arial, 'Helvetica Neue', sans-serif",systemfont_verdana:"Verdana, Geneva, sans-serif",systemfont_tahoma:"Tahoma, Geneva, sans-serif",systemfont_timesnewroman:"'Times New Roman', Times, serif",systemfont_georgia:"Georgia, 'Times New Roman', serif",systemfont_couriernew:"'Courier New', Courier, monospace",systemfont_trebuchetms:"'Trebuchet MS', 'Helvetica Neue', sans-serif",systemfont_impact:"Impact, 'Arial Black', sans-serif",systemfont_comicsansms:"'Comic Sans MS', 'Comic Sans', cursive",systemfont_sylfaen:"Palatino, 'Times New Roman', serif",systemfont_calibri:"Calibri, Carlito, 'Helvetica Neue', sans-serif",systemfont_cambria:"Cambria, Georgia, serif",systemfont_consolas:"Consolas, 'Courier New', monospace",systemfont_microsoftyahei:"'Microsoft YaHei', 'PingFang SC', 'Hiragino Sans GB', sans-serif",systemfont_simsun:"SimSun, 'Songti SC', serif",systemfont_simhei:"SimHei, 'Heiti SC', sans-serif"},Ra=new Map,Pi=Ke.foldVisibleReturn;function T1(t){let e=5381;for(let n=0;n<t.length;n++)e=(e<<5)+e+t.charCodeAt(n)|0;return(e>>>0).toString(36)}function S1(t){for(const e of t){const n=Ra.get(e);if(n&&(n.refs--,!(n.refs>0))){Ra.delete(e);try{const r=[];document.fonts.forEach(i=>{i.family===n.family&&r.push(i)});for(const i of r)document.fonts.delete(i)}catch{}}}}const Qn=new Map,P1=512*1024*1024;let Fa=0;function _1(t){for(;Qn.size>0&&(Qn.size>2||Fa>P1);){let e=null,n=1/0;for(const[i,s]of Qn)i!==t&&s.at<n&&(n=s.at,e=i);if(!e)break;const r=Qn.get(e);Fa-=r.parsed.fileSize||0,Qn.delete(e)}}function E1(t){if(!t)return;const e=Qn.get(t);e&&(Fa-=e.parsed.fileSize||0,Qn.delete(t))}async function C1(t,e,n,r){const i=n.key;if(i){const c=Qn.get(i);if(c)return c.at=Date.now(),ce(t,e,`pkg cache hit: ${c.parsed.fileSize} bytes`),c.parsed}let s;try{s=await n.scenePkg(r)}catch(c){throw r.aborted||c instanceof Error?c:new Error(String(c))}ce(t,e,`pkg body: ${s.byteLength} bytes`);const a=s instanceof Uint8Array?s:new Uint8Array(s),o=Ye.parsePkg(a);return i&&(Qn.set(i,{parsed:o,at:Date.now()}),Fa+=o.fileSize||0,_1(i)),o}function I1(t,e){rr(t);const n=(e.canvas instanceof HTMLCanvasElement?e.canvas:null)??document.createElement("canvas"),r=Ns(t,e),i=n.clientWidth||window.innerWidth||1,s=n.clientHeight||window.innerHeight||1;n.width=Math.max(1,Math.round(i*r)),n.height=Math.max(1,Math.round(s*r)),e.canvas instanceof HTMLCanvasElement||(n.style.cssText="position:absolute;inset:0;width:100%;height:100%;",t.wrap?.appendChild(n)),t.canvas=n;let a=!1;const o=console.warn.bind(console);console.warn=(...p)=>{const m=p.map(g=>typeof g=="string"?g:String(g?.message??g)).join(" ");if(m.includes("[we-scene]"))try{ce(t,e,m.slice(0,300))}catch{}o(...p)};const c=new AbortController;let u;t.sceneCleanup=()=>{a=!0,console.warn=o,c.abort(),t.sceneTextUpdate=void 0,u&&(u(),u=void 0),t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0)};let l=null,f,d,h;t.sceneCtl={pause(){d?.()},resume(){h?.()},applyUserProperties(p){f?f(p):l={...l||{},...p}}},(async()=>{try{const p=e.source??Jd(`${e.mediaBase}/${e.src}`);if(!e.source&&(!e.mediaBase||!e.src))throw new Error("\u573A\u666F\u58C1\u7EB8\u7F3A\u5C11 mediaBase/src");ce(t,e,"mountScene start");const m=await C1(t,e,p,c.signal);if(a)return;let g=null;try{g=await p.project?.(c.signal)??null}catch{}if(!n.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0}))throw new Error("WEBGL2_UNAVAILABLE");n.setAttribute("data-webwallgl-gl","1");const y=Ye.getEntry(m,"scene.json");if(!y)throw new Error("pkg \u4E2D\u6CA1\u6709 scene.json\uFF08\u4E0D\u662F\u573A\u666F\u58C1\u7EB8\uFF1F\uFF09");const b=At.parseScene(JSON.parse(zt(y)),g);if(e.clearColor){const C=b.general??={};C.clearcolor=e.clearColor,C.clearenabled=!0}{const C=b.general?.zoom,W=Number(C&&typeof C=="object"?C.value:C);b.cameraTransforms={zoom:Number.isFinite(W)&&W>0?W:1}}const v=U0(b.properties||{});t.liveUserProps=v;const k=()=>At.recomputeLayerVisibility(b.layers);if(t.onSceneInfo){const C=b.general?.orthogonalprojection||{},W=Number(C.width)>0?Number(C.width):n.width,x=Number(C.height)>0?Number(C.height):n.height,_=b.layers||[],V={width:W,height:x,layerCount:_.length,hasModels:_.some(j=>!!j.model),hasParticles:_.some(j=>!!j.particle),hasText:_.some(j=>!!j.text)},F=t.onSceneInfo;t.onSceneInfo=void 0,F(V)}const A=[];th&&(b.layers=b.layers.filter(C=>!(th&&C.isComponent)));const T=C=>{const W=C.startsWith("shaders/")?C:"shaders/"+C,x=C.startsWith("shaders/")?C.slice(8):C,_=Ye.getEntry(m,W);let V=_?zt(_):b1[x]??null;const F=window.__shaderPatch;if(V&&F){const j=x.replace(/\.(frag|vert|h)$/,""),X=F[j]||F[x];if(typeof X=="function")try{const K=X(V,x);typeof K=="string"&&(V=K)}catch{}}return Promise.resolve(V)},S=ht.createRenderer(n,{shaderResolver:T,diag:C=>ce(t,e,`renderer: ${C}`),fboCapFactor:0});if(t.renderer=S,a)return;const P=g?.general?.supportsaudioprocessing!==!1,M=jd(),B=Pe.createSimulatedMedia(),N=Kd.createSimulatedWindowTitle();let O=null;const q={mediaDriver:null,lastSnap:{get:()=>null,setHasThumbnail:()=>{}}},H={current:null};let G=null;const Y=()=>G??t.mediaSource??B;let J=N;const ne={enabled:P&&!t.audioDisabled},fe=C=>new Float32Array(C),Ne={left16:fe(16),right16:fe(16),left32:fe(32),right32:fe(32),left64:fe(64),right64:fe(64),level:0,silent:!0},Qe=(()=>{const C={left64:fe(64),right64:fe(64),left32:fe(32),right32:fe(32),left16:fe(16),right16:fe(16),preL64:fe(64),preR64:fe(64),level:0,silent:!0},W=(x,_)=>{const V=_.length/x.length;for(let F=0;F<x.length;F++){let j=0;const X=Math.floor(F*V),K=Math.max(X+1,Math.floor((F+1)*V));for(let D=X;D<K;D++)j+=_[D];x[F]=j/(K-X)}};return{active:!1,snapshot:C,pump(){const x=t.audioBridge?.();if(!x||!x.left||!x.right){this.active=!1;return}const _=Math.min(64,x.left.length,x.right.length);let V=0;for(let F=0;F<_;F++){const j=x.left[F]||0,X=x.right[F]||0;C.left64[F]=j,C.right64[F]=X,C.preL64[F]=j,C.preR64[F]=X,F<48&&(V+=j)}for(let F=_;F<64;F++)C.left64[F]=0,C.right64[F]=0,C.preL64[F]=0,C.preR64[F]=0;W(C.left32,C.left64),W(C.right32,C.right64),W(C.left16,C.left64),W(C.right16,C.right64),C.level=Math.min(1,V/48),C.silent=C.level<.02,this.active=!0}}})(),Ve=()=>Qe.active?Qe.snapshot:H.current?H.current.snapshot:M.snapshot;S.setAudioProvider(()=>ne.enabled?Ve():Ne);const Fe=new Map,Le=new Map,Tt=[],Xe=(C,W)=>{if(!C||!W||!W.sandbox)return;let x=Le.get(C);x||(x=[],Le.set(C,x)),x.push(W)};window.__audioStats=()=>({enabled:ne.enabled,live:!!H.current,level:ne.enabled?Math.round((H.current?H.current.snapshot:M.snapshot).level*1e3)/1e3:0,silent:ne.enabled?(H.current?H.current.snapshot:M.snapshot).silent:!0,bass:ne.enabled?Math.round((H.current?H.current.snapshot:M.snapshot).left64[2]*1e3)/1e3:0}),window.__audioMute=C=>(ne.enabled=!C,ne.enabled),ce(t,e,`audio: ${H.current?"live mic":"simulated"} stream, supportsaudioprocessing=${P}`);const It=Kd.createShortcutHandler(C=>{ce(t,e,`openUserShortcut: ${C}`)}),Ue={enabled:!t.mediaDisabled,override:null},We=[];let Oe=null,it;q.lastSnap={get:()=>Oe,setHasThumbnail:C=>{Oe&&(Oe.hasThumbnail=C)}};const ve=()=>Y().snapshot,un=C=>{if(!(!C||!C.hasMediaHook||We.includes(C))&&(We.push(C),!!ve().hasMedia))for(const{name:W,event:x}of Pe.diffMediaEvents(null,ve()))try{C.callMedia(W,x)}catch{}};window.__mediaStats=()=>({enabled:Ue.enabled,live:!!O,hooks:We.length,title:ve().title,artist:ve().artist,album:ve().album,state:ve().state,position:Math.round(ve().position),duration:ve().duration,hasThumbnail:ve().hasThumbnail,lyric:ve().lyricLine,primaryColor:ve().primaryColor?[ve().primaryColor.x,ve().primaryColor.y,ve().primaryColor.z]:null}),window.__mediaSet=C=>{Object.assign(ve(),C||{});const W=Pe.diffMediaEvents(Oe,ve());for(const{name:x,event:_}of W)for(const V of We)V.callMedia(x,_);return Oe=Pe.cloneMediaSnapshot(ve()),window.__mediaStats()};const jr=()=>{const C=Pe.diffMediaEvents(Oe,ve());for(const{name:W,event:x}of C)for(const _ of We)try{_.callMedia(W,x)}catch{}Oe=Pe.cloneMediaSnapshot(ve())},Zt=C=>{const W=Y(),x=W?.[C];if(typeof x=="function")try{x.call(W)}catch(_){ce(t,e,`media ${C} \u5931\u8D25: ${_?.message}`)}return jr(),ve()},St={get snapshot(){return ve()},skipNext:()=>Zt("skipNext"),skipPrevious:()=>Zt("skipPrevious"),play:()=>Zt("play"),pause:()=>Zt("pause"),playPause:()=>Zt("playPause")};t.mediaCtl=St,window.__mediaControl=St,window.__system={media:St,windowTitle:J.snapshot,shortcuts:It.last,live:null},window.__liveSystem=()=>({audio:"off",media:"offline",window:"offline"});const ct=qb.createPointerSource(e.canvas?{target:e.canvas,viewport:()=>({w:e.canvas.clientWidth||window.innerWidth||1,h:e.canvas.clientHeight||window.innerHeight||1})}:{});S.setPointerProvider(()=>ct),t.pointerCtl={push:C=>ct.pushExternal(C),leave:()=>ct.pushExternalLeave()};{const C=u;u=()=>{C?.(),ct.dispose()}}const mt=Ke.createInputView(),Kn=jb.createEngineTimers({setTimeout:(C,W)=>window.setTimeout(C,W),clearTimeout:C=>window.clearTimeout(C),setInterval:(C,W)=>window.setInterval(C,W),clearInterval:C=>window.clearInterval(C)},{onError:(()=>{let C=!1;return W=>{C||(C=!0,ce(t,e,`engine \u5B9A\u65F6\u5668\u56DE\u8C03\u629B\u9519\uFF08\u6B64\u540E\u540C\u7C7B\u9759\u9ED8\uFF09: ${String(W?.message||W).slice(0,90)}`))}})()}),_n={setTimeout:Kn.setTimeout,clearTimeout:Kn.clearTimeout,setInterval:Kn.setInterval,clearInterval:Kn.clearInterval};{const C=u;u=()=>{C?.(),Kn.dispose()}}window.__pointerStats=()=>{const C=ct.state,W=x=>Math.round(x*1e3)/1e3;return{normalized:{u:W(C.u),v:W(C.v)},last:{u:W(C.lastU),v:W(C.lastV)},world:{x:Math.round(C.wx),y:Math.round(C.wy)},originY:C.originY!=null?Math.round(C.originY):null,screen:{x:C.screenX,y:C.screenY,w:C.screenW,h:C.screenH},leftDown:C.leftDown,has:C.has,delta:W(ct.normalizedDelta()),counts:{move:C.moveCount,down:C.downCount,up:C.upCount}}};const Ae=new Map;Ae.set("util/white",{glTex:ht.makeTexture(S.gl,new Uint8Array([255,255,255,255]),1,1),width:1,height:1,rg88:!1}),Ae.set("util/noflow",{glTex:ht.makeTexture(S.gl,new Uint8Array([127,127,127,255]),1,1),width:1,height:1,rg88:!1}),Ae.set("util/noise",{glTex:ht.makeTexture(S.gl,Vb.generateNoiseTexture(),256,256),width:256,height:256,rg88:!1,mips:null});{const C=x=>{const _=Pe.renderThumbnail(x,512);return{glTex:ht.makeTextureMip(S.gl,[_],!1),width:_.width,height:_.height,rg88:!1,mips:[_],generated:!0}},W=B.tracks||[];W.length&&(Ae.set("$mediaThumbnail",C(W[0])),Ae.set("$mediaPreviousThumbnail",C(W[W.length-1])))}const _i=(C,W,x)=>{const _=p1(C,W,x,512),V=m1(C,W,x),F=S.gl,j=Ae.get("$mediaThumbnail"),X=!!j?.generated;j&&!X&&Ae.set("$mediaPreviousThumbnail",j);const K=Ae.get("$mediaThumbnail");if(K?.glTex?(F.bindTexture(F.TEXTURE_2D,K.glTex),F.texImage2D(F.TEXTURE_2D,0,F.RGBA,_.width,_.height,0,F.RGBA,F.UNSIGNED_BYTE,_.rgba),K.width=_.width,K.height=_.height,K.mips=[_],K.generated=!1):Ae.set("$mediaThumbnail",{glTex:ht.makeTextureMip(F,[_],!1),width:_.width,height:_.height,rg88:!1,mips:[_],generated:!1}),X){const D=Ae.get("$mediaPreviousThumbnail");D?.glTex&&(F.bindTexture(F.TEXTURE_2D,D.glTex),F.texImage2D(F.TEXTURE_2D,0,F.RGBA,_.width,_.height,0,F.RGBA,F.UNSIGNED_BYTE,_.rgba),D.width=_.width,D.height=_.height,D.mips=[_],D.generated=!1)}return V};if(e.liveSystem){const C={handle:null,dead:!1};(t.wallpaperDisposers??=[]).push(()=>{C.dead=!0;try{C.handle?.dispose()}catch{}C.handle=null});try{const W=async x=>{try{const _=await fetch(x.url,{cache:"no-store"});if(!_.ok)return;const V=await _.blob(),F=await createImageBitmap(V,{premultiplyAlpha:"none"}),j=_i(F,F.width,F.height);F.close?.();const X=Y().snapshot;j&&(X.primaryColor=Pe.mediaVec3(...j.primary),X.secondaryColor=Pe.mediaVec3(...j.secondary),X.tertiaryColor=Pe.mediaVec3(...j.tertiary),X.textColor=Pe.mediaVec3(.98,.98,1),X.highContrastColor=Pe.mediaVec3(1,1,1)),X.hasThumbnail=!0,q.lastSnap.setHasThumbnail(!1),ce(t,e,`liveSystem: artwork ${x.title||x.trackKey}`)}catch(_){ce(t,e,`liveSystem: artwork \u5931\u8D25 (${_ instanceof Error?_.message:_})`)}};if(O=await sh({origin:location.origin,onArtwork:x=>{W(x)}}),C.dead){try{O.dispose()}catch{}O=null}else{if(C.handle=O,G=O.media,J=O.windowTitle,q.mediaDriver=O.media,O.status().audio==="mic"&&(H.current=O.audio),Y().snapshot.hasMedia){for(const{name:_,event:V}of Pe.diffMediaEvents(null,Y().snapshot))for(const F of We)try{F.callMedia(_,V)}catch{}Oe=Pe.cloneMediaSnapshot(Y().snapshot)}const x=O.status();ce(t,e,`liveSystem: audio=${x.audio} media=${x.media} window=${x.window}`+(x.title?` title="${x.title}"`:"")+(x.hasArtwork?" artwork=1":"")),ce(t,e,`audio: ${H.current?"live mic":"simulated"} stream, supportsaudioprocessing=${P}`),window.__system={media:St,windowTitle:J.snapshot,shortcuts:It.last,live:()=>O.status()},window.__liveSystem=()=>O.status()}}catch(W){ce(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u56DE\u9000\u6A21\u62DF\u6E90 (${W instanceof Error?W.message:W})`),O=null}}{const C=u;u=()=>{C?.(),O?.dispose(),O=null}}const Jt=new Map,Zn=async C=>{if(Ae.has(C))return Ae.get(C);const W=Ye.getEntry(m,`materials/${C}.tex`);if(!W){if(Vr.isBuiltinParticleTextureName(C)){const j=Vr.buildBuiltinParticleTexture(C);if(j){const X={glTex:ht.makeTextureMip(S.gl,[j],!1),width:j.width,height:j.height,rg88:!1,mips:[j],generated:!0};return Ae.set(C,X),X}}return null}const x=Ma.parseTex(W),_=Ma.decodeMip0(x),V=x.format===8;let F=null;if(_.video!==void 0){const j=URL.createObjectURL(new Blob([_.video],{type:"video/mp4"})),X=il(j,{muted:!0,renderDpr:Ns(t,e),maxW:n.clientWidth||window.innerWidth||1,maxH:n.clientHeight||window.innerHeight||1});for(const I of[X.active,X.standby])I.style.cssText="position:fixed;left:-9999px;top:-9999px;width:2px;height:2px;opacity:0;pointer-events:none",document.body.appendChild(I),(t.videoTextures??=[]).push(I);(t.objectUrls??=[]).push(j),(t.videoPairs??=[]).push(X),X.active.addEventListener("loadedmetadata",()=>{ce(t,e,`video tex '${C}': ${X.active.videoWidth}x${X.active.videoHeight}`)}),X.active.addEventListener("error",()=>{ce(t,e,`video tex '${C}' ERROR: ${X.active.error?.code}`)});const K=[],D=I=>{for(const U of K)I.addEventListener("ended",U)},z={play:()=>{a||X.resume()},pause:()=>X.pause(),stop:()=>{X.pause();try{X.active.currentTime=0}catch{}},isPlaying:()=>!X.active.paused&&!X.active.ended,duration:()=>Number.isFinite(X.active.duration)?X.active.duration:0,getCurrentTime:()=>X.active.currentTime||0,setCurrentTime:I=>{try{X.active.currentTime=I}catch{}},getRate:()=>X.active.playbackRate||1,setRate:I=>{X.active.playbackRate=I,X.standby.playbackRate=I},getLoop:()=>X.active.loop,setLoop:I=>{X.active.loop=I,X.standby.loop=I},addEndedCallback:I=>{K.push(I),X.active.addEventListener("ended",I)}},L={get video(){return X.active},glTex:ht.makeTexture(S.gl,new Uint8Array([0,0,0,0]),1,1),width:_.width,height:_.height,rg88:!1,lastUploaded:-1,videoCtl:z};let E=0;return X.onSwap=I=>{L.lastUploaded=-1,D(I),E++,(E===1||E===10||E===100)&&ce(t,e,`video tex '${C}' loop swap ok x${E}`)},X.onFallback=()=>{ce(t,e,`video tex '${C}' loop fallback (native loop used)`)},Ae.set(C,L),L}else if(_.png!==void 0||_.image!==void 0&&_.fif===Ma.FIF.JPEG){const j=new Blob([_.png||_.image],{type:_.png?"image/png":"image/jpeg"}),X=await A1(j,_.png?null:_.image,_.width,_.height);F={glTex:ht.makeTexture(S.gl,null,0,0,X),width:X.width,height:X.height,rg88:V}}else{if(_.image!==void 0)return null;{const j=Ma.decodeMip0(x);F={glTex:ht.makeTextureMip(S.gl,[j],V),width:j.width,height:j.height,rg88:V,mips:[j]}}}if(!F)return null;if(x.frames?.list?.length){const j=x.frames.list;j.atlasWidth=F.width,j.atlasHeight=F.height,F.frames=j}return Ae.set(C,F),F},en=C=>{if(Ae.has(C))return Promise.resolve(Ae.get(C));const W=Jt.get(C);if(W)return W;const x=Zn(C);return Jt.set(C,x),x.finally(()=>{Jt.get(C)===x&&Jt.delete(C)}),x},qr=/uniform\s+sampler2D\s+g_Texture\d+\s*;\s*\/\/[^\n]*"default"\s*:\s*"([^"]+)"/g,Ps=async C=>{for(const W of C.materialPasses||[])if(W.shader)for(const x of["frag","vert"]){const _=Ye.getEntry(m,`shaders/${W.shader}.${x}`);if(!_)continue;const V=zt(_);qr.lastIndex=0;let F;for(;(F=qr.exec(V))!==null;){const j=F[1];!j||j.startsWith("util/")||j.startsWith("_rt_")||Ae.has(j)||await en(j)}}};let _s=0;const En=[];for(let C=0;C<b.layers.length;C++){const W=b.layers[C];if(W.image)try{let x;if(Pn.BUILTIN_MODELS[W.image])x=Pn.BUILTIN_MODELS[W.image];else{const L=Ye.getEntry(m,W.image);if(!L)continue;x=JSON.parse(zt(L))}At.applySolidFromModel(W,x);const _=W.srcObject?.instance?.usertextures,V=_?.[0]&&typeof _[0].name=="string"&&_[0].name.startsWith("$")?_[0].name:null,F=V&&Ae.has(V)?V:null;if(F&&(W.textureName=F,W.solid=!1),x&&typeof x=="object"&&"width"in x&&"height"in x){const L=x;(W.size?.[0]||0)===0&&(W.size?.[1]||0)===0&&L.width>0&&L.height>0&&(W.size=[L.width,L.height])}const j=At.resolveMaterial(x);if(!j)continue;let X;if(Pn.BUILTIN_MATERIALS[j.materialPath])X=Pn.BUILTIN_MATERIALS[j.materialPath];else{const L=Ye.getEntry(m,j.materialPath);if(L)X=JSON.parse(zt(L));else if(W.solid&&Pn.BUILTIN_MATERIALS["materials/util/solidlayer.json"])X=Pn.BUILTIN_MATERIALS["materials/util/solidlayer.json"];else continue}const K=X.passes?.[0],D=K?.textures||[],z=D[0];if(W.materialBlending=typeof K?.blending=="string"?K.blending:null,K?.combos){for(const L of Object.keys(K.combos))if(L.toLowerCase()==="spritesheet"&&Number(K.combos[L])===1){W.spriteSheet=!0;break}}for(let L=0;L<D.length;L++){const E=D[L];typeof E!="string"||!E||E.startsWith("util/")||E.startsWith("_rt_")||En.push(en(E).then(I=>{I&&L===0&&!F&&(W.textureName=E,_s++,I.videoCtl&&(W.videoCtl=I.videoCtl))}))}K?.shader&&Ye.getEntry(m,`shaders/${K.shader}.frag`)&&Pn.attachLayerMaterialEffect(W,K);for(const L of W.effects||[])Pn.resolveEffectChain(m,L,zt);for(const L of W.effects||[]){for(const E of L.passes||[])for(const I of E.textures||[])typeof I=="string"&&I!==""&&!I.startsWith("util/")&&!I.startsWith("_rt_")&&En.push(en(I));En.push(Ps(L))}}catch(x){console.warn(`\u56FE\u5C42 ${W.name||C} \u52A0\u8F7D\u5931\u8D25: ${x.message}`)}}if(!nh){for(const C of b.layers)if(!(!C.isText||!(C.effects||[]).length))try{for(const W of C.effects||[])Pn.resolveEffectChain(m,W,zt);for(const W of C.effects||[])for(const x of W.passes||[])for(const _ of x.textures||[])typeof _=="string"&&_!==""&&!_.startsWith("util/")&&!_.startsWith("_rt_")&&En.push(en(_))}catch(W){console.warn(`\u6587\u5B57\u5C42\u6548\u679C ${C.name} \u89E3\u6790\u5931\u8D25: ${W.message}`)}}await Promise.all(En);for(const[C,W]of Ae){if(!W?.videoCtl)continue;b.layers.some(_=>_.textureName===C&&_.visible&&!_.destroyed)&&!t.paused&&W.videoCtl.play()}const Pt=[],Ei=[],fn=new Map;let Be=0;const Xr=async C=>{const W=await en(C);if(W)return W;const x=Vr.buildBuiltinParticleTexture(C);if(!x)return null;const _={glTex:ht.makeTextureMip(S.gl,[x],!1),width:x.width,height:x.height,rg88:!1,mips:[x],generated:!0,frames:Vr.builtinParticleFrames(C)??void 0};return Ae.set(C,_),Be++,_},Es=C=>{if(!C)return null;const W=C.mips&&C.mips[0];if(W?.rgba&&typeof Vr.prepareParticleNormalTexture=="function"){const x=Vr.prepareParticleNormalTexture(W);if(x&&x!==W)return{glTex:ht.makeTextureMip(S.gl,[x],!1),width:x.width,height:x.height,rg88:!1,mips:[x],generated:!0}}return C},Ci=async(C,W,x,_)=>{if(_>3)return null;const V=Ye.getEntry(m,C);if(!V)return ce(t,e,`particle '${C}' \u4E0D\u5728 pkg\uFF0C\u8DF3\u8FC7`),null;const F=JSON.parse(zt(V)),j=new Wb.ParticleSystem(S.gl,F,x,W);let X=null,K=null;if(F.material){const E=Ye.getEntry(m,F.material);if(E){const I=JSON.parse(zt(E));j.setMaterial(I);const U=I?.passes?.[0]?.textures||[];X=U[0]||null,K=U[1]||null}}const D=await Xr(X||"particle/halo");if(!D)return ce(t,e,`particle '${C}' \u65E0\u8D34\u56FE\u53EF\u7528\uFF0C\u8DF3\u8FC7`),null;j.setTexture({glTex:D.glTex,width:D.width,height:D.height,frames:D.frames});const z=K||(j.refract?Vr.particleNormalNameForAlbedo(X||"particle/halo"):null);if(z){const E=Es(await Xr(z));E&&j.setNormalTexture({glTex:E.glTex,width:E.width,height:E.height})}j.setVisible(!!W.visible),Pt.push(j);const L=W.id;if(L!==void 0){let E=fn.get(L);E||(E=[],fn.set(L,E)),E.push(j)}for(const E of F.children||[]){if(!E||typeof E.name!="string")continue;const I=String(E.origin??"0 0 0").trim().split(/\s+/).map(Number),U=String(E.scale??"1 1 1").trim().split(/\s+/).map(Number),Q=String(E.angles??"0 0 0").trim().split(/\s+/).map(Number),$=E.type==="eventfollow"?"particle":!E.type||E.type==="static"?"origin":null,Z=j.localToWorld(I[0]||0,I[1]||0),se={...W,origin:[Z[0],Z[1],(W.origin?.[2]||0)+(I[2]||0)],scale:[(W.scale?.[0]??1)*(U[0]||1),(W.scale?.[1]??1)*(U[1]||1),(W.scale?.[2]??1)*(U[2]||1)],angles:[(W.angles?.[0]||0)+(Q[0]||0),(W.angles?.[1]||0)+(Q[1]||0),(W.angles?.[2]||0)+(Q[2]||0)]},te=await Ci(E.name,se,E.instanceoverride||x,_+1);te&&$&&te.attachFollow(j,$,[I[0]||0,I[1]||0,I[2]||0])}return j};if(!c1){for(const C of b.layers)if(C.particle)try{await Ci(C.particle,C,C.instanceoverride,0)}catch(W){console.warn(`\u7C92\u5B50\u56FE\u5C42 ${C.name} \u52A0\u8F7D\u5931\u8D25: ${W.message}`),ce(t,e,`particle '${C.name}' FAIL: ${W.message.slice(0,80)}`)}}if(Pt.length>0){const C=u;u=()=>{C?.();for(const W of Pt)W.dispose()}}const Gr=[];for(const C of b.layers)if(!(!C.sound||!C.sound.length))try{for(const W of C.sound){const x=Ye.getEntry(m,W);if(!x)continue;const _=(W.split(".").pop()||"").toLowerCase(),V=_==="mp3"?"audio/mpeg":_==="ogg"?"audio/ogg":_==="flac"?"audio/flac":"audio/wav",F=new Blob([x],{type:V}),j=URL.createObjectURL(F);(t.objectUrls??=[]).push(j);const X=document.createElement("audio");X.src=j,X.loop=C.soundprops?.playbackmode==="loop",X.volume=Math.max(0,Math.min(1,C.soundprops?.volume??1)),X.muted=e.muted!==!1,C.soundCtl={play(){if(X.ended)try{X.currentTime=0}catch{}X.play().catch(()=>{})},pause(){X.pause()},stop(){X.pause();try{X.currentTime=0}catch{}},isPlaying:()=>!X.paused&&!X.ended,getVolume:()=>X.volume,setVolume:K=>{X.volume=Math.max(0,Math.min(1,K))}},!C.soundprops?.startsilent&&!t.paused&&X.play().catch(()=>{}),Gr.push(X);break}}catch(W){console.warn(`\u58F0\u97F3\u56FE\u5C42 ${C.name} \u52A0\u8F7D\u5931\u8D25: ${W.message}`)}const Ua=C=>{for(const W of Gr)W.volume=Math.max(0,Math.min(1,C)),W.muted=C<=0};if(t.sceneAudio={setVolume:Ua,audios:Gr},a)return;const $r={dt:1/60,t:0};let kr=0;S.setParticleRenderer(()=>{const C=Math.min(.05,Math.max(0,$r.dt));if(ct.state.has){const{wx:W,wy:x,originY:_}=ct.state,V=_??x;for(const F of Pt)F.setPointer(W,V)}if(Ei.length)for(const W of Ei)W.syncLayerTransform();for(const W of Pt)W.layer&&W.layer.runtimeCreated&&W.syncLayerTransform();for(const W of Pt)W.advance(C,ne.enabled?Ve():null);if(kr<2&&(kr++,kr===2)){const W=Pt.reduce((x,_)=>x+_.liveCount(),0);ce(t,e,`particles live: ${W} across ${Pt.length} systems`)}},(C,W,x,_,V)=>{if(C===void 0)return;const F=fn.get(C);if(F)for(const j of F)j.render(x,_,V,W.projW,W.projH)}),ce(t,e,`particles: ${Pt.length} systems, ${Be} builtin tex generated`),window.__particleStats=()=>({t:$r.t,systems:Pt.map(C=>{let W=0,x=1/0,_=-1/0,V=1/0,F=-1/0,j=1/0,X=-1/0;for(const K of C.pool){if(!K.alive)continue;W++;const D=C.originX+K.x*C.scaleX,z=C.originY+K.y*C.scaleY;D<x&&(x=D),D>_&&(_=D),z<V&&(V=z),z>F&&(F=z);const L=Math.abs(K.size)*C.sysScale;L<j&&(j=L),L>X&&(X=L)}return{layer:C.layer&&C.layer.name,opacityMul:Math.round(C.opacityMul*1e4)/1e4,live:W,max:C.maxCount,blend:C.blend,renderer:C.renderers.map(K=>K.kind).join("+"),origin:[Math.round(C.originX),Math.round(C.originY)],bbox:W?[Math.round(x),Math.round(V),Math.round(_),Math.round(F)]:null,size:W?[Math.round(j),Math.round(X)]:null}})}),window.__particleToggle=(C,W)=>{for(let x=0;x<Pt.length;x++)Pt[x].setVisible(W===void 0?C:x===W);return Pt.length};const dn=[],Cs=new Map,Ii=new Map,Ar=C=>{if(!C||!C.puppet)return null;let W=Ii.get(C);return W||(W=new Map,Ii.set(C,W)),W};for(const C of b.layers)if(C.image)try{if(Pn.BUILTIN_MODELS[C.image])continue;const W=Ye.getEntry(m,C.image);if(!W)continue;const x=JSON.parse(zt(W));if(!x.puppet)continue;const _=Ye.getEntry(m,x.puppet);if(!_)continue;const V=As.parseMDL(new Uint8Array(_)),F=C.textureName?Ae.get(C.textureName):null;if(!F){ce(t,e,`puppet '${C.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}C.puppet=V,dn.push({mdl:V,tex:F,layer:C});const j=V.animations[0];ce(t,e,`puppet '${C.name}' v=${V.vertexCount} bones=${V.bones.length}`+(j?` anim='${j.name}' ${j.fps}fps\xD7${j.frameCount}`:" \u65E0\u52A8\u753B"))}catch(W){console.warn(`puppet \u56FE\u5C42 ${C.name} \u52A0\u8F7D\u5931\u8D25: ${W.message}`),ce(t,e,`puppet '${C.name}' \u5931\u8D25: ${W.message}`)}for(const C of b.layers)if(C.model&&!C.puppet)try{const W=Ye.getEntry(m,C.model);if(!W)continue;const x=As.parseMDL(new Uint8Array(W));let _=null;if(x.materialPath){const F=Ye.getEntry(m,x.materialPath);if(F){const X=JSON.parse(zt(F))?.passes?.[0]?.textures?.[0];typeof X=="string"&&X&&(_=X)}}_&&(await en(_),C.textureName=_);const V=_?Ae.get(_):null;if(!V){ce(t,e,`model '${C.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}C.puppet=x,dn.push({mdl:x,tex:V,layer:C}),ce(t,e,`model '${C.name}' v=${x.vertexCount} static ${x.materialPath||""}`)}catch(W){console.warn(`model \u56FE\u5C42 ${C.name} \u52A0\u8F7D\u5931\u8D25: ${W.message}`),ce(t,e,`model '${C.name}' \u5931\u8D25: ${W.message}`)}let xr=null;if(dn.length>0)try{xr=As.createMDLRenderer(S.gl);for(const W of dn)xr.upload(W.mdl);const C=new Map;for(const W of dn)C.set(W.layer,W);S.setPuppetRenderer((W,x,_)=>{const V=C.get(W);V&&xr.draw(x,V.mdl,{time:_.time,animLayers:W.animationLayers,boneOverrides:Ii.get(W),overrideTex:_.overrideTex||null,color:[W.color[0]*W.brightness,W.color[1]*W.brightness,W.color[2]*W.brightness,W.alpha]},V.tex)})}catch(C){console.warn(`puppet \u6E32\u67D3\u5668\u521D\u59CB\u5316\u5931\u8D25: ${C.message}`),ce(t,e,`puppet renderer \u5931\u8D25: ${C.message}`),xr=null;for(const W of dn)W.layer.puppet=null}if(a)return;ce(t,e,`puppet: ${dn.length} meshes`);const Jn=As.applyAttachmentBindOrigins(b.layers);Jn.length&&ce(t,e,`attachments: ${Jn.length} hanging layers`);const Cn=At.collectTransformDirty(b.layers,Jn.map(C=>C.layer));if(Cn.size){ce(t,e,`transform graph: ${Cn.size} live layers`);for(const[C,W]of fn)if(Cn.has(C))for(const x of W)Ei.push(x)}const _t=[],qt=[],De=new Map,Xt={};let tn=null,hn=null,mn=0;if(!nh&&b.layers.some(C=>C.isText)){const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=za(Mr(t.cfg.fit),W,x,n.width,n.height),V=Math.min(3,Math.max(.5,n.width/Math.max(1,_.viewW))),F=new Map,j=[],X=new Set;for(const z of b.layers)z.isText&&z.textFont&&X.add(z.textFont);for(const z of m.entries||[])typeof z.name=="string"&&/^fonts\/.+\.(ttf|otf|woff2?)$/i.test(z.name)&&X.add(z.name);for(const z of X){const L=`${e.src}|${z}`,E=Ra.get(L);if(E){E.refs++,j.push(L),F.set(z,E.family);continue}const I=x1[z.toLowerCase()];if(I){F.set(z,I);continue}try{const U=Ye.getEntry(m,z);if(!U)continue;const Q=w1(U instanceof Uint8Array?U:new Uint8Array(U)),$="wefont_"+T1(L)+"_"+z.split("/").pop().replace(/[^a-zA-Z0-9]/g,"_"),Z=URL.createObjectURL(new Blob([Q])),se=new FontFace($,`url(${Z})`);if(await se.load(),a){URL.revokeObjectURL(Z);break}document.fonts.add(se),(t.objectUrls??=[]).push(Z),F.set(z,$),Ra.set(L,{family:$,refs:1}),j.push(L)}catch(U){console.warn(`\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25 ${z}: ${U.message}`)}}if(j.length){const z=t.sceneCleanup;t.sceneCleanup=()=>{S1(j),z?.()}}tn=document.createElement("canvas"),hn=tn.getContext("2d");const K=2048;for(const z of b.layers)if(z.isText)try{const L={layer:z,sandbox:null,texName:"__wstext_"+z.id,entry:null,lastKey:null,quality:V};if(z.textScript&&(L.sandbox=Ke.evalTextScript(z.textScript,z.textScriptProps,{text:z.text??"",font:z.textFont||"",pointsize:z.textPointsize,color:z.textColor,angles:z.angles,origin:z.origin,scale:z.scale,visible:z.visible,canvasSize:{width:W,height:x},userProperties:v,shared:Xt,audioViews:Fe,inputView:mt,..._n,mediaControl:St,windowTitle:J.snapshot,openUserShortcut:It.openUserShortcut,getLayerText:Q=>De.get(Q),onError:Q=>{ce(t,e,`text script '${z.name}' \u5931\u8D25: ${String(Q.message||Q).slice(0,120)}`)}}),L.sandbox&&(A.push(L.sandbox),qt.push({sandbox:L.sandbox,layer:z}),L.sandbox.hasMediaHook&&un(L.sandbox),L.sandbox.hasAnimEventHook&&Xe(z,{sandbox:L.sandbox,kind:"text"}))),De.set(z.name||"",String(z.text??"")),z.textAnchor!=="center"&&z.size[0]>0&&z.size[1]>0){const Q=z.size[0]*(z.scale[0]||1)/2,$=z.size[1]*(z.scale[1]||1)/2,Z=z.textAnchor;let se=0,te=0;Z.includes("left")&&(se+=Q),Z.includes("right")&&(se-=Q),Z.includes("top")&&(te-=$),Z.includes("bottom")&&(te+=$),z.origin[0]+=se,z.origin[1]+=te,z.localOrigin&&(z.localOrigin[0]+=se,z.localOrigin[1]+=te)}const E=rh*Math.max(1,z.textPointsize),I=Ke.textLayerHasTintMask(z)?8:256,U=Math.min(I,Ke.textCanvasMargin(E,0));L.boxW=z.size[0]>0?z.size[0]:E*4,L.boxH=z.size[1]>0?z.size[1]:E*1.6,L.margin=U,z.size=[L.boxW+U*2,L.boxH+U*2],L.entry={glTex:ht.makeTexture(S.gl,new Uint8Array([0,0,0,0]),1,1),width:1,height:1,rg88:!1},Ae.set(L.texName,L.entry),z.textureName=L.texName,z.solid=!1,_t.push(L)}catch(L){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${z.name} \u521D\u59CB\u5316\u5931\u8D25: ${L.message}`)}if(_t.length>0){const z=u;u=()=>{z?.();for(const L of _t)S.gl.deleteTexture(L.entry.glTex)}}const D=z=>{if(!hn||!tn)return;const L=hn;for(const E of _t){const I=E.layer;let U=String(I.text??"");if(E.sandbox&&E.sandbox.hasUpdate){E.sandbox.engine.runtime=z;const se=E.sandbox.callUpdate(U);se!=null?U=String(se):E.sandbox.thisLayer.text&&(U=String(E.sandbox.thisLayer.text))}else E.sandbox&&typeof E.sandbox.thisLayer?.text=="string"&&(U=String(E.sandbox.thisLayer.text));if(De.set(I.name||"",U),!I.visible)continue;const Q=Math.max(1,E.sandbox?E.sandbox.thisLayer.pointsize:I.textPointsize),$=E.sandbox&&E.sandbox.thisLayer.font||I.textFont||"",Z=`${U}\0${Q}\0${$}\0${I.alpha}\0${I.textCastshadow}\0${I.textMaxwidth||0}\0${I.limitwidth?1:0}\0${I.maxrows||0}\0${I.limitrows?1:0}`;if(E.lastKey!==Z){E.lastKey=Z;try{const se=rh*Q,te=E.boxW,ee=E.boxH,ue=Math.abs(I.scale[0]||1),we=Math.abs(I.scale[1]||1),ke=$&&F.get($)||"sans-serif";L.setTransform(1,0,0,1,0,0),L.font=`${se}px "${ke}", sans-serif`;const ge=L.measureText(""),Je=(ge.fontBoundingBoxAscent||0)+(ge.fontBoundingBoxDescent||0),Re=I.textSpacing||[0,0],Ut=Ke.layoutText(U,{boxW:te,boxH:ee,pointsize:se,lineHeight:(Je>0?Je:se*1.25)+Re[1],spacing:Re,padding:I.textPadding||0,maxwidth:I.textMaxwidth||0,limitwidth:!!I.textLimitwidth,maxrows:I.textMaxrows||0,limitrows:!!I.textLimitrows,limituseellipsis:!!I.textLimituseellipsis,halign:I.textHAlign,valign:I.textVAlign},ze=>L.measureText(ze).width),$t=E.margin;if(Ke.shouldGrowMediaPlaceholder(te,ee,!!E.sandbox?.hasMediaHook)){const ze=Ke.textCanvasMarginGrow(Ut,te,ee,$t);I.size[0]=te+ze*2,I.size[1]=ee+ze*2}let st=Math.max(1,Math.round(I.size[0]*ue*E.quality)),pt=Math.max(1,Math.round(I.size[1]*we*E.quality));const yn=Math.min(1,K/Math.max(st,pt));st=Math.max(1,Math.round(st*yn)),pt=Math.max(1,Math.round(pt*yn)),tn.width!==st||tn.height!==pt?(tn.width=st,tn.height=pt):L.clearRect(0,0,st,pt);const be=`${se}px "${ke}", sans-serif`,Se=Math.min(st/I.size[0],pt/I.size[1]);L.setTransform(Se,0,0,Se,0,0),L.translate($t,$t),Ke.drawTextLayer(L,Ut,{font:be,color:I.textColor,alpha:I.alpha,brightness:I.brightness,spacing:Re,pointsize:se,opaquebackground:!!I.textOpaquebackground,backgroundcolor:I.textBackgroundcolor,backgroundbrightness:I.textBackgroundbrightness,castshadow:!!I.textCastshadow});const ye=E.entry;S.gl.bindTexture(S.gl.TEXTURE_2D,ye.glTex),S.gl.texImage2D(S.gl.TEXTURE_2D,0,S.gl.RGBA,S.gl.RGBA,S.gl.UNSIGNED_BYTE,tn),ye.width=st,ye.height=pt}catch(se){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${I.name} \u7ED8\u5236\u5931\u8D25: ${se.message}`),E.lastKey=null}}}};t.sceneTextUpdate=D,window.__textWidgets=_t,ce(t,e,`text widgets: ${_t.length} (scripts ${_t.filter(z=>z.sandbox).length}, fonts ${F.size}, quality ${V.toFixed(2)})`)}if(a)return;const Mt=[],In=[],Gt=[],Tr=[],pn={},Sr=[],Qr=[],Pr=new Map,Mi=(C,W)=>{if(!W||typeof W.callCursor!="function"||!W.hasCursorHook)return;const x=Pr.get(C);x?x.push(W):Pr.set(C,[W])};for(const C of _t)C.sandbox&&Mi(C.layer,C.sandbox);{const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=v,V=(E,I)=>{const U=b.general||{};if(E==="zoom"&&typeof I=="number"&&Number.isFinite(I)&&I>0){b.cameraTransforms.zoom=I,U.zoom&&typeof U.zoom=="object"?U.zoom.value=I:U.zoom=I;return}U[E]&&typeof U[E]=="object"&&"value"in U[E]?U[E].value=I:U[E]=I};let F=1+Math.max(0,...b.layers.map(E=>Number(E.id)||0));const j={recomputeVisibility:k,getSceneLayer:E=>b.layers.find(I=>I.name===E&&!I.destroyed)||null,getSceneLayerById:E=>b.layers.find(I=>I.id===E&&!I.destroyed)||null,enumerateSceneLayers:()=>b.layers.filter(E=>!E.destroyed),getSceneAnimation:E=>{if(E==null||E==="")return null;if(pn[E])return pn[E];for(const I of b.layers)if(I.animations&&I.animations[E])return I.animations[E];return null},cameraTransforms:b.cameraTransforms,getInitialLayerConfig:E=>{const I=E&&typeof E=="object"?E.name:String(E||"");return b.layers.find(U=>U.name===I)||null},createSceneLayer:E=>{let I=E&&typeof E=="object"?E:null,U=null;if(typeof E=="string"){const $=E;if(I=b.layers.find(Z=>Z&&!Z.destroyed&&Z.image===$&&Z.textureName)||b.layers.find(Z=>Z&&!Z.destroyed&&Z.image===$)||null,!I)if(/^models\//.test($)&&Ye.getEntry(m,$))U={path:$,kind:"model"},I={image:$,origin:[0,0,0],scale:[1,1,1],angles:[0,0,0],size:[0,0],color:[1,1,1],visible:!0,alpha:1,brightness:1};else if(/^particles\//.test($)&&Ye.getEntry(m,$))U={path:$,kind:"particle"},I={particle:$,origin:[0,0,0],scale:[1,1,1],angles:[0,0,0],size:[0,0],color:[1,1,1],visible:!0,alpha:1,brightness:1};else return ce(t,e,`createLayer('${$}') \u627E\u4E0D\u5230\u5DF2\u52A0\u8F7D\u7684\u540C\u6A21\u578B\u5C42`),null}I||(I={});const Q={...I,id:F++,origin:Array.isArray(I.origin)?I.origin.slice():[0,0,0],scale:Array.isArray(I.scale)?I.scale.slice():[1,1,1],angles:Array.isArray(I.angles)?I.angles.slice():[0,0,0],size:Array.isArray(I.size)?I.size.slice():[0,0],color:Array.isArray(I.color)?I.color.slice():[1,1,1],childIds:null,hasChildren:!1,destroyed:!1,animations:{},animationList:[],objectScripts:null};if(delete Q.textureAnimation,delete Q.videoTextureApi,delete Q.soundCtl,delete Q.videoCtl,Array.isArray(I.effects)&&(Q.effects=I.effects.map($=>({...$,passes:Array.isArray($.passes)?$.passes.map(Z=>({...Z})):$.passes}))),b.layers.push(Q),Q.runtimeCreated=!0,U&&U.kind==="model"){const $=U.path;try{const Z=JSON.parse(zt(Ye.getEntry(m,$))),se=At.resolveMaterial(Z),te=se&&Ye.getEntry(m,se.materialPath),ue=(te?JSON.parse(zt(te)):null)?.passes?.[0];if(ue?.combos){for(const ke of Object.keys(ue.combos))if(ke.toLowerCase()==="spritesheet"&&Number(ue.combos[ke])===1){Q.spriteSheet=!0;break}}const we=ue?.textures?.[0];typeof we=="string"&&we&&!we.startsWith("util/")&&!we.startsWith("_rt_")&&en(we).then(ke=>{if(ke&&(Q.textureName=we,Q.size[0]===0||Q.size[1]===0)){const ge=ke.frames&&Array.isArray(ke.frames)?ke.frames[0]:null;Q.size=[ge&&ge.width||ke.width,ge&&ge.height||ke.height]}})}catch(Z){ce(t,e,`createLayer('${$}') \u8D44\u4EA7\u5B9E\u4F8B\u5316\u5931\u8D25: ${String(Z.message||Z).slice(0,120)}`)}}else if(U&&U.kind==="particle"){const $=U.path;Ci($,Q,null,0).then(Z=>{Z||ce(t,e,`createLayer('${$}') \u7C92\u5B50\u7CFB\u7EDF\u88C5\u914D\u5931\u8D25`)})}return Q},mediaControl:St,windowTitle:J.snapshot,openUserShortcut:It.openUserShortcut,isScreensaver:!1};S.setConstantScriptRuntime?.(Ke.evalObjectScript,{userProperties:_,audioViews:Fe,shared:Xt,inputView:mt,timers:Kn,animEventQueue:Tt,...j,onSandbox:(E,I)=>{E&&E.hasMediaHook&&un(E),E&&E.hasAnimEventHook&&Xe(I&&I.layer,{sandbox:E,kind:"const"})}});const X={origin:"localOrigin",scale:"localScale",angles:"localAngles"},K=(E,I)=>{const U=X[I];return U&&E&&Array.isArray(E[U])?U:I};for(const E of b.layers){const I=E.objectAnimations;if(I){E.animations=E.animations||{},E.animationList=E.animationList||[];for(const[U,Q]of Object.entries(I))try{const $=xs.createAnimation(Q.animation);$.field=U,$.baseValue=Q.value;const Z=K(E,U),se=U==="volume"?E.soundprops?.volume:U==="maxwidth"?E.textMaxwidth:U==="zoom"?b.cameraTransforms?.zoom:E[Z];$.baseNumeric=Array.isArray(se)?se.slice():se,$.slot=Z,E.animationList.push($),$.name&&(E.animations[$.name]=$),In.push({layer:E,field:U,slot:Z,ctrl:$})}catch($){ce(t,e,`animation '${E.name}.${U}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String($.message).slice(0,80)}`)}if(E.animationList.length){const U=new Map;for(const Q of E.animationList)U.set(Q.field,Q);xs.linkAnimations(U,Q=>ce(t,e,`${E.name}: ${Q}`)),E.animationsByField=Object.fromEntries(U)}}}for(const E of b.layers){const I=E.particleOverrideAnimations;if(I)for(const[U,Q]of Object.entries(I))try{const $=xs.createAnimation(Q.animation);$.baseNumeric=typeof Q.value=="number"?Q.value:Number(Q.value)||0,Gt.push({layer:E,key:U,ctrl:$})}catch($){ce(t,e,`override animation '${E.name}.${U}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String($.message).slice(0,80)}`)}}let D=!1;for(const E of b.layers){for(const[U,Q]of(E.effects||[]).entries()){const $=Q.visibleScript;if($)try{const Z=Ke.evalObjectScript($.script,$.scriptproperties,{canvasSize:{width:W,height:x},userProperties:_,audioViews:Fe,inputView:mt,..._n,layer:E,targetEffect:Q,...j,shared:Xt,onError:ue=>ce(t,e,`effect visible script '${E.name}#${U}' \u5931\u8D25: ${String(ue.message||ue).slice(0,80)}`)});if(!Z)continue;A.push(Z);const se=Z.init(Q.visible),te=Pi(se);te!==void 0&&(Q.visible=te),Z.applyUserProperties(_),Z.hasMediaHook&&un(Z);let ee=null;Z.hasUpdate&&(ee={effect:Q,sandbox:Z,last:se},Sr.push(ee)),Z.hasAnimEventHook&&Xe(E,{sandbox:Z,kind:"effectVisible",effect:Q,run:ee})}catch(Z){console.warn(`\u6548\u679C\u5F00\u5173\u811A\u672C ${E.name}#${U} \u6C42\u503C\u5931\u8D25: ${Z.message}`)}}const I=E.objectScripts;if(I)for(const[U,Q]of Object.entries(I))try{const $=Ke.evalObjectScript(Q.script,Q.scriptproperties,{canvasSize:{width:W,height:x},screenResolution:{x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1},timeOfDay:(()=>{const Z=new Date;return(Z.getHours()*3600+Z.getMinutes()*60+Z.getSeconds())/86400})(),userProperties:_,audioViews:Fe,inputView:mt,layer:E,getAnimationForProperty:()=>E.animationsByField&&E.animationsByField[U]||null,...j,getBoneOverrides:Ar,shared:Xt,..._n,onError:Z=>ce(t,e,`object script '${E.name}.${U}' \u5931\u8D25: ${String(Z.message||Z).slice(0,90)}`)});if($){A.push($);const Z=K(E,U),se=E[Z],te=U==="angles"&&Array.isArray(se)?Ke.radToScriptAngles(se):Array.isArray(se)?{x:se[0]??0,y:se[1]??0,z:se[2]??0}:se,ee=$.init(te);if(ee!=null){if(U==="visible"){const ue=Pi(ee);ue!==void 0&&E.visibleSelf!==ue&&(E.visibleSelf=ue,D=!0)}else if(typeof ee=="number"&&Number.isFinite(ee))(U==="alpha"||U==="brightness")&&(E[U]=ee);else if(typeof ee=="object"&&ee.x!==void 0){const ue=ee;Number.isFinite(Number(ue.x))&&Number.isFinite(Number(ue.y))&&(E[Z]=U==="angles"?Ke.scriptAnglesToRad(ue):[Number(ue.x)||0,Number(ue.y)||0,Number(ue.z)||0])}}$.applyUserProperties(_),Mi(E,$),$.hasMediaHook&&un($),$.hasUpdate&&Mt.push({layer:E,field:U,slot:Z,kind:U==="visible"?"bool":U==="alpha"||U==="brightness"?"scalar":"vec3",sandbox:$,last:U==="visible"?ee:void 0}),$.hasAnimEventHook&&Xe(E,{sandbox:$,kind:U==="visible"?"bool":U==="alpha"||U==="brightness"?"scalar":"vec3",field:U,slot:Z})}}catch($){console.warn(`\u5BF9\u8C61\u811A\u672C ${E.name}.${U} \u6C42\u503C\u5931\u8D25: ${$.message}`)}}for(const E of qt){const I=E.sandbox.init(E.layer.text??"");typeof I=="string"&&(E.layer.text=I),E.sandbox.applyUserProperties(v)}D&&k();const z=b.generalScripts;if(z){for(const[E,I]of Object.entries(z))try{const U=Ke.evalObjectScript(I.script,I.scriptproperties,{canvasSize:{width:W,height:x},userProperties:_,audioViews:Fe,inputView:mt,..._n,...j,shared:Xt,onError:$=>ce(t,e,`general script '${E}' \u5931\u8D25: ${String($.message||$).slice(0,80)}`)});if(!U)continue;A.push(U),U.init(I.value),U.applyUserProperties(_),U.hasMediaHook&&un(U);const Q=$=>V(E,$);U.hasUpdate&&Qr.push({field:E,sandbox:U,write:Q})}catch(U){console.warn(`general \u811A\u672C ${E} \u6C42\u503C\u5931\u8D25: ${U.message}`)}Qr.length&&ce(t,e,`general scripts: ${Qr.map(E=>E.field).join(",")}`)}const L=b.generalAnimations;if(L){for(const[E,I]of Object.entries(L))try{const U=xs.createAnimation(I.animation);U.field=E,U.baseValue=I.value,U.baseNumeric=I.value,U.name&&(pn[U.name]=U),Tr.push({field:E,ctrl:U,write:Q=>V(E,Q)})}catch(U){ce(t,e,`general animation '${E}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(U.message).slice(0,80)}`)}Tr.length&&ce(t,e,`general animations: ${Tr.map(E=>E.field).join(",")}`)}}Mt.length&&(ce(t,e,`object scripts: ${Mt.length}`),window.__objScripts=Mt,window.__effectScripts=Sr),window.__mediaHooks=We,window.__sceneLayers=b.layers,window.__compositeStats=()=>S.compositeStats?.()??null,window.__compositeEnable=C=>S.setCompositeEnabled?.(C),window.__scene=b,window.__textures=Ae;const _r=Array.from(Pr.keys());_r.length&&ce(t,e,`cursor hooks: ${_r.length} layers`);let Er=null,nn=null,Cr=!1;const lt=()=>({worldPosition:Ke.makeCursorEventVec(ct.state.wx,ct.state.originY!=null?ct.state.originY:ct.state.wy,0)}),Lt=(C,W,x)=>{const _=Pr.get(C);if(_)for(const V of _)V.callCursor(W,x)},Ir=()=>{if(_r.length===0)return;const C=ct.state;if(!C.has)return;const W=S.getParallaxOffset?S.getParallaxOffset():{x:0,y:0},x=b.general?.orthogonalprojection?.height||n.height,_=Xb.hitTestLayers(b.layers,C.wx,C.wy,x,{parOffX:W.x,parOffY:W.y,alignTable:ht.ALIGN,filter:F=>Pr.has(F)}),V=lt();_!==Er&&(Er&&Lt(Er,"cursorLeave",V),Er=_,_&&Lt(_,"cursorEnter",V)),_&&Lt(_,"cursorMove",V),C.leftDown&&!Cr?(nn=_,_&&Lt(_,"cursorDown",V)):!C.leftDown&&Cr&&(nn&&Lt(nn,"cursorUp",V),nn&&nn===_&&Lt(_,"cursorClick",V),nn=null),Cr=C.leftDown},Bi=performance.now();let Is=0,er=0;const gn=[],tr=[];let Ms=-1/0,Ri=0;const Yr=C=>{if(a||t.paused)return;const x=1e3/(t.cfg.sceneFps||60);if(C-Ms>=x){Ms=C,ir(t,C),tl(t,n,t.cfg);const _=Math.max(0,(C-Bi-Is)/1e3);if(mt.update(ct.state),Ue.enabled){if(O?.media)O.media.pump();else{const L=Y();typeof L?.update=="function"&&L.update(_)}const D=ve(),z=Pe.diffMediaEvents(Oe,D);if(z.length){for(const{name:L,event:E}of z)for(const I of We)I.disabled||I.callMedia(L,E);Oe=Pe.cloneMediaSnapshot(D)}if(it!==D.thumbnail&&typeof D.thumbnail=="string"&&D.thumbnail){const L=D.thumbnail;it=L,(async()=>{try{const E=await fetch(L,{cache:"no-store"}).then(Z=>Z.ok?Z.blob():null);if(!E)return;const I=await createImageBitmap(E,{premultiplyAlpha:"none"});if(it!==L){I.close?.();return}const U=I.width,Q=I.height,$=_i(I,U,Q);if(I.close?.(),$){const Z=ve();Z.primaryColor=Pe.mediaVec3(...$.primary),Z.secondaryColor=Pe.mediaVec3(...$.secondary),Z.tertiaryColor=Pe.mediaVec3(...$.tertiary),Z.textColor=Pe.mediaVec3(.98,.98,1),Z.highContrastColor=Pe.mediaVec3(1,1,1)}ce(t,e,`media: $mediaThumbnail \u5DF2\u66F4\u65B0\uFF08${U}\xD7${Q}\uFF09`)}catch(E){ce(t,e,`media: \u5C01\u9762\u4E0A\u4F20\u5931\u8D25\uFF08${E instanceof Error?E.message:E}\uFF09`)}})()}}O?.windowTitle?O.windowTitle.pump():N.update(_);const V=Math.max(0,_-Ri);Ri=_,$r.dt=V,$r.t=_;let F=!1;const j=(D,z)=>{const L=Le.get(D);if(!(!L||!L.length)){window.__animEventsFired=(window.__animEventsFired||0)+z.length;{const E=window,I=E.__animEventLog||(E.__animEventLog=[]);for(const U of z)I.push({l:String(D&&(D.name||D.id)),f:U.frame,n:U.name}),I.length>400&&I.shift()}for(const E of z)for(const I of L){const U=I.sandbox;if(!(!U||U.disabled))if(I.kind==="text"){const Q=U.callAnimationEvent(E,String(D.text??""));typeof Q=="string"&&(D.text=Q)}else if(I.kind==="effectVisible"){const Q=I.run&&I.run.last!==void 0&&I.run.last!==null?I.run.last:!!I.effect.visible,$=U.callAnimationEvent(E,Q);I.run&&(typeof $=="boolean"||typeof $=="number"&&Number.isFinite($))&&(I.run.last=$);const Z=Pi($);Z!==void 0&&(I.effect.visible=Z)}else if(I.kind==="const"){const Q=U.callAnimationEvent(E,U.__lastConstValue);(typeof Q=="number"&&Number.isFinite(Q)||Q&&typeof Q=="object"&&Number.isFinite(Number(Q.x))&&Number.isFinite(Number(Q.y)))&&(U.__lastConstValue=Q)}else if(I.kind==="bool"){const Q=U.callAnimationEvent(E,!!D.visible),$=Pi(Q);$!==void 0&&D.visibleSelf!==$&&(D.visibleSelf=$,F=!0)}else if(I.kind==="scalar"){const Q=U.callAnimationEvent(E,Number(D[I.field])||0),$=Number(Q);Number.isFinite($)&&(D[I.field]=$)}else{const Q=D[I.slot],$=I.field==="angles"?Ke.radToScriptAngles(Q):{x:Q&&Q[0]||0,y:Q&&Q[1]||0,z:Q&&Q[2]||0},Z=U.callAnimationEvent(E,$),se=Z&&typeof Z=="object"&&"x"in Z?Z:$;D[I.slot]=I.field==="angles"?Ke.scriptAnglesToRad(se):[Number(se.x)||0,Number(se.y)||0,Number(se.z)||0]}}}};for(const D of In){D.ctrl.advance(V);const z=D.field,L=D.slot||z,E=D.ctrl.applyTo(D.ctrl.baseNumeric);if(Array.isArray(E)){const I=D.layer[L];if(Array.isArray(I))for(let U=0;U<E.length&&U<I.length;U++)I[U]=E[U]}else Number.isFinite(E)&&(z==="visible"?D.layer.visibleSelf!==!!E&&(D.layer.visibleSelf=!!E,F=!0):z==="volume"?(D.layer.soundprops.volume=E,D.layer.soundCtl?.setVolume?.(E)):z==="maxwidth"?D.layer.textMaxwidth=E:z==="zoom"?E>0&&(b.cameraTransforms.zoom=E):D.layer[L]=E)}for(const D of Gt){D.ctrl.advance(V);const z=D.ctrl.applyTo(D.ctrl.baseNumeric);if(typeof z!="number"||!Number.isFinite(z))continue;const L=fn.get(D.layer.id);if(L)for(const E of L)E.setOverrideValue(D.key,z)}for(const D of In){const z=D.ctrl.takeEvents();z.length&&j(D.layer,z)}for(const D of Gt){const z=D.ctrl.takeEvents();z.length&&j(D.layer,z)}for(const D of Tr)D.ctrl.takeEvents();for(const D of Tr){D.ctrl.advance(V);const z=D.ctrl.applyTo(D.ctrl.baseNumeric);typeof z=="number"&&Number.isFinite(z)?D.write(z):Array.isArray(z)&&Number.isFinite(z[0])&&D.write(z[0])}for(const D of Sr){if(D.sandbox.disabled)continue;D.sandbox.engine.frametime=V,D.sandbox.engine.runtime=_;const z=D.sandbox.callUpdate(D.last!==void 0&&D.last!==null?D.last:!!D.effect.visible);(typeof z=="boolean"||typeof z=="number"&&Number.isFinite(z))&&(D.last=z);const L=Pi(z);L!==void 0&&(D.effect.visible=L)}for(const D of Qr){if(D.sandbox.disabled)continue;D.sandbox.engine.frametime=V,D.sandbox.engine.runtime=_;const z=b.general||{},L=z[D.field]&&typeof z[D.field]=="object"&&"value"in z[D.field]?z[D.field].value:z[D.field],E=D.sandbox.callUpdate(L);E!==void 0&&D.write(E)}const X={x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1};for(const D of A)!D||D.disabled||(D.engine.frametime=V,D.engine.runtime=_,D.engine.screenResolution=X);for(const D of Mt){if(D.sandbox.disabled)continue;D.sandbox.engine.frametime=V,D.sandbox.engine.runtime=_,D.sandbox.engine.screenResolution=X;const z=D.layer[D.field];if(D.kind==="bool"){const L=D.last!==void 0&&D.last!==null?D.last:!!z,E=D.sandbox.callUpdate(L);(typeof E=="boolean"||typeof E=="number"&&Number.isFinite(E))&&(D.last=E);const I=Pi(E);I!==void 0&&(D.field==="visible"?D.layer.visibleSelf!==I&&(D.layer.visibleSelf=I,F=!0):D.layer[D.field]=I)}else if(D.kind==="scalar"){const L=D.sandbox.callUpdate(Number(z)||0),E=Number(L);Number.isFinite(E)&&(D.layer[D.field]=E)}else{const L=D.slot||D.field,E=D.layer[L],I=D.field==="angles"?Ke.radToScriptAngles(E):{x:E[0]||0,y:E[1]||0,z:E[2]||0},U=D.sandbox.callUpdate(I),Q=U&&typeof U=="object"&&"x"in U?U:I;D.layer[L]=D.field==="angles"?Ke.scriptAnglesToRad(Q):[Q.x||0,Q.y||0,Q.z||0]}}F&&k(),Cn.size&&At.recomposeWorld(b.layers,Cn),ne.enabled&&(Qe.pump(),Qe.active||(H.current?H.current.pump():M.update(_)),Cb(Fe,Ve())),Jn.length&&As.followAttachments(Jn,_,Ar);for(const D of dn){const z=D.mdl,L=D.layer,E=z.animations;if(!E||!E.length||!L.animationLayers||!L.visible||!E.some(U=>U.events&&U.events.length))continue;let I=Cs.get(L);I||(I=new Map,Cs.set(L,I));for(let U=0;U<L.animationLayers.length;U++){const Q=L.animationLayers[U];if(!Q||Q.visible===!1||Q.visible===0)continue;const $=E.find(ee=>ee.id===Q.animation);if(!$||!$.events||!$.events.length)continue;const Z=_*(typeof Q.rate=="number"?Q.rate:1)*$.fps,se=I.has(U)?I.get(U):Z,te=xs.crossedEvents($.events,se,Z,$.frameCount,$.mode==="loop"?"loop":$.mode==="mirror"?"mirror":"single");te.length&&j(L,te),I.set(U,Z)}}const K=t.coverAlign;S.render(b,Ae,n.width,n.height,_,Mr(t.cfg.fit),K.x,K.y).then(()=>{if(t.onFirstFrame){const D=t.onFirstFrame;t.onFirstFrame=void 0;try{D()}catch{}}if(!(a||t.paused)){if(Tt.length){for(const D of Tt)j(D.layer,D.events);Tt.length=0}try{Ir()}catch{}ct.beginFrame();try{t.sceneTextUpdate&&C>=mn&&(mn=C+100,t.sceneTextUpdate(_))}catch{}t.raf=requestAnimationFrame(Yr)}}).catch(D=>{console.warn("scene render error:",D),ce(t,e,`render: ${String(D.message||D).slice(0,200)}`),a=!0})}else t.paused||(t.raf=requestAnimationFrame(Yr))},Bs=()=>{a||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(Yr))},Rs=C=>{if(a)return;const W=b.properties||{},x=O0(W,v,C);if(Object.keys(x).length){Hr(b.general||{},W,0);for(const _ of b.layers){const V=_.srcObject;if(!V)continue;Hr(V,W,0);const F=Tn(V.visible);F&&F in x&&(_.visibleSelf=At.parseBool(V.visible,!0));const j=Tn(V.color);j&&j in x&&(_.color=At.parseColor(V.color),_.isText&&(_.textColor=_.color));const X=Tn(V.alpha);X&&X in x&&(_.alpha=At.parseNum(V.alpha,1));const K=Tn(V.brightness);K&&K in x&&(_.brightness=At.parseNum(V.brightness,1));const D=Tn(V.volume);if(D&&D in x){const L=At.parseNum(V.volume,1);_.soundprops&&(_.soundprops.volume=L),_.soundCtl?.setVolume?.(L)}for(let L=0;L<(V.animationlayers||[]).length;L++){const E=V.animationlayers[L],I=_.animationLayers?.[L];if(!E||!I)continue;const U=Tn(E.visible);U&&U in x&&(I.visible=At.parseBool(E.visible,!0));const Q=Tn(E.rate);Q&&Q in x&&(I.rate=At.parseNum(E.rate,1));const $=Tn(E.blend);$&&$ in x&&(I.blend=At.parseNum(E.blend,1))}for(let L=0;L<(V.effects||[]).length;L++){const E=V.effects[L],I=_.effects?.[L];if(!E||!I)continue;const U=Tn(E.visible);U&&U in x&&!I.visibleScript&&(I.visible=At.parseBool(E.visible,!0))}const z=V.instanceoverride;if(z&&typeof z=="object"&&_.particle){let L=!1;for(const E of Object.keys(z)){if(E==="id")continue;const I=Tn(z[E]);if(I&&I in x){L=!0;break}}if(L){const E=fn.get(_.id);if(E)for(const I of E)I.reapplyOverride?.()}}}for(const _ of A)if(!(!_||_.disabled))try{_.applyUserProperties(x)}catch{}k();for(const _ of b.layers){if(!_.particle)continue;const V=fn.get(_.id);if(V)for(const F of V)F.setVisible(!!_.visible)}S.applyConstUserProperties?.(x);for(const _ of _t)_.lastKey=null;ce(t,e,`props hot: ${Object.keys(x).join(",")}`)}};d=()=>{t.raf!==void 0&&(cancelAnimationFrame(t.raf),t.raf=void 0),er||(er=performance.now()),gn.length=0;for(const C of Ae.values())C?.videoCtl?.isPlaying?.()&&(gn.push(C.videoCtl),C.videoCtl.pause());tr.length=0;for(const C of Gr)!C.paused&&!C.ended&&(tr.push(C),C.pause())},h=()=>{er&&(Is+=performance.now()-er,er=0);for(const C of gn)try{C.play()}catch{}gn.length=0;for(const C of tr)C.play().catch(()=>{});tr.length=0,Bs()},f=Rs,l&&(Rs(l),l=null),Bs();{const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=Mr(t.cfg.fit),V=za(_,W,x,n.width,n.height);ce(t,e,`fit ${_}: view ${Math.round(V.viewW)}x${Math.round(V.viewH)} scene ${W}x${x} canvas ${n.width}x${n.height}`);{const F=_h(b.layers);Number.isFinite(F.minX)&&Number.isFinite(F.minY)&&(t.coverPeek={contentW:F.maxX-F.minX,contentH:F.maxY-F.minY,projW:W,projH:x},ce(t,e,`cover peek gate: content ${Math.round(F.maxX-F.minX)}x${Math.round(F.maxY-F.minY)}`))}}ce(t,e,`renderer started: ${b.layers.length} layers`)}catch(p){if(a||p&&p.name==="AbortError")return;console.warn("scene render failed:",p);const m=p instanceof Error?p:new Error(String(p));ce(t,e,`failed: ${String(m.message||m).slice(0,200)}`),t.onError?t.onError(m):t.fallbackPage?.()}})()}const M1='data-we-shim="1"',ah="data-we-shim-src";function B1(t){try{const e=new URL(t),n=e.pathname,r=n.lastIndexOf("/");return e.pathname=r<0?"/":n.slice(0,r+1),e.hash="",e.search="",e.href}catch{const e=t.replace(/[#?].*$/,""),n=e.lastIndexOf("/");return n<0?e:e.slice(0,n+1)}}function R1(t){const e=/<meta[^>]+http-equiv\s*=\s*["']?Content-Security-Policy["']?[^>]*>/gi;let n;for(;n=e.exec(t);){const r=n[0],i=/content\s*=\s*"([^"]*)"/i.exec(r)?.[1]??/content\s*=\s*'([^']*)'/i.exec(r)?.[1]??"";if(/script-src/i.test(i)&&!/script-src[^;]*'unsafe-inline'/i.test(i)&&!/script-src[^;]*\*/i.test(i))return!0}return!1}function oh(t){return t.replace(/<\/script/gi,"<\\/script")}function F1(t,e,n){if(t||(t=""),t.includes(M1)||t.includes(ah))return t;const r=n.baseHref&&!/<base\b/i.test(t)?`<base href="${n.baseHref.replace(/"/g,"&quot;")}">`:"",i=`<script ${ah}="1">
647
- ${oh(e)}
761
+ `};function u2(t){if(!t||t.length<12)return t;const e=t[0],n=t[1],r=t[2],i=t[3];if(!(e===0&&n===1&&r===0&&i===0)&&!(e===79&&n===84&&r===84&&i===79))return t;const o=Uint8Array.from(t),c=new DataView(o.buffer,o.byteOffset,o.byteLength),u=c.getUint16(4);if(u<=0||12+u*16>o.length)return t;const l=(g,y,w)=>{let A=0;const b=y+w;for(let v=y;v<b;v+=4){const x=o[v]||0,P=v+1<b?o[v+1]:0,S=v+2<b?o[v+2]:0,k=v+3<b?o[v+3]:0;A=A+(x<<24|P<<16|S<<8|k)>>>0}c.setUint32(g+4,A)};let d=!1;for(let g=0;g<u;g++){const y=12+g*16,w=String.fromCharCode(o[y],o[y+1],o[y+2],o[y+3]);if(w!=="vhea"&&w!=="hhea")continue;const A=c.getUint32(y+8),b=c.getUint32(y+12);if(b!==36||A+b>o.length)continue;const v=c.getUint32(A);v===65536||v===69632||(c.setUint32(A,65536),l(y,A,b),d=!0)}let f=-1,h=0,p=0;for(let g=0;g<u;g++){const y=12+g*16;if(String.fromCharCode(o[y],o[y+1],o[y+2],o[y+3])==="cmap"){f=y,h=c.getUint32(y+8),p=c.getUint32(y+12);break}}if(f<0||h+p>o.length)return d?o:t;const m=c.getUint16(h+2);for(let g=0;g<m;g++){const y=h+4+g*8,w=c.getUint32(y+4),A=h+w;if(A+14>o.length||c.getUint16(A)!==4)continue;const b=c.getUint16(A+6),v=b>>>1;if(v<1)continue;const x=2*Math.pow(2,Math.floor(Math.log2(v))),P=Math.floor(Math.log2(v)),S=b-x,k=c.getUint16(A+8),_=c.getUint16(A+10),I=c.getUint16(A+12);k===x&&_===P&&I===S||(c.setUint16(A+8,x),c.setUint16(A+10,P),c.setUint16(A+12,S),d=!0)}return d?(l(f,h,p),o):t}function f2(t,e,n,r,i){if(e===r&&n===i)return"keep";if(e===i&&n===r&&r>0&&i>0){if(t===6||t===5)return"rot-ccw";if(t===8||t===7)return"rot-cw"}return"keep"}function d2(t){if(t.length<4||t[0]!==255||t[1]!==216)return 1;const e=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=2;for(;n+4<=t.length;){if(t[n]!==255){n++;continue}const r=t[n+1];if(r===216||r===1||r>=208&&r<=215){n+=2;continue}if(r===218)break;const i=e.getUint16(n+2);if(r===225&&n+10<=t.length&&t[n+4]===69&&t[n+5]===120&&t[n+6]===105&&t[n+7]===102&&t[n+8]===0&&t[n+9]===0){const s=n+10,a=t[s]===77&&t[s+1]===77,o=t[s]===73&&t[s+1]===73;if(a||o){const c=d=>e.getUint16(d,o),u=d=>e.getUint32(d,o),l=s+u(s+4);if(l>=0&&l+2<=e.byteLength){const d=c(l);for(let f=0;f<d;f++){const h=l+2+f*12;if(h+12>e.byteLength)break;if(c(h)===274)return c(h+2)===3&&u(h+4)===1?c(h+8):1}}}}n+=2+i}return 1}async function h2(t,e,n,r,i=1){const s=Number.isFinite(i)&&i>0?Math.min(1,i):1,a=n>0?Math.max(1,Math.round(n*s)):1,o=r>0?Math.max(1,Math.round(r*s)):1,c=s<.999&&n>0&&r>0?{resizeWidth:a,resizeHeight:o,resizeQuality:"high"}:null;let u;try{u=await createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none",...c||{}})}catch{try{u=await createImageBitmap(t,{premultiplyAlpha:"none",...c||{}})}catch{u=await createImageBitmap(t,{premultiplyAlpha:"none"})}}const l=f2(e?d2(e):1,u.width,u.height,a,o);if(l==="keep")return u;const d=document.createElement("canvas");d.width=a,d.height=o;const f=d.getContext("2d");if(!f)return u;l==="rot-cw"?(f.translate(a,0),f.rotate(Math.PI/2)):(f.translate(0,o),f.rotate(-Math.PI/2)),f.drawImage(u,0,0);const h=await createImageBitmap(d);return u.close?.(),h}function m2(t,e,n){const{width:r,height:i,rgba:s}=t,a=Math.max(1,Math.round(e)),o=Math.max(1,Math.round(n));if(a===r&&o===i)return t;const c=new Uint8Array(a*o*4),u=r/a,l=i/o;for(let d=0;d<o;d++){const f=Math.min(i-1,Math.max(0,(d+.5)*l-.5)),h=Math.floor(f),p=Math.min(i-1,h+1),m=f-h;for(let g=0;g<a;g++){const y=Math.min(r-1,Math.max(0,(g+.5)*u-.5)),w=Math.floor(y),A=Math.min(r-1,w+1),b=y-w,v=(h*r+w)*4,x=(h*r+A)*4,P=(p*r+w)*4,S=(p*r+A)*4,k=(d*a+g)*4;for(let _=0;_<4;_++){const I=s[v+_]*(1-b)+s[x+_]*b,B=s[P+_]*(1-b)+s[S+_]*b;c[k+_]=Math.round(I*(1-m)+B*m)}}}return{width:a,height:o,rgba:c}}const p2={systemfont_segoe:"'Segoe UI', 'Helvetica Neue', Arial, sans-serif",systemfont_arial:"Arial, 'Helvetica Neue', sans-serif",systemfont_verdana:"Verdana, Geneva, sans-serif",systemfont_tahoma:"Tahoma, Geneva, sans-serif",systemfont_timesnewroman:"'Times New Roman', Times, serif",systemfont_georgia:"Georgia, 'Times New Roman', serif",systemfont_couriernew:"'Courier New', Courier, monospace",systemfont_trebuchetms:"'Trebuchet MS', 'Helvetica Neue', sans-serif",systemfont_impact:"Impact, 'Arial Black', sans-serif",systemfont_comicsansms:"'Comic Sans MS', 'Comic Sans', cursive",systemfont_sylfaen:"Palatino, 'Times New Roman', serif",systemfont_calibri:"Calibri, Carlito, 'Helvetica Neue', sans-serif",systemfont_cambria:"Cambria, Georgia, serif",systemfont_consolas:"Consolas, 'Courier New', monospace",systemfont_microsoftyahei:"'Microsoft YaHei', 'PingFang SC', 'Hiragino Sans GB', sans-serif",systemfont_simsun:"SimSun, 'Songti SC', serif",systemfont_simhei:"SimHei, 'Heiti SC', sans-serif"},Uo=new Map,ti=ot.foldVisibleReturn;function op(t,e){return e==="maxwidth"?{get:()=>Number(t.textMaxwidth)||0,set:n=>{t.textMaxwidth=n,t.lastKey=null}}:e==="pointsize"?{get:()=>Number(t.textPointsize)||0,set:n=>{t.textPointsize=n,t.lastKey=null}}:e==="volume"?{get:()=>t.soundprops?Number(t.soundprops.volume)??1:Number(t.volume)||1,set:n=>{const r=Math.max(0,Math.min(1,n));t.soundprops&&(t.soundprops.volume=r),t.volume=r,t.soundCtl?.setVolume&&t.soundCtl.setVolume(r)}}:{get:()=>Number(t[e])||0,set:n=>{t[e]=n}}}const g2=1;function y2(t,e){if(t.storageProvider)return ot.makeSandboxStorage(t.storageProvider.screen,t.storageProvider.global);let n=null;try{n=typeof window<"u"&&window.localStorage?window.localStorage:null}catch{n=null}if(!n)return ot.makeSandboxStorage();const r="wst:"+(e?encodeURIComponent(e):"nokey")+":",i="wst:global:",s=a=>({get:o=>{const c=n.getItem(a+o);return c===null?null:c},set:(o,c)=>n.setItem(a+o,c),remove:o=>n.removeItem(a+o),clear:()=>{const o=[];for(let c=0;c<n.length;c++){const u=n.key(c);u&&u.startsWith(a)&&o.push(u)}for(const c of o)n.removeItem(c)},keys:()=>{const o=[];for(let c=0;c<n.length;c++){const u=n.key(c);u&&u.startsWith(a)&&o.push(u.slice(a.length))}return o}});return ot.makeSandboxStorage(s(r),s(i))}function b2(t){let e=5381;for(let n=0;n<t.length;n++)e=(e<<5)+e+t.charCodeAt(n)|0;return(e>>>0).toString(36)}function w2(t){for(const e of t){const n=Uo.get(e);if(n&&(n.refs--,!(n.refs>0))){Uo.delete(e);try{const r=[];document.fonts.forEach(i=>{i.family===n.family&&r.push(i)});for(const i of r)document.fonts.delete(i)}catch{}}}}const Er=new Map,v2=512*1024*1024;let Oo=0;function A2(t){for(;Er.size>0&&(Er.size>2||Oo>v2);){let e=null,n=1/0;for(const[i,s]of Er)i!==t&&s.at<n&&(n=s.at,e=i);if(!e)break;const r=Er.get(e);Oo-=r.parsed.fileSize||0,Er.delete(e)}}function x2(t){if(!t)return;const e=Er.get(t);e&&(Oo-=e.parsed.fileSize||0,Er.delete(t))}async function k2(t,e,n,r){const i=n.key;if(i){const c=Er.get(i);if(c)return c.at=Date.now(),be(t,e,`pkg cache hit: ${c.parsed.fileSize} bytes`),c.parsed}let s;try{s=await n.scenePkg(r)}catch(c){throw r.aborted||c instanceof Error?c:new Error(String(c))}be(t,e,`pkg body: ${s.byteLength} bytes`);const a=s instanceof Uint8Array?s:new Uint8Array(s),o=at.parsePkg(a);return i&&(Er.set(i,{parsed:o,at:Date.now()}),Oo+=o.fileSize||0,A2(i)),o}function T2(t,e){Or(t);const n=(e.canvas instanceof HTMLCanvasElement?e.canvas:null)??document.createElement("canvas"),r=Vi(t,e),i=n.clientWidth||window.innerWidth||1,s=n.clientHeight||window.innerHeight||1;n.width=Math.max(1,Math.round(i*r)),n.height=Math.max(1,Math.round(s*r)),e.canvas instanceof HTMLCanvasElement||(n.style.cssText="position:absolute;inset:0;width:100%;height:100%;",t.wrap?.appendChild(n)),t.canvas=n;let a=!1;const o=console.warn.bind(console);console.warn=(...m)=>{const g=m.map(y=>typeof y=="string"?y:String(y?.message??y)).join(" ");if(g.includes("[we-scene]"))try{be(t,e,g.slice(0,300))}catch{}o(...m)};const c=new AbortController;let u;t.sceneCleanup=()=>{a=!0,console.warn=o,c.abort(),t.sceneTextUpdate=void 0,u&&(u(),u=void 0),t.renderer&&(t.renderer.dispose?.(),t.renderer=void 0)};let l=null,d,f,h,p;t.sceneCtl={pause(){f?.()},resume(){h?.()},applyUserProperties(m){d?d(m):l={...l||{},...m}},setQuality(m){t.cfg.quality={...fa(t.cfg.quality),...m??{}},p?.(fa(t.cfg.quality))}},(async()=>{try{const m=e.source??Ym(`${e.mediaBase}/${e.src}`);if(!e.source&&(!e.mediaBase||!e.src))throw new Error("\u573A\u666F\u58C1\u7EB8\u7F3A\u5C11 mediaBase/src");be(t,e,"mountScene start");const g=await k2(t,e,m,c.signal);if(a)return;let y=null;try{y=await m.project?.(c.signal)??null}catch{}if(!n.getContext("webgl2",{premultipliedAlpha:!1,antialias:!1,alpha:!1,preserveDrawingBuffer:!0}))throw new Error("WEBGL2_UNAVAILABLE");n.setAttribute("data-webwallgl-gl","1");const A=at.getEntry(g,"scene.json")??at.getEntry(g,"gifscene.json")??at.getEntry(g,"scenes/scene.json")??at.getEntry(g,"scenes/gifscene.json");if(!A)throw new Error("pkg \u4E2D\u6CA1\u6709 scene.json\uFF08\u4E0D\u662F\u573A\u666F\u58C1\u7EB8\uFF1F\uFF09");const b=zt.parseScene(JSON.parse(jt(A)),y);if(e.clearColor){const T=b.general??={};T.clearcolor=e.clearColor,T.clearenabled=!0}{const T=b.general?.zoom,C=Number(T&&typeof T=="object"?T.value:T);b.cameraTransforms={zoom:Number.isFinite(C)&&C>0?C:1}}const v=nb(b.properties||{});t.liveUserProps=v;const x=()=>zt.recomputeLayerVisibility(b.layers);if(t.onSceneInfo){const T=b.general?.orthogonalprojection||{},C=Number(T.width)>0?Number(T.width):n.width,R=Number(T.height)>0?Number(T.height):n.height,F=b.layers||[],$={width:C,height:R,layerCount:F.length,hasModels:F.some(L=>!!L.model),hasParticles:F.some(L=>!!L.particle),hasText:F.some(L=>!!L.text)},H=t.onSceneInfo;t.onSceneInfo=void 0,H($)}const P=[],S=y2(e,m.key);Zm&&(b.layers=b.layers.filter(T=>!(Zm&&T.isComponent)));const k=T=>{const C=T.startsWith("shaders/")?T:"shaders/"+T,R=T.startsWith("shaders/")?T.slice(8):T,F=at.getEntry(g,C);let $=F?jt(F):l2[R]??null;const H=window.__shaderPatch;if($&&H){const L=R.replace(/\.(frag|vert|h)$/,""),X=H[L]||H[R];if(typeof X=="function")try{const Q=X($,R);typeof Q=="string"&&($=Q)}catch{}}return Promise.resolve($)},_=pt.createRenderer(n,{shaderResolver:k,diag:T=>be(t,e,`renderer: ${T}`),fboCapFactor:0,workshopId:e.src??cu(e.source?.key),parallaxFormula:e.parallaxFormula});if(t.renderer=_,a)return;Ti.setParticleFrameTargetProvider(()=>_.getFrameTarget?.()??null),Ti.setParticleSceneCapture((T,C)=>_.captureSceneTexture?.(T,C)??null);{const T=u;u=()=>{T?.(),Ti.setParticleFrameTargetProvider(null),Ti.setParticleSceneCapture(null)}}const I=y?.general?.supportsaudioprocessing!==!1,B=nm(),V=We.createSimulatedMedia(),O=Gm.createSimulatedWindowTitle();let U=null;const W={mediaDriver:null,lastSnap:{get:()=>null,setHasThumbnail:()=>{}}},ie={current:null},we=We.createWallpaperAudioMedia(We.MEDIA_PLAYBACK,We.mediaVec3);let Y=null;const oe=T=>!!(T&&T.snapshot&&T.snapshot.hasMedia),he=()=>oe(Y)?Y:oe(t.mediaSource)?t.mediaSource:(we.hasCurrent()?we:null)??V;let Ae=O;const Pe={enabled:I&&!t.audioDisabled},Ce=T=>new Float32Array(T),Le={left16:Ce(16),right16:Ce(16),left32:Ce(32),right32:Ce(32),left64:Ce(64),right64:Ce(64),level:0,silent:!0},Ne=(()=>{const T={left64:Ce(64),right64:Ce(64),left32:Ce(32),right32:Ce(32),left16:Ce(16),right16:Ce(16),preL64:Ce(64),preR64:Ce(64),level:0,silent:!0},C=(R,F)=>{const $=F.length/R.length;for(let H=0;H<R.length;H++){let L=0;const X=Math.floor(H*$),Q=Math.max(X+1,Math.floor((H+1)*$));for(let re=X;re<Q;re++)L+=F[re];R[H]=L/(Q-X)}};return{active:!1,snapshot:T,pump(){const R=t.audioBridge?.();if(!R||!R.left||!R.right){this.active=!1;return}const F=Math.min(64,R.left.length,R.right.length);let $=0;for(let H=0;H<F;H++){const L=R.left[H]||0,X=R.right[H]||0;T.left64[H]=L,T.right64[H]=X,T.preL64[H]=L,T.preR64[H]=X,H<48&&($+=L)}for(let H=F;H<64;H++)T.left64[H]=0,T.right64[H]=0,T.preL64[H]=0,T.preR64[H]=0;C(T.left32,T.left64),C(T.right32,T.right64),C(T.left16,T.left64),C(T.right16,T.right64),T.level=Math.min(1,$/48),T.silent=T.level<.02,this.active=!0}}})(),De=()=>Ne.active?Ne.snapshot:ie.current?ie.current.snapshot:B.snapshot;let Re=null;_.setAudioProvider(()=>Pe.enabled?Re||De():Le);const Fe=new Map,Xe=new Map,$e=[],Ye=(T,C)=>{if(!T||!C||!C.sandbox)return;let R=Xe.get(T);R||(R=[],Xe.set(T,R)),R.push(C)};window.__audioStats=()=>({enabled:Pe.enabled,live:!!ie.current,level:Pe.enabled?Math.round((ie.current?ie.current.snapshot:B.snapshot).level*1e3)/1e3:0,silent:Pe.enabled?(ie.current?ie.current.snapshot:B.snapshot).silent:!0,bass:Pe.enabled?Math.round((ie.current?ie.current.snapshot:B.snapshot).left64[2]*1e3)/1e3:0}),window.__audioMute=T=>(Pe.enabled=!T,Pe.enabled),be(t,e,`audio: ${ie.current?"live mic":"simulated"} stream, supportsaudioprocessing=${I}`);const nt=Gm.createShortcutHandler(T=>{be(t,e,`openUserShortcut: ${T}`)}),dn={enabled:!t.mediaDisabled,override:null},st=[],gt=new Set;let Vt=0,xn=0,Pt=null,xt=(()=>{const T=new Date;return(T.getHours()*3600+T.getMinutes()*60+T.getSeconds())/86400})(),tn=-1;const Mt=T=>{if(!(!T||!T.hasResizeHook||typeof T.callResize!="function")&&!gt.has(T)&&(gt.add(T),Pt))try{T.callResize(Pt.w,Pt.h)}catch{}},Pi=(T,C)=>{for(const R of gt)if(!(!R||R.disabled))try{R.callResize(T,C)}catch{}};let nn=null,_i;W.lastSnap={get:()=>nn,setHasThumbnail:T=>{nn&&(nn.hasThumbnail=T)}};const ct=()=>he().snapshot,tr=T=>{if(!(!T||!T.hasMediaHook||st.includes(T))&&(st.push(T),!!ct().hasMedia))for(const{name:C,event:R}of We.diffMediaEvents(null,ct()))try{T.callMedia(C,R)}catch{}};window.__mediaStats=()=>({enabled:dn.enabled,live:!!U,hooks:st.length,title:ct().title,artist:ct().artist,album:ct().album,state:ct().state,position:Math.round(ct().position),duration:ct().duration,hasThumbnail:ct().hasThumbnail,lyric:ct().lyricLine,primaryColor:ct().primaryColor?[ct().primaryColor.x,ct().primaryColor.y,ct().primaryColor.z]:null}),window.__mediaSet=T=>{try{Object.assign(ct(),T||{})}catch{be(t,e,"__mediaSet: \u5F53\u524D\u5A92\u4F53\u5FEB\u7167\u4E3A\u53EA\u8BFB\u89C6\u56FE\uFF08\u58C1\u7EB8\u97F3\u9891\u9A71\u52A8\uFF09\uFF0C\u8986\u5199\u8DF3\u8FC7")}const C=We.diffMediaEvents(nn,ct());for(const{name:R,event:F}of C)for(const $ of st)$.callMedia(R,F);return nn=We.cloneMediaSnapshot(ct()),window.__mediaStats()};const pa=()=>{const T=We.diffMediaEvents(nn,ct());for(const{name:C,event:R}of T)for(const F of st)try{F.callMedia(C,R)}catch{}nn=We.cloneMediaSnapshot(ct())},hn=T=>{const C=he(),R=C?.[T];if(typeof R=="function")try{R.call(C)}catch(F){be(t,e,`media ${T} \u5931\u8D25: ${F?.message}`)}return pa(),ct()},Cr={get snapshot(){return ct()},skipNext:()=>hn("skipNext"),skipPrevious:()=>hn("skipPrevious"),play:()=>hn("play"),pause:()=>hn("pause"),playPause:()=>hn("playPause")};t.mediaCtl=Cr,window.__mediaControl=Cr,window.__system={media:Cr,windowTitle:Ae.snapshot,shortcuts:nt.last,live:null},window.__liveSystem=()=>({audio:"off",media:"offline",window:"offline"});const lt=wA.createPointerSource(e.canvas?{target:e.canvas,viewport:()=>({w:e.canvas.clientWidth||window.innerWidth||1,h:e.canvas.clientHeight||window.innerHeight||1})}:{});_.setPointerProvider(()=>lt),t.pointerCtl={push:T=>lt.pushExternal(T),leave:()=>lt.pushExternalLeave()};{const T=u;u=()=>{T?.(),lt.dispose()}}const Un=ot.createInputView(),kn=bA.createEngineTimers({setTimeout:(T,C)=>window.setTimeout(T,C),clearTimeout:T=>window.clearTimeout(T),setInterval:(T,C)=>window.setInterval(T,C),clearInterval:T=>window.clearInterval(T)},{onError:(()=>{let T=!1;return C=>{T||(T=!0,be(t,e,`engine \u5B9A\u65F6\u5668\u56DE\u8C03\u629B\u9519\uFF08\u6B64\u540E\u540C\u7C7B\u9759\u9ED8\uFF09: ${String(C?.message||C).slice(0,90)}`))}})()}),nr={setTimeout:kn.setTimeout,clearTimeout:kn.clearTimeout,setInterval:kn.setInterval,clearInterval:kn.clearInterval};{const T=u;u=()=>{T?.(),kn.dispose()}}window.__pointerStats=()=>{const T=lt.state,C=R=>Math.round(R*1e3)/1e3;return{normalized:{u:C(T.u),v:C(T.v)},last:{u:C(T.lastU),v:C(T.lastV)},world:{x:Math.round(T.wx),y:Math.round(T.wy)},originY:T.originY!=null?Math.round(T.originY):null,screen:{x:T.screenX,y:T.screenY,w:T.screenW,h:T.screenH},leftDown:T.leftDown,has:T.has,delta:C(lt.normalizedDelta()),counts:{move:T.moveCount,down:T.downCount,up:T.upCount}}};const yt=1.15,Oe=new Map;{const C=(b.general??null)?.orthogonalprojection??null,R=Number(C?.width)||0,F=Number(C?.height)||0,$=R>0&&F>0&&C?.auto!==!0,H=Vi(t,e)||1,L=(n.clientWidth||window.innerWidth||1280)*H,X=(n.clientHeight||window.innerHeight||720)*H;if($){const Q={canvasDeviceW:L,canvasDeviceH:X,viewW:R,viewH:F,safety:yt};for(const re of b.layers){if(!re||re.destroyed||!re.visible)continue;const q=re.image||re.model;if(!q)continue;let K=null;try{if(An.BUILTIN_MODELS[q])K=An.BUILTIN_MODELS[q];else{const ue=at.getEntry(g,q);ue&&(K=JSON.parse(jt(ue)))}}catch{K=null}if(!K||K.meshes||K.puppet)continue;const D=K.material;if(!D)continue;const E=at.getEntry(g,D);if(!E)continue;let z=[];try{z=(JSON.parse(jt(E))?.passes||[]).flatMap(pe=>Array.isArray(pe?.textures)?pe.textures:[])}catch{z=[]}const ee=re.size||[0,0],G=Math.abs(Number(ee[0]))>0&&Math.abs(Number(ee[1]))>0?[Number(ee[0]),Number(ee[1])]:[Number(K.width||0),Number(K.height||0)];if(!(Math.abs(G[0])>0)||!(Math.abs(G[1])>0))continue;const J=re.scale||[1,1,1],ge=!!(re.sizeAnimation||re.scaleAnimation||re.animationlayers?.length),ae=Np(G,[Number(J[0]??1),Number(J[1]??1)],Number((re.angles||[0,0,0])[2]||0),{...Q,safety:yt*(ge?1.4:1)});if(ae>0)for(const ue of z){if(typeof ue!="string"||!ue||ue.startsWith("util/")||ue.startsWith("_rt_"))continue;const pe=Oe.get(ue)||0;ae>pe&&Oe.set(ue,ae)}}be(t,e,`[S4] \u56FE\u5C42\u8DB3\u8FF9\u8868 ${Oe.size} \u4E2A\u8D34\u56FE\uFF08\u89C6\u53E3 ${R}x${F} \u4E16\u754C \u2192 \u753B\u5E03 ${Math.round(L)}x${Math.round(X)} \u8BBE\u5907\u50CF\u7D20\uFF0Csafety=${yt}\uFF09`)}else be(t,e,"[S4] \u6B63\u4EA4\u6295\u5F71\u975E\u663E\u5F0F\uFF08auto/\u900F\u89C6\uFF09\uFF1A\u8DF3\u8FC7\u56FE\u5C42\u8DB3\u8FF9\u6A21\u578B\uFF0C\u56DE\u9000\u5230\u5168\u5C40\u6863\u4F4D")}const Ke=new Map,Ei=Dp();let ni="",On=!1;const Ir=Ip(t,e),Rr=Rp(t,e),ga=32,Ve={texCount:0,cpuDecoded:0,cpuReleased:0,gpuUploaded:0,compressed:0,r8Native:0,framesScaled:[],scaled:[],textures:[],pkgBytes:0},ya=(()=>{if(typeof location>"u")return!0;const T=new URLSearchParams(location.search).get("texr8");return!(T==="0"||T==="off"||T==="native")})(),ba=(()=>{if(typeof location>"u")return!0;const T=new URLSearchParams(location.search).get("texcompress");return!(T==="0"||T==="off"||T==="native")})(),bs=()=>{const T=Vi(t,e)||1,C=(n.clientWidth||window.innerWidth||1280)*T,R=(n.clientHeight||window.innerHeight||720)*T;return Math.max(C,R)},ws=T=>Fp(T,Ir,Rr),wa=T=>{const C=T?.images?.[0]?.[0];return!!T?.frames?.list?.length?Math.max(Number(C?.width||0),Number(C?.height||0)):Math.max(Number(T?.width||0),Number(T?.height||0),0)||Math.max(Number(C?.width||0),Number(C?.height||0))},ri=(T,C)=>{const R=wa(C);if(Ei||On)return R;const F=Up(R,T),$=Oe.get(ni)||0;return Lp(F,R,$)},rt=(T,C,R)=>{if(Ei||On)return 0;const F=T?.images?.[0];if(!F)return 0;const $=F[0],H=!!T?.frames?.list?.length,L=H?Math.max(Number($?.width||0),Number($?.height||0)):Math.max(Number(T?.width||0),Number(T?.height||0),0)||Math.max(Number($?.width||0),Number($?.height||0)),X=F.map((q,K)=>H?Math.max(Number(q.width||0),Number(q.height||0)):Math.max(1,Math.round(L/2**K))),Q=Oe.get(ni)||0,re=Q>0?Math.round(Q):Math.max(64,Math.round(bs()));return Op(X,C,re)},Mi=(T,C)=>{const R=Math.max(Number(T.width||0),Number(T.height||0));if(!C||R<=C*1.1)return T;const F=C/R;return m2(T,Math.max(1,Math.round(T.width*F)),Math.max(1,Math.round(T.height*F)))},va=async(T,C,R)=>{const F=document.createElement("canvas");F.width=T.width,F.height=T.height;const $=F.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!$)return null;$.putImageData(new ImageData(new Uint8ClampedArray(T.rgba.buffer,T.rgba.byteOffset,T.rgba.length),T.width,T.height),0,0);const H=document.createElement("canvas");H.width=C,H.height=R;const L=H.getContext("2d",{alpha:!0});if(!L)return null;L.imageSmoothingEnabled=!0,L.imageSmoothingQuality="high",L.drawImage(F,0,0,C,R);try{return await createImageBitmap(H,{premultiplyAlpha:"none"})}catch{return null}};Ve.pkgBytes=Number(g?.fileSize||0);{let T=null;try{T=await o2()}catch(C){be(t,e,`local assets \u88C5\u8F7D\u5931\u8D25\uFF08\u5FFD\u7565\uFF09\uFF1A${C?.message}`)}T&&be(t,e,`local assets: ${T.loaded}/${T.requested} tex\uFF08util ${T.util} / particle ${T.particle}\uFF09 ${(T.bytes/1e6).toFixed(1)}MB ${T.ms}ms source=${T.source} mode=${T.mode}`+(T.failed?` failed=${T.failed}`:""))}for(const T of Bo.SYSTEM_UTIL_TEXTURES){const C=Bo.buildSystemUtilTexture(T);if(!C)continue;const R={wrap:"repeat"};Ke.set(T,Bo.isNomipSystemTexture(T)?{glTex:pt.makeTexture(_.gl,C.rgba,C.width,C.height,null,R),width:C.width,height:C.height,rg88:!1,mips:null}:{glTex:pt.makeTextureMip(_.gl,[C],!1,R),width:C.width,height:C.height,rg88:!1,mips:[C]})}{const T=R=>{const F=We.renderThumbnail(R,512);return{glTex:pt.makeTextureMip(_.gl,[F],!1),width:F.width,height:F.height,rg88:!1,mips:[F],generated:!0}},C=V.tracks||[];C.length&&dn.enabled&&(Ke.set("$mediaThumbnail",T(C[0])),Ke.set("$mediaPreviousThumbnail",T(C[C.length-1])))}const Aa=(T,C,R)=>{const F=KA(T,C,R,512),$=YA(T,C,R),H=_.gl,L=Ke.get("$mediaThumbnail"),X=!!L?.generated;L&&!X&&Ke.set("$mediaPreviousThumbnail",L);const Q=Ke.get("$mediaThumbnail");if(Q?.glTex?(H.bindTexture(H.TEXTURE_2D,Q.glTex),H.texImage2D(H.TEXTURE_2D,0,H.RGBA,F.width,F.height,0,H.RGBA,H.UNSIGNED_BYTE,F.rgba),H.generateMipmap(H.TEXTURE_2D),Q.width=F.width,Q.height=F.height,Q.mips=[F],Q.generated=!1):Ke.set("$mediaThumbnail",{glTex:pt.makeTextureMip(H,[F],!1),width:F.width,height:F.height,rg88:!1,mips:[F],generated:!1}),X){const re=Ke.get("$mediaPreviousThumbnail");re?.glTex&&(H.bindTexture(H.TEXTURE_2D,re.glTex),H.texImage2D(H.TEXTURE_2D,0,H.RGBA,F.width,F.height,0,H.RGBA,H.UNSIGNED_BYTE,F.rgba),H.generateMipmap(H.TEXTURE_2D),re.width=F.width,re.height=F.height,re.mips=[F],re.generated=!1)}return $};if(e.liveSystem){const T={handle:null,dead:!1};(t.wallpaperDisposers??=[]).push(()=>{T.dead=!0;try{T.handle?.dispose()}catch{}T.handle=null});try{const C=async R=>{try{const F=await fetch(R.url,{cache:"no-store"});if(!F.ok)return;const $=await F.blob(),H=await createImageBitmap($,{premultiplyAlpha:"none"}),L=Aa(H,H.width,H.height);H.close?.();const X=he().snapshot;L&&(X.primaryColor=We.mediaVec3(...L.primary),X.secondaryColor=We.mediaVec3(...L.secondary),X.tertiaryColor=We.mediaVec3(...L.tertiary),X.textColor=We.mediaVec3(.98,.98,1),X.highContrastColor=We.mediaVec3(1,1,1)),X.hasThumbnail=!0,W.lastSnap.setHasThumbnail(!1),be(t,e,`liveSystem: artwork ${R.title||R.trackKey}`)}catch(F){be(t,e,`liveSystem: artwork \u5931\u8D25 (${F instanceof Error?F.message:F})`)}};if(U=await np({origin:location.origin,onArtwork:R=>{C(R)}}),T.dead){try{U.dispose()}catch{}U=null}else{if(T.handle=U,Y=U.media,Ae=U.windowTitle,W.mediaDriver=U.media,U.status().audio==="mic"&&(ie.current=U.audio),he().snapshot.hasMedia){for(const{name:F,event:$}of We.diffMediaEvents(null,he().snapshot))for(const H of st)try{H.callMedia(F,$)}catch{}nn=We.cloneMediaSnapshot(he().snapshot)}const R=U.status();be(t,e,`liveSystem: audio=${R.audio} media=${R.media} window=${R.window}`+(R.title?` title="${R.title}"`:"")+(R.hasArtwork?" artwork=1":"")),be(t,e,`audio: ${ie.current?"live mic":"simulated"} stream, supportsaudioprocessing=${I}`),window.__system={media:Cr,windowTitle:Ae.snapshot,shortcuts:nt.last,live:()=>U.status()},window.__liveSystem=()=>U.status()}}catch(C){be(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u56DE\u9000\u6A21\u62DF\u6E90 (${C instanceof Error?C.message:C})`),U=null}}{const T=u;u=()=>{T?.(),U?.dispose(),U=null}}const Ci=new Map,Wo=async T=>{if(ni=T,On=!1,Ke.has(T))return Ke.get(T);const C=at.getEntry(g,`materials/${T}.tex`);if(!C){if(await sp(T),en.isBuiltinParticleTextureName(T)){const L=en.buildBuiltinParticleTexture(T);if(L){const X={glTex:pt.makeTextureMip(_.gl,[L],!1),width:L.width,height:L.height,rg88:!1,mips:[L],generated:!0};return Ke.set(T,X),X}}if(!Ke.has(T)&&ou.isBuiltinGradientTextureName(T)){const L=ou.buildBuiltinGradientTexture(T);if(L){const X={glTex:pt.makeTextureMip(_.gl,[L],!1,{wrap:"repeat"}),width:L.width,height:L.height,rg88:!1,mips:[L],generated:!0};return Ke.set(T,X),X}}return null}const R=er.parseTex(C);if(!R.isVideo&&R.images&&R.images.length>1){const L=R.textureWidth||R.width,X=R.textureHeight||R.height;if(L>0&&X>0&&L*X<=4096*4096){const Q=_.gl,re=[];try{for(const q of R.images){const K=q[0];if(!K||K.data===void 0||K.compression!==0)throw new Error("skip");const D=K.width*4,E=new Uint8Array(L*X*4);for(let z=0;z<X;z++)E.set(K.data.subarray(z*D,z*D+L*4),z*L*4);re.push(E)}}catch{re.length=0}if(re.length>1){const q=pt.makeTexture(Q,re[0],L,X,null);let K=0;const D=window.setInterval(()=>{a||t.paused||(K=(K+1)%re.length,Q.bindTexture(Q.TEXTURE_2D,q),Q.texSubImage2D(Q.TEXTURE_2D,0,0,0,L,X,Q.RGBA,Q.UNSIGNED_BYTE,re[K]))},100);(t.wallpaperDisposers??=[]).push(()=>window.clearInterval(D));const E={glTex:q,width:L,height:X,rg88:!1,generated:!0};return E.declaredWidth=R.textureWidth,E.declaredHeight=R.textureHeight,Ke.set(T,E),be(t,e,`tex '${T}': animated multi-image, ${re.length} frames @ ${L}x${X}`),E}}}const F=er.decodeMip0(R),$=R.format===8;let H=null;if(F.video!==void 0){const L=URL.createObjectURL(new Blob([F.video],{type:"video/mp4"})),X=Uu(L,{muted:!0,renderDpr:Vi(t,e),maxW:n.clientWidth||window.innerWidth||1,maxH:n.clientHeight||window.innerHeight||1});for(const E of[X.active,X.standby])E.style.cssText="position:fixed;left:-9999px;top:-9999px;width:2px;height:2px;opacity:0;pointer-events:none",document.body.appendChild(E),(t.videoTextures??=[]).push(E);(t.objectUrls??=[]).push(L),(t.videoPairs??=[]).push(X),X.active.addEventListener("loadedmetadata",()=>{be(t,e,`video tex '${T}': ${X.active.videoWidth}x${X.active.videoHeight}`)}),X.active.addEventListener("error",()=>{be(t,e,`video tex '${T}' ERROR: ${X.active.error?.code}`)});const Q=[],re=E=>{for(const z of Q)E.addEventListener("ended",z)},q={play:()=>{a||X.resume()},pause:()=>X.pause(),stop:()=>{X.pause();try{X.active.currentTime=0}catch{}},isPlaying:()=>!X.active.paused&&!X.active.ended,duration:()=>Number.isFinite(X.active.duration)?X.active.duration:0,getCurrentTime:()=>X.active.currentTime||0,setCurrentTime:E=>{try{X.active.currentTime=E}catch{}},getRate:()=>X.active.playbackRate||1,setRate:E=>{X.active.playbackRate=E,X.standby.playbackRate=E},getLoop:()=>X.active.loop,setLoop:E=>{X.active.loop=E,X.standby.loop=E},addEndedCallback:E=>{Q.push(E),X.active.addEventListener("ended",E)}},K={get video(){return X.active},glTex:pt.makeTexture(_.gl,new Uint8Array([0,0,0,0]),1,1),width:F.width,height:F.height,rg88:!1,lastUploaded:-1,videoCtl:q};let D=0;return X.onSwap=E=>{K.lastUploaded=-1,re(E),D++,(D===1||D===10||D===100)&&be(t,e,`video tex '${T}' loop swap ok x${D}`)},X.onFallback=()=>{be(t,e,`video tex '${T}' loop fallback (native loop used)`)},Ke.set(T,K),K}else if(F.png!==void 0||F.image!==void 0&&F.fif===er.FIF.JPEG){const L=new Blob([F.png||F.image],{type:F.png?"image/png":"image/jpeg"}),X=Math.max(Number(F.width||0),Number(F.height||0))||1,Q=!!R?.frames?.list?.length||Iu(Number(F.width||0),Number(F.height||0));On=Q;const re=Q?X:ri(ws(T),R)||X,q=Math.min(1,re/X),K=await h2(L,F.png?null:F.image,F.width,F.height,q);q<.999&&Ve.scaled.push({name:T,how:"decode-resize",from:`${F.width}x${F.height}`,to:`${K.width}x${K.height}`}),H={glTex:pt.makeTexture(_.gl,null,0,0,K),width:K.width,height:K.height,rg88:$}}else{if(F.image!==void 0)return null;{const L=R?.images?.[0]?.[0],X=!!R?.frames?.list?.length||Iu(Number(L?.width||0),Number(L?.height||0));On=X;const Q=X?1:ws(T),re=ri(Q,R),q=rt(R,re,Q);{const E=ba?pt.compressedFormatFor(_.gl,R?.format):null,z=R?.images?.[0];if(E&&z&&z.length&&!(Number(R?.flags)&64)&&!X){const ee=[];let G=!0;const J=Math.max(1,Math.floor(Number(R?.width||z[0].width)/2**q)),ge=Math.max(1,Math.floor(Number(R?.height||z[0].height)/2**q)),ae=Math.min(z[q].width,Math.ceil(J/4)*4),ue=Math.min(z[q].height,Math.ceil(ge/4)*4);for(let pe=0;pe<z.length-q;pe++){const Ie=z[q+pe],je=Math.max(1,Math.floor(ae/2**pe)),qe=Math.max(1,Math.floor(ue/2**pe));if(je>Ie.width||qe>Ie.height)break;const Tt=je===Ie.width&&qe===Ie.height?Ie.data:er.cropBlocks(Ie.data,Ie.width,je,qe,E.blockBytes);if(Tt.length!==Math.ceil(je/4)*Math.ceil(qe/4)*E.blockBytes){G=!1;break}ee.push({width:je,height:qe,data:Tt})}if(G&&ee.length){const pe=_.gl,Ie=ee[0];H={glTex:pt.makeCompressedTextureMip(pe,ee,E.internalFormat),width:Ie.width,height:Ie.height,rg88:!1,compressed:!0,cpuMips:null,looksAlbedo:!1,packedNormal:!0,mipLevel:q},Ve.compressed+=Ie.width*Ie.height*(R.format===7?.5:1),Ve.scaled.push({name:T,how:`compressed-${R.format}${q?`+mip${q}`:""}`,from:`${L?.width}x${L?.height}`,to:`${Ie.width}x${Ie.height}`})}}}const K=H?null:er.decodeMipLevel(R,q),D=!H&&ya&&Number(R?.format)===9&&!X&&!(Number(R?.flags)&64)&&K!=null&&K.png===void 0&&K.image===void 0&&K.video===void 0;if(!H&&K&&(K.png!==void 0||K.image!==void 0||K.video!==void 0)){const E=er.decodeMip0(R);H={glTex:pt.makeTextureMip(_.gl,[E],$),width:E.width,height:E.height,rg88:$,cpuMips:[E]},Ve.cpuDecoded+=E.rgba.byteLength}else if(!H&&D&&K){const E=K,z=E.width*E.height,ee=new Uint8Array(z);for(let G=0;G<z;G++)ee[G]=E.rgba[G*4];H={glTex:pt.makeR8TextureMip(_.gl,[{width:E.width,height:E.height,data:ee}]),width:E.width,height:E.height,rg88:!1,r8:!0,albedoR8:!0,cpuMips:null,looksAlbedo:!1,packedNormal:!1,mipLevel:q},Ve.r8Native+=z,Ve.scaled.push({name:T,how:`r8${q?`+mip${q}`:""}`,from:`${L?.width}x${L?.height}`,to:`${E.width}x${E.height}`})}else if(!H){const E=K,z=Math.max(E.width,E.height),ee=R.images?.[0]?.length||1,G=Math.max(1,Math.round(E.width*re/z)),J=Math.max(1,Math.round(E.height*re/z));let ge=E,ae=null,ue=q>0?`mip${q}`:"";if(q===0&&ee===1&&re>0&&z>re)if($||Hp(E.rgba)){const Ie=$?null:await va(E,G,J);Ie?(ae=Ie,ge={width:Ie.width,height:Ie.height,rgba:E.rgba},ue="resample-native"):E.width*E.height<=16e6||$?(ge=Mi(E,re),ue="resample"):ue="skip-big-alpha"}else E.width*E.height<=16e6?(ge=Mi(E,re),ue="resample"):ue="skip-big-alpha";const pe=en.rgbaLooksLikeAlbedo(E.rgba);H={glTex:ae?pt.makeTexture(_.gl,null,0,0,ae):pt.makeTextureMip(_.gl,[ge],$),width:ge.width,height:ge.height,rg88:ae?!1:$,cpuMips:pe?[ge]:null,looksAlbedo:pe,packedNormal:en.isPackedNormalTexture(E),mipLevel:q},Ve.cpuDecoded+=E.rgba.byteLength,pe||(Ve.cpuReleased+=E.rgba.byteLength),ue&&Ve.scaled.push({name:T,how:ue,from:`${R.images[0][0].width}x${R.images[0][0].height}`,to:`${ge.width}x${ge.height}`})}}}if(!H)return null;if(H.declaredWidth=R.textureWidth,H.declaredHeight=R.textureHeight,R.frames?.list?.length){const L=R.frames.list;L.atlasWidth=H.width,L.atlasHeight=H.height;const X=L[0];H.geomFrame={width:Math.abs(Number(X?.width??H.declaredWidth??0)),height:Math.abs(Number(X?.height??H.declaredHeight??0))};const Q=Number(L.nativeAtlasWidth)||Number(R.images?.[0]?.[0]?.width||0)||H.width;L.nativeAtlasWidth=Q;const re=Q>0?H.width/Q:1;re<.999&&(zp(L,re),Ve.framesScaled.push(`${T} x${re.toFixed(3)}`)),H.frames=L}if(H.looksAlbedo===void 0&&H.glTex){const L=H.cpuMips&&H.cpuMips[0];H.looksAlbedo=L?.rgba?en.rgbaLooksLikeAlbedo(L.rgba):!1,H.packedNormal===void 0&&(H.packedNormal=L?.rgba?en.isPackedNormalTexture(L):!1),!H.looksAlbedo&&H.cpuMips&&(Ve.cpuReleased+=L?.rgba?L.rgba.byteLength:0,H.cpuMips=null)}H.resourceScale=ws(T),Ve.texCount++;{const L=Number(R?.format),X=H.compressed?L===7||L===3?.5:1:H.r8?1:H.rg88?2:4;Ve.gpuUploaded+=Math.round(H.width*H.height*X*(4/3))}return Ve.textures.push({name:T,size:`${H.width}x${H.height}`,scale:H.resourceScale,level:H.mipLevel??0,native:wa(R),need:Math.round(Oe.get(T)||0),target:ri(H.resourceScale,R)}),Ke.set(T,H),be(t,e,`tex '${T}': ${H.width}x${H.height} declared=${H.declaredWidth}x${H.declaredHeight} R=${H.resourceScale} lvl=${H.mipLevel??0} frames=${Array.isArray(H.frames)?H.frames.length:"none"} video=${!!H.videoCtl}`),H},zn=T=>{if(Ke.has(T))return Promise.resolve(Ke.get(T));const C=Ci.get(T);if(C)return C;const R=Wo(T);return Ci.set(T,R),R.finally(()=>{Ci.get(T)===R&&Ci.delete(T)}),R},Ii=/uniform\s+sampler2D\s+g_Texture\d+\s*;\s*\/\/[^\n]*"default"\s*:\s*"([^"]+)"/g,vs=async T=>{for(const C of T.materialPasses||[])if(C.shader)for(const R of["frag","vert"]){const F=at.getEntry(g,`shaders/${C.shader}.${R}`);if(!F)continue;const $=jt(F);Ii.lastIndex=0;let H;for(;(H=Ii.exec($))!==null;){const L=H[1];!L||L.startsWith("util/")||L.startsWith("_rt_")||Ke.has(L)||await zn(L)}}};window.__memStats=()=>({resourceScale:Ir,resourceScaleNormal:Rr,texCount:Ve.texCount,cpuDecodedMB:+(Ve.cpuDecoded/1e6).toFixed(1),cpuReleasedMB:+(Ve.cpuReleased/1e6).toFixed(1),gpuUploadedMB:+(Ve.gpuUploaded/1e6).toFixed(1),compressedMB:+(Ve.compressed/1e6).toFixed(1),r8NativeMB:+(Ve.r8Native/1e6).toFixed(1),pkgBytes:Ve.pkgBytes||0,framesScaled:Ve.framesScaled.slice(0,20),scaledCount:Ve.scaled.length,scaled:Ve.scaled.slice(0,40),textures:Ve.textures.slice(0,60)});let xa=0;const rr=[];for(let T=0;T<b.layers.length;T++){const C=b.layers[T];if(C.image)try{let R;if(An.BUILTIN_MODELS[C.image])R=An.BUILTIN_MODELS[C.image];else{const K=at.getEntry(g,C.image);if(!K)continue;R=JSON.parse(jt(K))}zt.applySolidFromModel(C,R);const F=C.srcObject?.instance?.usertextures,$=F?.[0]&&typeof F[0].name=="string"&&F[0].name.startsWith("$")?F[0].name:null,H=$&&Ke.has($)?$:null;if(H&&(C.textureName=H,C.solid=!1),R&&typeof R=="object"&&"width"in R&&"height"in R){const K=R;(C.size?.[0]||0)===0&&(C.size?.[1]||0)===0&&K.width>0&&K.height>0&&(C.size=[K.width,K.height])}const L=zt.resolveMaterial(R);if(!L)continue;let X;if(An.BUILTIN_MATERIALS[L.materialPath])X=An.BUILTIN_MATERIALS[L.materialPath];else{const K=at.getEntry(g,L.materialPath);if(K)X=JSON.parse(jt(K));else if(C.solid&&An.BUILTIN_MATERIALS["materials/util/solidlayer.json"])X=An.BUILTIN_MATERIALS["materials/util/solidlayer.json"];else continue}const Q=X.passes?.[0],re=Q?.textures||[],q=re[0];if(C.materialBlending=typeof Q?.blending=="string"?Q.blending:null,Q?.combos)for(const K of Object.keys(Q.combos)){const D=K.toLowerCase();D==="spritesheet"&&Number(Q.combos[K])===1&&(C.spriteSheet=!0),D==="lighting"&&Number(Q.combos[K])===1&&(C.lightingEnabled=!0)}for(let K=0;K<re.length;K++){const D=re[K];typeof D!="string"||!D||D.startsWith("util/")||D.startsWith("_rt_")||rr.push(zn(D).then(E=>{if(E&&K===0&&!H&&(C.textureName=D,xa++,E.videoCtl&&(C.videoCtl=E.videoCtl),be(t,e,`autosize gate: model.autosize=${R?.autosize} size=${C.size?.[0]}x${C.size?.[1]}`),R?.autosize&&C.size&&(C.size[0]===0||C.size[1]===0))){const z=Array.isArray(E.frames)&&E.frames.length?E.frames[0]:null,ee=Math.abs(Number(z?.width??0)),G=Math.abs(Number(z?.height??0)),J=Math.abs(Number(E.geomFrame?.width||0)),ge=Math.abs(Number(E.geomFrame?.height||0)),ae=J>0?J:ee>0?ee:Number(E.declaredWidth||0),ue=ge>0?ge:G>0?G:Number(E.declaredHeight||0);ae>0&&ue>0?(C.size=[ae,ue],be(t,e,`autosize applied: layer.size=${ae}x${ue}`)):be(t,e,`autosize skipped: fw=${ee} fh=${G} declared=${E.declaredWidth}x${E.declaredHeight}`)}}))}Q?.shader&&at.getEntry(g,`shaders/${Q.shader}.frag`)&&An.attachLayerMaterialEffect(C,Q);for(const K of C.effects||[])An.resolveEffectChain(g,K,jt);for(const K of C.effects||[]){for(const D of K.passes||[]){for(const E of D.textures||[])typeof E=="string"&&E!==""&&!E.startsWith("util/")&&!E.startsWith("_rt_")&&rr.push(zn(E));for(const E of D.textureFallbacks||[])typeof E=="string"&&E!==""&&!E.startsWith("util/")&&!E.startsWith("_rt_")&&rr.push(zn(E))}rr.push(vs(K))}}catch(R){console.warn(`\u56FE\u5C42 ${C.name||T} \u52A0\u8F7D\u5931\u8D25: ${R.message}`)}}if(!Jm){for(const T of b.layers)if(!(!T.isText||!(T.effects||[]).length))try{for(const C of T.effects||[])An.resolveEffectChain(g,C,jt);for(const C of T.effects||[])for(const R of C.passes||[])for(const F of R.textures||[])typeof F=="string"&&F!==""&&!F.startsWith("util/")&&!F.startsWith("_rt_")&&rr.push(zn(F))}catch(C){console.warn(`\u6587\u5B57\u5C42\u6548\u679C ${T.name} \u89E3\u6790\u5931\u8D25: ${C.message}`)}}await Promise.all(rr);{const C=(b.general??(b.general={})).orthogonalprojection??null,R=Number(C?.width)>0&&Number(C?.height)>0;if(C){const F=Go(b.layers);be(t,e,`auto ortho probe: auto=${C.auto} explicit=${R} bounds=${Math.round(F.minX)},${Math.round(F.minY)}..${Math.round(F.maxX)},${Math.round(F.maxY)} sizes=${b.layers.map($=>`${$.size?.[0]}x${$.size?.[1]}`).join("|")}`)}if(C&&C.auto===!0&&!R){const F=Go(b.layers),$=F.maxX-F.minX,H=F.maxY-F.minY;Math.abs(F.minX)<.5&&Math.abs(F.minY)<.5&&Number.isFinite($)&&Number.isFinite(H)&&$>0&&H>0&&(C.width=$,C.height=H,be(t,e,`auto ortho: content ${Math.round($)}x${Math.round(H)}\uFF08orthogonalprojection.auto\uFF09`))}}be(t,e,`resources R=${Ir}${Rr!==Ir?` (normal R=${Rr})`:""} tex=${Ve.texCount} gpu\u2248${(Ve.gpuUploaded/1e6).toFixed(1)}MB cpuDecoded=${(Ve.cpuDecoded/1e6).toFixed(1)}MB released=${(Ve.cpuReleased/1e6).toFixed(1)}MB scaled=${Ve.scaled.length}`+(Ve.scaled.length?` \u4F8B: ${Ve.scaled.slice(0,3).map(T=>`${T.name}(${T.how} ${T.from}\u2192${T.to})`).join(" ")}`:"")+(Ve.framesScaled.length?` \u5E27\u56FE\u96C6\u7F29\u653E: ${Ve.framesScaled.slice(0,3).join(" ")}`:""));for(const[T,C]of Ke){if(!C?.videoCtl)continue;b.layers.some(F=>F.textureName===T&&F.visible&&!F.destroyed)&&!t.paused&&C.videoCtl.play()}const Ct=[],As=[],Hn=new Map;let ka=0;const ir=async(T,C="albedo")=>{const R=at.getEntry(g,`materials/${T}.tex`)?await zn(T):null;if(R)return R;await sp(T);let F=en.buildBuiltinParticleTexture(T);if(!F)return null;F=C==="normal"?en.convertParticleNormalFormat(F,F.format):en.convertParticleTexFormat(F,F.format);const $={glTex:pt.makeTextureMip(_.gl,[F],!1),width:F.width,height:F.height,rg88:!1,mips:[F],generated:!0,frames:F.frames&&F.frames.length?F.frames:en.builtinParticleFrames(T)??void 0};return Ke.set(T,$),ka++,$},Ta=T=>{if(!T)return null;if(T.looksAlbedo===!1)return T;const C=T.cpuMips&&T.cpuMips[0]||T.mips&&T.mips[0];if(C?.rgba&&typeof en.prepareParticleNormalTexture=="function"){const R=en.prepareParticleNormalTexture(C);if(R&&R!==C)return{glTex:pt.makeTextureMip(_.gl,[R],!1),width:R.width,height:R.height,rg88:!1,mips:[R],generated:!0}}return T},Ri=async(T,C,R,F)=>{if(F>3)return null;const $=at.getEntry(g,T);if(!$)return be(t,e,`particle '${T}' \u4E0D\u5728 pkg\uFF0C\u8DF3\u8FC7`),null;const H=JSON.parse(jt($)),L=new Ti.ParticleSystem(_.gl,H,R,C);let X=null,Q=null;if(H.material){const D=at.getEntry(g,H.material);if(D){const E=JSON.parse(jt(D));L.setMaterial(E);const z=E?.passes?.[0]?.textures||[];X=z[0]||null,Q=z[1]||null}}const re=await ir(X||"particle/halo");if(!re)return be(t,e,`particle '${T}' \u65E0\u8D34\u56FE\u53EF\u7528\uFF0C\u8DF3\u8FC7`),null;L.setTexture({glTex:re.glTex,width:re.width,height:re.height,frames:re.frames});const q=Q||(L.refract?en.particleNormalNameForAlbedo(X||"particle/halo"):null);if(q){const D=Ta(await ir(q,"normal"));D&&(D.packed=D.packedNormal===!0,L.setNormalTexture({glTex:D.glTex,width:D.width,height:D.height,packed:!!D.packed}))}L.setVisible(!!C.visible),Ct.push(L);const K=C.id;if(K!==void 0){let D=Hn.get(K);D||(D=[],Hn.set(K,D)),D.push(L)}for(const D of H.children||[]){if(!D||typeof D.name!="string")continue;const E=String(D.origin??"0 0 0").trim().split(/\s+/).map(Number),z=String(D.scale??"1 1 1").trim().split(/\s+/).map(Number),ee=String(D.angles??"0 0 0").trim().split(/\s+/).map(Number),G=D.type==="eventfollow"?"particle":!D.type||D.type==="static"?"origin":null,J=L.localToWorld(E[0]||0,E[1]||0),ge={...C,origin:[J[0],J[1],(C.origin?.[2]||0)+(E[2]||0)],scale:[(C.scale?.[0]??1)*(z[0]||1),(C.scale?.[1]??1)*(z[1]||1),(C.scale?.[2]??1)*(z[2]||1)],angles:[(C.angles?.[0]||0)+(ee[0]||0),(C.angles?.[1]||0)+(ee[1]||0),(C.angles?.[2]||0)+(ee[2]||0)]},ae=await Ri(D.name,ge,D.instanceoverride||R,F+1);ae&&G?ae.attachFollow(L,G,[E[0]||0,E[1]||0,E[2]||0]):ae&&(D.type==="eventdeath"||D.type==="eventspawn")&&ae.attachEventParent(L,D.type,[E[0]||0,E[1]||0,E[2]||0])}return L};if(!LA){for(const T of b.layers)if(T.particle)try{await Ri(T.particle,T,T.instanceoverride,0)}catch(C){console.warn(`\u7C92\u5B50\u56FE\u5C42 ${T.name} \u52A0\u8F7D\u5931\u8D25: ${C.message}`),be(t,e,`particle '${T.name}' FAIL: ${C.message.slice(0,80)}`)}}if(Ct.length>0){const T=u;u=()=>{T?.();for(const C of Ct)C.dispose()}}const Br=[],Gt=t2();Gt.setVolume(Jo(t,e));const rn=()=>Gt.dispose();for(const T of b.layers)if(!(!T.sound||!T.sound.length))try{for(const C of T.sound){const R=at.getEntry(g,C);if(!R)continue;const F=(C.split(".").pop()||"").toLowerCase(),$=F==="mp3"?"audio/mpeg":F==="ogg"?"audio/ogg":F==="flac"?"audio/flac":"audio/wav",H=new Blob([R],{type:$}),L=URL.createObjectURL(H);(t.objectUrls??=[]).push(L);const X=document.createElement("audio");X.src=L,X.loop=T.soundprops?.playbackmode==="loop",X.volume=Math.max(0,Math.min(1,T.soundprops?.volume??1)),X.muted=e.muted!==!1,Gt.attach(X),T.soundCtl={play(){if(X.ended)try{X.currentTime=0}catch{}Gt.resume(),X.play().catch(()=>{}),we.markPlayed(X)},pause(){X.pause()},stop(){X.pause();try{X.currentTime=0}catch{}we.markStopped(X)},isPlaying:()=>!X.paused&&!X.ended,getVolume:()=>X.volume,setVolume:Q=>{X.volume=Math.max(0,Math.min(1,Q))}},we.register(X,T.name||""),!T.soundprops?.startsilent&&!t.paused&&(Gt.resume(),X.play().catch(()=>{})),Br.push(X);break}}catch(C){console.warn(`\u58F0\u97F3\u56FE\u5C42 ${T.name} \u52A0\u8F7D\u5931\u8D25: ${C.message}`)}const Ze=T=>{const C=Math.max(0,Math.min(1,T));for(const R of Br)Gt.routes(R)?(R.volume=1,R.muted=C<=0):(R.volume=C,R.muted=C<=0);Gt.setVolume(C)};if(t.sceneAudio={setVolume:Ze,audios:Br,dispose:rn},Ru(t),a)return;const Tn={dt:1/60,t:0};let Bi=0,Vn=!1;_.setParticleRenderer(()=>{if(Vn)return;const T=Math.min(.05,Math.max(0,Tn.dt));if(lt.state.has){const{wx:C,wy:R,originY:F}=lt.state,$=F??R;for(const H of Ct)H.setPointer(C,$)}if(As.length)for(const C of As)C.syncLayerTransform();for(const C of Ct)C.layer&&C.layer.runtimeCreated&&C.syncLayerTransform();{const C=_.getParallaxOffset?_.getParallaxOffset():null;for(const R of Ct)if(!C||!C.active||!R.layer||!R.layer.parallaxDepth)R.setParallaxOffset(0,0);else{const F=Ko(R.layer,C);R.setParallaxOffset(F[0],F[1])}}for(const C of Ct)C.advance(T,Pe.enabled?De():null);if(Bi<2&&(Bi++,Bi===2)){const C=Ct.reduce((R,F)=>R+F.liveCount(),0);be(t,e,`particles live: ${C} across ${Ct.length} systems`)}},(T,C,R,F,$)=>{if(Vn||T===void 0)return;const H=Hn.get(T);if(H)for(const L of H)L.render(R,F,$,C.projW,C.projH)});const Wn=T=>{_.setAntiAliasing?.(T.antiAliasing),_.setEffectsEnabled?.(T.postProcessing!=="off"),_.setFboCapFactor?.(qA(T.postProcessing)),Vn=T.particles==="off",Ti.setParticleQualityScale?.(jA(T.particles)),Ti.setParticleDensityTier?.(T.particles==="off"?"high":T.particles);for(const C of Ct)C._applyOverride?.();be(t,e,`quality: aa=${T.antiAliasing} particles=${T.particles} post=${T.postProcessing}`)};p=Wn,Wn(fa(e.quality)),be(t,e,`particles: ${Ct.length} systems, ${ka} builtin tex generated`),window.__particleStats=()=>({t:Tn.t,systems:Ct.map(T=>{let C=0,R=1/0,F=-1/0,$=1/0,H=-1/0,L=1/0,X=-1/0,Q=0;for(const re of T.pool){if(!re.alive)continue;C++,(re.frameMix||0)>Q&&(Q=re.frameMix);const q=T.originX+re.x*T.scaleX,K=T.originY+re.y*T.scaleY;q<R&&(R=q),q>F&&(F=q),K<$&&($=K),K>H&&(H=K);const D=Math.abs(re.size)*T.sysScale;D<L&&(L=D),D>X&&(X=D)}return{layer:T.layer&&T.layer.name,opacityMul:Math.round(T.opacityMul*1e4)/1e4,live:C,max:T.maxCount,blend:T.blend,renderer:T.renderers.map(re=>re.kind).join("+"),origin:[Math.round(T.originX),Math.round(T.originY)],bbox:C?[Math.round(R),Math.round($),Math.round(F),Math.round(H)]:null,size:C?[Math.round(L),Math.round(X)]:null,frameCount:T.frameCount,frameMixMax:Math.round(Q*1e3)/1e3,refract:!!T.refract,refractAmount:Math.round((Number.isFinite(T.refractAmount)?T.refractAmount:.05)*1e3)/1e3}})}),window.__particleToggle=(T,C)=>{for(let R=0;R<Ct.length;R++)Ct[R].setVisible(C===void 0?T:R===C);return Ct.length};const It=[],Fr=new Map,ii=new Map,sn=T=>{if(!T||!T.puppet)return null;let C=ii.get(T);return C||(C=new Map,ii.set(T,C)),C};for(const T of b.layers)if(T.image)try{if(An.BUILTIN_MODELS[T.image])continue;const C=at.getEntry(g,T.image);if(!C)continue;const R=JSON.parse(jt(C));if(!R.puppet)continue;const F=at.getEntry(g,R.puppet);if(!F)continue;const $=la.parseMDL(new Uint8Array(F)),H=T.textureName?Ke.get(T.textureName):null;if(!H){be(t,e,`puppet '${T.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}T.puppet=$,It.push({mdl:$,tex:H,layer:T});const L=$.animations[0];be(t,e,`puppet '${T.name}' v=${$.vertexCount} bones=${$.bones.length}`+(L?` anim='${L.name}' ${L.fps}fps\xD7${L.frameCount}`:" \u65E0\u52A8\u753B"))}catch(C){console.warn(`puppet \u56FE\u5C42 ${T.name} \u52A0\u8F7D\u5931\u8D25: ${C.message}`),be(t,e,`puppet '${T.name}' \u5931\u8D25: ${C.message}`)}for(const T of b.layers)if(T.model&&!T.puppet)try{const C=at.getEntry(g,T.model);if(!C)continue;const R=la.parseMDL(new Uint8Array(C));let F=null;if(R.materialPath){const H=at.getEntry(g,R.materialPath);if(H){const X=JSON.parse(jt(H))?.passes?.[0],Q=X?.textures?.[0];typeof Q=="string"&&Q&&(F=Q);const re=X?.combos?.LIGHTING??X?.combos?.lighting;Number(re)===1&&(T.lightingEnabled=!0)}}if(F)try{await zn(F),T.textureName=F}catch(H){be(t,e,`model '${T.name}' \u7684\u8D34\u56FE '${F}' \u52A0\u8F7D\u5931\u8D25\uFF0C\u8DF3\u8FC7\u8BE5\u5C42\uFF1A${H?.message}`)}const $=F?Ke.get(F):null;if(!$){be(t,e,`model '${T.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}T.puppet=R,It.push({mdl:R,tex:$,layer:T}),be(t,e,`model '${T.name}' v=${R.vertexCount} static ${R.materialPath||""}`)}catch(C){console.warn(`model \u56FE\u5C42 ${T.name} \u52A0\u8F7D\u5931\u8D25: ${C.message}`),be(t,e,`model '${T.name}' \u5931\u8D25: ${C.message}`)}let Fi=null;if(It.length>0)try{Fi=la.createMDLRenderer(_.gl);for(const C of It)Fi.upload(C.mdl);const T=new Map;for(const C of It)T.set(C.layer,C);_.setPuppetRenderer((C,R,F)=>{const $=T.get(C);$&&Fi.draw(R,$.mdl,{time:F.time,animLayers:C.animationLayers,boneOverrides:ii.get(C),overrideTex:F.overrideTex||null,keepZ:!!F.keepZ,color:[C.color[0]*C.brightness*(F.ambient?.[0]??1),C.color[1]*C.brightness*(F.ambient?.[1]??1),C.color[2]*C.brightness*(F.ambient?.[2]??1),C.alpha]},$.tex)})}catch(T){console.warn(`puppet \u6E32\u67D3\u5668\u521D\u59CB\u5316\u5931\u8D25: ${T.message}`),be(t,e,`puppet renderer \u5931\u8D25: ${T.message}`),Fi=null;for(const C of It)C.layer.puppet=null}if(a)return;be(t,e,`puppet: ${It.length} meshes`);const mn=la.applyAttachmentBindOrigins(b.layers);mn.length&&be(t,e,`attachments: ${mn.length} hanging layers`);const jn=zt.collectTransformDirty(b.layers,mn.map(T=>T.layer));if(jn.size){be(t,e,`transform graph: ${jn.size} live layers`);for(const[T,C]of Hn)if(jn.has(T))for(const R of C)As.push(R)}const Sn=[],Sa=[],Di=new Map,pn={};let Pn=null,sr=null,Ni=0;if(!Jm&&b.layers.some(T=>T.isText)){const T=b.general?.orthogonalprojection,C=T?.width||n.width,R=T?.height||n.height,F=Qo(Ur(t.cfg.fit),C,R,n.width,n.height),$=Math.min(3,Math.max(.5,n.width/Math.max(1,F.viewW))),H=new Map,L=[],X=new Set;for(const q of b.layers)q.isText&&q.textFont&&X.add(q.textFont);for(const q of g.entries||[])typeof q.name=="string"&&/^fonts\/.+\.(ttf|otf|woff2?)$/i.test(q.name)&&X.add(q.name);for(const q of X){const K=`${e.src}|${q}`,D=Uo.get(K);if(D){D.refs++,L.push(K),H.set(q,D.family);continue}const E=p2[q.toLowerCase()];if(E){H.set(q,E);continue}try{const z=at.getEntry(g,q),ee=z?z instanceof Uint8Array?z:new Uint8Array(z):await c2(q);if(!ee)continue;const G=u2(ee),J="wefont_"+b2(K)+"_"+q.split("/").pop().replace(/[^a-zA-Z0-9]/g,"_"),ge=URL.createObjectURL(new Blob([G])),ae=new FontFace(J,`url(${ge})`);if(await ae.load(),a){URL.revokeObjectURL(ge);break}document.fonts.add(ae),(t.objectUrls??=[]).push(ge),H.set(q,J),Uo.set(K,{family:J,refs:1}),L.push(K)}catch(z){console.warn(`\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25 ${q}: ${z.message}`)}}if(L.length){const q=t.sceneCleanup;t.sceneCleanup=()=>{w2(L),q?.()}}Pn=document.createElement("canvas"),sr=Pn.getContext("2d");const Q=2048;for(const q of b.layers)if(q.isText)try{const K={layer:q,sandbox:null,texName:"__wstext_"+q.id,entry:null,lastKey:null,quality:$};if(q.textScript&&(K.sandbox=ot.evalTextScript(q.textScript,q.textScriptProps,{text:q.text??"",font:q.textFont||"",pointsize:q.textPointsize,color:q.textColor,angles:q.angles,origin:q.origin,scale:q.scale,visible:q.visible,canvasSize:{width:C,height:R},timeOfDay:xt,userProperties:v,shared:pn,storage:S,audioViews:Fe,inputView:Un,...nr,mediaControl:Cr,windowTitle:Ae.snapshot,openUserShortcut:nt.openUserShortcut,getLayerText:ee=>Di.get(ee),onError:ee=>{be(t,e,`text script '${q.name}' \u5931\u8D25: ${String(ee.message||ee).slice(0,120)}`)}}),K.sandbox&&(P.push(K.sandbox),Sa.push({sandbox:K.sandbox,layer:q}),K.sandbox.hasMediaHook&&tr(K.sandbox),Mt(K.sandbox),K.sandbox.hasAnimEventHook&&Ye(q,{sandbox:K.sandbox,kind:"text"}))),Di.set(q.name||"",String(q.text??"")),q.textAnchor!=="center"&&q.size[0]>0&&q.size[1]>0){const ee=q.size[0]*(q.scale[0]||1)/2,G=q.size[1]*(q.scale[1]||1)/2,J=q.textAnchor;let ge=0,ae=0;J.includes("left")&&(ge+=ee),J.includes("right")&&(ge-=ee),J.includes("top")&&(ae-=G),J.includes("bottom")&&(ae+=G),q.origin[0]+=ge,q.origin[1]+=ae,q.localOrigin&&(q.localOrigin[0]+=ge,q.localOrigin[1]+=ae)}const D=ep*Math.max(1,q.textPointsize),E=ot.textLayerHasTintMask(q)?8:256,z=Math.min(E,ot.textCanvasMargin(D,0));K.boxW=q.size[0]>0?q.size[0]:D*4,K.boxH=q.size[1]>0?q.size[1]:D*1.6,K.margin=z,q.size=[K.boxW+z*2,K.boxH+z*2],K.entry={glTex:pt.makeTexture(_.gl,new Uint8Array([0,0,0,0]),1,1),width:1,height:1,rg88:!1},Ke.set(K.texName,K.entry),q.textureName=K.texName,q.solid=!1,Sn.push(K)}catch(K){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${q.name} \u521D\u59CB\u5316\u5931\u8D25: ${K.message}`)}if(Sn.length>0){const q=u;u=()=>{q?.();for(const K of Sn)_.gl.deleteTexture(K.entry.glTex)}}const re=q=>{if(!sr||!Pn)return;const K=sr;for(const D of Sn){const E=D.layer;let z=String(E.text??"");if(D.sandbox&&D.sandbox.hasUpdate){D.sandbox.engine.runtime=q,D.sandbox.engine.timeOfDay=xt;const ge=D.sandbox.callUpdate(z);ge!=null?z=String(ge):D.sandbox.thisLayer.text&&(z=String(D.sandbox.thisLayer.text))}else D.sandbox&&typeof D.sandbox.thisLayer?.text=="string"&&(z=String(D.sandbox.thisLayer.text));if(Di.set(E.name||"",z),!E.visible)continue;const ee=Math.max(1,D.sandbox?D.sandbox.thisLayer.pointsize:E.textPointsize),G=D.sandbox&&D.sandbox.thisLayer.font||E.textFont||"",J=`${z}\0${ee}\0${G}\0${E.alpha}\0${E.textCastshadow}\0${E.textMaxwidth||0}\0${E.limitwidth?1:0}\0${E.maxrows||0}\0${E.limitrows?1:0}`;if(D.lastKey!==J){D.lastKey=J;try{const ge=ep*ee,ae=D.boxW,ue=D.boxH,pe=Math.abs(E.scale[0]||1),Ie=Math.abs(E.scale[1]||1),je=G&&H.get(G)||"sans-serif";K.setTransform(1,0,0,1,0,0),K.font=`${ge}px "${je}", sans-serif`;const qe=K.measureText(""),Tt=(qe.fontBoundingBoxAscent||0)+(qe.fontBoundingBoxDescent||0),bt=E.textSpacing||[0,0],wt=ot.layoutText(z,{boxW:ae,boxH:ue,pointsize:ge,lineHeight:(Tt>0?Tt:ge*1.25)+bt[1],spacing:bt,padding:E.textPadding||0,maxwidth:E.textMaxwidth||0,limitwidth:!!E.textLimitwidth,maxrows:E.textMaxrows||0,limitrows:!!E.textLimitrows,limituseellipsis:!!E.textLimituseellipsis,halign:E.textHAlign,valign:E.textVAlign},an=>K.measureText(an).width);let En=D.margin;const yn=!E.textAnchor||E.textAnchor==="center"||E.textAnchor==="none";if(D.sandbox?.hasMediaHook&&!ot.textLayerHasTintMask(E)&&yn){const an=ot.textCanvasMarginGrow(wt,ae,ue,En);(ot.shouldGrowMediaPlaceholder(ae,ue,!0)||an>En)&&(E.size[0]=ae+an*2,E.size[1]=ue+an*2),an!==En&&(D.margin=an,En=an)}let ut=Math.max(1,Math.round(E.size[0]*pe*D.quality)),Qt=Math.max(1,Math.round(E.size[1]*Ie*D.quality));const zi=Math.min(1,Q/Math.max(ut,Qt));ut=Math.max(1,Math.round(ut*zi)),Qt=Math.max(1,Math.round(Qt*zi)),Pn.width!==ut||Pn.height!==Qt?(Pn.width=ut,Pn.height=Qt):K.clearRect(0,0,ut,Qt);const qo=`${ge}px "${je}", sans-serif`,_a=Math.min(ut/E.size[0],Qt/E.size[1]);K.setTransform(_a,0,0,_a,0,0),K.translate(En,En),ot.drawTextLayer(K,wt,{font:qo,color:E.textColor,alpha:E.alpha,brightness:E.brightness,spacing:bt,pointsize:ge,opaquebackground:!!E.textOpaquebackground,backgroundcolor:E.textBackgroundcolor,backgroundbrightness:E.textBackgroundbrightness,castshadow:!!E.textCastshadow});const ks=D.entry;_.gl.bindTexture(_.gl.TEXTURE_2D,ks.glTex),_.gl.texImage2D(_.gl.TEXTURE_2D,0,_.gl.RGBA,_.gl.RGBA,_.gl.UNSIGNED_BYTE,Pn),ks.width=ut,ks.height=Qt}catch(ge){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${E.name} \u7ED8\u5236\u5931\u8D25: ${ge.message}`),D.lastKey=null}}}};t.sceneTextUpdate=re,window.__textWidgets=Sn,be(t,e,`text widgets: ${Sn.length} (scripts ${Sn.filter(q=>q.sandbox).length}, fonts ${H.size}, quality ${$.toFixed(2)})`)}if(a)return;const it=[],gn=new Set,si=[],ar=[],ai=[],Li=[],oi=[],Ui={},or=[],_n=[],ci=new Map,xs=(T,C)=>{if(!C||typeof C.callCursor!="function"||!C.hasCursorHook)return;const R=ci.get(T);R?R.push(C):ci.set(T,[C])};for(const T of Sn)T.sandbox&&xs(T.layer,T.sandbox);{const T=b.general?.orthogonalprojection,C=T?.width||n.width,R=T?.height||n.height,F=v,$=(D,E)=>{const z=b.general||{};if(D==="zoom"&&typeof E=="number"&&Number.isFinite(E)&&E>0){b.cameraTransforms.zoom=E,z.zoom&&typeof z.zoom=="object"?z.zoom.value=E:z.zoom=E;return}z[D]&&typeof z[D]=="object"&&"value"in z[D]?z[D].value=E:z[D]=E};let H=1+Math.max(0,...b.layers.map(D=>Number(D.id)||0));const L={recomputeVisibility:x,markTransformDirty:D=>{D&&D.id!==void 0&&D.id!==null&&gn.add(D.id)},getSceneLayer:D=>b.layers.find(E=>E.name===D&&!E.destroyed)||null,getSceneLayerById:D=>b.layers.find(E=>E.id===D&&!E.destroyed)||null,enumerateSceneLayers:()=>b.layers.filter(D=>!D.destroyed),getSceneAnimation:D=>{if(D==null||D==="")return null;if(Ui[D])return Ui[D];for(const E of b.layers)if(E.animations&&E.animations[D])return E.animations[D];return null},cameraTransforms:b.cameraTransforms,getInitialLayerConfig:D=>{const E=D&&typeof D=="object"?D.name:String(D||"");return b.layers.find(z=>z.name===E)||null},createSceneLayer:D=>{let E=D&&typeof D=="object"?D:null,z=null;if(typeof D=="string"){const G=D;if(E=b.layers.find(J=>J&&!J.destroyed&&J.image===G&&J.textureName)||b.layers.find(J=>J&&!J.destroyed&&J.image===G)||null,!E)if(/^models\//.test(G)&&at.getEntry(g,G))z={path:G,kind:"model"},E={image:G,origin:[0,0,0],scale:[1,1,1],angles:[0,0,0],size:[0,0],color:[1,1,1],visible:!0,alpha:1,brightness:1};else if(/^particles\//.test(G)&&at.getEntry(g,G))z={path:G,kind:"particle"},E={particle:G,origin:[0,0,0],scale:[1,1,1],angles:[0,0,0],size:[0,0],color:[1,1,1],visible:!0,alpha:1,brightness:1};else return be(t,e,`createLayer('${G}') \u627E\u4E0D\u5230\u5DF2\u52A0\u8F7D\u7684\u540C\u6A21\u578B\u5C42`),null}E||(E={});const ee={...E,id:H++,origin:Array.isArray(E.origin)?E.origin.slice():[0,0,0],scale:Array.isArray(E.scale)?E.scale.slice():[1,1,1],angles:Array.isArray(E.angles)?E.angles.slice():[0,0,0],size:Array.isArray(E.size)?E.size.slice():[0,0],color:Array.isArray(E.color)?E.color.slice():[1,1,1],childIds:null,hasChildren:!1,destroyed:!1,animations:{},animationList:[],objectScripts:null};if(delete ee.textureAnimation,delete ee.videoTextureApi,delete ee.soundCtl,delete ee.videoCtl,Array.isArray(E.effects)&&(ee.effects=E.effects.map(G=>({...G,passes:Array.isArray(G.passes)?G.passes.map(J=>({...J})):G.passes}))),b.layers.push(ee),ee.runtimeCreated=!0,z&&z.kind==="model"){const G=z.path;try{const J=JSON.parse(jt(at.getEntry(g,G))),ge=zt.resolveMaterial(J),ae=ge&&at.getEntry(g,ge.materialPath),pe=(ae?JSON.parse(jt(ae)):null)?.passes?.[0];if(pe?.combos){for(const je of Object.keys(pe.combos))if(je.toLowerCase()==="spritesheet"&&Number(pe.combos[je])===1){ee.spriteSheet=!0;break}}const Ie=pe?.textures?.[0];typeof Ie=="string"&&Ie&&!Ie.startsWith("util/")&&!Ie.startsWith("_rt_")&&zn(Ie).then(je=>{if(je&&(ee.textureName=Ie,ee.size[0]===0||ee.size[1]===0)){const qe=je.geomFrame,Tt=je.frames&&Array.isArray(je.frames)?je.frames[0]:null;ee.size=[qe&&qe.width||Tt&&Tt.width||je.declaredWidth||je.width,qe&&qe.height||Tt&&Tt.height||je.declaredHeight||je.height]}})}catch(J){be(t,e,`createLayer('${G}') \u8D44\u4EA7\u5B9E\u4F8B\u5316\u5931\u8D25: ${String(J.message||J).slice(0,120)}`)}}else if(z&&z.kind==="particle"){const G=z.path;Ri(G,ee,null,0).then(J=>{J||be(t,e,`createLayer('${G}') \u7C92\u5B50\u7CFB\u7EDF\u88C5\u914D\u5931\u8D25`)})}return ee},mediaControl:Cr,windowTitle:Ae.snapshot,openUserShortcut:nt.openUserShortcut,isScreensaver:!1};_.setConstantScriptRuntime?.(ot.evalObjectScript,{userProperties:F,audioViews:Fe,shared:pn,storage:S,inputView:Un,timers:kn,animEventQueue:$e,...L,onSandbox:(D,E)=>{D&&D.hasMediaHook&&tr(D),Mt(D),D&&D.hasAnimEventHook&&Ye(E&&E.layer,{sandbox:D,kind:"const"})}});const X={origin:"localOrigin",scale:"localScale",angles:"localAngles"},Q=(D,E)=>{const z=X[E];return z&&D&&Array.isArray(D[z])?z:E};for(const D of b.layers){const E=D.objectAnimations;if(E){D.animations=D.animations||{},D.animationList=D.animationList||[];for(const[z,ee]of Object.entries(E))try{const G=ua.createAnimation(ee.animation);G.field=z,G.baseValue=ee.value;const J=Q(D,z),ge=z==="volume"?D.soundprops?.volume:z==="maxwidth"?D.textMaxwidth:z==="zoom"?b.cameraTransforms?.zoom:D[J];G.baseNumeric=Array.isArray(ge)?ge.slice():ge,G.slot=J,D.animationList.push(G),G.name&&(D.animations[G.name]=G),si.push({layer:D,field:z,slot:J,ctrl:G})}catch(G){be(t,e,`animation '${D.name}.${z}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(G.message).slice(0,80)}`)}if(D.animationList.length){const z=new Map;for(const ee of D.animationList)z.set(ee.field,ee);ua.linkAnimations(z,ee=>be(t,e,`${D.name}: ${ee}`)),D.animationsByField=Object.fromEntries(z)}}}for(const D of b.layers){const E=D.particleOverrideAnimations;if(E)for(const[z,ee]of Object.entries(E))try{const G=ua.createAnimation(ee.animation);G.baseNumeric=typeof ee.value=="number"?ee.value:Number(ee.value)||0,ar.push({layer:D,key:z,ctrl:G})}catch(G){be(t,e,`override animation '${D.name}.${z}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(G.message).slice(0,80)}`)}}for(const D of b.layers)(Array.isArray(D.animationLayers)?D.animationLayers:[]).forEach((z,ee)=>{const G=z.visibleScript;if(G)try{const J=ot.evalObjectScript(G.script,G.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:xt,userProperties:F,audioViews:Fe,inputView:Un,layer:D,...nr,...L,shared:pn,storage:S,onError:ue=>be(t,e,`animationlayer visible script '${D.name}[${ee}]' \u5931\u8D25: ${String(ue.message||ue).slice(0,80)}`)});if(!J)return;P.push(J);const ge=J.init(z.visible!==!1),ae=ti(ge);ae!==void 0&&(z.visible=ae),J.applyUserProperties(F),J.hasMediaHook&&tr(J),Mt(J),Li.push({layer:D,index:ee,sandbox:J}),J.hasAnimEventHook&&Ye(D,{sandbox:J,kind:"animLayer",animLayerIndex:ee})}catch(J){be(t,e,`animationlayer script '${D.name}[${ee}]' \u6C42\u503C\u5931\u8D25: ${String(J.message).slice(0,80)}`)}});for(const D of b.layers){const E=D.particleOverrideScripts;if(E)for(const[z,ee]of Object.entries(E))try{const G=ot.evalObjectScript(ee.script,ee.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:xt,userProperties:F,audioViews:Fe,inputView:Un,layer:D,...nr,...L,shared:pn,storage:S,onError:J=>be(t,e,`override script '${D.name}.${z}' \u5931\u8D25: ${String(J.message||J).slice(0,80)}`)});if(!G)continue;P.push(G),G.init(ee.value),G.applyUserProperties(F),G.hasMediaHook&&tr(G),Mt(G),G.hasUpdate&&ai.push({layer:D,key:z,sandbox:G})}catch(G){be(t,e,`override script '${D.name}.${z}' \u6C42\u503C\u5931\u8D25: ${String(G.message).slice(0,80)}`)}}let re=!1;for(const D of b.layers){for(const[z,ee]of(D.effects||[]).entries()){const G=ee.visibleScript;if(G)try{const J=ot.evalObjectScript(G.script,G.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:xt,userProperties:F,audioViews:Fe,inputView:Un,...nr,layer:D,targetEffect:ee,...L,shared:pn,storage:S,onError:pe=>be(t,e,`effect visible script '${D.name}#${z}' \u5931\u8D25: ${String(pe.message||pe).slice(0,80)}`)});if(!J)continue;P.push(J);const ge=J.init(ee.visible),ae=ti(ge);ae!==void 0&&(ee.visible=ae),J.applyUserProperties(F),J.hasMediaHook&&tr(J),Mt(J);let ue=null;J.hasUpdate&&(ue={effect:ee,sandbox:J,last:ge},or.push(ue)),J.hasAnimEventHook&&Ye(D,{sandbox:J,kind:"effectVisible",effect:ee,run:ue})}catch(J){console.warn(`\u6548\u679C\u5F00\u5173\u811A\u672C ${D.name}#${z} \u6C42\u503C\u5931\u8D25: ${J.message}`)}}const E=D.objectScripts;if(E)for(const[z,ee]of Object.entries(E))try{const G=ot.evalObjectScript(ee.script,ee.scriptproperties,{canvasSize:{width:C,height:R},screenResolution:{x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1},timeOfDay:xt,userProperties:F,audioViews:Fe,inputView:Un,layer:D,getAnimationForProperty:()=>D.animationsByField&&D.animationsByField[z]||null,...L,getBoneOverrides:sn,shared:pn,storage:S,...nr,onError:J=>be(t,e,`object script '${D.name}.${z}' \u5931\u8D25: ${String(J.message||J).slice(0,90)}`)});if(G){P.push(G);const J=Q(D,z),ge=D[J],ae=z==="angles"&&Array.isArray(ge)?ot.radToScriptAngles(ge):Array.isArray(ge)?{x:ge[0]??0,y:ge[1]??0,z:ge[2]??0}:ge,ue=G.init(ae);if(ue!=null){if(z==="visible"){const pe=ti(ue);pe!==void 0&&D.visibleSelf!==pe&&(D.visibleSelf=pe,re=!0)}else if(typeof ue=="number"&&Number.isFinite(ue))["alpha","brightness","maxwidth","pointsize","volume","intensity","exponent"].includes(z)&&op(D,z).set(ue);else if(typeof ue=="object"&&ue.x!==void 0){const pe=ue;Number.isFinite(Number(pe.x))&&Number.isFinite(Number(pe.y))&&(D[J]=z==="angles"?ot.scriptAnglesToRad(pe):[Number(pe.x)||0,Number(pe.y)||0,Number(pe.z)||0])}}G.applyUserProperties(F),xs(D,G),G.hasMediaHook&&tr(G),Mt(G),G.hasUpdate&&it.push({layer:D,field:z,slot:J,kind:z==="visible"?"bool":["alpha","brightness","maxwidth","pointsize","volume","intensity","exponent"].includes(z)?"scalar":"vec3",sandbox:G,last:z==="visible"?ue:void 0}),G.hasAnimEventHook&&Ye(D,{sandbox:G,kind:z==="visible"?"bool":z==="alpha"||z==="brightness"?"scalar":"vec3",field:z,slot:J})}}catch(G){console.warn(`\u5BF9\u8C61\u811A\u672C ${D.name}.${z} \u6C42\u503C\u5931\u8D25: ${G.message}`)}}for(const D of Sa){const E=D.sandbox.init(D.layer.text??"");typeof E=="string"&&(D.layer.text=E),D.sandbox.applyUserProperties(v)}re&&x();const q=b.generalScripts;if(q){for(const[D,E]of Object.entries(q))try{const z=ot.evalObjectScript(E.script,E.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:xt,userProperties:F,audioViews:Fe,inputView:Un,...nr,...L,shared:pn,storage:S,onError:G=>be(t,e,`general script '${D}' \u5931\u8D25: ${String(G.message||G).slice(0,80)}`)});if(!z)continue;P.push(z),z.init(E.value),z.applyUserProperties(F),z.hasMediaHook&&tr(z),Mt(z);const ee=G=>$(D,G);z.hasUpdate&&_n.push({field:D,sandbox:z,write:ee})}catch(z){console.warn(`general \u811A\u672C ${D} \u6C42\u503C\u5931\u8D25: ${z.message}`)}_n.length&&be(t,e,`general scripts: ${_n.map(D=>D.field).join(",")}`)}const K=b.generalAnimations;if(K){for(const[D,E]of Object.entries(K))try{const z=ua.createAnimation(E.animation);z.field=D,z.baseValue=E.value,z.baseNumeric=E.value,z.name&&(Ui[z.name]=z),oi.push({field:D,ctrl:z,write:ee=>$(D,ee)})}catch(z){be(t,e,`general animation '${D}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(z.message).slice(0,80)}`)}oi.length&&be(t,e,`general animations: ${oi.map(D=>D.field).join(",")}`)}}it.length&&(be(t,e,`object scripts: ${it.length}`),window.__objScripts=it,window.__effectScripts=or),window.__mediaHooks=st,window.__sceneLayers=b.layers,window.__compositeStats=()=>_.compositeStats?.()??null,window.__compositeEnable=T=>_.setCompositeEnabled?.(T),window.__scene=b,window.__textures=Ke;const Oi=Array.from(ci.keys());Oi.length&&be(t,e,`cursor hooks: ${Oi.length} layers`);let Pa={hovered:[],pressed:[],lastLeftDown:!1};const jo=()=>({worldPosition:ot.makeCursorEventVec(lt.state.wx,lt.state.originY!=null?lt.state.originY:lt.state.wy,0)}),Dr=(T,C,R)=>{const F=ci.get(T);if(F)for(const $ of F)$.callCursor(C,R)},li=()=>{if(Oi.length===0)return;const T=lt.state;if(!T.has)return;const C=_.getParallaxOffset?_.getParallaxOffset():null,R=b.general?.orthogonalprojection?.height||n.height,F=vA.hitTestLayersAll(b.layers,T.wx,T.wy,R,{parallaxCtx:C,alignTable:pt.ALIGN,perspEye:_.getPerspectiveEye?_.getPerspectiveEye():null,filter:L=>ci.has(L)}),$=AA.planCursorDispatch(Pa,F,T.leftDown);Pa=$.next;const H=jo();for(const L of $.leave)Dr(L,"cursorLeave",H);for(const L of $.enter)Dr(L,"cursorEnter",H);for(const L of $.move)Dr(L,"cursorMove",H);for(const L of $.down)Dr(L,"cursorDown",H);for(const L of $.up)Dr(L,"cursorUp",H);for(const L of $.click)Dr(L,"cursorClick",H)},M=performance.now();let j=0,te=0;const Z=[],ne=[],de=new ys(t.cfg.sceneFps||60);let me=t.cfg.sceneFps||60,ye=0;const fe=.05,se=T=>{if(a||t.paused)return;const C=t.cfg.sceneFps||60;if(C!==me&&(me=C,de.setFps(C)),de.shouldRender(T)){zr(t,T),Du(t,n,t.cfg);const R=n.clientWidth||window.innerWidth||1,F=n.clientHeight||window.innerHeight||1;(R!==Vt||F!==xn)&&(Vt=R,xn=F,Pt={w:R,h:F},Pi(R,F));const $=Math.max(0,(T-M-j)/1e3);if(Un.update(lt.state),dn.enabled){if(U?.media)U.media.pump();else{const ee=he();typeof ee?.update=="function"&&ee.update($)}const E=ct(),z=We.diffMediaEvents(nn,E);if(z.length){for(const{name:ee,event:G}of z)for(const J of st)J.disabled||J.callMedia(ee,G);nn=We.cloneMediaSnapshot(E)}if(_i!==E.thumbnail&&typeof E.thumbnail=="string"&&E.thumbnail){const ee=E.thumbnail;_i=ee,(async()=>{try{const G=await fetch(ee,{cache:"no-store"}).then(pe=>pe.ok?pe.blob():null);if(!G)return;const J=await createImageBitmap(G,{premultiplyAlpha:"none"});if(_i!==ee){J.close?.();return}const ge=J.width,ae=J.height,ue=Aa(J,ge,ae);if(J.close?.(),ue){const pe=ct();pe.primaryColor=We.mediaVec3(...ue.primary),pe.secondaryColor=We.mediaVec3(...ue.secondary),pe.tertiaryColor=We.mediaVec3(...ue.tertiary),pe.textColor=We.mediaVec3(.98,.98,1),pe.highContrastColor=We.mediaVec3(1,1,1)}be(t,e,`media: $mediaThumbnail \u5DF2\u66F4\u65B0\uFF08${ge}\xD7${ae}\uFF09`)}catch(G){be(t,e,`media: \u5C01\u9762\u4E0A\u4F20\u5931\u8D25\uFF08${G instanceof Error?G.message:G}\uFF09`)}})()}}U?.windowTitle?U.windowTitle.pump():O.update($);const H=Math.max(0,$-ye);ye=$;const L=H,X=Math.min(H,fe);Tn.dt=L,Tn.t=$;let Q=!1;const re=(E,z)=>{const ee=Xe.get(E);if(!(!ee||!ee.length)){window.__animEventsFired=(window.__animEventsFired||0)+z.length;{const G=window,J=G.__animEventLog||(G.__animEventLog=[]);for(const ge of z)J.push({l:String(E&&(E.name||E.id)),f:ge.frame,n:ge.name}),J.length>400&&J.shift()}for(const G of z)for(const J of ee){const ge=J.sandbox;if(!(!ge||ge.disabled))if(J.kind==="text"){const ae=ge.callAnimationEvent(G,String(E.text??""));typeof ae=="string"&&(E.text=ae)}else if(J.kind==="effectVisible"){const ae=J.run&&J.run.last!==void 0&&J.run.last!==null?J.run.last:!!J.effect.visible,ue=ge.callAnimationEvent(G,ae);J.run&&(typeof ue=="boolean"||typeof ue=="number"&&Number.isFinite(ue))&&(J.run.last=ue);const pe=ti(ue);pe!==void 0&&(J.effect.visible=pe)}else if(J.kind==="const"){const ae=ge.callAnimationEvent(G,ge.__lastConstValue);(typeof ae=="number"&&Number.isFinite(ae)||ae&&typeof ae=="object"&&Number.isFinite(Number(ae.x))&&Number.isFinite(Number(ae.y)))&&(ge.__lastConstValue=ae)}else if(J.kind==="bool"){const ae=ge.callAnimationEvent(G,!!E.visible),ue=ti(ae);ue!==void 0&&E.visibleSelf!==ue&&(E.visibleSelf=ue,Q=!0)}else if(J.kind==="scalar"){const ae=ge.callAnimationEvent(G,Number(E[J.field])||0),ue=Number(ae);Number.isFinite(ue)&&(E[J.field]=ue)}else{const ae=E[J.slot],ue=J.field==="angles"?ot.radToScriptAngles(ae):{x:ae&&ae[0]||0,y:ae&&ae[1]||0,z:ae&&ae[2]||0},pe=ge.callAnimationEvent(G,ue),Ie=pe&&typeof pe=="object"&&"x"in pe?pe:ue;E[J.slot]=J.field==="angles"?ot.scriptAnglesToRad(Ie):[Number(Ie.x)||0,Number(Ie.y)||0,Number(Ie.z)||0]}}}};for(const E of si){E.ctrl.advance(L);const z=E.field,ee=E.slot||z,G=E.ctrl.applyTo(E.ctrl.baseNumeric);if(Array.isArray(G)){const J=E.layer[ee];if(Array.isArray(J))for(let ge=0;ge<G.length&&ge<J.length;ge++)J[ge]=G[ge]}else Number.isFinite(G)&&(z==="visible"?E.layer.visibleSelf!==!!G&&(E.layer.visibleSelf=!!G,Q=!0):z==="volume"?(E.layer.soundprops.volume=G,E.layer.soundCtl?.setVolume?.(G)):z==="maxwidth"?E.layer.textMaxwidth=G:z==="zoom"?G>0&&(b.cameraTransforms.zoom=G):E.layer[ee]=G)}for(const E of ar){E.ctrl.advance(L);const z=E.ctrl.applyTo(E.ctrl.baseNumeric);if(typeof z!="number"||!Number.isFinite(z))continue;const ee=Hn.get(E.layer.id);if(ee)for(const G of ee)G.setOverrideValue(E.key,z)}for(const E of Li){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=xt;const z=E.layer.animationLayers?.[E.index];if(!z)continue;const ee=E.sandbox.callUpdate(z.visible!==!1),G=ti(ee);G!==void 0&&(z.visible=G)}for(const E of ai){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.screenResolution={x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1},E.sandbox.engine.timeOfDay=xt;const z=E.sandbox.callUpdate(void 0),ee=Hn.get(E.layer.id);if(!ee)continue;let G=z;if(z&&typeof z=="object"){const J=z;(J.x!==void 0||J.y!==void 0)&&(G=[Number(J.x)||0,Number(J.y)||0,Number(J.z)||0])}for(const J of ee)E.key==="colorn"&&Array.isArray(G)?J.setColorOverride(G):J.setOverrideValue(E.key,G)}for(const E of si){const z=E.ctrl.takeEvents();z.length&&re(E.layer,z)}for(const E of ar){const z=E.ctrl.takeEvents();z.length&&re(E.layer,z)}for(const E of oi)E.ctrl.takeEvents();for(const E of oi){E.ctrl.advance(L);const z=E.ctrl.applyTo(E.ctrl.baseNumeric);typeof z=="number"&&Number.isFinite(z)?E.write(z):Array.isArray(z)&&Number.isFinite(z[0])&&E.write(z[0])}const q=Math.floor(T/1e3);if(q!==tn){tn=q;const E=new Date;xt=(E.getHours()*3600+E.getMinutes()*60+E.getSeconds())/86400}for(const E of or){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=xt;const z=E.sandbox.callUpdate(E.last!==void 0&&E.last!==null?E.last:!!E.effect.visible);(typeof z=="boolean"||typeof z=="number"&&Number.isFinite(z))&&(E.last=z);const ee=ti(z);ee!==void 0&&(E.effect.visible=ee)}for(const E of _n){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=xt;const z=b.general||{},ee=z[E.field]&&typeof z[E.field]=="object"&&"value"in z[E.field]?z[E.field].value:z[E.field],G=E.sandbox.callUpdate(ee);G!==void 0&&E.write(G)}const K={x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1};for(const E of P)!E||E.disabled||(E.engine.frametime=X,E.engine.runtime=$,E.engine.screenResolution=K,E.engine.timeOfDay=xt);for(const E of it){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.screenResolution=K,E.sandbox.engine.timeOfDay=xt;const z=E.layer[E.field];if(E.kind==="bool"){const ee=E.last!==void 0&&E.last!==null?E.last:!!z,G=E.sandbox.callUpdate(ee);(typeof G=="boolean"||typeof G=="number"&&Number.isFinite(G))&&(E.last=G);const J=ti(G);J!==void 0&&(E.field==="visible"?E.layer.visibleSelf!==J&&(E.layer.visibleSelf=J,Q=!0):E.layer[E.field]=J)}else if(E.kind==="scalar"){const ee=op(E.layer,E.field),G=E.sandbox.callUpdate(Number(ee.get())||0),J=Number(G);Number.isFinite(J)&&ee.set(J)}else{const ee=E.slot||E.field,G=E.layer[ee],J=E.field==="angles"?ot.radToScriptAngles(G):{x:G[0]||0,y:G[1]||0,z:G[2]||0},ge=E.sandbox.callUpdate(J),ae=ge&&typeof ge=="object"&&"x"in ge?ge:J;E.layer[ee]=E.field==="angles"?ot.scriptAnglesToRad(ae):[ae.x||0,ae.y||0,ae.z||0]}}if(Q&&x(),gn.size){for(const E of gn)jn.add(E);gn.clear()}if(jn.size&&zt.recomposeWorld(b.layers,jn),Pe.enabled){Ne.pump(),Ne.active||(ie.current?ie.current.pump():B.update($));const E=Gt.readBands(),z=De();if(E){const ee={left64:z.left64.slice(),right64:z.right64.slice(),left32:z.left32.slice(),right32:z.right32.slice(),left16:z.left16.slice(),right16:z.right16.slice(),level:z.level,silent:!1};n2(ee,E,g2),Re=ee,rm(Fe,ee)}else Re=z,rm(Fe,z)}mn.length&&la.followAttachments(mn,$,sn);for(const E of It){const z=E.mdl,ee=E.layer,G=z.animations;if(!G||!G.length||!ee.animationLayers||!ee.visible||!G.some(ge=>ge.events&&ge.events.length))continue;let J=Fr.get(ee);J||(J=new Map,Fr.set(ee,J));for(let ge=0;ge<ee.animationLayers.length;ge++){const ae=ee.animationLayers[ge];if(!ae||ae.visible===!1||ae.visible===0)continue;const ue=G.find(qe=>qe.id===ae.animation);if(!ue||!ue.events||!ue.events.length)continue;const pe=$*(typeof ae.rate=="number"?ae.rate:1)*ue.fps,Ie=J.has(ge)?J.get(ge):pe,je=ua.crossedEvents(ue.events,Ie,pe,ue.frameCount,ue.mode==="loop"?"loop":ue.mode==="mirror"?"mirror":"single");je.length&&re(ee,je),J.set(ge,pe)}}const D=t.coverAlign;_.render(b,Ke,n.width,n.height,$,Ur(t.cfg.fit),D.x,D.y).then(()=>{if(t.onFirstFrame){const E=t.onFirstFrame;t.onFirstFrame=void 0;try{E()}catch{}}if(!(a||t.paused)){if($e.length){for(const E of $e)re(E.layer,E.events);$e.length=0}try{li()}catch{}lt.beginFrame();try{t.sceneTextUpdate&&T>=Ni&&(Ni=T+100,t.sceneTextUpdate($))}catch{}t.raf=requestAnimationFrame(se)}}).catch(E=>{console.warn("scene render error:",E),be(t,e,`render: ${String(E.message||E).slice(0,200)}`),a=!0})}else t.paused||(t.raf=requestAnimationFrame(se))},_e=()=>{a||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(se))},xe=T=>{if(a)return;const C=b.properties||{},R=rb(C,v,T);if(Object.keys(R).length){Ai(b.general||{},C,0);for(const F of b.layers){const $=F.srcObject;if(!$)continue;Ai($,C,0);const H=Qn($.visible);H&&H in R&&(F.visibleSelf=zt.parseBool($.visible,!0));const L=Qn($.color);L&&L in R&&(F.color=zt.parseColor($.color),F.isText&&(F.textColor=F.color));const X=Qn($.alpha);X&&X in R&&(F.alpha=zt.parseNum($.alpha,1));const Q=Qn($.brightness);Q&&Q in R&&(F.brightness=zt.parseNum($.brightness,1));const re=Qn($.volume);if(re&&re in R){const K=zt.parseNum($.volume,1);F.soundprops&&(F.soundprops.volume=K),F.soundCtl?.setVolume?.(K)}for(let K=0;K<($.animationlayers||[]).length;K++){const D=$.animationlayers[K],E=F.animationLayers?.[K];if(!D||!E)continue;const z=Qn(D.visible);z&&z in R&&(E.visible=zt.parseBool(D.visible,!0));const ee=Qn(D.rate);ee&&ee in R&&(E.rate=zt.parseNum(D.rate,1));const G=Qn(D.blend);G&&G in R&&(E.blend=zt.parseNum(D.blend,1))}for(let K=0;K<($.effects||[]).length;K++){const D=$.effects[K],E=F.effects?.[K];if(!D||!E)continue;const z=Qn(D.visible);z&&z in R&&!E.visibleScript&&(E.visible=zt.parseBool(D.visible,!0))}const q=$.instanceoverride;if(q&&typeof q=="object"&&F.particle){let K=!1;for(const D of Object.keys(q)){if(D==="id")continue;const E=Qn(q[D]);if(E&&E in R){K=!0;break}}if(K){const D=Hn.get(F.id);if(D)for(const E of D)E.reapplyOverride?.()}}}for(const F of P)if(!(!F||F.disabled))try{F.applyUserProperties(R)}catch{}x();for(const F of b.layers){if(!F.particle)continue;const $=Hn.get(F.id);if($)for(const H of $)H.setVisible(!!F.visible)}_.applyConstUserProperties?.(R);for(const F of Sn)F.lastKey=null;be(t,e,`props hot: ${Object.keys(R).join(",")}`)}};f=()=>{t.raf!==void 0&&(cancelAnimationFrame(t.raf),t.raf=void 0),te||(te=performance.now()),Z.length=0;for(const T of Ke.values())T?.videoCtl?.isPlaying?.()&&(Z.push(T.videoCtl),T.videoCtl.pause());ne.length=0;for(const T of Br)!T.paused&&!T.ended&&(ne.push(T),T.pause())},h=()=>{te&&(j+=performance.now()-te,te=0);for(const T of Z)try{T.play()}catch{}Z.length=0;for(const T of ne)T.play().catch(()=>{});ne.length=0,de.reset(),_e()},d=xe,l&&(xe(l),l=null),_e();{const T=b.general?.orthogonalprojection,C=T?.width||n.width,R=T?.height||n.height,F=Ur(t.cfg.fit),$=Qo(F,C,R,n.width,n.height);be(t,e,`fit ${F}: view ${Math.round($.viewW)}x${Math.round($.viewH)} scene ${C}x${R} canvas ${n.width}x${n.height}`);{const H=Go(b.layers);Number.isFinite(H.minX)&&Number.isFinite(H.minY)&&(t.coverPeek={contentW:H.maxX-H.minX,contentH:H.maxY-H.minY,projW:C,projH:R},be(t,e,`cover peek gate: content ${Math.round(H.maxX-H.minX)}x${Math.round(H.maxY-H.minY)}`))}}be(t,e,`renderer started: ${b.layers.length} layers`)}catch(m){if(a||m&&m.name==="AbortError")return;console.warn("scene render failed:",m);const g=m instanceof Error?m:new Error(String(m));be(t,e,`failed: ${String(g.message||g).slice(0,200)}`),t.onError?t.onError(g):t.fallbackPage?.()}})()}const S2='data-we-shim="1"',cp="data-we-shim-src";function P2(t){try{const e=new URL(t),n=e.pathname,r=n.lastIndexOf("/");return e.pathname=r<0?"/":n.slice(0,r+1),e.hash="",e.search="",e.href}catch{const e=t.replace(/[#?].*$/,""),n=e.lastIndexOf("/");return n<0?e:e.slice(0,n+1)}}function _2(t){const e=/<meta[^>]+http-equiv\s*=\s*["']?Content-Security-Policy["']?[^>]*>/gi;let n;for(;n=e.exec(t);){const r=n[0],i=/content\s*=\s*"([^"]*)"/i.exec(r)?.[1]??/content\s*=\s*'([^']*)'/i.exec(r)?.[1]??"";if(/script-src/i.test(i)&&!/script-src[^;]*'unsafe-inline'/i.test(i)&&!/script-src[^;]*\*/i.test(i))return!0}return!1}function lp(t){return t.replace(/<\/script/gi,"<\\/script")}function E2(t,e,n){if(t||(t=""),t.includes(S2)||t.includes(cp))return t;const r=n.baseHref&&!/<base\b/i.test(t)?`<base href="${n.baseHref.replace(/"/g,"&quot;")}">`:"",i=`<script ${cp}="1">
762
+ ${lp(e)}
648
763
  <\/script>`,s=n.seedScript&&n.seedScript.trim()?`<script>
649
- ${oh(n.seedScript)}
650
- <\/script>`:"",a=`${r}${i}${s}`,o=/<head(\s[^>]*)?>/i.exec(t);if(o){const u=o.index+o[0].length;return t.slice(0,u)+a+t.slice(u)}const c=/<html(\s[^>]*)?>/i.exec(t);if(c){const u=c.index+c[0].length;return t.slice(0,u)+`<head>${a}</head>`+t.slice(u)}return`<!DOCTYPE html><html><head>${a}</head><body>${t}</body></html>`}const D1=`/**
764
+ ${lp(n.seedScript)}
765
+ <\/script>`:"",a=`${r}${i}${s}`,o=/<head(\s[^>]*)?>/i.exec(t);if(o){const u=o.index+o[0].length;return t.slice(0,u)+a+t.slice(u)}const c=/<html(\s[^>]*)?>/i.exec(t);if(c){const u=c.index+c[0].length;return t.slice(0,u)+`<head>${a}</head>`+t.slice(u)}return`<!DOCTYPE html><html><head>${a}</head><body>${t}</body></html>`}const M2=`/**
651
766
  * WE \u7F51\u9875\u58C1\u7EB8\u517C\u5BB9 shim\uFF08\u6CE8\u5165\u5230 iframe\uFF0C\u5FC5\u987B\u5728\u4F5C\u8005\u811A\u672C\u4E4B\u524D\u6267\u884C\uFF09\u3002
652
767
  *
653
768
  * \u8BED\u6599\uFF1A\u672C\u673A\u5E93 42 \u5F20 web \u58C1\u7EB8\u626B\u63CF\uFF082026-09\uFF09\u2014\u2014
@@ -674,7 +789,7 @@ ${oh(n.seedScript)}
674
789
  w.document.documentElement.setAttribute("data-we-shim", "1");
675
790
  }
676
791
  } catch (_) {
677
- /* \u5FFD\u7565 */
792
+
678
793
  }
679
794
 
680
795
  var audioListener = null;
@@ -1151,6 +1266,7 @@ ${oh(n.seedScript)}
1151
1266
  liveMedia.push(new w.WeakRef(el));
1152
1267
  }
1153
1268
  function applyMediaVolume(el) {
1269
+ if (!mediaVolDesc || !mediaMutedDesc) return;
1154
1270
  if (el.__weBaseVol != null) {
1155
1271
  mediaVolDesc.set.call(el, el.__weBaseVol * hostVolume);
1156
1272
  } else {
@@ -1229,6 +1345,33 @@ ${oh(n.seedScript)}
1229
1345
  }
1230
1346
  installMediaVolumeHooks();
1231
1347
 
1348
+ // \u2014\u2014 \u65B0\u5EFA\u5A92\u4F53\u5143\u7D20\u7684\u97F3\u91CF\u6536\u655B \u2014\u2014
1349
+ // \u5C5E\u6027 hook \u53EA\u62E6\u5F97\u5230\u300C\u4F5C\u8005\u7528 JS \u8D4B .volume/.muted\u300D\u4E0E\u65B0 Audio() \u6784\u9020\uFF1B
1350
+ // createElement + innerHTML \u63D2\u5165\u3001\u4E14\u4ECE\u672A\u8D4B\u8FC7\u503C\u7684 <audio>/<video>\uFF08autoplay
1351
+ // \u76F4\u63A5\u5F00\u8D70\uFF09\u65E2\u6CA1\u767B\u8BB0\u4E5F\u6CA1\u5237\u65B0\uFF0C\u4E3B\u97F3\u91CF\u4E3A 0 \u65F6\u7167\u6837\u51FA\u58F0\u2014\u2014\u8868\u73B0\u4E3A\u300C\u6062\u590D\u64AD\u653E/\u6302
1352
+ // \u540E\u53F0\u4E00\u6BB5\u65F6\u95F4\u540E\u5192\u4E00\u5C0F\u6BB5\u97F3\u4E50\u300D\u3002\u5BF9\u63D2\u5165 DOM \u7684\u5A92\u4F53\u5143\u7D20\u7ACB\u5373\u6309\u5F53\u524D\u4E3B\u97F3\u91CF\u843D
1353
+ // \u4E00\u6B21\u771F\u5B9E\u5C5E\u6027\uFF1B\u4E0D\u8FDB DOM\u7684\u5143\u7D20\u89C2\u5BDF\u4E0D\u5230\uFF08\u7F55\u89C1\uFF0C\u63A5\u53D7\uFF09\u3002
1354
+ try {
1355
+ var mediaObserver = new w.MutationObserver(function (records) {
1356
+ for (var i = 0; i < records.length; i++) {
1357
+ var added = records[i].addedNodes;
1358
+ for (var j = 0; j < added.length; j++) {
1359
+ var n = added[j];
1360
+ if (!n || n.nodeType !== 1) continue;
1361
+ if (n.tagName === "AUDIO" || n.tagName === "VIDEO") {
1362
+ applyMediaVolume(n);
1363
+ } else if (n.querySelectorAll) {
1364
+ var inner = n.querySelectorAll("audio,video");
1365
+ for (var k = 0; k < inner.length; k++) applyMediaVolume(inner[k]);
1366
+ }
1367
+ }
1368
+ }
1369
+ });
1370
+ mediaObserver.observe(w.document, { childList: true, subtree: true });
1371
+ } catch (_) {
1372
+ /* \u65E7\u5F15\u64CE\u65E0 MutationObserver\uFF1A\u9000\u5316\u4E3A\u4EC5\u5C5E\u6027 hook\uFF0C\u884C\u4E3A\u540C\u65E7\u7248 */
1373
+ }
1374
+
1232
1375
  // \u2014\u2014 \u7236\u9875\u63A7\u5236\u9762 \u2014\u2014
1233
1376
  // \u5B98\u65B9 setPaused \u53EA\u5728\u6682\u505C\u72B6\u6001\u5B9E\u9645\u53D8\u5316\u65F6\u8C03\u7528\u4E00\u6B21\uFF1B\u91CD\u590D\u8C03\u7528\u53BB\u91CD\u3002
1234
1377
  // \u6682\u505C\u8FD8\u8981\u51BB\u7ED3\u9875\u5185\u5A92\u4F53\uFF1A\u5B98\u65B9\u662F\u8FDB\u7A0B\u7EA7\u51BB\u7ED3\uFF08\u65E0\u58F0\u3001\u89E3\u7801\u5668\u53EF\u56DE\u6536\uFF09\uFF0C\u4F5C\u8005\u7684
@@ -1455,31 +1598,25 @@ ${oh(n.seedScript)}
1455
1598
  };
1456
1599
 
1457
1600
  // \u2014\u2014 \u5916\u90E8\u6307\u9488\u6CE8\u5165\uFF08\u684C\u9762 underlay \u5C42\u6536\u4E0D\u5230\u9F20\u6807\u4E8B\u4EF6\uFF0C\u7236\u9875\u7ECF __wp.pushPointer \u63A8\u5165\uFF09\u2014\u2014
1458
- //
1459
1601
  // \u573A\u666F\u58C1\u7EB8\u90A3\u6761\u901A\u9053\u662F\u300C\u5199\u4E00\u4E2A\u72B6\u6001\u5BF9\u8C61\u3001\u6E32\u67D3\u5668\u6BCF\u5E27\u8BFB\u300D\uFF08render/pointer.js\uFF09\uFF1B\u7F51\u9875\u58C1\u7EB8
1460
1602
  // \u6CA1\u6709\u8FD9\u6837\u7684\u5355\u4E00\u6D88\u8D39\u70B9 \u2014\u2014 \u4F5C\u8005\u4EE3\u7801\u5C31\u662F**\u76D1\u542C DOM \u4E8B\u4EF6**\u7684\uFF0C\u6240\u4EE5\u8FD9\u91CC\u5FC5\u987B\u628A\u63A8\u9001
1461
1603
  // \u8FD8\u539F\u6210\u4E00\u4E32\u5408\u6210\u4E8B\u4EF6\u3002\u8BED\u6599\uFF08\u672C\u673A 49 \u5F20 web\uFF09\uFF1Amousemove 24 \u5F20\u3001click 29 \u5F20\u3001
1462
1604
  // mouseover/out 17 \u5F20\u3001mouseenter/leave 8 \u5F20\u3001pointer* 16 \u5F20\uFF08createjs \u7CFB\u4E00\u5F8B\u8D70
1463
1605
  // pointerdown/move/up\uFF09\u3001.button 18 \u5F20\u3001.which 17 \u5F20\u3001pointerId/relatedTarget 15 \u5F20\u3002
1464
- //
1465
1606
  // \u4E09\u6761\u8981\u70B9\uFF08\u90FD\u6709\u8BED\u6599\u4F9D\u636E\uFF0C\u6539\u9519\u4E86\u4F1A\u9759\u9ED8\u5931\u6548\uFF09\uFF1A
1466
- //
1467
1607
  // 1. **\u5FC5\u987B elementFromPoint \u6309\u547D\u4E2D\u5143\u7D20\u6D3E\u53D1**\uFF0C\u4E0D\u80FD\u4E00\u5F8B\u6253 document\u3002\u4F5C\u8005\u65E2\u6709\u6302
1468
1608
  // document/window \u7684\uFF0815 \u5F20\uFF0C\u9760\u5192\u6CE1\u6536\u5230\uFF09\uFF0C\u4E5F\u6709\u6302 canvas \u4E0A\u8BFB \`event.offsetX\`
1469
1609
  // \u7684\uFF081748506393 \u6D41\u4F53 \`pointers[0].dx = (e.offsetX - \u2026)\`\uFF09\u3002offsetX/offsetY \u7531
1470
1610
  // \u6D4F\u89C8\u5668\u6309 target \u7684 padding box \u73B0\u7B97 \u2014\u2014 target \u6253\u9519\u5C31\u662F\u9519\u7684\u504F\u79FB\uFF0C\u4E14\u65E0\u4EFB\u4F55\u62A5\u9519\u3002
1471
1611
  // pageX/pageY \u540C\u7406\u7531 clientX + \u6EDA\u52A8\u91CF\u73B0\u7B97\uFF0C\u4E0D\u7528\u6211\u4EEC\u586B\u3002
1472
- //
1473
1612
  // 2. **over/out/enter/leave \u94FE\u8981\u6309 W3C \u8BED\u4E49\u8865\u5168**\u30021748506393 \u9760 canvas \u7684
1474
1613
  // \`mouseenter\` \u628A \`pointers[0].down\` \u7F6E true\uFF08\u4E0D\u8FDB\u8FD9\u4E2A\u5206\u652F\u5219\u9F20\u6807\u600E\u4E48\u52A8\u90FD\u4E0D\u51FA\u67D3\u6599\uFF09\u3001
1475
1614
  // \u9760 window \u7684 \`mouseleave\` \u590D\u4F4D\uFF1B1081733658 animatedGrid \u9760 \`document.body\` \u7684
1476
1615
  // mouseover/mouseleave \u8D77\u505C\u6574\u4E2A\u7F51\u683C\u52A8\u753B\u3002leave/enter \u4E0D\u5192\u6CE1\uFF0C\u5FC5\u987B\u81EA\u5DF1\u6CBF\u7956\u5148\u94FE\u8D70\u5230
1477
1616
  // \u6700\u8FD1\u516C\u5171\u7956\u5148\uFF0C\u53EA\u53D1\u751F\u53D8\u5316\u7684\u90A3\u4E00\u6BB5\u3002
1478
- //
1479
1617
  // 3. **click \u8981\u9760 down/up \u8FB9\u7F18\u5408\u6210**\uFF0C\u4E14 down \u4E0E up \u7684 target \u4E0D\u540C\uFF08\u62D6\u62FD\uFF09\u65F6\u4E0D\u53D1\u3002
1480
1618
  // 29 \u5F20\u542C click \u662F\u6700\u5927\u7684\u6D88\u8D39\u65B9\uFF1B\u8F6E\u8BE2\u63A8\u9001\u91CC\u6CA1\u6709\u300C\u70B9\u51FB\u300D\u8FD9\u4E2A\u4E8B\u4EF6\uFF0C\u53EA\u6709\u6309\u952E\u63A9\u7801\u7684
1481
1619
  // \u8DF3\u53D8\uFF0C\u8FB9\u7F18\u4E22\u4E86\u5C31\u7B49\u4E8E\u6574\u7C7B\u4EA4\u4E92\u6D88\u5931\u3002
1482
- //
1483
1620
  // \u786C\u9650\u5236\uFF08\u5199\u5728\u8FD9\u91CC\u907F\u514D\u53CD\u590D\u8BD5\uFF09\uFF1ACSS \`:hover\` \u7531\u6D4F\u89C8\u5668\u81EA\u5DF1\u7684 hit-test \u9A71\u52A8\uFF0C\u5408\u6210\u4E8B\u4EF6
1484
1621
  // \u6C38\u8FDC\u70B9\u4E0D\u4EAE\u5B83\uFF0818 \u5F20\u542B \`:hover\`\uFF09\u2014\u2014 \u7EAF CSS hover \u52A8\u753B\u7684\u58C1\u7EB8\u65E0\u6CD5\u7528\u6CE8\u5165\u901A\u9053\u54CD\u5E94\uFF0C
1485
1622
  // \u8FD9\u4E0D\u662F\u5B9E\u73B0\u7F3A\u9677\uFF0C\u662F\u5408\u6210\u4E8B\u4EF6\u7684\u56FA\u6709\u8FB9\u754C\u3002
@@ -2063,7 +2200,7 @@ ${oh(n.seedScript)}
2063
2200
  installRafThrottle();
2064
2201
  })(window);
2065
2202
 
2066
- `;function xt(t,e){try{const n=t.iframe?.contentWindow;n&&e(n)}catch{}}function N1(t,e,n){const r=e.contentWindow;if(!r||r.requestAnimationFrame?.__weThrottled)return;const i=t.cfg.sceneFps||30;if(i>=60)return;const s=1e3/i;try{const a=r.requestAnimationFrame.bind(r),o=new Map;let c=0;r.requestAnimationFrame=u=>{const l=++c,f=r.setTimeout(()=>{o.delete(l),a(d=>{try{u(d)}catch{}})},s);return o.set(l,f),l},r.cancelAnimationFrame=u=>{const l=o.get(u);l!==void 0&&(r.clearTimeout(l),o.delete(u))}}catch{}}const L1=new Float32Array(128);function U1(t,e,n){const r=Math.min(64,e.length),i=Math.min(64,n.length);for(let s=0;s<r;s++)t[s]=Number(e[s])||0;for(let s=0;s<i;s++)t[64+s]=Number(n[s])||0;return t}const O1=1.8,z1=1.8,H1=30;function ch(t){const e=Number(t)||0;return e<=0?0:Math.min(1,Math.pow(e,z1)*O1)}function V1(){const t=jd(),e=new Float32Array(64),n=new Float32Array(64);return{tick(r){t.update(r/1e3)},snapshot(){const r=t.snapshot,i=r.preL64,s=r.preR64;for(let a=0;a<64;a++)i&&s?(e[a]=ch(i[a]),n[a]=ch(s[a])):(e[a]=(Number(r.left64[a])||0)*.2,n[a]=(Number(r.right64[a])||0)*.2);return{left:e,right:n}}}}function W1(t){const e=new Float32Array(64),n=new Float32Array(64);return{snapshot(){const r=t.audioBridge?.(),i=r?.left,s=r?.right,a=i&&s?Math.min(64,i.length,s.length):0;for(let o=0;o<a;o++)e[o]=Math.max(0,Math.min(1,Number(i[o])||0)),n[o]=Math.max(0,Math.min(1,Number(s[o])||0));for(let o=a;o<64;o++)e[o]=0,n[o]=0;return{left:e,right:n}}}}function j1(t){const e=new Float32Array(64),n=new Float32Array(64);return{tick(){t.audio.pump()},snapshot(){const r=t.audio.snapshot;for(let i=0;i<64;i++)e[i]=Math.max(0,Math.min(1,Number(r.left64[i])||0)),n[i]=Math.max(0,Math.min(1,Number(r.right64[i])||0));return{left:e,right:n}}}}function q1(t,e){if(t.wrap)return t.wrap;const n=e.canvas;if(!n)return null;if(n instanceof HTMLCanvasElement){const r=n.parentElement;return r?(ce(t,e,"\u7F51\u9875\u58C1\u7EB8\u6302\u5728 canvas \u7236\u5BB9\u5668\u4E0A\uFF08canvas \u4E0D\u80FD\u6709\u5B50\u8282\u70B9\uFF1B\u66F4\u9002\u5408\u7A7A div\uFF09"),r):null}return n}function X1(t,e,n){const r=[];return e!=null&&Number.isFinite(e)&&r.push(`window.__weSetFps(${Number(e)});`),n!=null&&Number.isFinite(n)&&r.push(`window.__weSetVolume(${Math.max(0,Math.min(1,Number(n)))});`),t&&Object.keys(t).length&&r.push(`window.__weSeedProps(${JSON.stringify(t)});`),r.join(`
2067
- `)}function G1(t,e,n){const r="position:absolute;border:none;background:transparent;",i=()=>{e.style.cssText=r+"inset:0;width:100%;height:100%;"};i();let s="";const a=()=>{if(!e.isConnected)return;let d=null;try{d=e.contentDocument}catch{return}if(!d)return;const h=n.clientWidth||window.innerWidth||0,p=n.clientHeight||window.innerHeight||0,m=Mr(t.cfg.fit)==="cover";i();const g=m&&h>0&&p>0?tw(d):null,w=g?ew(h,p,g.contentAspect):null,y=w?`${Math.round(w.width)}x${Math.round(w.height)}`:"full";if(!w){s="full";return}e.style.cssText=r+`left:${w.left}px;top:${w.top}px;width:${w.width}px;height:${w.height}px;`,y!==s&&(s=y,ce(t,t.cfg,`\u7F51\u9875\u58C1\u7EB8\u9732\u5E95\u81EA\u9002\u914D\uFF1A\u89C6\u53E3\u6309\u5185\u5BB9\u6BD4\u4F8B\u6539\u4E3A ${Math.round(w.width)}\xD7${Math.round(w.height)}\uFF08cover \u5C45\u4E2D\u88C1\u5207\uFF09`))},o=()=>a();window.addEventListener("resize",o);let c;typeof ResizeObserver<"u"&&(c=new ResizeObserver(()=>a()),c.observe(n));const u=[],l=()=>{a();for(const d of[120,400,1200])u.push(window.setTimeout(a,d));try{const d=e.contentDocument;if(d)for(const h of d.querySelectorAll("video,img"))h.addEventListener("loadedmetadata",a,{once:!0}),h.addEventListener("load",a,{once:!0})}catch{}};e.addEventListener("load",l),t.webRelayout=a;const f=t.sceneCleanup;t.sceneCleanup=()=>{window.removeEventListener("resize",o),c?.disconnect();for(const d of u)clearTimeout(d);e.removeEventListener("load",l),t.webRelayout===a&&(t.webRelayout=void 0);try{f?.()}catch{}}}function $1(t,e,n,r,i){if(!Number.isFinite(t)||!Number.isFinite(e)||!(n.width>0)||!(n.height>0))return null;const s=r.width>0&&i.width>0?r.width/i.width:1,a=r.height>0&&i.height>0?r.height/i.height:1;return{x:(t*n.width-(r.left-n.left))/(s||1),y:(e*n.height-(r.top-n.top))/(a||1)}}function Q1(t,e,n){const r=(i,s)=>{if(!e.isConnected)return null;const a=n.getBoundingClientRect(),o=e.getBoundingClientRect();return $1(Number(i),Number(s),{left:a.left,top:a.top,width:a.width||n.clientWidth||window.innerWidth||0,height:a.height||n.clientHeight||window.innerHeight||0},{left:o.left,top:o.top,width:o.width,height:o.height},{width:e.clientWidth,height:e.clientHeight})};t.pointerCtl={push(i){const s=r(i?.u,i?.v);s&&xt(t,a=>a.__wePushPointer?.(s.x,s.y,Number(i.buttons)||0,Number(i.mods)||0))},leave(){xt(t,i=>i.__wePointerLeave?.())},wheel(i){if(!e.isConnected)return;const s=i.u!==void 0&&i.v!==void 0?r(i.u,i.v):null;xt(t,a=>a.__wePushWheel?.(s?s.x:NaN,s?s.y:NaN,Number(i.dx)||0,Number(i.dy)||0,Number(i.mode)||0,Number(i.mods)||0))}}}function Hc(t,e,n,r,i){const s=document.createElement("iframe");s.setAttribute("sandbox","allow-scripts allow-same-origin"),s.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:none;background:transparent;",!t.wrap&&getComputedStyle(n).position==="static"&&(n.style.position="relative"),s.src=r,n.appendChild(s),t.iframe=s,i.blobUrl&&(t.objectUrls??=[]).push(i.blobUrl),G1(t,s,n),i.injected&&Q1(t,s,n);const a=c=>{if(c.source!==s.contentWindow)return;const u=c.data;if(!u||u.op!=="we-frame"||t.paused)return;const l=typeof u.t=="number"?u.t:performance.now();i.frameClock&&(i.frameClock.last=l),ir(t,l)};window.addEventListener("message",a);const o=t.sceneCleanup;t.sceneCleanup=()=>{window.removeEventListener("message",a);try{o?.()}catch{}},s.addEventListener("load",()=>{try{const l=s.contentDocument;l&&window.__blockContextMenu?.(l),i.injected||N1(t,s,l)}catch{}xt(t,l=>{const f={};for(const[d,h]of Object.entries(t.liveUserProps??{}))f[d]={value:h};l.__weApplyProps?.(f),l.__weSetFps?.(t.cfg.sceneFps??60),l.__weSetVolume?.(t.cfg.muted===!1?1:0),t.paused&&l.__weSetPaused?.(!0)});try{t.onFirstFrame?.(),t.onFirstFrame=void 0}catch{}const c=n.clientWidth||window.innerWidth||1,u=n.clientHeight||window.innerHeight||1;try{t.onSceneInfo?.({width:c,height:u,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}})}const Y1=.005,K1=.01,Z1=.2,J1=6;function ew(t,e,n){if(!(t>0)||!(e>0)||!(n>0))return null;const r=t/e;if(Math.abs(r-n)<=Y1)return null;if(r<n){const s=e*n;return{width:s,height:e,left:(t-s)/2,top:0}}const i=t/n;return{width:t,height:i,left:0,top:(e-i)/2}}function tw(t){const e=t.defaultView;if(!e)return null;const n=e.innerWidth,r=e.innerHeight;if(!(n>0)||!(r>0))return null;const i=[...t.querySelectorAll("video,img")];for(const s of i){const a=s.getBoundingClientRect();if(a.width<=0||a.height<=0||a.width<n*.98||Math.abs(a.left)>n*.02||a.top>r*.02||r-a.height<r*K1)continue;const o=s.videoWidth||s.naturalWidth||0,c=s.videoHeight||s.naturalHeight||0;if(!(o>0)||!(c>0))continue;const u=o/c;if(!(!Number.isFinite(u)||u<Z1||u>J1))return{contentAspect:u}}return null}function Wr(t){if(!t)return"rgb(128,128,128)";const e=Math.round(Math.max(0,Math.min(1,Number(t.x)||0))*255),n=Math.round(Math.max(0,Math.min(1,Number(t.y)||0))*255),r=Math.round(Math.max(0,Math.min(1,Number(t.z)||0))*255);return`rgb(${e},${n},${r})`}function nw(t){const e=typeof t.thumbnail=="string"?t.thumbnail.trim():"";if(e)return e;try{const n=document.createElement("canvas");n.width=n.height=64;const r=n.getContext("2d");if(!r)return"";const i=t.primaryColor,s=t.secondaryColor,a=r.createLinearGradient(0,0,64,64);return a.addColorStop(0,Wr(i)),a.addColorStop(1,Wr(s)),r.fillStyle=a,r.fillRect(0,0,64,64),n.toDataURL("image/jpeg",.85)}catch{return""}}function rw(){return Pe.createSimulatedMedia()}function iw(t,e,n){const r=Pe.diffMediaEvents(e,n);for(const{name:i,event:s}of r)if(i==="mediaStatusChanged")xt(t,a=>a.__wePushMedia?.({op:"status",enabled:!!s.enabled}));else if(i==="mediaPropertiesChanged")xt(t,a=>a.__wePushMedia?.({op:"properties",title:s.title??"",artist:s.artist??"",album:s.album??"",albumArtist:s.albumArtist??""}));else if(i==="mediaThumbnailChanged"){const a=nw(n);xt(t,o=>o.__wePushMedia?.({op:"thumbnail",thumbnail:a,hasThumbnail:!!s.hasThumbnail||!!a,primaryColor:Wr(s.primaryColor),secondaryColor:Wr(s.secondaryColor),tertiaryColor:Wr(s.tertiaryColor),textColor:Wr(s.textColor),highContrastColor:Wr(s.highContrastColor)}))}else i==="mediaPlaybackChanged"?xt(t,a=>a.__wePushMedia?.({op:"playback",state:Number(s.state)||0})):i==="mediaTimelineChanged"&&xt(t,a=>a.__wePushMedia?.({op:"timeline",position:Number(s.position)||0,duration:Number(s.duration)||0}));return Pe.cloneMediaSnapshot(n)}function lh(t,e,n,r={driver:null}){if(!e)return;const i=W1(t),s=()=>t.audioBridge?i:r.driver??e;let a=0,o=0;const c=l=>{if(a=requestAnimationFrame(c),t.paused||!t.iframe)return;const f=t.cfg.sceneFps||60,h=1e3/Math.min(Math.max(1,f),H1);if(!(l-o<h*.85)){o=l;try{const p=s();p.tick?.(l);const m=p.snapshot(),g=U1(L1,m.left,m.right);xt(t,w=>w.__wePushAudio?.(g)),n&&l-n.last>200&&ir(t,l)}catch{}}};a=requestAnimationFrame(c);const u=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(a);try{u?.()}catch{}}}function uh(t,e){if(!e)return;const n=()=>t.mediaSource??e;let r=0,i=null,s=0;const a=c=>{if(r=requestAnimationFrame(a),!(t.paused||!t.iframe)&&!(c-s<200)){s=c;try{const u=n();u.update?.(c/1e3),i=iw(t,i,u.snapshot)}catch{}}};r=requestAnimationFrame(a);const o=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(r);try{o?.()}catch{}}}function sw(t){t.sceneCtl={pause(){t.paused=!0,xt(t,e=>e.__weSetPaused?.(!0))},resume(){t.paused=!1,xt(t,e=>e.__weSetPaused?.(!1))},applyUserProperties(e){const n={...t.liveUserProps??{}};for(const[r,i]of Object.entries(e??{})){const s=i&&typeof i=="object"&&"value"in i?i.value:i;n[r]=s}t.liveUserProps=n,xt(t,r=>r.__weApplyProps?.(e))}}}function aw(t){try{return new URL(t,location.href).origin===location.origin}catch{return!1}}function ow(t){const e=t?.general?.properties;if(!e||typeof e!="object")return{};const n={};for(const[r,i]of Object.entries(e)){if(!i||typeof i!="object"||typeof i.type!="string")continue;const s=i.value,a=i.type.toLowerCase();if(s==null){if(a==="file"||a==="directory"){n[r]={value:""};continue}if(!("value"in i))continue}n[r]={value:s}}return n}async function cw(t){try{const e=new URL("project.json",new URL(t,location.href)),n=await fetch(e.href,{credentials:"same-origin"});return n.ok?ow(await n.json()):{}}catch{return{}}}function lw(t,e){const n={...t};if(e)for(const[r,i]of Object.entries(e))n[r]={value:i};return n}function uw(t,e){rr(t),t.cfg=e;const n=q1(t,e);if(!n){ce(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u53EF\u7528\u5BB9\u5668"),t.onError?.(new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u53EF\u7528\u5BB9\u5668"));return}const r=e.src??"";if(!r){ce(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"),t.onError?.(new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"));return}sw(t);const i=e,s=i._webAudio===null||t.audioDisabled?null:i._webAudio??V1(),a=i._webMedia===null||t.mediaDisabled?null:i._webMedia??rw(),o=f=>{ce(t,e,`\u7F51\u9875\u58C1\u7EB8 shim \u6CE8\u5165\u5931\u8D25\uFF08${f}\uFF09\uFF0C\u9000\u56DE\u88F8 iframe`),Hc(t,e,n,r,{injected:!1}),lh(t,null),uh(t,null);let d=0;const h=p=>{t.iframe&&(d=requestAnimationFrame(h),!t.paused&&ir(t,p))};d=requestAnimationFrame(h),(t.wallpaperDisposers??=[]).push(()=>cancelAnimationFrame(d))},c={last:0},u={driver:null},l=()=>{if(lh(t,s,c,u),uh(t,a),e.liveSystem&&s){const f={handle:null,dead:!1};(t.wallpaperDisposers??=[]).push(()=>{f.dead=!0,u.driver=null;try{f.handle?.dispose()}catch{}f.handle=null}),(async()=>{try{const d=await sh({origin:location.origin});if(f.dead){try{d.dispose()}catch{}return}f.handle=d;const h=d.status();h.audio==="mic"?(u.driver=j1(d),ce(t,e,"liveSystem: \u7F51\u9875\u58C1\u7EB8\u97F3\u9891\u6539\u7528\u9EA6\u514B\u98CE")):ce(t,e,`liveSystem: \u9EA6\u514B\u98CE\u4E0D\u53EF\u7528\uFF08${h.audio}\uFF09\uFF0C\u7F51\u9875\u58C1\u7EB8\u6CBF\u7528\u6A21\u62DF\u6E90`)}catch(d){ce(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u7F51\u9875\u58C1\u7EB8\u6CBF\u7528\u6A21\u62DF\u6E90 (${d?.message??d})`)}})()}};(async()=>{const f=await cw(r),d=lw(f,t.liveUserProps);if(t.liveUserProps=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.value])),aw(r)){Hc(t,e,n,r,{injected:!0,frameClock:c}),l(),t.iframe?.addEventListener("load",()=>{let p=!1;xt(t,m=>{p=typeof m.__weSetPaused=="function"}),p||ce(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u540C\u6E90\u5165\u53E3\u672A\u68C0\u6D4B\u5230 WE shim\uFF08host \u672A\u6CE8\u5165\uFF1F\uFF09\uFF1BSpine \u7C7B\u58C1\u7EB8\u8BF7\u786E\u8BA4 /web/ HTML \u6539\u5199")},{once:!0});return}try{const h=await fetch(r,{credentials:"same-origin"});if(!h.ok){o(`HTTP ${h.status}`);return}const p=await h.text();if(R1(p)){o("CSP \u963B\u6B62 inline script");return}const m=F1(p,D1,{baseHref:B1(r),seedScript:X1(d,e.sceneFps,e.muted===!1?1:0)}),g=new Blob([m],{type:"text/html;charset=utf-8"}),w=URL.createObjectURL(g);Hc(t,e,n,w,{blobUrl:w,injected:!0,frameClock:c}),l()}catch(h){o(h instanceof Error?h.message:String(h))}})()}function Vc(t,e){const n=String(e.type??"").toLowerCase();e={...e,type:n},t.cfg=e,(n==="video"||n==="gif"||n==="image")&&e.src?Kb(t,e):n==="scene"&&(e.source||e.src)?I1(t,e):n==="web"&&e.src?uw(t,e):t.onUnhandledType?.(e)}class Yn{x;y;z;constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new Yn(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new Yn(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return typeof e=="number"?new Yn(this.x*e,this.y*e,this.z*e):new Yn(this.x*e.x,this.y*e.y,this.z*e.z)}toString(){return`${this.x} ${this.y} ${this.z}`}}function on(t,e,n){if(t instanceof Yn)return t;if(Array.isArray(t))return new Yn(t[0]??0,t[1]??0,t[2]??0);if(typeof t=="object"&&t!==null){const r=t;return new Yn(r.x??0,r.y??0,r.z??0)}return new Yn(t,e??0,n??0)}const fw=[.35,.38,.45],dw=[.12,.13,.17],hw=[.72,.76,.84],fh=[.95,.96,.98];function mw(t,e){if(!Array.isArray(t)||t.length===0)return{line:"",index:-1};let n=-1;for(let r=0;r<t.length;r++){const i=Number(t[r]?.[0]);if(Number.isFinite(i)&&i<=e)n=r;else break}return{line:n>=0?String(t[n][1]??""):"",index:n}}function dh(t){const e=Number(t.position)||0,n=Array.isArray(t.lyrics)?t.lyrics:[],{line:r,index:i}=mw(n,e),s=t.state!==void 0?t.state:t.playing===!1?2:t.playing?1:0,a=t.thumbnail?String(t.thumbnail):"";return{hasMedia:t.hasMedia??(t.title!=null||t.artist!=null||!!t.playing),state:s,title:String(t.title??""),artist:String(t.artist??""),album:String(t.album??""),albumArtist:String(t.albumArtist??t.artist??""),position:e,duration:Number(t.duration)||0,hasThumbnail:t.hasThumbnail??!!a,...a?{thumbnail:a}:{},primaryColor:on(t.primaryColor??fw),secondaryColor:on(t.secondaryColor??dw),tertiaryColor:on(t.tertiaryColor??hw),textColor:on(t.textColor??fh),highContrastColor:on(t.highContrastColor??t.textColor??fh),trackIndex:Number(t.trackIndex)||0,lyrics:n,lyricLine:r,lyricIndex:i}}function pw(t={},e={}){let n={...t},r=dh(n);return{get snapshot(){return r},set(i){n={...n,...i},r=dh(n)},update(){},skipNext:e.skipNext,skipPrevious:e.skipPrevious,play:e.play,pause:e.pause,playPause:e.playPause}}function gw(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function yw(t){const e=t?.type;return typeof e=="string"&&e.toLowerCase()==="web"}const Wc=new Set(["video","gif","image"]);function bw(t){const e=t?.type;if(typeof e!="string")return null;const n=e.toLowerCase();return Wc.has(n)?n:null}function Da(t,e=!0){if(t instanceof HTMLCanvasElement)return t;const n=t.querySelector(":scope > canvas[data-webwallgl]");if(n instanceof HTMLCanvasElement){if(e||n.getAttribute("data-webwallgl-gl")!=="1")return n;n.remove()}const r=document.createElement("canvas");return r.setAttribute("data-webwallgl","1"),r.style.cssText="position:absolute;inset:0;width:100%;height:100%;display:block;",getComputedStyle(t).position==="static"&&(t.style.position="relative"),t.appendChild(r),r}async function hh(t,e){const n={fit:gw(e.fit),renderDpr:e.renderDpr??1,sceneFps:e.fps??60,muted:(e.volume??0)<=0,loop:!0,canvas:t,source:e.source};let r=null;try{r=await e.source.project?.()??null}catch{r=null}if(yw(r)){let o;try{o=(await e.source.webEntry?.())?.url}catch{o=void 0}if(!o&&e.source.key){const c=r&&typeof r.file=="string"&&String(r.file).trim().replace(/^\/+/,"")||"index.html";o=`${e.source.key.replace(/\/+$/,"")}/${c}`}if(!o)throw new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u6CD5\u89E3\u6790\u5165\u53E3 URL\uFF08\u9700\u8981 Source.webEntry \u6216 httpSource\uFF09");return{...n,type:"web",src:o,source:e.source}}const i=bw(r);if(i){let o,c;try{const f=await e.source.mediaEntry?.();o=f?.url,c=f?.type}catch{o=void 0}if(!o&&e.source.key){const f=r&&typeof r.file=="string"?String(r.file).trim().replace(/^\/+/,""):"";f&&(o=`${e.source.key.replace(/\/+$/,"")}/${f}`)}if(!o)throw new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08${i}\uFF09\uFF1A\u65E0\u6CD5\u89E3\u6790\u8D44\u6E90 URL\uFF08\u9700\u8981 Source.mediaEntry \u6216 project.file + httpSource\uFF09`);const u=Wc.has(String(c).toLowerCase())?String(c).toLowerCase():i,l=u==="video"?t:Da(t);return{...n,type:u,src:o,canvas:l,source:e.source}}if(!(typeof r?.type=="string"?String(r.type).trim():"")&&typeof e.source.mediaEntry=="function"){let o,c;try{const l=await e.source.mediaEntry();o=l?.url,c=l?.type}catch{o=void 0}const u=(Wc.has(String(c).toLowerCase())?String(c).toLowerCase():null)??(o?Oc(o):null);if(o&&u){const l=u==="video"?t:Da(t);return{...n,type:u,src:o,canvas:l,source:e.source}}}const a=Da(t);return{...n,type:"scene",canvas:a,source:e.source}}function mh(t,e){const n=Ch(),r={ready:[],error:[],diagnostic:[]};let i={...e??{},source:null},s=t;const a=p=>{for(const m of r.error)try{m(p)}catch{}},o=p=>{n.onDiagnostic=(m,g)=>{try{p.onDiagnostic?.(m,g)}catch{}for(const w of r.diagnostic)try{w(m,g)}catch{}},n.onError=m=>{try{p.onError?.(m)}catch{}a(m)},n.onSceneInfo=m=>{n.info=m},"audio"in p&&c(p.audio??null),"media"in p&&(n.mediaSource=p.media??null,n.mediaDisabled=p.media===null)},c=p=>{if(n.audioDisabled=p===null,!p){n.audioBridge=null;return}n.audioBridge=()=>{try{const m=p.snapshot();return m&&m.left&&m.right?m:null}catch{return null}}},u=()=>new Promise(p=>{const m=n.onFirstFrame;n.onFirstFrame=()=>{n.onFirstFrame=void 0,m?.();const g=n.info??{width:0,height:0,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1};try{i.onReady?.(g)}catch{}for(const w of r.ready)try{w(g)}catch{}p()}}),l=()=>{let p=()=>{};return{promise:new Promise((g,w)=>{p=d.on("error",y=>w(y))}),off:p}},f=()=>{if(n.cfg.type!=="web"&&n.cfg.type!=="video"){if(rr(n),t instanceof HTMLCanvasElement){a(new Error("\u91CD\u6302\u5931\u8D25\uFF1A\u8C03\u7528\u65B9\u76F4\u63A5\u4F20\u5165\u4E86 canvas\uFF0C\u5176 WebGL \u4E0A\u4E0B\u6587\u5DF2\u5728\u5378\u8F7D\u65F6\u5F52\u8FD8\u4E14\u65E0\u6CD5\u590D\u6D3B\uFF08loseContext \u540E\u540C\u4E00 canvas \u62FF\u4E0D\u56DE\u53EF\u7528\u4E0A\u4E0B\u6587\uFF09\uFF0C\u800C\u5E93\u4E0D\u80FD\u66FF\u8C03\u7528\u65B9\u66FF\u6362 DOM\u3002\u8BF7\u6539\u4F20\u4E00\u4E2A\u7A7A\u5BB9\u5668\u8BA9\u5E93\u81EA\u5EFA\u753B\u5E03\uFF0C\u6216\u91CD\u65B0\u8C03\u7528 mount()\u3002"));return}const m=Da(t,!1);m!==n.cfg.canvas&&(n.cfg={...n.cfg,canvas:m},s=m)}Vc(n,n.cfg)},d={get canvas(){return s},pause(){n.paused=!0,n.sceneCtl?.pause();for(const p of n.videoPairs??[])p.pause();n.videoPairs?.length||n.video?.pause()},resume(){if(n.paused=!1,el(n),n.sceneCtl?.resume(),n.videoPairs?.length)for(const p of n.videoPairs)p.resume();else n.video&&n.video.play().catch(()=>{})},get paused(){return!!n.paused},setFit(p){n.cfg.fit=p,Wa(n),n.webRelayout?.();const m=Va(p),g=w=>{w.style.objectFit=m.objectFit,w.style.background=m.background,w.style.objectPosition="50% 50%"};for(const w of n.videoPairs??[])for(const y of[w.active,w.standby])y.isConnected&&g(y);!n.videoPairs?.length&&n.video?.isConnected&&g(n.video)},setFps(p){n.cfg.sceneFps=p,xt(n,m=>m.__weSetFps?.(p))},setVolume(p){const m=Math.max(0,Math.min(1,p));if(n.cfg.muted=m<=0,n.sceneAudio?.setVolume(m),xt(n,g=>g.__weSetVolume?.(m)),n.videoPairs?.length)for(const g of n.videoPairs)g.setVolume(m);else n.video&&(n.video.volume=m,n.video.muted=m<=0);m<=0&&n.webcodecsPreferred&&n.cfg.type==="video"&&f()},setRenderDpr(p){n.cfg.renderDpr=p,f()},setProperties(p){const m={};for(const[g,w]of Object.entries(p))m[g]={value:w};n.sceneCtl?.applyUserProperties(m)},getProperties(){return{...n.liveUserProps??{}}},setAudio(p){i={...i,audio:p},c(p),n.audioDisabled=!1},setMedia(p){i={...i,media:p},n.mediaSource=p??null,n.mediaDisabled=!1},get media(){const p=n.mediaCtl;if(p)return p;const m={hasMedia:!1,state:0,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,primaryColor:on(0,0,0),secondaryColor:on(0,0,0),tertiaryColor:on(0,0,0),textColor:on(1,1,1),highContrastColor:on(1,1,1),trackIndex:0,lyrics:[],lyricLine:"",lyricIndex:-1},g=()=>m;return{get snapshot(){return m},skipNext:g,skipPrevious:g,play:g,pause:g,playPause:g}},pushPointer(p,m,g,w){n.pointerCtl?.push({u:p,v:m,buttons:g,mods:w})},pointerLeave(){n.pointerCtl?.leave()},pushWheel(p,m,g,w){n.pointerCtl?.wheel?.({dx:p,dy:m,mode:g,mods:w})},async load(p){const m=i.source;if(m&&m!==p)try{m.dispose?.()}catch{}i={...i,source:p},o(i);const g=await hh(s,i);g.type!=="web"&&g.canvas instanceof HTMLCanvasElement&&(s=g.canvas),n.cfg=g,n.paused=!1,n.info=void 0,Wa(n),i.properties&&(n.liveUserProps={...i.properties});const w=u(),y=l();Vc(n,g);try{await Promise.race([w,y.promise])}finally{y.off()}},release(){rr(n)},restore(){f()},destroy(p){Ih(n),p?.releasePkgCache&&E1(n.cfg.source?.key??i.source?.key);try{i.source?.dispose?.()}catch{}n.onDiagnostic=void 0,n.onError=void 0,n.onFirstFrame=void 0,n.onSceneInfo=void 0,r.ready.length=0,r.error.length=0,r.diagnostic.length=0},get stats(){return Bh(n)},get info(){return n.info??null},on(p,m){const g=r[p];return g.push(m),()=>{const w=g.indexOf(m);w>=0&&g.splice(w,1)}}},h=async p=>{i=p,o(p);const m=await hh(t,p);m.type!=="web"&&m.canvas instanceof HTMLCanvasElement&&(s=m.canvas),n.cfg=m,n.paused=!1,n.info=void 0,Wa(n),p.properties&&Object.keys(p.properties).length&&(n.liveUserProps={...p.properties});const g=u(),w=l();Vc(n,n.cfg);try{await Promise.race([g,w.promise])}finally{w.off()}p.autoplay===!1&&d.pause(),(p.volume??0)>0&&d.setVolume(p.volume),p.properties&&Object.keys(p.properties).length&&d.setProperties(p.properties)};return d.__applyOptions=h,d}async function ww(t,e){const n=mh(t,e);return await n.__applyOptions(e),n}export{a1 as bytesSource,pw as createMediaSource,mh as createScene,s1 as fileSource,Jd as httpSource,on as mediaColor,o1 as mediaSource,ww as mount,Oc as sniffMediaType};
2203
+ `;function Ht(t,e){try{const n=t.iframe?.contentWindow;n&&e(n)}catch{}}function C2(t,e,n){const r=e.contentWindow;if(!r||r.requestAnimationFrame?.__weThrottled)return;const i=t.cfg.sceneFps||30;if(i>=60)return;const s=1e3/i;try{const a=r.requestAnimationFrame.bind(r),o=new Map;let c=0;r.requestAnimationFrame=u=>{const l=++c,d=r.setTimeout(()=>{o.delete(l),a(f=>{try{u(f)}catch{}})},s);return o.set(l,d),l},r.cancelAnimationFrame=u=>{const l=o.get(u);l!==void 0&&(r.clearTimeout(l),o.delete(u))}}catch{}}const I2=new Float32Array(128);function R2(t,e,n){const r=Math.min(64,e.length),i=Math.min(64,n.length);for(let s=0;s<r;s++)t[s]=Number(e[s])||0;for(let s=0;s<i;s++)t[64+s]=Number(n[s])||0;return t}const B2=1.8,F2=1.8,D2=30;function up(t){const e=Number(t)||0;return e<=0?0:Math.min(1,Math.pow(e,F2)*B2)}function N2(){const t=nm(),e=new Float32Array(64),n=new Float32Array(64);return{tick(r){t.update(r/1e3)},snapshot(){const r=t.snapshot,i=r.preL64,s=r.preR64;for(let a=0;a<64;a++)i&&s?(e[a]=up(i[a]),n[a]=up(s[a])):(e[a]=(Number(r.left64[a])||0)*.2,n[a]=(Number(r.right64[a])||0)*.2);return{left:e,right:n}}}}function L2(t){const e=new Float32Array(64),n=new Float32Array(64);return{snapshot(){const r=t.audioBridge?.(),i=r?.left,s=r?.right,a=i&&s?Math.min(64,i.length,s.length):0;for(let o=0;o<a;o++)e[o]=Math.max(0,Math.min(1,Number(i[o])||0)),n[o]=Math.max(0,Math.min(1,Number(s[o])||0));for(let o=a;o<64;o++)e[o]=0,n[o]=0;return{left:e,right:n}}}}function U2(t){const e=new Float32Array(64),n=new Float32Array(64);return{tick(){t.audio.pump()},snapshot(){const r=t.audio.snapshot;for(let i=0;i<64;i++)e[i]=Math.max(0,Math.min(1,Number(r.left64[i])||0)),n[i]=Math.max(0,Math.min(1,Number(r.right64[i])||0));return{left:e,right:n}}}}function O2(t,e){if(t.wrap)return t.wrap;const n=e.canvas;if(!n)return null;if(n instanceof HTMLCanvasElement){const r=n.parentElement;return r?(be(t,e,"\u7F51\u9875\u58C1\u7EB8\u6302\u5728 canvas \u7236\u5BB9\u5668\u4E0A\uFF08canvas \u4E0D\u80FD\u6709\u5B50\u8282\u70B9\uFF1B\u66F4\u9002\u5408\u7A7A div\uFF09"),r):null}return n}function z2(t,e,n){const r=[];return e!=null&&Number.isFinite(e)&&r.push(`window.__weSetFps(${Number(e)});`),n!=null&&Number.isFinite(n)&&r.push(`window.__weSetVolume(${Math.max(0,Math.min(1,Number(n)))});`),t&&Object.keys(t).length&&r.push(`window.__weSeedProps(${JSON.stringify(t)});`),r.join(`
2204
+ `)}function H2(t,e,n){const r="position:absolute;border:none;background:transparent;",i=()=>{e.style.cssText=r+"inset:0;width:100%;height:100%;"};i();let s="";const a=()=>{if(!e.isConnected)return;let f=null;try{f=e.contentDocument}catch{return}if(!f)return;const h=n.clientWidth||window.innerWidth||0,p=n.clientHeight||window.innerHeight||0,m=Ur(t.cfg.fit)==="cover";i();const g=m&&h>0&&p>0?Q2(f):null,y=g?G2(h,p,g.contentAspect):null,w=y?`${Math.round(y.width)}x${Math.round(y.height)}`:"full";if(!y){s="full";return}e.style.cssText=r+`left:${y.left}px;top:${y.top}px;width:${y.width}px;height:${y.height}px;`,w!==s&&(s=w,be(t,t.cfg,`\u7F51\u9875\u58C1\u7EB8\u9732\u5E95\u81EA\u9002\u914D\uFF1A\u89C6\u53E3\u6309\u5185\u5BB9\u6BD4\u4F8B\u6539\u4E3A ${Math.round(y.width)}\xD7${Math.round(y.height)}\uFF08cover \u5C45\u4E2D\u88C1\u5207\uFF09`))},o=()=>a();window.addEventListener("resize",o);let c;typeof ResizeObserver<"u"&&(c=new ResizeObserver(()=>a()),c.observe(n));const u=[],l=()=>{a();for(const f of[120,400,1200])u.push(window.setTimeout(a,f));try{const f=e.contentDocument;if(f)for(const h of f.querySelectorAll("video,img"))h.addEventListener("loadedmetadata",a,{once:!0}),h.addEventListener("load",a,{once:!0})}catch{}};e.addEventListener("load",l),t.webRelayout=a;const d=t.sceneCleanup;t.sceneCleanup=()=>{window.removeEventListener("resize",o),c?.disconnect();for(const f of u)clearTimeout(f);e.removeEventListener("load",l),t.webRelayout===a&&(t.webRelayout=void 0);try{d?.()}catch{}}}function V2(t,e,n,r,i){if(!Number.isFinite(t)||!Number.isFinite(e)||!(n.width>0)||!(n.height>0))return null;const s=r.width>0&&i.width>0?r.width/i.width:1,a=r.height>0&&i.height>0?r.height/i.height:1;return{x:(t*n.width-(r.left-n.left))/(s||1),y:(e*n.height-(r.top-n.top))/(a||1)}}function W2(t,e,n){const r=(i,s)=>{if(!e.isConnected)return null;const a=n.getBoundingClientRect(),o=e.getBoundingClientRect();return V2(Number(i),Number(s),{left:a.left,top:a.top,width:a.width||n.clientWidth||window.innerWidth||0,height:a.height||n.clientHeight||window.innerHeight||0},{left:o.left,top:o.top,width:o.width,height:o.height},{width:e.clientWidth,height:e.clientHeight})};t.pointerCtl={push(i){const s=r(i?.u,i?.v);s&&Ht(t,a=>a.__wePushPointer?.(s.x,s.y,Number(i.buttons)||0,Number(i.mods)||0))},leave(){Ht(t,i=>i.__wePointerLeave?.())},wheel(i){if(!e.isConnected)return;const s=i.u!==void 0&&i.v!==void 0?r(i.u,i.v):null;Ht(t,a=>a.__wePushWheel?.(s?s.x:NaN,s?s.y:NaN,Number(i.dx)||0,Number(i.dy)||0,Number(i.mode)||0,Number(i.mods)||0))}}}function pu(t,e,n,r,i){const s=document.createElement("iframe");s.setAttribute("sandbox","allow-scripts allow-same-origin"),s.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:none;background:transparent;",!t.wrap&&getComputedStyle(n).position==="static"&&(n.style.position="relative"),s.src=r,n.appendChild(s),t.iframe=s,i.blobUrl&&(t.objectUrls??=[]).push(i.blobUrl),H2(t,s,n),i.injected&&W2(t,s,n);const a=c=>{if(c.source!==s.contentWindow)return;const u=c.data;if(!u||u.op!=="we-frame"||t.paused)return;const l=typeof u.t=="number"?u.t:performance.now();i.frameClock&&(i.frameClock.last=l),zr(t,l)};window.addEventListener("message",a);const o=t.sceneCleanup;t.sceneCleanup=()=>{window.removeEventListener("message",a);try{o?.()}catch{}},s.addEventListener("load",()=>{try{const l=s.contentDocument;l&&window.__blockContextMenu?.(l),i.injected||C2(t,s,l)}catch{}Ht(t,l=>{const d={};for(const[f,h]of Object.entries(t.liveUserProps??{}))d[f]={value:h};l.__weApplyProps?.(d),l.__weSetFps?.(t.cfg.sceneFps??60),l.__weSetVolume?.(Jo(t)),t.paused&&l.__weSetPaused?.(!0)});try{t.onFirstFrame?.(),t.onFirstFrame=void 0}catch{}const c=n.clientWidth||window.innerWidth||1,u=n.clientHeight||window.innerHeight||1;try{t.onSceneInfo?.({width:c,height:u,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1})}catch{}})}const j2=.005,q2=.01,X2=.2,$2=6;function G2(t,e,n){if(!(t>0)||!(e>0)||!(n>0))return null;const r=t/e;if(Math.abs(r-n)<=j2)return null;if(r<n){const s=e*n;return{width:s,height:e,left:(t-s)/2,top:0}}const i=t/n;return{width:t,height:i,left:0,top:(e-i)/2}}function Q2(t){const e=t.defaultView;if(!e)return null;const n=e.innerWidth,r=e.innerHeight;if(!(n>0)||!(r>0))return null;const i=[...t.querySelectorAll("video,img")];for(const s of i){const a=s.getBoundingClientRect();if(a.width<=0||a.height<=0||a.width<n*.98||Math.abs(a.left)>n*.02||a.top>r*.02||r-a.height<r*q2)continue;const o=s.videoWidth||s.naturalWidth||0,c=s.videoHeight||s.naturalHeight||0;if(!(o>0)||!(c>0))continue;const u=o/c;if(!(!Number.isFinite(u)||u<X2||u>$2))return{contentAspect:u}}return null}function Si(t){if(!t)return"rgb(128,128,128)";const e=Math.round(Math.max(0,Math.min(1,Number(t.x)||0))*255),n=Math.round(Math.max(0,Math.min(1,Number(t.y)||0))*255),r=Math.round(Math.max(0,Math.min(1,Number(t.z)||0))*255);return`rgb(${e},${n},${r})`}function Y2(t){const e=typeof t.thumbnail=="string"?t.thumbnail.trim():"";if(e)return e;try{const n=document.createElement("canvas");n.width=n.height=64;const r=n.getContext("2d");if(!r)return"";const i=t.primaryColor,s=t.secondaryColor,a=r.createLinearGradient(0,0,64,64);return a.addColorStop(0,Si(i)),a.addColorStop(1,Si(s)),r.fillStyle=a,r.fillRect(0,0,64,64),n.toDataURL("image/jpeg",.85)}catch{return""}}function K2(){return We.createSimulatedMedia()}function Z2(t,e,n){const r=We.diffMediaEvents(e,n);for(const{name:i,event:s}of r)if(i==="mediaStatusChanged")Ht(t,a=>a.__wePushMedia?.({op:"status",enabled:!!s.enabled}));else if(i==="mediaPropertiesChanged")Ht(t,a=>a.__wePushMedia?.({op:"properties",title:s.title??"",artist:s.artist??"",album:s.album??"",albumArtist:s.albumArtist??""}));else if(i==="mediaThumbnailChanged"){const a=Y2(n);Ht(t,o=>o.__wePushMedia?.({op:"thumbnail",thumbnail:a,hasThumbnail:!!s.hasThumbnail||!!a,primaryColor:Si(s.primaryColor),secondaryColor:Si(s.secondaryColor),tertiaryColor:Si(s.tertiaryColor),textColor:Si(s.textColor),highContrastColor:Si(s.highContrastColor)}))}else i==="mediaPlaybackChanged"?Ht(t,a=>a.__wePushMedia?.({op:"playback",state:Number(s.state)||0})):i==="mediaTimelineChanged"&&Ht(t,a=>a.__wePushMedia?.({op:"timeline",position:Number(s.position)||0,duration:Number(s.duration)||0}));return We.cloneMediaSnapshot(n)}function fp(t,e,n,r={driver:null}){if(!e)return;const i=L2(t),s=()=>t.audioBridge?i:r.driver??e;let a=0,o=0;const c=l=>{if(a=requestAnimationFrame(c),t.paused||!t.iframe)return;const d=t.cfg.sceneFps||60,h=1e3/Math.min(Math.max(1,d),D2);if(!(l-o<h*.85)){o=l;try{const p=s();p.tick?.(l);const m=p.snapshot(),g=R2(I2,m.left,m.right);Ht(t,y=>y.__wePushAudio?.(g)),n&&l-n.last>200&&zr(t,l)}catch{}}};a=requestAnimationFrame(c);const u=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(a);try{u?.()}catch{}}}function dp(t,e){if(!e)return;const n=()=>t.mediaSource??e;let r=0,i=null,s=0;const a=c=>{if(r=requestAnimationFrame(a),!(t.paused||!t.iframe)&&!(c-s<200)){s=c;try{const u=n();u.update?.(c/1e3),i=Z2(t,i,u.snapshot)}catch{}}};r=requestAnimationFrame(a);const o=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(r);try{o?.()}catch{}}}function J2(t){t.sceneCtl={pause(){t.paused=!0,Ht(t,e=>e.__weSetPaused?.(!0))},resume(){t.paused=!1,Ht(t,e=>e.__weSetPaused?.(!1))},applyUserProperties(e){const n={...t.liveUserProps??{}};for(const[r,i]of Object.entries(e??{})){const s=i&&typeof i=="object"&&"value"in i?i.value:i;n[r]=s}t.liveUserProps=n,Ht(t,r=>r.__weApplyProps?.(e))}}}function ex(t){try{return new URL(t,location.href).origin===location.origin}catch{return!1}}function tx(t){const e=t?.general?.properties;if(!e||typeof e!="object")return{};const n={};for(const[r,i]of Object.entries(e)){if(!i||typeof i!="object"||typeof i.type!="string")continue;const s=i.value,a=i.type.toLowerCase();if(s==null){if(a==="file"||a==="directory"){n[r]={value:""};continue}if(!("value"in i))continue}n[r]={value:s}}return n}async function nx(t){try{const e=new URL("project.json",new URL(t,location.href)),n=await fetch(e.href,{credentials:"same-origin"});return n.ok?tx(await n.json()):{}}catch{return{}}}function rx(t,e){const n={...t};if(e)for(const[r,i]of Object.entries(e))n[r]={value:i};return n}function ix(t,e){Or(t),t.cfg=e;const n=O2(t,e);if(!n){be(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u53EF\u7528\u5BB9\u5668"),t.onError?.(new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u53EF\u7528\u5BB9\u5668"));return}const r=e.src??"";if(!r){be(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"),t.onError?.(new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"));return}J2(t);const i=e,s=i._webAudio===null||t.audioDisabled?null:i._webAudio??N2(),a=i._webMedia===null||t.mediaDisabled?null:i._webMedia??K2(),o=d=>{be(t,e,`\u7F51\u9875\u58C1\u7EB8 shim \u6CE8\u5165\u5931\u8D25\uFF08${d}\uFF09\uFF0C\u9000\u56DE\u88F8 iframe`),pu(t,e,n,r,{injected:!1}),fp(t,null),dp(t,null);let f=0;const h=p=>{t.iframe&&(f=requestAnimationFrame(h),!t.paused&&zr(t,p))};f=requestAnimationFrame(h),(t.wallpaperDisposers??=[]).push(()=>cancelAnimationFrame(f))},c={last:0},u={driver:null},l=()=>{if(fp(t,s,c,u),dp(t,a),e.liveSystem&&s){const d={handle:null,dead:!1};(t.wallpaperDisposers??=[]).push(()=>{d.dead=!0,u.driver=null;try{d.handle?.dispose()}catch{}d.handle=null}),(async()=>{try{const f=await np({origin:location.origin});if(d.dead){try{f.dispose()}catch{}return}d.handle=f;const h=f.status();h.audio==="mic"?(u.driver=U2(f),be(t,e,"liveSystem: \u7F51\u9875\u58C1\u7EB8\u97F3\u9891\u6539\u7528\u9EA6\u514B\u98CE")):be(t,e,`liveSystem: \u9EA6\u514B\u98CE\u4E0D\u53EF\u7528\uFF08${h.audio}\uFF09\uFF0C\u7F51\u9875\u58C1\u7EB8\u6CBF\u7528\u6A21\u62DF\u6E90`)}catch(f){be(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u7F51\u9875\u58C1\u7EB8\u6CBF\u7528\u6A21\u62DF\u6E90 (${f?.message??f})`)}})()}};(async()=>{const d=await nx(r),f=rx(d,t.liveUserProps);if(t.liveUserProps=Object.fromEntries(Object.entries(f).map(([h,p])=>[h,p.value])),ex(r)){pu(t,e,n,r,{injected:!0,frameClock:c}),l(),t.iframe?.addEventListener("load",()=>{let p=!1;Ht(t,m=>{p=typeof m.__weSetPaused=="function"}),p||be(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u540C\u6E90\u5165\u53E3\u672A\u68C0\u6D4B\u5230 WE shim\uFF08host \u672A\u6CE8\u5165\uFF1F\uFF09\uFF1BSpine \u7C7B\u58C1\u7EB8\u8BF7\u786E\u8BA4 /web/ HTML \u6539\u5199")},{once:!0});return}try{const h=await fetch(r,{credentials:"same-origin"});if(!h.ok){o(`HTTP ${h.status}`);return}const p=await h.text();if(_2(p)){o("CSP \u963B\u6B62 inline script");return}const m=E2(p,M2,{baseHref:P2(r),seedScript:z2(f,e.sceneFps,Jo(t,e))}),g=new Blob([m],{type:"text/html;charset=utf-8"}),y=URL.createObjectURL(g);pu(t,e,n,y,{blobUrl:y,injected:!0,frameClock:c}),l()}catch(h){o(h instanceof Error?h.message:String(h))}})()}function gu(t,e){const n=String(e.type??"").toLowerCase();e={...e,type:n},t.cfg=e,(n==="video"||n==="gif"||n==="image")&&e.src?PA(t,e):n==="scene"&&(e.source||e.src)?T2(t,e):n==="web"&&e.src?ix(t,e):t.onUnhandledType?.(e)}class Mr{x;y;z;constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new Mr(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new Mr(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return typeof e=="number"?new Mr(this.x*e,this.y*e,this.z*e):new Mr(this.x*e.x,this.y*e.y,this.z*e.z)}toString(){return`${this.x} ${this.y} ${this.z}`}}function Dn(t,e,n){if(t instanceof Mr)return t;if(Array.isArray(t))return new Mr(t[0]??0,t[1]??0,t[2]??0);if(typeof t=="object"&&t!==null){const r=t;return new Mr(r.x??0,r.y??0,r.z??0)}return new Mr(t,e??0,n??0)}const sx=[.35,.38,.45],ax=[.12,.13,.17],ox=[.72,.76,.84],hp=[.95,.96,.98];function cx(t,e){if(!Array.isArray(t)||t.length===0)return{line:"",index:-1};let n=-1;for(let r=0;r<t.length;r++){const i=Number(t[r]?.[0]);if(Number.isFinite(i)&&i<=e)n=r;else break}return{line:n>=0?String(t[n][1]??""):"",index:n}}function mp(t){const e=Number(t.position)||0,n=Array.isArray(t.lyrics)?t.lyrics:[],{line:r,index:i}=cx(n,e),s=t.state!==void 0?t.state:t.playing===!1?2:t.playing?1:0,a=t.thumbnail?String(t.thumbnail):"";return{hasMedia:t.hasMedia??(t.title!=null||t.artist!=null||!!t.playing),state:s,title:String(t.title??""),artist:String(t.artist??""),album:String(t.album??""),albumArtist:String(t.albumArtist??t.artist??""),position:e,duration:Number(t.duration)||0,hasThumbnail:t.hasThumbnail??!!a,...a?{thumbnail:a}:{},primaryColor:Dn(t.primaryColor??sx),secondaryColor:Dn(t.secondaryColor??ax),tertiaryColor:Dn(t.tertiaryColor??ox),textColor:Dn(t.textColor??hp),highContrastColor:Dn(t.highContrastColor??t.textColor??hp),trackIndex:Number(t.trackIndex)||0,lyrics:n,lyricLine:r,lyricIndex:i}}function lx(t={},e={}){let n={...t},r=mp(n);return{get snapshot(){return r},set(i){n={...n,...i},r=mp(n)},update(){},skipNext:e.skipNext,skipPrevious:e.skipPrevious,play:e.play,pause:e.pause,playPause:e.playPause}}function ux(t){const e=t?.type;return typeof e=="string"&&e.toLowerCase()==="web"}const yu=new Set(["video","gif","image"]);function fx(t){const e=t?.type;if(typeof e!="string")return null;const n=e.toLowerCase();return yu.has(n)?n:null}function zo(t,e=!0){if(t instanceof HTMLCanvasElement)return t;const n=t.querySelector(":scope > canvas[data-webwallgl]");if(n instanceof HTMLCanvasElement){if(e||n.getAttribute("data-webwallgl-gl")!=="1")return n;n.remove()}const r=document.createElement("canvas");return r.setAttribute("data-webwallgl","1"),r.style.cssText="position:absolute;inset:0;width:100%;height:100%;display:block;",getComputedStyle(t).position==="static"&&(t.style.position="relative"),t.appendChild(r),r}async function pp(t,e){const n={fit:Ur(e.fit),renderDpr:e.renderDpr??0,sceneFps:e.fps??60,muted:(e.volume??0)<=0,loop:!0,canvas:t,source:e.source,quality:e.quality};let r=null;try{r=await e.source.project?.()??null}catch{r=null}if(ux(r)){let c;try{c=(await e.source.webEntry?.())?.url}catch{c=void 0}if(!c&&e.source.key){const u=r&&typeof r.file=="string"&&String(r.file).trim().replace(/^\/+/,"")||"index.html";c=`${e.source.key.replace(/\/+$/,"")}/${u}`}if(!c)throw new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u65E0\u6CD5\u89E3\u6790\u5165\u53E3 URL\uFF08\u9700\u8981 Source.webEntry \u6216 httpSource\uFF09");return{...n,type:"web",src:c,source:e.source}}const i=fx(r);if(i){let c,u;try{const f=await e.source.mediaEntry?.();c=f?.url,u=f?.type}catch{c=void 0}if(!c&&e.source.key){const f=r&&typeof r.file=="string"?String(r.file).trim().replace(/^\/+/,""):"";f&&(c=`${e.source.key.replace(/\/+$/,"")}/${f}`)}if(!c)throw new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08${i}\uFF09\uFF1A\u65E0\u6CD5\u89E3\u6790\u8D44\u6E90 URL\uFF08\u9700\u8981 Source.mediaEntry \u6216 project.file + httpSource\uFF09`);const l=yu.has(String(u).toLowerCase())?String(u).toLowerCase():i,d=l==="video"?t:zo(t);return{...n,type:l,src:c,canvas:d,source:e.source}}if(!(typeof r?.type=="string"?String(r.type).trim():"")&&typeof e.source.mediaEntry=="function"){let c,u;try{const d=await e.source.mediaEntry();c=d?.url,u=d?.type}catch{c=void 0}const l=(yu.has(String(u).toLowerCase())?String(u).toLowerCase():null)??(c?lu(c):null);if(c&&l){const d=l==="video"?t:zo(t);return{...n,type:l,src:c,canvas:d,source:e.source}}}const a=zo(t),o=cu(e.source.key);return{...n,type:"scene",canvas:a,source:e.source,...o?{src:o}:{}}}function gp(t,e){const n=Wp(),r={ready:[],error:[],diagnostic:[]};let i={...e??{},source:null},s=t;const a=p=>{for(const m of r.error)try{m(p)}catch{}},o=p=>{n.onDiagnostic=(m,g)=>{try{p.onDiagnostic?.(m,g)}catch{}for(const y of r.diagnostic)try{y(m,g)}catch{}},n.onError=m=>{try{p.onError?.(m)}catch{}a(m)},n.onSceneInfo=m=>{n.info=m},"audio"in p&&c(p.audio??null),"media"in p&&(n.mediaSource=p.media??null,n.mediaDisabled=p.media===null)},c=p=>{if(n.audioDisabled=p===null,!p){n.audioBridge=null;return}n.audioBridge=()=>{try{const m=p.snapshot();return m&&m.left&&m.right?m:null}catch{return null}}},u=()=>new Promise(p=>{const m=n.onFirstFrame;n.onFirstFrame=()=>{n.onFirstFrame=void 0,m?.();const g=n.info??{width:0,height:0,layerCount:0,hasModels:!1,hasParticles:!1,hasText:!1};try{i.onReady?.(g)}catch{}for(const y of r.ready)try{y(g)}catch{}p()}}),l=()=>{let p=()=>{};return{promise:new Promise((g,y)=>{p=f.on("error",w=>y(w))}),off:p}},d=()=>{if(n.cfg.type!=="web"&&n.cfg.type!=="video"){if(Or(n),t instanceof HTMLCanvasElement){a(new Error("\u91CD\u6302\u5931\u8D25\uFF1A\u8C03\u7528\u65B9\u76F4\u63A5\u4F20\u5165\u4E86 canvas\uFF0C\u5176 WebGL \u4E0A\u4E0B\u6587\u5DF2\u5728\u5378\u8F7D\u65F6\u5F52\u8FD8\u4E14\u65E0\u6CD5\u590D\u6D3B\uFF08loseContext \u540E\u540C\u4E00 canvas \u62FF\u4E0D\u56DE\u53EF\u7528\u4E0A\u4E0B\u6587\uFF09\uFF0C\u800C\u5E93\u4E0D\u80FD\u66FF\u8C03\u7528\u65B9\u66FF\u6362 DOM\u3002\u8BF7\u6539\u4F20\u4E00\u4E2A\u7A7A\u5BB9\u5668\u8BA9\u5E93\u81EA\u5EFA\u753B\u5E03\uFF0C\u6216\u91CD\u65B0\u8C03\u7528 mount()\u3002"));return}const m=zo(t,!1);m!==n.cfg.canvas&&(n.cfg={...n.cfg,canvas:m},s=m)}gu(n,n.cfg)},f={get canvas(){return s},pause(){n.paused=!0,n.sceneCtl?.pause();for(const p of n.videoPairs??[])p.pause();n.videoPairs?.length||n.video?.pause()},resume(){if(n.paused=!1,Fu(n),n.sceneCtl?.resume(),n.videoPairs?.length)for(const p of n.videoPairs)p.resume();else n.video&&n.video.play().catch(()=>{})},get paused(){return!!n.paused},setFit(p){n.cfg.fit=p,ec(n),n.webRelayout?.();const m=Zo(p),g=y=>{y.style.objectFit=m.objectFit,y.style.background=m.background,y.style.objectPosition="50% 50%"};for(const y of n.videoPairs??[])for(const w of[y.active,y.standby])w.isConnected&&g(w);!n.videoPairs?.length&&n.video?.isConnected&&g(n.video)},setFps(p){n.cfg.sceneFps=p,Ht(n,m=>m.__weSetFps?.(p))},setVolume(p){const m=Math.max(0,Math.min(1,p));if(n.userVolume=m,n.cfg.muted=m<=0,n.sceneAudio?.setVolume(m),Ht(n,g=>g.__weSetVolume?.(m)),n.videoPairs?.length)for(const g of n.videoPairs)g.setVolume(m);else n.video&&(n.video.volume=m,n.video.muted=m<=0);m<=0&&n.webcodecsPreferred&&n.cfg.type==="video"&&d()},setRenderDpr(p){n.cfg.renderDpr=p,d()},setQuality(p){const m={...fa(i.quality??n.cfg.quality),...p??{}};i={...i,quality:m},n.cfg.quality=m,n.sceneCtl?.setQuality?.(p??{})},getQuality(){return fa(i.quality??n.cfg.quality)},setProperties(p){const m={};for(const[g,y]of Object.entries(p))m[g]={value:y};n.sceneCtl?.applyUserProperties(m)},getProperties(){return{...n.liveUserProps??{}}},setAudio(p){i={...i,audio:p},c(p),n.audioDisabled=!1},setMedia(p){i={...i,media:p},n.mediaSource=p??null,n.mediaDisabled=!1},get media(){const p=n.mediaCtl;if(p)return p;const m={hasMedia:!1,state:0,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,primaryColor:Dn(0,0,0),secondaryColor:Dn(0,0,0),tertiaryColor:Dn(0,0,0),textColor:Dn(1,1,1),highContrastColor:Dn(1,1,1),trackIndex:0,lyrics:[],lyricLine:"",lyricIndex:-1},g=()=>m;return{get snapshot(){return m},skipNext:g,skipPrevious:g,play:g,pause:g,playPause:g}},pushPointer(p,m,g,y){n.pointerCtl?.push({u:p,v:m,buttons:g,mods:y})},pointerLeave(){n.pointerCtl?.leave()},pushWheel(p,m,g,y){n.pointerCtl?.wheel?.({dx:p,dy:m,mode:g,mods:y})},async load(p){const m=i.source;if(m&&m!==p)try{m.dispose?.()}catch{}i={...i,source:p},o(i);const g=await pp(s,i);g.type!=="web"&&g.canvas instanceof HTMLCanvasElement&&(s=g.canvas),n.cfg=g,n.paused=!1,n.info=void 0,ec(n),i.properties&&(n.liveUserProps={...i.properties});const y=u(),w=l();gu(n,g);try{await Promise.race([y,w.promise])}finally{w.off()}},release(){Or(n)},restore(){d()},destroy(p){jp(n),p?.releasePkgCache&&x2(n.cfg.source?.key??i.source?.key);try{i.source?.dispose?.()}catch{}n.onDiagnostic=void 0,n.onError=void 0,n.onFirstFrame=void 0,n.onSceneInfo=void 0,r.ready.length=0,r.error.length=0,r.diagnostic.length=0},get stats(){return Xp(n)},get info(){return n.info??null},on(p,m){const g=r[p];return g.push(m),()=>{const y=g.indexOf(m);y>=0&&g.splice(y,1)}}},h=async p=>{i=p,o(p);const m=await pp(t,p);m.type!=="web"&&m.canvas instanceof HTMLCanvasElement&&(s=m.canvas),n.cfg=m,n.paused=!1,n.info=void 0,ec(n),p.properties&&Object.keys(p.properties).length&&(n.liveUserProps={...p.properties});const g=u(),y=l();gu(n,n.cfg);try{await Promise.race([g,y.promise])}finally{y.off()}p.autoplay===!1&&f.pause(),(p.volume??0)>0&&f.setVolume(p.volume),p.properties&&Object.keys(p.properties).length&&f.setProperties(p.properties)};return f.__applyOptions=h,f}async function dx(t,e){const n=gp(t,e);return await n.__applyOptions(e),n}export{DA as bytesSource,lx as createMediaSource,gp as createScene,FA as fileSource,Ym as httpSource,Dn as mediaColor,NA as mediaSource,dx as mount,lu as sniffMediaType,cu as workshopIdFromSourceKey};
2068
2205
 
2069
2206
  //# sourceMappingURL=webwallgl.min.mjs.map