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/README.en.md +17 -103
- package/README.md +17 -103
- package/package.json +1 -1
- package/types.d.ts +41 -2
- package/webwallgl.d.ts +15 -0
- package/webwallgl.global.js +6267 -1024
- package/webwallgl.global.js.map +1 -1
- package/webwallgl.global.min.js +211 -74
- package/webwallgl.global.min.js.map +1 -1
- package/webwallgl.min.mjs +211 -74
- package/webwallgl.min.mjs.map +1 -1
- package/webwallgl.mjs +6267 -1025
- package/webwallgl.mjs.map +1 -1
package/webwallgl.global.min.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
(function(It,fn){typeof exports=="object"&&typeof module<"u"?fn(exports):typeof define=="function"&&define.amd?define(["exports"],fn):(It=typeof globalThis<"u"?globalThis:It||self,fn(It.WebWallGL={}))})(this,function(It){"use strict";function fn(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function dn(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 Xr(t,e,n,r,i,s){const a=fn();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 Gr(t,e,n,r){return dn(t,new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,e,n,r,1]))}function Gc(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 Ei(t,e,n,r){return dn(t,new Float32Array([e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1]))}function $c(t,e){const n=Math.cos(e),r=Math.sin(e);return dn(t,new Float32Array([n,r,0,0,-r,n,0,0,0,0,1,0,0,0,0,1]))}function gh(t,e){const n=Math.cos(e),r=Math.sin(e);return dn(t,new Float32Array([1,0,0,0,0,n,r,0,0,-r,n,0,0,0,0,1]))}function yh(t,e){const n=Math.cos(e),r=Math.sin(e);return dn(t,new Float32Array([n,0,-r,0,0,1,0,0,r,0,n,0,0,0,0,1]))}function bh(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 _s(t,e){const n=t&&typeof t=="object"?t.value:t;return typeof n=="number"&&Number.isFinite(n)?n:e}function wh(t){const e=t&&t.general;return!e||e.orthogonalprojection?!1:_s(e.fov,0)>0}function vh(t,e){return e&&e.perspective&&t&&t.isSkybox&&e.eye?e.eye:t.origin}function kh(t,e,n){const r=Yc([t[0]-e[0],t[1]-e[1],t[2]-e[2]]),i=Yc(Kc(n,r)),s=Kc(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 Ah(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 xh=[[16,9],[16,10],[21,9],[32,9]];function Th(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 xh){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 Sh(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 Ua(t,e,n,r,i,s,a){const o=Qc(s),c=Qc(a);if(t==="cover"){const u=Th(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 Ph(t,e,n,r,i,s){const a=t.general,o=t.camera,c=o&&o.eye?za(o.eye):[0,0,0],u=o&&o.center?za(o.center):[0,0,-1],l=o&&o.up?za(o.up):[0,1,0];if(wh(t)){const b=n>0?e/n:1.7777777777777777,v=_s(a.fov,50),k=Math.max(_s(a.nearz,.01),1e-4),A=Math.max(_s(a.farz,1e4),k+1),T=kh(c,u,l),S=bh(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=fn(),d=a&&a.orthogonalprojection&&a.orthogonalprojection.width||e,h=a&&a.orthogonalprojection&&a.orthogonalprojection.height||n,p=Ua(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=Xr(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 Qc(t){const e=Number(t);return Number.isFinite(e)?e<0?0:e>1?1:e:.5}function za(t){return String(t).trim().split(/\s+/).map(Number)}function Yc(t){const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]}function Kc(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 $r(t){const e=Number(t);return Number.isFinite(e)?e*.5:0}function Es(t,e){const n=e?.renderDpr??t.cfg?.renderDpr??1;return Math.min(window.devicePixelRatio||1,n)}function xr(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function Ha(t){const e=xr(t);return e==="contain"?{objectFit:"contain",background:"rgba(10,12,16,0.85)"}:e==="stretch"?{objectFit:"fill",background:"transparent"}:{objectFit:"cover",background:"transparent"}}function _h(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 Jn(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,Rh(),Jc(t)}function Eh(t){try{Jn(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 Ch=new TextDecoder,Ot=t=>Ch.decode(t).replace(/^\uFEFF/,""),Zc=500;function er(t,e){const n=t.frameMeter.stamps;n.push(e),t.frameMeter.last=e;const r=e-Zc;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 Jc(t){t.frameMeter.stamps.length=0,t.frameMeter.last=0,t.frameMeter.fps=0}function Ih(t){return!t.frameMeter.last||t.paused?{fps:0,running:!1}:performance.now()-t.frameMeter.last>Math.max(Zc,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 Va(t){t.coverAlign.x=t.coverAlign.y=t.coverAlign.tx=t.coverAlign.ty=.5,Mh(t)}function Mh(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 Bh=["__scene","__sceneLayers","__textures","__objScripts","__textWidgets","__mediaHooks","__mediaControl","__mediaStats","__mediaSet","__system","__liveSystem","__audioStats","__audioMute","__particleStats","__particleToggle","__pointerStats","__compositeStats","__compositeEnable"];function Rh(){const t=window;for(const e of Bh)e in t&&delete t[e]}function el(t,e,n){const r=Es(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 Fh=.5,tl=.12,Dh=.125,Nh=.0625,nl=64;function rl(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=tl,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 ${nl}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,nl+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(()=>{})}},U=()=>{if(S)return;T=requestAnimationFrame(U);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(Fh,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(tl,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?Nh:Dh,w=performance.now(),g=!1,i.play().catch(()=>{}),u=!0,p=performance.now()}else if(i.paused)try{i.currentTime=0}catch{}}};T=requestAnimationFrame(U),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(U)))},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 Wa=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},Mt=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)},Cn=t=>{const e=le(t);return(e&1)===0?-(e>>1):e+1>>1},In=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Ie=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Bt=new TextDecoder,ja=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),qa={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Mn=ja(qa),Xa={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Bn=ja(Xa),Ga={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Rn=ja(Ga),$a=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,il={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Lh=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Cs{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 Oh=/^[0-9a-fA-F]+$/,Ci=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Uh=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},sl=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),Ii=(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},al=(t,e,n)=>{const r=_e(t,n(e),n);t.splice(r+1,0,e)},mt=()=>{let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}},Qa=(t,e)=>{const n=t.indexOf(e);n!==-1&&t.splice(n,1)},ol=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return t[n]},Ya=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1},zh=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},Hh=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},Is=t=>{throw new Error(`Unexpected value: ${t}`)},cl=(t,e,n)=>{const r=t.getUint8(e),i=t.getUint8(e+1),s=t.getUint8(e+2);return r<<16|i<<8|s},Vh=(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)},Mi=(t,e,n)=>Math.max(e,Math.min(n,t)),Tt="und",Bi=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},Ka=(t,e)=>Math.round(t/e)*e,ll=(t,e)=>Math.round(t*e)/e,Za=(t,e)=>Math.floor(t/e)*e,Wh=t=>{let e=0;for(;t;)e++,t>>=1;return e},Ja=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},jh=/^[a-z]{3}$/,ul=t=>jh.test(t),Qr=1e6*(1+Number.EPSILON),fl=(t,e)=>{const n={...t,...e};if(t.headers||e.headers){const r=t.headers?eo(t.headers):{},i=e.headers?eo(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},eo=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},dl=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 Rs(1e3*o),i())throw a}};class qh{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let to=null;const no=()=>to!==null?to:to=!!(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 ro=null;const Xh=()=>ro!==null?ro:ro=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let io=null;const so=()=>io!==null?io:io=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Gh=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.`,$h=(async()=>{})().constructor,ie=t=>t instanceof $h||t instanceof Promise?!0:typeof t?.then=="function",Yr=(t,e)=>t!==-1?t:e,ao=(t,e,n,r)=>t<=r&&n<=e,hl=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},Qh=(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},oo=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ms=t=>typeof t=="number"&&!Number.isNaN(t),tr=(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("/")},Ri=(t,e)=>{let n=0;for(let r=0;r<t.length;r++)e(t[r])&&n++;return n},co=(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},Bs=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}},lo=(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.`)},Rs=t=>new Promise(e=>setTimeout(e,t));class uo{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 hn;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(hn||(hn={}));class pe{constructor(){}static get level(){return pe._level}static set level(e){if(e!==hn.Silent&&e!==hn.Errors&&e!==hn.Warnings&&e!==hn.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 uo}static on(e,n,r){return pe._emitter.on(e,n,r)}static _error(...e){pe._emitter._emit("error",e),pe._level>=hn.Errors&&console.error(...e)}static _warn(...e){pe._emitter._emit("warn",e),pe._level>=hn.Warnings&&console.warn(...e)}static _info(...e){pe._emitter._emit("info",e),pe._level>=hn.Info&&console.info(...e)}}pe._level=hn.Info,pe._emitterInstance=null;class Fs{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 Yh{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 Fn={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 Fi=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],fo=[-1,1,2,3,4,5,6,8],ml=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Ee(t),n=ho(e),{frequencyIndex:r,sampleRate:i}=mo(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=fo[s]);let o=n,c=!1,u=i;if(n===5||n===29)c=n===29,u=mo(e).sampleRate,o=ho(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}ho(e)===5&&e.readBits(1)&&(u=mo(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}},ho=t=>{const e=t.readBits(5);return e===31?32+t.readBits(6):e},mo=t=>{const e=t.readBits(4);return e===15?{frequencyIndex:e,sampleRate:t.readBits(24)}:{frequencyIndex:e,sampleRate:e<Fi.length?Fi[e]:null}};const Ds=[48e3,44100,32e3],pl=[24e3,22050,16e3];var ct;(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"})(ct||(ct={}));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 Ns=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})},gl=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=cl(r,n):(R(e===4),i=r.getUint32(n,!1)),n+=e,yield{offset:n,length:i},n+=i}},yl=(t,e)=>{if(e.description){const i=(In(e.description)[4]&3)+1;return gl(t,i)}else return Ns(t)},Ls=t=>t&31,Os=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)},po=new Uint8Array([0,0,0,1]),bl=t=>{const e=t.reduce((i,s)=>i+po.byteLength+s.byteLength,0),n=new Uint8Array(e);let r=0;for(const i of t)n.set(po,r),r+=po.byteLength,n.set(i,r),r+=i.byteLength;return n},wl=(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:Vh(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},Kh=(t,e)=>{if(e.description){const i=(In(e.description)[4]&3)+1;return wl(t,i)}else return bl(t)},go=t=>{try{const e=[],n=[],r=[];for(const o of Ns(t)){const c=t.subarray(o.offset,o.offset+o.length),u=Ls(c[0]);u===ct.SPS?e.push(c):u===ct.PPS?n.push(c):u===ct.SPS_EXT&&r.push(c)}if(e.length===0||n.length===0)return null;const i=e[0],s=Us(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}},vl=t=>{try{const e=Ie(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}},kl={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}},Us=t=>{try{const e=new Ee(Os(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=Cn(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),Cn(e),Cn(e);const B=le(e);for(let N=0;N<B;N++)Cn(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),U=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*(U+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=kl[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&&Al(e);const Y=e.readBits(1);Y&&Al(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,U=d+1,q=(2-w)*U,H=Ll.find(Y=>Y.level>=s)??Mt(Ll),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}},Al=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)},Zh=(t,e)=>{if(e.description){const i=(In(e.description)[21]&3)+1;return wl(t,i)}else return bl(t)},zs=(t,e)=>{if(e.description){const i=(In(e.description)[21]&3)+1;return gl(t,i)}else return Ns(t)},Kr=t=>t>>1&63,yo=t=>{try{const e=new Ee(Os(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}=Jh(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),U=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+U)*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)&&em(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(tm(e,k),e.readBits(1)){const N=le(e);for(let U=0;U<N;U++)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=rm(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}},bo=t=>{try{const e=[],n=[],r=[],i=[];for(const u of Ns(t)){const l=t.subarray(u.offset,u.offset+u.length),f=Kr(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=yo(n[0]);if(!s)return null;let a=0;if(r.length>0){const u=r[0],l=new Ee(Os(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),Cn(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&le(l),Cn(l),Cn(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:Kr(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}},Jh=(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}},em=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&&Cn(t);for(let s=0;s<i;s++)Cn(t)}},tm=(t,e)=>{const n=[];for(let r=0;r<e;r++)n[r]=nm(t,r,e,n)},nm=(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},rm=(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=kl[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)&&im(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}},im=(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&&xl(t,l,s),i&&xl(t,l,s)}},xl=(t,e,n)=>{for(let r=0;r<e;r++)le(t),le(t),n&&(le(t),le(t)),t.readBits(1)},sm=t=>{try{const e=Ie(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 U=[];for(let q=0;q<N;q++){const H=e.getUint16(n,!1);n+=2,U.push(t.subarray(n,n+H)),n+=H}T.push({arrayCompleteness:M,nalUnitType:B,nalUnits:U})}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 pt;(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"})(pt||(pt={}));const am=(t,e)=>{const n=new Set;let r=pt.audAllowed;for(const s of zs(t,e)){if(r===pt.noMoreDataAllowed){n.add(s.offset);continue}const a=Kr(t[s.offset]);if(r===pt.eoBitstreamAllowed&&a!==37){n.add(s.offset);continue}let o=!1;a===35?r>pt.audAllowed?o=!0:r=pt.beforeFirstVcl:a<=31?r>pt.afterFirstVcl?o=!0:r=pt.afterFirstVcl:a===36?r!==pt.afterFirstVcl?o=!0:r=pt.eoBitstreamAllowed:a===37?r<pt.afterFirstVcl?o=!0:r=pt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?r>pt.beforeFirstVcl?o=!0:r=pt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&r<pt.afterFirstVcl&&(o=!0),o&&n.add(s.offset)}if(n.size===0)return null;const i=[];for(const s of zs(t,e))n.has(s.offset)||i.push(t.subarray(s.offset,s.offset+s.length));return Zh(i,e)},om={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}},Tl=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=Mt(Jr).level;for(const T of Jr)if(w<=T.maxPictureSize){y=T.level;break}const b=om[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}},cm=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,Sl=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)}},wo=t=>{for(const{type:e,data:n}of Sl(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 U=0;U<=N;U++){r.skipBits(12);const q=r.readBits(5);if(U===0&&(a=q),q>7){const H=r.readBits(1);U===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},lm=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,Pl=t=>{if(t.length<36)return null;const n=Ie(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)}},um=t=>{const e=Ie(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}},fm=[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],dm=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:fm[e]*r}},hm=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}},vo=(t,e,n)=>{switch(t){case"avc":{for(const r of yl(n,e)){const i=n[r.offset],s=Ls(i);if(s>=ct.NON_IDR_SLICE&&s<=ct.SLICE_DPC)return"delta";if(s===ct.IDR)return"key";if(s===ct.SEI&&!so()){const a=n.subarray(r.offset,r.offset+r.length),o=Os(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 zs(n,e)){const i=Kr(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 Sl(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:Is(t),R(!1)}};var Zr;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Zr||(Zr={}));const ko=(t,e)=>{const n=Ie(t);let r=0;const i=n.getUint32(r,!0);r+=4;const s=Bt.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=Bt.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=hl(d),p=Ie(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=Bt.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}}},Ao=[2,1,2,3,3,4,4,5],mm=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}},pm=[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],gm=1536,_l=[1,2,3,6],ym=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=_l[a];let f;return i<3?f=Ds[i]/1e3:f=pl[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}]}},bm=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}},El=t=>{const e=t.substreams[0];return R(e),e.fscod<3?Ds[e.fscod]:e.fscod2!==null&&e.fscod2<3?pl[e.fscod2]:null},Cl=t=>{const e=t.substreams[0];R(e);let n=Ao[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},wm=1683496997,Hs=18,xo=10,vm=4096,Il=32,Ml=20,km=8,Am=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],xm=[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],Tm=[16,16,20,20,0,24,24,0],Vs=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Sm=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Pm=8,_m=44646,Em=[32e3,44100,48e3,0],Cm=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Im=[512,1024,2048,4096],Bl=t=>{const e=Fl(t),n=Ie(t);let r=e?Math.ceil(e.frameSize/4)*4:0,i=null;for(;r+4<=t.length&&n.getUint32(r)===wm;){const a=Ws(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}},Rl=t=>{const e=Bl(t);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},Fl=t=>{if(t.length<Hs||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)!==Il-1)return null;const n=e.readBits(1),r=e.readBits(7)+1;if(r%km!==0)return null;const i=e.readBits(14)+1;if(i<96)return null;const s=e.readBits(6);if(s>=Vs.length)return null;const a=Am[e.readBits(4)];if(a===0)return null;const o=xm[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=Tm[e.readBits(3)];if(u===0)return null;const l=c!==0;return{frameSize:i,sampleRate:a,numberOfChannels:Vs[s]+(l?1:0),sampleCount:r*Il,channelLayout:Sm[s]|(l?Pm:0),amode:s,lfePresent:l,bitRate:o,pcmResolution:u}},Ws=t=>{if(t.length<xo||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=Em[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*Ja(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=Cm[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}}},Mm=t=>{if(t.length<Ml)return null;const e=Ie(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=Bm(o):a<Vs.length&&(c=Vs[a]+s),{sampleRate:n,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:t[12],sampleCount:Im[i],channelLayout:o,numberOfChannels:c}},Bm=t=>Ja(t)+Ja(t&_m);const Dl=["avc","hevc","vp9","av1","vp8","prores"],js=["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"],Nl=[...["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],...js],Ll=[{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}],Jr=[{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",Ul=".0.110.01.01.01.0",To=["ap4x","ap4h","apch","apcn","apcs","apco"],zl=["dtsc","dtsh","dtsl","dtse"],So=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}.${Ci(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}.${Ci(n.subarray(1,4))}`}else if(e==="hevc"){let u,l,f,d,h,p;if(s)u=s.generalProfileSpace,l=s.generalProfileIdc,f=sl(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=Ie(n),w=g.getUint8(1);u=w>>6&3,l=w&31,f=sl(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=Mt(Jr).level;for(const v of Jr)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=Mt(Jr).level;for(const A of Jr)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?qa[r.primaries]:1,g=r?.transfer?Xa[r.transfer]:1,w=r?.matrix?Ga[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(Ul)&&(b=b.slice(0,-Ul.length)),b}else{if(e==="prores")return c??"apch";e!==null&&Is(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Hl=t=>{switch(t.codec){case"avc":{let e=t.avcCodecInfo?.sequenceParameterSets[0];if(!e&&t.codecDescription&&(e=vl(t.codecDescription)?.sequenceParameterSets[0]),e){const n=Us(e);if(n)return{primaries:Mn[n.colourPrimaries],transfer:Bn[n.transferCharacteristics],matrix:Rn[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=sm(t.codecDescription)?.arrays.find(n=>n.nalUnitType===Ge.SPS_NUT)?.nalUnits[0]),e){const n=yo(e);if(n)return{primaries:Mn[n.colourPrimaries],transfer:Bn[n.transferCharacteristics],matrix:Rn[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(t.vp9CodecInfo)return{primaries:Mn[t.vp9CodecInfo.colourPrimaries],transfer:Bn[t.vp9CodecInfo.transferCharacteristics],matrix:Rn[t.vp9CodecInfo.matrixCoefficients],fullRange:!!t.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(t.av1CodecInfo)return{primaries:Mn[t.av1CodecInfo.colourPrimaries],transfer:Bn[t.av1CodecInfo.transferCharacteristics],matrix:Rn[t.av1CodecInfo.matrixCoefficients],fullRange:!!t.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(t.proresCodecInfo)return{primaries:Mn[t.proresCodecInfo.colourPrimaries],transfer:Bn[t.proresCodecInfo.transferCharacteristics],matrix:Rn[t.proresCodecInfo.matrixCoefficients],fullRange:t.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Po=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=ml(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&&js.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},qs=48e3,Vl=/^pcm-([usf])(\d+)(be)?$/,Rm=t=>{if(R(js.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=Vl.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}},Di=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":To.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":zl.includes(t)?"dts":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Vl.test(t)?t:t==="webvtt"?"webvtt":null;const Tr=4,Fm=[44100,48e3,32e3],Dm=[-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],Wl=1483304551,jl=1231971951,Nm=(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,Lm=(t,e,n,r)=>e===0?0:e===1?144*n/(r<<t):e===2?144*n/r:12*n/r*4,ql=(t,e)=>t===3?e===3?21:36:e===3?13:21,_o=(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=Dm[a*16*4+u*16+l];if(y===-1)return{header:null,bytesAdvanced:1};const b=y*1e3,v=Fm[f]>>a+o,k=Nm(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}},Eo=t=>{let e=2130706432,n=0;for(;e!==0;)n>>=1,n|=t&e,e>>=8;return n};var Xs;(function(t){t[t.FrameCount=1]="FrameCount",t[t.FileSize=2]="FileSize",t[t.Toc=4]="Toc"})(Xs||(Xs={}));const Ni=t=>t===3?1:2;class Dn{constructor(e){this.input=e}dispose(){}}const Ut=new Uint8Array(0);class Qe{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===Ut&&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===Ut}get microsecondTimestamp(){return Math.trunc(Qr*this.timestamp)}get microsecondDuration(){return Math.trunc(Qr*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 Qe(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 Qe(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 Om=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},Xl=t=>{const e=Ie(t);let n=0;const r=e.getUint8(n);n+=1,n+=3;const i=Ci(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(Ci(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)}},Gl=(t,e)=>t.systemId===e.systemId&&Qh(t.data,e.data);const ei=8,Li=16,nr=t=>{let e=ae(t);const n=Ve(t,4);let r=8;e===1&&(e=Ht(t),r=16);const s=e-r;return s<0?null:{name:n,totalSize:e,headerSize:r,contentSize:s}},Sr=t=>Mr(t)/65536,Co=t=>Mr(t)/1073741824,Io=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},mn=t=>{let e=$e(t);return t.skip(2),e=Math.min(e,t.remainingLength),Bt.decode(me(t,e))},Um=t=>{const e=nr(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 Bt.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Fs(r,"image/jpeg");case 14:return new Fs(r,"image/png");case 27:return new Fs(r,"image/bmp");default:return r}};const pn=16,Nn=new Uint32Array(256),ti=new Uint32Array(256),ni=new Uint32Array(256),ri=new Uint32Array(256),ii=new Uint32Array(256),lt=new Uint32Array(256),$l=new Uint32Array(10);let Ql=!1;const zm=()=>{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);Nn[s]=a<<24|a<<16|a<<8|a,lt[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;ti[s]=d,ni[s]=d>>>8|d<<24,ri[s]=d>>>16|d<<16,ii[s]=d>>>24|d<<8}let i=1;for(let s=0;s<10;s++)$l[s]=i<<24,i=i<<1^(i&128?283:0);Ql=!0};class Yl{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(pn/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(pn),this.out=new Uint8Array(pn),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),Ql||zm();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]^Nn[a>>>16&255]&4278190080^Nn[a>>>8&255]&16711680^Nn[a>>>0&255]&65280^Nn[a>>>24&255]&255^$l[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]=ti[Nn[o>>>24&255]&255]^ni[Nn[o>>>16&255]&255]^ri[Nn[o>>>8&255]&255]^ii[Nn[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=ti[e>>>24]^ni[i>>>16&255]^ri[r>>>8&255]^ii[n&255]^this.roundkey[y],l=ti[n>>>24]^ni[e>>>16&255]^ri[i>>>8&255]^ii[r&255]^this.roundkey[y+1],f=ti[r>>>24]^ni[n>>>16&255]^ri[e>>>8&255]^ii[i&255]^this.roundkey[y+2],d=ti[i>>>24]^ni[r>>>16&255]^ri[n>>>8&255]^ii[e&255]^this.roundkey[y+3],e=u,n=l,r=f,i=d}const h=lt[e>>>24&255]&4278190080^lt[i>>>16&255]&16711680^lt[r>>>8&255]&65280^lt[n>>>0&255]&255^this.roundkey[40],p=lt[n>>>24&255]&4278190080^lt[e>>>16&255]&16711680^lt[i>>>8&255]&65280^lt[r>>>0&255]&255^this.roundkey[41],m=lt[r>>>24&255]&4278190080^lt[n>>>16&255]&16711680^lt[e>>>8&255]&65280^lt[i>>>0&255]&255^this.roundkey[42],g=lt[i>>>24&255]&4278190080^lt[r>>>16&255]&16711680^lt[n>>>8&255]&65280^lt[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 Hm=(t,e,n)=>{let r=!1,i=0;const s=2**16,a=16,o=new Yl;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 Mo extends Dn{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 Om({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,ei,Li);if(ie(i)&&(i=await i),!i)break;const s=e,a=nr(i);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=Ve(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-Li){let o=this.reader.requestSliceRange(a,ei,Li);if(ie(o)&&(o=await o),o){const c=nr(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!==Mo)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 Zl(s),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){const s=i;i.trackBacking=new Jl(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&&js.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){R(e.info?.type==="audio");const s=Rm(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=Mt(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,ei,Li);ie(n)&&(n=await n),R(n);const r=nr(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 nu(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-ei&&this.traverseBox(e););}*iterateContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-ei;){const r=e.filePos,i=nr(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=r+i.totalSize}}traverseBox(e){const n=e.filePos,r=nr(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=Ht(e)):(e.skip(8),this.movieTimescale=ae(e),this.movieDurationInTimescale=ae(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...Fn,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Tt,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 Zl(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new Jl(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=de(e),u=!!(Hn(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=Ht(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const l=[Sr(e),Sr(e),Co(e),Sr(e),Sr(e),Co(e),Sr(e),Sr(e),Co(e)],f=Wa(Ka(qm(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?Ht(e):ae(e),h=o===1?Tg(e):Mr(e),p=Sr(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=Ht(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;ul(a.languageCode)||(a.languageCode=Tt)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=Ve(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...il},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=nr(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":To.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=ff(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=qs;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(zl.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=Ve(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=Ve(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=Ci(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=wo(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=Ve(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:Mn[c],transfer:Bn[u],matrix:Rn[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),Io(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=Io(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=Io(e);if(a.info.codecDescription=me(e,w),a.info.codec==="aac"){const y=ml(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=nc(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=Hn(e);if((p&o)===Zr.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=Ds[u]),a.info.numberOfChannels=Ao[l]+f}break;case"dec3":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio");const o=me(e,r.contentSize),c=bm(o);if(!c){pe._warn("Invalid dec3 box contents, ignoring.");break}const u=El(c);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=Cl(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;R(a.info?.type==="audio");const o=me(e,Math.min(r.contentSize,Ml)),c=Mm(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=Mr(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=Ht(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?Ht(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,Hn,ae],p=h[l],m=h[f],g=h[d],w=ae(e);for(let y=0;y<w;y++){const b=a===1?Ht(e):ae(e),v=a===1?Ht(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[Mt(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=Xl(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=Hn(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=Ht(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):Ht(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=Hn(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=Mr(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=Mr(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),Hn(e)&1){const d=Ve(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=tu(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(Hn(e)&1){const d=Ve(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(Ht(e));this.currentFragment&&(l+=this.currentFragment.moofOffset);const f=tu(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=!!(Hn(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]??=mn(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=Bt.decode(me(c,o.contentSize)):this.metadataTags.title??=mn(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=mn(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=mn(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=mn(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=mn(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=mn(c));break;case"\xA9day":if(!this.currentTrack){const u=new Date(mn(c));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=mn(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=mn(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=Bt.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=Um(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 Fs?(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=Ie(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=Ie(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 Kl{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 Bi(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!eu(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=Vm(i,r),a=await this.fetchPacketForSampleIndex(s,n);return!eu(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=Ya(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=jm(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=Wm(r,e);if(!i)return null;let s;if(n.metadataOnly)s=Ut;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 nu(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<f.length&&(l=f[e])}l??=ru(this.internalTrack.encryptionInfo),l&&(s=await iu(this.internalTrack,l,s,null))}}const a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new Qe(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=Ut;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??ru(this.internalTrack.encryptionInfo);f&&(a=await iu(this.internalTrack,f,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,u=new Qe(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,ei,Li);if(ie(g)&&(g=await g),!g)break;const w=m,y=nr(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 Zl extends Kl{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&&go(n.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=n&&bo(n.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!cm(this.internalTrack.info.vp9CodecInfo))){const n=await this.getFirstPacket({}),r=n&&Tl(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||!lm(this.internalTrack.info.av1CodecInfo))){const n=await this.getFirstPacket({}),r=n&&wo(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&&Pl(n.data)}if(!$a(this.internalTrack.info.colorSpace)){const n=Hl(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:So(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 Jl extends Kl{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&&Rl(e.data)}return{codec:Po(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)}},Vm=(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(Ii(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}},Wm=(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?Ii(t.keySampleIndices,e,w=>w)!==-1:!0}},jm=(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},qm=t=>{const[e,n]=t,r=Math.atan2(n,e);return Number.isFinite(r)?r*(180/Math.PI):0},eu=t=>t.sampleSizes.length===0,tu=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},nu=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},ru=t=>t.defaultConstantIv?{iv:t.defaultConstantIv,subsamples:null}:null,iu=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++)Gl(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&&Oh.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:Uh(l)})();t.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?Xm(a,i,e,n):Gm(a,i,e,n)},Xm=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=su(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},Gm=(t,e,n,r)=>{const i=new Yl;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=su(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},su=(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 $m=[re.EBML,re.Segment],Oi=[re.SeekHead,re.Info,re.Cluster,re.Tracks,re.Cues,re.Attachments,re.Chapters,re.Tags],Gs=[...$m,...Oi],Fo=8,Xt=2,Ln=2*Fo,au=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},Ui=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},Ae=(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},Qm=(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=au(t);return e===null||t.remainingLength<e?null:Ae(t,e)},ou=t=>{if(t.remainingLength<1)return null;if(de(t)===255)return;t.skip(-1);const n=Ui(t);if(n===null)return null;if(n!==72057594037927940)return n},On=t=>{R(t.remainingLength>=Xt);const e=Do(t);if(e===null)return null;const n=ou(t);return n===null?null:{id:e,size:n}},si=(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))},zi=(t,e)=>{const n=me(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return Bt.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?Pg(t):ff(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,Xt,Ln);if(ie(a)&&(a=await a),!a)break;const o=On(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};rr(o.size),s=a.filePos+o.size}return{pos:r!==null&&r>s?r:s,found:!1}},cu=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},Rt={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 rr(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const Ym=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 Un;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Un||(Un={}));var $s;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})($s||($s={}));var Hi;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Hi||(Hi={}));const Oo=[{id:re.SeekHead,flag:"seekHeadSeen"},{id:re.Info,flag:"infoSeen"},{id:re.Tracks,flag:"tracksSeen"},{id:re.Cues,flag:"cuesSeen"}],lu=10*2**20;class Km extends Dn{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 Ym({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,Xt,Ln);if(ie(n)&&(n=await n),!n)break;const r=On(n);if(!r)break;const i=r.id;let s=r.size;const a=n.filePos;if(i===re.EBML){rr(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,Gs,this.reader.fileSize)).pos-a);const o=Mt(this.segments);o&&(o.elementEndPos=a+s)}rr(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,Xt,Ln);if(ie(o)&&(o=await o),!o)break;const c=r,u=On(o);if(!u||!Oi.includes(u.id)&&u.id!==re.Void){const p=await cu(this.reader,c,Oi,Math.min(this.currentSegment.elementEndPos??1/0,c+lu));if(p){r=p;continue}else break}const{id:l,size:f}=u,d=o.filePos,h=Oo.findIndex(p=>p.id===l);if(h!==-1){const p=Oo[h].flag;this.currentSegment[p]=!0,rr(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,rr(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=Oo.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,Xt,Ln);if(ie(u)&&(u=await u),!u)continue;const l=On(u);if(!l)continue;const{id:f,size:d}=l;if(f!==c.id)continue;rr(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,Xt,Ln);ie(r)&&(r=await r),R(r);const i=e,s=On(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,Gs,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,Gs);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!==Un.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===Un.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[Mt(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===Un.None)continue;i.decoded||(i.data=this.decodeBlockData(n,i.data),i.decoded=!0);const s=tn.tempFromBytes(i.data),a=[],o=de(s)+1;switch(i.lacing){case Un.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 Un.FixedSize:{const u=s.length-1,l=Math.floor(u/o);for(let f=0;f<o;f++)a.push(l)}break;case Un.Ebml:{const u=Ui(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=Ui(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:Un.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,Xt,Ln);if(ie(r)&&(r=await r),!r)continue;const i=On(r);if(!i||i.id!==n.id)continue;const{size:s}=i;rr(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>=Xt;){const r=e.filePos;if(!this.traverseElement(e,n))return r}return e.filePos}traverseElement(e,n){const r=On(e);if(!r||n&&n.includes(r.id))return!1;const{id:i,size:s}=r,a=e.filePos;switch(rr(s),i){case re.DocType:this.isWebM=si(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=Ae(e,s)}break;case re.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Ae(e,s)}break;case re.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Ae(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:{...Fn,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!==$s.Block||o.data.algorithm!==Hi.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===Rt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Rt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===Rt.vp8)this.currentTrack.info.codec="vp8";else if(c===Rt.vp9)this.currentTrack.info.codec="vp9";else if(c===Rt.av1)this.currentTrack.info.codec="av1";else if(c===Rt.prores){const l=this.currentTrack.codecPrivate?Bt.decode(this.currentTrack.codecPrivate):"";To.includes(l)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=l)}const u=this.currentTrack;this.currentTrack.trackBacking=new Zm(u),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Rt.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===Rt.mp3?this.currentTrack.info.codec="mp3":c===Rt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=qs):c===Rt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Rt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Rt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Rt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Rt.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 Jm(u),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case re.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Ae(e,s)}break;case re.TrackType:{if(!this.currentTrack)break;const o=Ae(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:{...il},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;Ae(e,s)||(this.currentTrack=null)}break;case re.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ae(e,s)}break;case re.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ae(e,s)}break;case re.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ae(e,s)}break;case re.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ae(e,s)}break;case re.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ae(e,s)}break;case re.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ae(e,s)}break;case re.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=si(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=Ae(e,s)}break;case re.Name:{if(!this.currentTrack)break;this.currentTrack.name=zi(e,s)}break;case re.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=si(e,s),ul(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Tt)}break;case re.LanguageBCP47:{if(!this.currentTrack)break;const c=si(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Tt,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=Ae(e,s)}break;case re.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Ae(e,s)}break;case re.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Ae(e,s)}break;case re.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Ae(e,s)}break;case re.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Ae(e,s)}break;case re.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Ae(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=Ae(e,s),c=Rn[o];this.currentTrack.info.colorSpace.matrix=c}break;case re.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=Ae(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=Ae(e,s),c=Bn[o];this.currentTrack.info.colorSpace.transfer=c}break;case re.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=Ae(e,s),c=Mn[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=Wa(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=Ae(e,s)}break;case re.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Ae(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=Ae(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=Ae(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+Ae(e,s)}break;case re.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Ae(e,s)}break;case re.SimpleBlock:{if(!this.currentCluster)break;const o=Ui(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=nc(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=Ui(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const u=nc(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=Ae(e,s)}break;case re.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Ae(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:Ae(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=zi(e,s);break;case re.TagString:{if(!this.currentSimpleTagName)break;const o=zi(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 Yh(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=Qm(e,s)}break;case re.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=zi(e,s)}break;case re.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=si(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=zi(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:$s.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=Ae(e,s)}break;case re.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ae(e,s)}break;case re.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Hi.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case re.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Ae(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 Hi.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 uu{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 Bi(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=Ya(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);Ie(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?Ut: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?Ut:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);const l=new Qe(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-Xt;){if(c){const S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>i)break}let w=a.reader.requestSliceRange(g,Xt,Ln);if(ie(w)&&(w=await w),!w)break;const y=g,b=On(w);if(!b||!Oi.includes(b.id)&&b.id!==re.Void){const S=await cu(a.reader,y,Oi,Math.min(o.elementEndPos??1/0,y+lu));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,Gs,o.elementEndPos)).pos-A);const T=A+k;if(o.elementEndPos===null){let S=a.reader.requestSliceRange(T,Xt,Ln);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 Zm extends uu{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?go(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?bo(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Tl(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?wo(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Pl(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!$a(this.internalTrack.info.colorSpace)){const s=Hl(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:So(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 Jm extends uu{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&&Rl(e.data)}return{codec:Po({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 Uo=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,Tr,a);if(ie(o)&&(o=await o),!o||o.length<Tr)break;for(;o.remainingLength>=Tr;){const c=o.filePos,u=ae(o),l=t.fileSize!==null?t.fileSize-s:null,f=_o(u,l);if(f.header&&(!r||f.header.sampleRate===r.sampleRate&&f.header.mpegVersionId===r.mpegVersionId&&f.header.layer===r.layer&&Ni(f.header.channel)===Ni(r.channel)))return{header:f.header,startPos:s};o.filePos=c+f.bytesAdvanced,s=o.filePos}}return null};class ep extends Dn{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 Cs,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 tp(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Gt);if(ie(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=Vn(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Uo(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=ql(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===Wl||o===jl){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=Ie(l),d=f.getUint32(0,!1);this.xingData={frameCount:d&Xs.FrameCount?f.getUint32(4,!1):null,fileSize:d&Xs.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,Gt);if(ie(i)&&(i=await i),!i)break;const s=Vn(i);if(!s)break;r=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(ie(a)&&(a=await a),!a)break;na(a,s,this.metadataTags),n=i.filePos+s.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=ta){let i=this.reader.requestSlice(this.reader.fileSize-ta,ta);ie(i)&&(i=await i),R(i),Ve(i,3)==="TAG"&&_g(i,this.metadataTags)}return this.metadataTags}finally{e()}}}class tp{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=Lm(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 Tt}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return R(this.demuxer.firstFrameHeader),Ni(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return R(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Fn}}async getDecoderConfig(){return R(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Ni(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=Ut;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 Qe(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=Ii(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 fu=1399285583,np=79764919,du=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^np:e<<1;du[t]=e>>>0&4294967295}const rp=t=>{const e=Ie(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^du[r>>>24^s])>>>0}return e.setUint32(22,n,!0),r},ip=(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<<Wh(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=dm(t).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},sp=t=>{let e="audio/ogg";if(t.codecStrings){const n=[...new Set(t.codecStrings)];e+=`; codecs="${n.join(", ")}"`}return e};const Pr=27,ai=282,ap=ai+65025,Vi=t=>{const e=t.filePos;if(di(t)!==fu)return null;t.skip(1);const r=de(t),i=Sg(t),s=di(t),a=di(t),o=di(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}},op=(t,e)=>{for(;t.filePos<e-3;){const n=di(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===fu)return!0;t.skip(1)}}return!1};class cp extends Dn{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,Pr,ai);if(ie(n)&&(n=await n),!n)break;const r=Vi(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 lp(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=Ie(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:hm(s.data).modeBlockflags},ko(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=um(e.data);n.numberOfChannels=s.outputChannelCount,n.sampleRate=qs,n.codecInfo.opusInfo={preSkip:s.preSkip},ko(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,Pr,ai);if(ie(p)&&(p=await p),!p)return null;const m=Vi(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,Pr,ai);if(ie(i)&&(i=await i),!i)return null;const s=Vi(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 sp({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class lp{constructor(e,n){this.bitstream=e,this.demuxer=n,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Cs,this.internalSampleRate=e.codecInfo.codec==="opus"?qs: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 Tt}getDisposition(){return{...Fn,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}=ip(e.data,this.bitstream.codecInfo,n.vorbisLastBlocksize),a=new Qe(r.metadataOnly?Ut: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=Bi(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+ap,a-Pr);let A=this.demuxer.reader.requestSlice(v,k-v);if(ie(A)&&(A=await A),R(A),!op(A,k)){a=b+Pr;continue e}let S=this.demuxer.reader.requestSliceRange(A.filePos,Pr,ai);ie(S)&&(S=await S),R(S);const P=Vi(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 U=me(N,P.totalSize);M=rp(U)===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,Pr,ai);ie(b)&&(b=await b),R(b);const v=Vi(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:Ut,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(y)){const v=mu(l,u,f);R(v);const k=hu(l,v.page,v.segmentIndex);k&&(u=k.page,f=k.segmentIndex)}else for(;;){const v=mu(l,u,f);if(!v)break;const k=hu(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=Bi(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(Mt(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 hu=(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=ol(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}},mu=(t,e,n)=>{if(n>0)return{page:e,segmentIndex:n-1};const r=ol(t,i=>i.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var St;(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"})(St||(St={}));class up extends Dn{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=Ve(e,4),r=n!=="RIFX",i=n==="RF64",s=ir(e,r);let a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(Ve(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=Ve(d,4),p=ir(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=uf(g,r);u=uf(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 fp(this))})()}async parseFmtChunk(e,n,r){let i=this.reader.requestSlice(e,n);if(ie(i)&&(i=await i),!i)return;let s=Ki(i,r);const a=Ki(i,r),o=ir(i,r);i.skip(4);const c=Ki(i,r);let u;if(n===14?u=8:u=Ki(i,r),n>=18&&s!==357){const l=Ki(i,r),f=n-18;if(Math.min(f,l)>=22&&s===St.EXTENSIBLE){i.skip(6);const h=me(i,16);s=h[0]|h[1]<<8}}if((s===St.MULAW||s===St.ALAW)&&(u=8),s!==St.PCM&&s!==St.IEEE_FLOAT&&s!==St.ALAW&&s!==St.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===St.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===St.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=Ve(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+n-8;){i.filePos=a;const o=Ve(i,4),c=ir(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=Vn(r);if(i){const s=n-Gt;if(i.size=Math.min(i.size,s),i.size>0){const a=r.slice(e+Gt,i.size);na(a,i,this.metadataTags)}}}getCodec(){if(R(this.audioInfo),this.audioInfo.format===St.MULAW)return"ulaw";if(this.audioInfo.format===St.ALAW)return"alaw";if(this.audioInfo.format===St.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===St.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 oi=2048;class fp{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 Tt}getDisposition(){return{...Fn}}async getPacketAtIndex(e,n){R(e>=0),R(this.demuxer.audioInfo);const r=e*oi*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(oi*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=Ut;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*oi/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 Qe(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/oi,(this.demuxer.dataSize-1)/(oi*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/oi);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,ci=9,Wi=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 Qs=1024;class dp extends Dn{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Cs,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 hp(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Gt);if(ie(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=Vn(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,zo,ci);if(ie(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const n=Wi(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=Fi[n.samplingFrequencyIndex];R(r!==void 0);const i=Qs/r,s={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Qs,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,Gt);if(ie(r)&&(r=await r),!r)break;const i=Vn(r);if(!i)break;let s=this.reader.requestSlice(r.filePos,i.size);if(ie(s)&&(s=await s),!s)break;na(s,i,this.metadataTags),n=r.filePos+i.size}return this.metadataTags}finally{e()}}}class hp{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Qs}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 Tt}getCodec(){return"aac"}getInternalCodecId(){return R(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){R(this.demuxer.firstFrameHeader);const e=fo[this.demuxer.firstFrameHeader.channelConfiguration];return R(e!==void 0),e}getSampleRate(){R(this.demuxer.firstFrameHeader);const e=Fi[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return R(e!==void 0),e}getDisposition(){return{...Fn}}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=Ut;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 Qe(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=Ii(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 mp=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,pp=(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}},gp=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)},yp=(t,e)=>{if(e==="uncommon-u16")return $e(t)+1;if(e==="uncommon-u8")return de(t)+1;if(typeof e=="number")return e;Is(e),R(!1)},bp=(t,e)=>e==="uncommon-u16"?$e(t):e==="uncommon-u16-10"?$e(t)*10:e==="uncommon-u8"?de(t):typeof e=="number"?e:null,wp=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 vp extends Dn{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 Cs,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,Gt);if(ie(n)&&(n=await n),!n){this.lastSampleLoaded=!0;return}const r=Vn(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);ie(i)&&(i=await i),R(i),na(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=Hn(n),s=(r&128)!==0;switch(r&127){case Zr.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 kp(this);break}case Zr.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);ie(o)&&(o=await o),R(o),ko(me(o,i),this.metadataTags);break}case Zr.PICTURE:{let o=this.reader.requestSlice(e,i);ie(o)&&(o=await o),R(o);const c=ae(o),u=ae(o),l=Bt.decode(me(o,u)),f=ae(o),d=Bt.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=mp(s.readBits(4));if(!o)return null;R(this.audioInfo);const c=pp(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const l=gp(e),f=yp(e,o),d=bp(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=wp(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 kp{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 Tt}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{...Fn}}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=Ut;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 Qe(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 Jt=9e4,Ho=2**33,zt=188,Ap=t=>{let e="video/MP2T";const n=[...new Set(t.filter(Boolean))];return n.length>0&&(e+=`; codecs="${n.join(", ")}"`),e};const pu="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.",gu=5,xp=1212435798,Tp=1212436562,Sp=1146376960,Pp=new Set([133,134,162]),yu=new Set;class _p extends Dn{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=zt+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[zt]===71)this.packetOffset=0,this.packetStride=zt;else if(r[0]===71&&r[zt+16]===71)this.packetOffset=0,this.packetStride=zt+16;else if(r[4]===71&&r[4+zt+4]===71)this.packetOffset=4,this.packetStride=zt+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===gu&&A>=4){const S=m.readBits(32);v||=S===xp||S===Tp}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===gu&&H>=4){const Y=m.readBits(32);B||=(Y&4294967040)===Sp}m.pos=G}let N=null;const U=v&&Pp.has(k)?130:k;switch(U){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;U===3||U===4?q="mp3":U===15?q="aac":U===129?q="ac3":U===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:yu.has(k)||(pe._warn(`Note: MPEG-TS streams with stream_type 0x${k.toString(16)} are not currently supported.`),yu.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=li(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=go(w.suppliedPacket.data),!m.info.avcCodecInfo)continue;const b=m.info.avcCodecInfo.sequenceParameterSets[0];R(b);const v=Us(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:Mn[v.colourPrimaries],transfer:Bn[v.transferCharacteristics],matrix:Rn[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=bo(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=yo(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:Mn[k.colourPrimaries],transfer:Bn[k.transferCharacteristics],matrix:Rn[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},m.info.reorderSize=k.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:So({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=tn.tempFromBytes(w.suppliedPacket.data),b=Wi(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=fo[b.channelConfiguration],m.info.sampleRate=Fi[b.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const y=ae(tn.tempFromBytes(w.suppliedPacket.data)),b=_o(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=Ni(b.header.channel),m.info.sampleRate=b.header.sampleRate}else if(m.info.codec==="ac3"){const y=mm(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=Ao[y.acmod]+y.lfeon,m.info.sampleRate=Ds[y.fscod]}else if(m.info.codec==="eac3"){const y=ym(w.suppliedPacket.data);if(!y)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const b=El(y);if(b===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Cl(y),m.info.sampleRate=b}else if(m.info.codec==="dts"){const y=Bl(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:Po({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 Ep(u)):this.trackBackingEntries.push(new Cp(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 Ap(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(Ii(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,zt);if(ie(n)&&(n=await n),!n)return null;const r=me(n,zt);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*Jt;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 _r=(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(pu);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}},li=(t,e,n)=>{R(e.endPos!==null);const r=_r(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 Ys{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 Ys),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 Tt}getDisposition(){return{...Fn,primary:!1}}getTimeResolution(){return Jt}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 Qe(r.metadataOnly?Ut:e.data,i,e.pts/Jt,Math.max(n/Jt,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const n=this.elementaryStream.firstSection;R(n);const r=li(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=li(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=Bi(e*Jt),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=_r(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=_r(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<Jt/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=Za(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=Za(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=li(s,A,!0);R(T);const S=new ji(this.elementaryStream,T),P=new Wo(this,S);for(;!((Mt(P.presentationOrderPackets)?.pts??-1/0)>=i||!await P.readNextPacket()););const M=Ya(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 U=await P.readNext();R(U);const q=this.createEncodedPacket(U.packet,U.duration,r);return this.packetBuffers.set(q,P),this.packetSectionStarts.set(q,U.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=_r(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=_r(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 U=await u(v,a.fileSize??1/0,A);P=U?.pesPacketHeader??null,M=U?.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=li(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 U=P.sectionStartPos+s.packetStride;for(;;){const q=await s.readPacketHeader(U);if(!q)break e;if(q.pid===c&&q.payloadUnitStartIndicator===1){const H=await s.readSection(U,A);if(H){const G=_r(s,H,!1);if(G&&G.pts!==null){P=G,M=H,Vo(this.elementaryStream,P);break}}}U+=s.packetStride}}if(T){let U=T;if(N===0)e:for(let H=0;H<y;H++){let G=U.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=_r(s,J,!1);if(ne&&ne.pts!==null){U=ne;break}}}G-=s.packetStride}}const q=await b(U.sectionStartPos,H=>H.pts<=i&&H.randomAccessIndicator===1);return R(q),q}if(S)return null;k=v,v=Math.max(Za(v-f.sectionStartPos-o,s.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}}class Ep extends Ys{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 Cp extends Ys{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=Mt(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=li(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=Ls(S),M=P===ct.NON_IDR_SLICE||P===ct.SLICE_DPA||P===ct.IDR,B=P===ct.SEI||P===ct.SPS||P===ct.PPS||P===ct.AUD;else{if(P=Kr(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 U;if(n==="avc"){const q=l.subarray(k,k+A),H=le(new Ee(q));U=!a||H<=o,o=H}else U=l[k]>>7===1;U&&(a?N=!0:a=!0)}else B&&a&&(N=!0);if(N){const U=b-s;return this.seekTo(s),this.supplyPacket(U,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(ci);if(ie(c)&&(c=await c),c<ci)return;const u=this.readBytes(ci),l=Wi(tn.tempFromBytes(u));if(l){this.seekTo(o);let f=this.ensureBuffered(l.frameLength);return ie(f)&&(f=await f),this.supplyPacket(f,Math.round(Qs*Jt/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(Tr);if(ie(c)&&(c=await c),c<Tr)return;const u=this.readBytes(Tr),l=Ie(u).getUint32(0),f=_o(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*Jt/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=pm[3*f+l];R(d!==void 0),this.seekTo(o),c=this.ensureBuffered(d),ie(c)&&(c=await c);const h=Math.round(gm*Jt/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=_l[h];this.seekTo(o),c=this.ensureBuffered(f),ie(c)&&(c=await c);const m=p*256,g=Math.round(m*Jt/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(Hs);if(ie(c)&&(c=await c),c<Hs)return;const u=this.readBytes(Hs),l=Fl(u);let f=l?null:Ws(u);if(!l&&!f){this.seekTo(o+1);continue}if(f&&!f.asset){this.seekTo(o);const m=Math.min(f.frameSize,vm);let g=this.ensureBuffered(m);ie(g)&&(g=await g),f=Ws(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+xo;let w=this.ensureBuffered(g);if(ie(w)&&(w=await w),w<g)break;this.seekTo(o+m);const y=Ws(this.readBytes(xo));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*Jt/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(pu);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=vo(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 bu="application/vnd.apple.mpegurl",wu="#EXT-X-STREAM-INF:",vu="#EXT-X-I-FRAME-STREAM-INF:",ku="#EXT-X-MEDIA:",jo="#EXTINF:",Au="#EXT-X-MAP:",xu="#EXT-X-KEY:",Tu="#EXT-X-MEDIA-SEQUENCE:",Su="#EXT-X-BYTERANGE:",Pu="#EXT-X-PROGRAM-DATE-TIME:",Ip="#EXT-X-DISCONTINUITY",_u="#EXT-X-TARGETDURATION:",Mp="#EXT-X-ENDLIST",Eu="#EXT-X-PLAYLIST-TYPE:",Bp="#EXT-X-I-FRAMES-ONLY",Cu=t=>t.length===0||t.startsWith("#")&&!t.startsWith("#EXT");class qi{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 Rp{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=Ri(e,i=>i.getType()==="video")+1;e.push(new Mu(this,n,r))}else if(n.type==="audio"){const r=Ri(e,i=>i.getType()==="audio")+1;e.push(new Bu(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=Ri(e,a=>a.getType()==="video")+1;e.push(new Mu(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){const s=Ri(e,a=>a.getType()==="audio")+1;e.push(new Bu(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 Iu{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:ll(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 Mu extends Iu{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 Bu extends Iu{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())}}oo();const Ru=0,Fu=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});class zn extends uo{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 gt;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Ru,Fu),e=this._getFileSize(),R(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new gt;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 Hp(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 ui extends zn{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 zn||i instanceof qo))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=i instanceof zn?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return ie(n)?n.then(r):r(n)}}const Du=(t,e)=>t.path===e.path;class Fp extends ui{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 zn?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 Dp=.5*2**20,Np=(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)},Nu=new Set;class Xo extends ui{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&&(!Ms(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 Xo(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??Np,this._requestInit={...n.requestInit};let i=null;if(n.requestInit?.headers){const a={...eo(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=Op(i);a&&(this._offset=a.offset,this._length=a.length)}const s=2;this._orchestrator=new zp({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:Up.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:Mi(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 dl(this._options.fetchFn??fetch,this._url,fl(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"))&&(Nu.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.`),Nu.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 Rs(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 Rs(1e3*d);const h=await dl(this._options.fetchFn??fetch,this._url,fl(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 Lu(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 Lp=/^bytes=(\d+)-(\d*)$/,Op=t=>{const e=Lp.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 Lu extends zn{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&&(!Ms(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:Ie(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=mt();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:Ie(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:r,end:i,bytes:n,view:Ie(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 gt);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Up={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(ao(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+Dp),{start:t,end:e}}};class zp{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:Ie(d),offset:e}),m.length===0)return R(c),c;const{promise:g,resolve:w,reject:y}=mt(),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:Ie(k),offset:e})),c}checkHoleAgainstWorker(e,n,r){if(ao(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:Ie(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||ao(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=Ie(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=Ie(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 gt);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 gt);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class Hp extends zn{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:Mi(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},Uu=(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 Vp=/^0[xX][0-9a-fA-F]+$/,Wp=/^data:.*;base64,/i;class zu extends Rp{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 Rs(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 ea(v.source).requestEntireFile();R(A),e=df(A,A.length,{ignore:Cu}),v.source instanceof ui&&(this.rootPath=v.source.rootPath)}catch(v){b.error=v,b.hasError=!0}finally{Uu(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=Mt(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(pn),M=Ie(P);M.setUint32(8,Math.floor(c/2**32)),M.setUint32(12,c),k={...k,iv:P}}const T={path:tr(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(Au)){const k=new qi(v.slice(Au.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:tr(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(xu)){const k=new qi(v.slice(xu.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(!Vp.test(P))throw new Error(`Unsupported IV format '${P}'.`);let B=P.slice(2);B=B.padStart(pn*2,"0"),S=new Uint8Array(pn);for(let N=0;N<pn;N++){const U=-pn*2+N;S[N]=parseInt(B.slice(U,U+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:tr(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(Wp.test(T)){const M=T.indexOf(","),B=hl(T.slice(M+1));if(B.length>=8&&B[4]===112&&B[5]===115&&B[6]===115&&B[7]===104){const N=Ie(B).getUint32(0);P=Xl(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(Tu)){const k=v.slice(Tu.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(Su)){const k=w(v.slice(Su.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(Pu)){if(g)continue;const k=v.slice(Pu.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=Mt(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===Ip)u=null;else if(v.startsWith(_u)){const k=v.slice(_u.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===Mp){this.streamHasEnded=!0;break}else v.startsWith(Eu)&&v.slice(Eu.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=>Gl(f,l))&&(u=[...u,l]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:u})})}},a=new Js({source:new Fp(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 ea(h.source),m=Hm(p,async()=>{const g={stack:[],error:void 0,hasError:!1};try{const w=Ou(g,await this.input._getSourceCached({path:d.keyUri,isRoot:!1},Ag),!1),b=await new ea(w.source).requestSlice(0,pn);if(!b)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:me(b,pn),iv:d.iv}}catch(w){g.error=w,g.hasError=!0}finally{Uu(g)}},()=>{h.free()});l=new Lu(m).ref()}else R(!1);return l}),formats:this.input._formats.filter(c=>!(c instanceof $u)),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=co(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 jp extends Dn{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 ui);const e=await this.input._reader.requestEntireFile();R(e);const n=df(e,e.length,{ignore:Cu}),{rootPath:r}=this.input._rootSource,i=[],s=[];for(let f=1;f<n.length;f++){const d=n[f];if(d.startsWith(wu)){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=tr(r,p),g=new qi(d.slice(wu.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(vu)){const h=new qi(d.slice(vu.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=tr(r,p);i.push({fullPath:g,attributes:h,lineNumber:f,hasOnlyKeyPackets:!0})}else if(d.startsWith(ku)){const h=new qi(d.slice(ku.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=tr(r,w)),s.push({fullPath:g,attributes:h,lineNumber:f})}else if(d!==Bp){if(d.startsWith(jo)){const h=new zu(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(U=>U.codec)))}const g=f.attributes.get("video"),w=f.attributes.get("audio"),y=m.some(P=>Dl.includes(Di(P))),b=m.some(P=>Nl.includes(Di(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=tr(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=tr(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=Di(P);if(M!==null){if(Dl.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 U=null,q=null;if(N){const H=N.match(/^(\d+)x(\d+)$/);H&&(U=Number(H[1]),q=Number(H[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Tt,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:U,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 U=N.attributes.get("group-id"),q=N.attributes.get("type");if(U!==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:Ks(N.attributes),autoselect:Ks(N.attributes)||ju(N.attributes),languageCode:qu(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(Nl.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"),U=N!==null?Number(N.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Tt,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:U!==null&&Number.isInteger(U)&&U>0?U: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 U=N.attributes.get("group-id"),q=N.attributes.get("type");if(U!==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:Ks(N.attributes),autoselect:Ks(N.attributes)||ju(N.attributes),languageCode:qu(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===Tt&&(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 Vu(f)):this.trackBackings.push(new Wu(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 zu(this,e,r,null),this.segmentedInputs.push(n),n}async getMetadataTags(){return{}}async getMimeType(){return bu}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Hu{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 Vu){for(const s of i)if(await s.getCodec()===this.getCodec()){n=s;break}}else{R(this instanceof Wu);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{...Fn,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 Vu extends Hu{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Di(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 Wu extends Hu{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Di(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 Ks=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}".`)},ju=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}".`)},qu=t=>{if(t===null)return Tt;const e=t.split("-")[0];return e||Tt};class gn{constructor(){this._isIsobmff=!1}}class Xu extends gn{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=Ve(n,4);return r!=="ftyp"&&r!=="styp"?null:Ve(n,4)}_createDemuxer(e){return new Mo(e)}}class qp extends Xu{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=Ht(u),o=16}if(a<o)return!1;const c=Ve(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 Xp extends Xu{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Gu extends gn{async isSupportedEBMLOfDocType(e,n){let r=e._reader.requestSlice(0,Ln);if(ie(r)&&(r=await r),!r)return!1;const i=au(r);if(i===null||i<1||i>8||Ae(r,i)!==re.EBML)return!1;const a=ou(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-Xt;){const u=On(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(Ae(o,f)!==1)return!1;break;case re.EBMLReadVersion:if(Ae(o,f)!==1)return!1;break;case re.DocType:if(si(o,f)!==n)return!1;break;case re.DocTypeVersion:if(Ae(o,f)>4)return!1;break}o.filePos=d+f}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Km(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Gp extends Gu{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class $p extends gn{async _canReadInput(e){let n=0;for(;;){let f=e._reader.requestSlice(n,Gt);if(ie(f)&&(f=await f),!f)break;const d=Vn(f);if(!d)break;n=f.filePos+d.size}const r=await Uo(e._reader,n,n+4096);if(!r)return!1;const i=r.header,s=ql(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===Wl||o===jl)return!0;n=r.startPos+r.header.totalSize;const u=await Uo(e._reader,n,n+Tr);if(!u)return!1;const l=u.header;return!(i.channel!==l.channel||i.sampleRate!==l.sampleRate)}_createDemuxer(e){return new ep(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Qp extends gn{async _canReadInput(e){let n=e._reader.requestSlice(0,12);if(ie(n)&&(n=await n),!n)return!1;const r=Ve(n,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(n.skip(4),Ve(n,4)==="WAVE")}_createDemuxer(e){return new up(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Yp extends gn{async _canReadInput(e){let n=e._reader.requestSlice(0,4);return ie(n)&&(n=await n),n?Ve(n,4)==="OggS":!1}_createDemuxer(e){return new cp(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Kp extends gn{async _canReadInput(e){let n=0;for(;;){let i=e._reader.requestSlice(n,Gt);if(ie(i)&&(i=await i),!i)break;const s=Vn(i);if(!s)break;n=i.filePos+s.size}let r=e._reader.requestSlice(n,4);return ie(r)&&(r=await r),r?Ve(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new vp(e)}}class Zp extends gn{async _canReadInput(e){let n=0;for(;;){let a=e._reader.requestSlice(n,Gt);if(ie(a)&&(a=await a),!a)break;const o=Vn(a);if(!o)break;n=a.filePos+o.size}let r=e._reader.requestSliceRange(n,zo,ci);if(ie(r)&&(r=await r),!r)return!1;const i=Wi(r);if(!i||(n+=i.frameLength,r=e._reader.requestSliceRange(n,zo,ci),ie(r)&&(r=await r),!r))return!1;const s=Wi(r);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new dp(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Jp extends gn{async _canReadInput(e){const n=zt+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[zt]===71||i[0]===71&&i[zt+16]===71?!0:i[4]===71&&i[4+zt+4]===71}_createDemuxer(e){return new _p(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class $u extends gn{async _canReadInput(e){let n=e._reader.requestSlice(0,7);if(ie(n)&&(n=await n),!n||!(Ve(n,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof ui))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 jp(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return bu}}const eg=[new $u,new qp,new Xp,new Gu,new Gp,new Qp,new Yp,new Kp,new $p,new Zp,new Jp],tg=(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 ng=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},rg=(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});oo();let Qu=-1/0,Yu=-1/0,Go=null;typeof FinalizationRegistry<"u"&&(Go=new FinalizationRegistry(t=>{const e=performance.now();t.type==="video"?(e-Qu>=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."),Qu=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Yu>=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."),Yu=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class Er{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const $o=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ig=new Set($o);class en{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(Qr*this.timestamp)}get microsecondDuration(){return Math.trunc(Qr*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||!ig.has(n.format))throw new TypeError("init.format must be one of: "+$o.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&&lo(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??og(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?In(e):In(e).slice(),this._layout=r,this.colorSpace=new Qo(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&&lo(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 Qo(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&&lo(n.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new en(new VideoFrame(e,{timestamp:Math.trunc(n.timestamp*Qr),duration:Math.trunc((n.duration??0)*Qr)||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:Xh(),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 Qo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Er){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&&!$o.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=Bs({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Go?.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 Er?new en(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Gi(this._data)?new en(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(R(this._layout),new en(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 en(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||(Go?.unregister(this),this._data instanceof Er?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Gi(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(tf(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 Gi(this._data)?this._data.allocationSize(e):nf(this,e).allocationSize}async copyTo(e,n={}){if(!Lh(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(tf(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),Gi(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 Er){const u={stack:[],error:void 0,hasError:!1};try{const l=ng(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},n.colorSpace??"srgb"),!1);if(!(l instanceof en))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{rg(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=nf(this,n);R(this.format);const i=In(e);if(i.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);const s=Zs(this.format);let a;if(this._data instanceof Er){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:In(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 Er){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 Gi(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&&ef(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=Ju(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?Zu(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 Er||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&&ef(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=Wa(this.rotation+(e.rotate??0)),[r,i]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=Ju(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=Ka(u,e.roundDimensionsTo??1),l=Ka(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 sg){let g=m(this,f);if(ie(g)&&(g=await g),g!==null)return g}const{canvas:d,context:h,isNew:p}=Zu(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 en(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 sg=[],ag=3,Xi=[];let Ku=0;const Zu=(t,e)=>{for(const i of Xi)if(i.canvas.width===t&&i.canvas.height===e)return i.age=Ku++,{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 Xi.length>=ag&&Xi.splice(co(Xi,i=>i.age),1),Xi.push({canvas:n,context:r,age:Ku++}),{canvas:n,context:r,isNew:!0}};class Qo{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(qa);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(Xa);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(Ga);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 Gi=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Ju=(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}},ef=(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.")},tf=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.")}},og=(t,e,n)=>{const r=Zs(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},Zs=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:Is(t),R(!1)}},nf=(t,e)=>{const n={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,i=cg(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 ug(i,a,s)},cg=(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(!lg(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},lg=(t,e)=>{if(t===null)return!0;const n=Zs(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},ug=(t,e,n)=>{const r=Zs(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 rf=[],fg=[];const Cr=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.")},fi=t=>{if(!Ms(t))throw new TypeError("timestamp must be a number.")},Yo=(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 Ko{constructor(e){if(!(e instanceof $i))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Cr(e),this._track.input._disposed)throw new gt;return Yo(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Cr(e);const n=await this.getFirstPacket(e);return n?n.type==="key"?n:this.getNextKeyPacket(n,e):null}async getPacket(e,n={}){if(fi(e),Cr(n),this._track.input._disposed)throw new gt;return Yo(this._track,this._track._backing.getPacket(e,n),n)}async getNextPacket(e,n={}){if(!(e instanceof Qe))throw new TypeError("packet must be an EncodedPacket.");if(Cr(n),this._track.input._disposed)throw new gt;return Yo(this._track,this._track._backing.getNextPacket(e,n),n)}async getKeyPacket(e,n={}){if(fi(e),Cr(n),this._track.input._disposed)throw new gt;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 Qe))throw new TypeError("packet must be an EncodedPacket.");if(Cr(n),this._track.input._disposed)throw new gt;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 Qe))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 Qe))throw new TypeError("endPacket must be an EncodedPacket.");if(Cr(r),this._track.input._disposed)throw new gt;const i=[];let{promise:s,resolve:a}=mt(),{promise:o,resolve:c}=mt(),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}=mt()),await o;continue}i.push(g),a(),{promise:s,resolve:a}=mt(),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 gt;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 dg{constructor(e,n){this.onSample=e,this.onError=n}}class hg{mediaSamplesInRange(e=-1/0,n=1/0,r){fi(e),fi(n);const i=[];let s=!1,a=null,{promise:o,resolve:c}=mt(),{promise:u,resolve:l}=mt(),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}=mt())},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=sf(i.length);if(i.length+p.getDecodeQueueSize()>P){({promise:u,resolve:l}=mt()),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 gt;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){Hh(e);const r=zh(e),i=[],s=[];let{promise:a,resolve:o}=mt(),{promise:c,resolve:u}=mt(),l=!1,f=!1,d=null,h=null,p=!1;const m=b=>{s.push(b),o(),{promise:a,resolve:o}=mt()},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=sf(s.length);for(;s.length+d.getDecodeQueueSize()>M&&!f;)({promise:c,resolve:u}=mt()),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(fi(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 gt;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 sf=t=>t===0?40:8;class mg extends dg{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 qh,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=rf.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 en))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(so()){if(r==="avc"&&this.decoderConfig.description){const l=vl(In(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const f=Us(l.sequenceParameterSets[0]);f&&f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}$a(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),no()||al(this.inputTimestamps,e.timestamp,n=>n),so()&&this.currentPacketIndex===0){if(this.codec==="avc"){const n=[];let r=!1;for(const s of yl(e.data,this.decoderConfig)){const a=Ls(e.data[s.offset]);if(r||=a>=1&&a<=5,a===ct.AUD){if(r)break;n.length=0}a>=20&&a<=31||n.push(e.data.subarray(s.offset,s.offset+s.length))}const i=Kh(n,this.decoderConfig);e=new Qe(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const n=am(e.data,this.decoderConfig);n&&(e=new Qe(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 pg),!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=vo(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 zs(e,this.decoderConfig)){const r=Kr(e[n.offset]);if(r===Ge.RASL_N||r===Ge.RASL_R)return!0}return!1}sampleHandler(e){if(no()){if(this.sampleQueue.length>0&&e.timestamp>=Mt(this.sampleQueue).timestamp){for(const n of this.sampleQueue)this.finalizeAndEmitSample(n);this.sampleQueue.length=0}al(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=mt();this.mergeAlphaPromises.push(r.promise);const i={sample:null};this.finalSamples.push(i);try{if(!n)i.sample=new en(e);else{R(this.merger);const s=await this.merger.merge(e,n);i.sample=new en(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Qa(this.finalSamples,i),this.onError(s)}finally{Qa(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),no()){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 Zo=null;class pg{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,n){if(this.workers.length===0){if(!Zo){const o=new Blob([`(${gg.toString()})()`],{type:"application/javascript"});Zo=URL.createObjectURL(o)}const a=Mi(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(Zo);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=mt();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 gg=()=>{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)}},yg=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 hg{constructor(e,n={}){if(!(e instanceof ec))throw new TypeError("videoTrack must be an InputVideoTrack.");yg(n),super(),this._track=e,this._decoderOptions=n}async _createDecoder(e,n){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Gh("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 mg(e,n,r,s,i,a)}_createPacketSink(){return new Ko(this._track)}async getSample(e,n={}){fi(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 $i{constructor(e,n){this.input=e,this._backing=n}isVideoTrack(){return this instanceof ec}isAudioTrack(){return this instanceof af}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Ue(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Ue(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Ue(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Ue(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 Ue(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 ll(r,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,n){const r=new Ko(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 $i))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(Ir({filter:n=>n.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Ir({filter:n=>n.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Ir({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Ir({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Ir({filter:n=>n.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Jo(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&&=Jo(e),this.hasPairableTrack(async n=>n.isVideoTrack()&&(!e||await e(n)))}hasPairableAudioTrack(e){return e&&=Jo(e),this.hasPairableTrack(async n=>n.isAudioTrack()&&(!e||await e(n)))}}const Ue=(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},Jo=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 ec extends $i{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 Ue(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 Ue(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Ue(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Ue(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Ue(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Ue(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Bs({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Bs({num:Ue(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Ue(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Ue(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Ue(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=Ue(e,"displayWidth","getDisplayWidth");if(i!==null)return i}const r=Ue(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Ue(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=Ue(e,"displayHeight","getDisplayHeight");if(i!==null)return i}const r=Ue(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Ue(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),rf.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 Qe))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),vo(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&&(!Ms(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 Ko(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=wg(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:vg(P),minFrameRate:d/g,maxFrameRate:d/m,averageFrameRate:d*y/w,medianFrameRate:P,frameRateIsConstant:f!==null&&m===1&&g===1,probedPacketCount:o}}}class af extends $i{constructor(e,n){super(e,n),this._backing=n}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Ue(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Ue(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Ue(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),fg.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 Qe))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const of=t=>-(t??-1/0),Qi=t=>-t,Yi=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}},Ir=(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}),tc=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)},wg=(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=cf(p,m,1e6),S=cf(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},cf=(t,e,n)=>{for(let r=1;r<=n;r++){const i=Math.floor(t*r)+1;if(i/r<e)return Bs({num:i,den:r})}return null},vg=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};oo();const kg=1,Ag=2;class Js extends uo{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 zn||e.source instanceof qo))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof zn&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Js))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&tg(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof zn?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 ui);const n=await this._rootSource._resolveRequest(e);return this._emit("source",{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=kg){const r=this._sourceCache.find(a=>a.cacheGroup===n&&Du(a.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const i=this._sourceCachePromises.find(a=>a.cacheGroup===n&&Du(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(Ri(this._sourceCache,f=>f.cacheGroup===n&&f.sourceRef.source._refCount===1)>=4){const f=co(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(),Qa(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 ea(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 lf})()}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 lf)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&&=Yi(e);const r=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return tc(r,e)}async getVideoTracks(e){e&&=Yi(e);const r=(await this.getTracks()).filter(i=>i.isVideoTrack());return tc(r,e)}async getAudioTracks(e){e&&=Yi(e);const r=(await this.getTracks()).filter(i=>i.isAudioTrack());return tc(r,e)}async getPrimaryVideoTrack(e){e&&=Yi(e);const n=Ir(e,{sortBy:async i=>[Qi((await i.getDisposition()).default),Qi(await i.hasPairableAudioTrack()),Qi(!await i.hasOnlyKeyPackets()),of(await i.getBitrate())]});return(await this.getVideoTracks(n))[0]??null}async getPrimaryAudioTrack(e){e&&=Yi(e);const n=await this.getPrimaryVideoTrack(),r=Ir(e,{sortBy:async s=>[Qi(!n||s.canBePairedWith(n)),Qi((await s.getDisposition()).default),of(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 ec(this,e):new af(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 lf extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class gt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class ea{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 gt;if(e<0||this.fileSizeNonStrict!==null&&e+n>this.fileSizeNonStrict)return null;if(n===0){const s=new Uint8Array(0);return new tn(s,Ie(s),0,e,e)}const r=e+n,i=this.source._read(e,r,Ru,Fu);return ie(i)?i.then(s=>s?new tn(s.bytes,s.view,s.offset,e,r):null):i?new tn(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new gt;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Mi(this.fileSizeNonStrict-e,n,r));{const i=this.requestSlice(e,r),s=a=>a||(R(this.fileSizeNonStrict!==null),this.requestSlice(e,Mi(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 tn(i,Ie(i),0,0,r)})()}}class tn{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 tn(e,Ie(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 tn(this.bytes,this.view,this.offset,e,e+n)}}const Ft=(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)=>{Ft(t,e);const n=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,n},de=t=>(Ft(t,1),t.view.getUint8(t.bufferPos++)),Ki=(t,e)=>{Ft(t,2);const n=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,n},$e=t=>{Ft(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},Hn=t=>{Ft(t,3);const e=cl(t.view,t.bufferPos);return t.bufferPos+=3,e},nc=t=>{Ft(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},ir=(t,e)=>{Ft(t,4);const n=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,n},ae=t=>{Ft(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},di=t=>{Ft(t,4);const e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},Mr=t=>{Ft(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},xg=t=>{Ft(t,4);const e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},uf=(t,e)=>{let n,r;return e?(n=ir(t,!0),r=ir(t,!0)):(r=ir(t,!1),n=ir(t,!1)),r*4294967296+n},Ht=t=>{const e=ae(t),n=ae(t);return e*4294967296+n},Tg=t=>{const e=Mr(t),n=ae(t);return e*4294967296+n},Sg=t=>{const e=di(t);return xg(t)*4294967296+e},Pg=t=>{Ft(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},ff=t=>{Ft(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},Ve=(t,e)=>{Ft(t,e);let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t.bytes[t.bufferPos++]);return n},df=(t,e,n)=>Bt.decode(me(t,e)).split(`
|
|
2
|
-
`).map(s=>s.trim()).filter(s=>s.length>0&&!n?.ignore?.(s));var Br;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(Br||(Br={}));var hi;(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"})(hi||(hi={}));const ta=128,Gt=10,mi=["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"],_g=(t,e)=>{const n=t.filePos;e.raw??={},e.raw.TAG??=me(t,ta-3),t.filePos=n;const r=pi(t,30);r&&(e.title??=r);const i=pi(t,30);i&&(e.artist??=i);const s=pi(t,30);s&&(e.album??=s);const a=pi(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=pi(t,28),t.skip(2)}else t.skip(-30),u=pi(t,30);u&&(e.comment??=u);const l=de(t);l<mi.length&&(e.genre??=mi[l])},pi=(t,e)=>{const n=me(t,e),r=Yr(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()},Vn=t=>{const e=t.filePos,n=Ve(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=Eo(a);return s&Br.Footer&&(o+=Gt),{majorVersion:r,revision:i,flags:s,size:o}},na=(t,e,n)=>{if(![2,3,4].includes(e.majorVersion)){pe._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const r=e.flags&Br.Footer?e.size-Gt:e.size,i=me(t,r),s=new Eg(e,i);if(e.flags&Br.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Br.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&Br.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(mi[p]!==void 0){n.genre??=mi[p];break}}if(h=/^\d+$/.exec(d),h){const p=Number.parseInt(h[0]);if(mi[p]!==void 0){n.genre??=mi[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 Eg{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?Eo(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:Eo(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 hi.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 hi.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){const s=new TextDecoder("utf-16le"),a=Yr(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=Yr(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=Yr(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Bt.decode(i.subarray(0,s))}case hi.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Yr(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 hi.UTF_8:{const s=Yr(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Bt.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const n=this.readId3V2TextEncoding();return this.readId3V2Text(n,e)}}function hf(){return typeof VideoDecoder=="function"&&typeof VideoFrame=="function"}const mf=6,pf=16;function Cg(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)),U=Math.max(1,Math.round((t.container.clientHeight||window.innerHeight)*B));e.width!==N&&(e.width=N),e.height!==U&&(e.height=U)};c(),window.addEventListener("resize",c);const u=[];let l=null,f=null,d=null,h=0,p=0,m=mf,g=0,w=!1,y=-1,b=0,v=!1;const k=B=>{const N=e.width,U=e.height,q=B.displayWidth,H=B.displayHeight;if(N<=0||U<=0||q<=0||H<=0)return;const G=t.fit();if(G==="stretch"){B.draw(n,0,0,N,U);return}const Y=G==="cover"?Math.max(N/q,U/H):Math.min(N/q,U/H),J=Math.round(q*Y),ne=Math.round(H*Y),fe=Math.round((N-J)/2),Ne=Math.round((U-ne)/2);G==="contain"&&(n.fillStyle="#000",n.fillRect(0,0,N,U)),B.draw(n,fe,Ne,J,ne)},A=()=>h+(performance.now()-s)/1e3%p,T=()=>{g++,m<pf&&g%30===1&&(m=Math.min(pf,m+2),!w&&m>=mf+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 U=t.fps(),q=performance.now();if(!(U>0&&q-b<1e3/U-.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 Js({source:new Xo(t.src),formats:eg});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 U=await B.getDisplayWidth(),q=await B.getDisplayHeight();t.onDiag?.(`${B.codec} ${U}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 Ig(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=gf(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=Bg(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 rc(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 Mg(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 gf(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}function Bg(t,e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t.subarray(e,e+n))}catch{return gf(t,e,n)}}const Rg=Object.freeze(Object.defineProperty({__proto__:null,getEntry:rc,parsePkg:Ig,verifyLayout:Mg},Symbol.toStringTag,{value:"Module"})),ic={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"},sr={UNKNOWN:-1,JPEG:2,PNG:13,GIF:25,WEBP:35,MP4:35};function Fg(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===sr.PNG)return{width:n.width,height:n.height,png:n.data};if(t.freeImageFormat!==sr.UNKNOWN)return{width:n.width,height:n.height,image:n.data,fif:t.freeImageFormat};const r=sc(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:yf(r,n.width,n.height,t.width,t.height)}:{width:n.width,height:n.height,rgba:r}}function Dg(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!==sr.UNKNOWN){n.push({width:r.width,height:r.height,image:r.data,fif:t.freeImageFormat});continue}const i=sc(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:yf(n[0].rgba,n[0].width,n[0].height,t.width,t.height)}),n}function yf(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 sc(t,e,n,r){switch(t){case 0:return Ng(e,n,r);case 1:return Lg(e,n,r);case 2:return Og(e,n,r);case 4:return Wg(e,n,r);case 6:return Vg(e,n,r);case 7:return Hg(e,n,r);case 8:return Ug(e,n,r);case 9:return zg(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: "+(ic[t]||t))}}function Ng(t,e,n){return new Uint8Array(t.buffer,t.byteOffset,e*n*4).slice()}function Lg(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 Og(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 Ug(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 zg(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 Hg(t,e,n){return ac(t,e,n,!0,0)}function Vg(t,e,n){return ac(t,e,n,!1,3)}function Wg(t,e,n){return ac(t,e,n,!1,5)}function ac(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=jg(o,r),d=qg(o,r),h=i===3?Xg(o):i===5?Gg(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 bf(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 jg(t,e){const n=e?0:8,r=bf(t,n),i=bf(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 qg(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 Xg(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 Gg(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 wf(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 it(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function vf(t,e){return it(t,e)|0}const Zi=new DataView(new ArrayBuffer(4));function ar(t,e){return Zi.setUint8(0,t[e]),Zi.setUint8(1,t[e+1]),Zi.setUint8(2,t[e+2]),Zi.setUint8(3,t[e+3]),Zi.getFloat32(0,!0)}function $g(t){let e=0;const n=ra(t,e,9);if(e+=9,n!=="TEXV0005\0")throw new Error("\u4E0D\u662F .tex \u6587\u4EF6: "+n);const r=ra(t,e,9);if(e+=9,r!=="TEXI0001\0")throw new Error("\u672A\u77E5 TEXI \u5B50\u5BB9\u5668: "+r);const i=it(t,e);e+=4;const s=it(t,e);e+=4;const a=it(t,e);e+=4;const o=it(t,e);e+=4;const c=it(t,e);e+=4;const u=it(t,e);e+=4,e+=4;const l=ra(t,e,9);e+=9;const f=it(t,e);e+=4;let d=sr.UNKNOWN,h=0;if(l==="TEXB0004\0"){d=it(t,e)|0,e+=4;const v=it(t,e);e+=4,d===sr.UNKNOWN&&v===1&&(d=sr.MP4),h=v===1?4:3}else if(l==="TEXB0003\0")d=it(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===sr.MP4,m=[];for(let v=0;v<f;v++){const k=it(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=it(t,e);e+=4;const P=it(t,e);e+=4;let M=0,B=0;h>=2&&(M=it(t,e),e+=4,B=vf(t,e),e+=4);const N=vf(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 U=t.subarray(e,e+N);e+=N;let q=U;M===1&&(q=wf(U,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=ra(t,e,9);if(v.indexOf("TEXS")===0){let k=e+9;const A=it(t,k);k+=4;let T=0,S=0;v==="TEXS0003\0"&&(T=it(t,k),k+=4,S=it(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 U=0;U<A;U++){const q=k+U*M;if(q+32>t.length)break;const H=ar(t,q+8),G=ar(t,q+12),Y=ar(t,q+16),J=ar(t,q+20),ne=ar(t,q+24),fe=ar(t,q+28);B.push({imageId:ar(t,q)|0,duration:ar(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(U=>{if(!(U.width>0&&U.height>0))return!1;const q=[U.x,U.x+U.uDir[0],U.x+U.vDir[0],U.x+U.uDir[0]+U.vDir[0]],H=[U.y,U.y+U.uDir[1],U.y+U.vDir[1],U.y+U.uDir[1]+U.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:ic[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 ra(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}const Qg=Object.freeze(Object.defineProperty({__proto__:null,FIF:sr,TEXTURE_FORMATS:ic,decodeMip0:Fg,decodeMips:Dg,decodePixels:sc,lz4Decompress:wf,parseTex:$g},Symbol.toStringTag,{value:"Module"}));function Yg(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 Kg(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 kf(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 Zg(t,e,n,r){const[i,s,a,o]=kf(t,e,n);return Math.max(r,i,s,a,o)}function Jg(t,e,n){return t<=4&&e<=4&&!!n}function e0(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 Af=/^add[A-Z]/;function xf(){return{log:()=>{},warn:()=>{},error:()=>{},info:()=>{},debug:()=>{}}}function Tf(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 gi(t,e){return()=>{}}function Sf(t,e){t.isScreensaver=!!e.isScreensaver,typeof e.isRunningInEditor=="boolean"&&(t.isRunningInEditor=cc(e.isRunningInEditor)),t.setInterval||(t.setInterval=e.setInterval||gi),t.setTimeout||(t.setTimeout=e.setTimeout||gi),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 xe{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 xe(e);return new xe(this.x+n.x,this.y+n.y,this.z+n.z)}subtract(e){const n=new xe(e);return new xe(this.x-n.x,this.y-n.y,this.z-n.z)}multiply(e){return e&&typeof e=="object"?new xe(this.x*e.x,this.y*e.y,this.z*e.z):new xe(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 xe(n(this.x,e.x),n(this.y,e.y),n(this.z,e.z)):new xe(n(this.x,e),n(this.y,e),n(this.z,e))}copy(){return new xe(this.x,this.y,this.z)}mix(e,n){const r=new xe(e),i=Number(n),s=Number.isFinite(i)?i:0;return new xe(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 xe(0,0,0):new xe(this.x/e,this.y/e,this.z/e)}dot(e){const n=new xe(e);return this.x*n.x+this.y*n.y+this.z*n.z}toString(){return this.x+" "+this.y+" "+this.z}}const Pf=xe;function oc(t){if(t instanceof xe||!t||typeof t!="object"||Array.isArray(t)||!("x"in t)&&!("y"in t)&&!("z"in t)||Object.getPrototypeOf(t)===xe.prototype)return t;try{Object.setPrototypeOf(t,xe.prototype)}catch{}return t}function _f(t){return t&&t.cursorWorldPosition?t:{cursorWorldPosition:new xe(0,0,0),cursorScreenPosition:new xe(0,0,0),cursorPosition:new xe(0,0,0),cursorPositionLast:new xe(0,0,0),cursorLeftDown:!1}}function t0(t,e,n){return new xe(t||0,e||0,n||0)}function n0(){const t={cursorWorldPosition:new xe(0,0,0),cursorScreenPosition:new xe(0,0,0),cursorPosition:new xe(0,0,0),cursorPositionLast:new xe(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 Ef={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},Cf={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 xe(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 xe(c,s===0?0:o/s,s)}},If={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})},Mf=Object.freeze({PLAYBACK_STOPPED:0,PLAYBACK_PLAYING:1,PLAYBACK_PAUSED:2}),ia=["mediaPropertiesChanged","mediaThumbnailChanged","mediaPlaybackChanged","mediaTimelineChanged","mediaStatusChanged","mediaLyricsChanged"],r0=["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"],i0=new RegExp(`(^[ \\t]*|;|\\})[ \\t]*(?:var|let|const)[ \\t]+(?=(?:${r0.join("|")})\\b)`,"gm"),s0={WEMath:!0,WEColor:!0,WEVector:!0};function Bf(t){return typeof t!="string"?t:t.replace(/([!=])==(\s*)(['"])(-?\d+)\3/g,"$1=$2$3$4$3")}function Rf(t){return Bf(t).replace(/\bimport\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]\s*;?/g,(e,n,r)=>{const i=String(r);return s0[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(i0,"$1")}function a0(t){if(typeof t=="boolean")return t;if(typeof t=="number"&&Number.isFinite(t))return t!==0}function Ff(t){const e=Math.floor(Number(t));return Number.isFinite(e)&&e>=1?Math.min(64,e):64}function sa(t){return t!==null&&typeof t=="object"&&"value"in t?t.value:t}function cc(t){const e=!!t;return Object.assign(()=>e,{valueOf(){return e},toString(){return e?"true":"false"}})}function Df(t,e,n,r){if(n!==null&&typeof n=="object"&&typeof n.user=="string"){const i=sa(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]=sa(n)}function Nf(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 o0(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=Rf(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))Df(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"&&Af.test(v))return k=>(k&&typeof k=="object"&&typeof k.name=="string"&&!(k.name in i)&&(i[k.name]=sa(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:es(n.origin||[0,0,0])},o={registerAsset:b=>b,frametime:1/60,runtime:0,canvasSize:Nf(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||gi,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||gi,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:cc(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};Sf(o,n);const c=n.audioViews;o.registerAudioBuffers=b=>{const v=Ff(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:es(n.origin||[0,0,0]),angles:[0,0,0],scale:[1,1,1]}},sortLayer:()=>{},getLayerIndex:()=>0},l=n.shared||{},f={console:xf()},d=_f(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(Vt,ri){typeof exports=="object"&&typeof module<"u"?ri(exports):typeof define=="function"&&define.amd?define(["exports"],ri):(Vt=typeof globalThis<"u"?globalThis:Vt||self,ri(Vt.WebWallGL={}))})(this,function(Vt){"use strict";var ri=typeof document<"u"?document.currentScript:null;function Ir(){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 Ei(t,e,n,r,i,s){const a=Ir();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 ii(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 qo(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 Rr(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 vs(t,e){const n=t&&typeof t=="object"?t.value:t;return typeof n=="number"&&Number.isFinite(n)?n:e}function wp(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 vs(e.fov,0)>0}function vp(t,e){return e&&e.perspective&&t&&t.isSkybox&&e.eye?e.eye:t.origin}function Ap(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 xp(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 kp=[[16,9],[16,10],[21,9],[32,9]];function Tp(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 kp){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 Xo(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 $o(t,e,n,r,i,s,a){const o=Pu(s),c=Pu(a);if(t==="cover"){const u=Tp(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 Sp(t,e,n,r,i,s){const a=t.general,o=t.camera,c=o&&o.eye?Go(o.eye):[0,0,0],u=o&&o.center?Go(o.center):[0,0,-1],l=o&&o.up?Go(o.up):[0,1,0];if(wp(t)){const A=n>0?e/n:1.7777777777777777,b=vs(a.fov,50),v=Math.max(vs(a.nearz,.01),1e-4),x=Math.max(vs(a.farz,1e4),v+1),P=Ap(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=Ir(),f=a&&a.orthogonalprojection&&a.orthogonalprojection.width||e,h=a&&a.orthogonalprojection&&a.orthogonalprojection.height||n,p=$o(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=Ei(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 Pp(t,e){if(!t||t.perspective||!(t.viewW>0)||!(t.viewH>0))return null;const n=vs(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 Go(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 ya(t){const e=Number(t);return Number.isFinite(e)?e*.5:0}const _p=Object.freeze(["3233141951"]);function Ep(t){const e=t&&t.parallaxFormula;if(e==="mirage"||e==="legacy")return e;const n=t&&t.workshopId!=null?String(t.workshopId):"";return n&&_p.includes(n)?"mirage":"legacy"}function Mp(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=ya(t.parallaxDepth[0]),s=ya(t.parallaxDepth[1]);return[i*n,s*r]}function Cp(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 Qo(t,e){return!e||!e.active?[0,0]:e.mode==="mirage"?Cp(t,e):Mp(t,e)}const Ip=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 Rp(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/Ip))}return i>=1.5?1:i>=.9?.8:.6}function Bp(t,e){const n=Cu("resourcesNormal");return n!==null?n:1}const Fp=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)<Fp}function Dp(t,e,n){return t.startsWith("util/")||t.startsWith("_rt_")?1:/normal/i.test(t)?n:e}function Np(t){const e=typeof location<"u"?location.search:"",n=new URLSearchParams(e).get("resources");return n==="native"||n==="off"||n==="0"}function Lp(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 Up(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 Op(t,e){return!t||e>=1?t:Math.max(Mu,Math.round(t*e))}function zp(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 Hp(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 Vp(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 Wp=4096;function Mi(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=Wp/s;return Math.max(.25,Math.min(i,a))}function Br(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function Yo(t){const e=Br(t);return e==="contain"?{objectFit:"contain",background:"rgba(10,12,16,0.85)"}:e==="stretch"?{objectFit:"fill",background:"transparent"}:{objectFit:"cover",background:"transparent"}}function Ko(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 jp(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 Fr(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,Yp(),Fu(t)}function qp(t){try{Fr(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 Xp=new TextDecoder,jt=t=>Xp.decode(t).replace(/^\uFEFF/,""),Bu=500;function Dr(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 $p(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 Ci{static EPS_MS=.5;interval=0;nextAt=0;armed=!1;constructor(e){this.interval=Ci.intervalFor(e)}static intervalFor(e){const n=Number(e);return n>0&&isFinite(n)?1e3/n:0}setFps(e){this.interval=Ci.intervalFor(e)}shouldRender(e){const n=this.interval;return n<=0?!0:this.armed?e+Ci.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 ye(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 Zo(t){t.coverAlign.x=t.coverAlign.y=t.coverAlign.tx=t.coverAlign.ty=.5,Gp(t)}function Gp(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 Qp=["__scene","__sceneLayers","__textures","__objScripts","__textWidgets","__mediaHooks","__mediaControl","__mediaStats","__mediaSet","__system","__liveSystem","__audioStats","__audioMute","__particleStats","__particleToggle","__pointerStats","__compositeStats","__compositeEnable"];function Yp(){const t=window;for(const e of Qp)e in t&&delete t[e]}function Du(t,e,n){const r=Mi(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 Kp=.5,Nu=.12,Zp=.125,Jp=.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(Kp,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?Jp:Zp,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 D(t){if(!t)throw new Error("Assertion failed.")}const Jo=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},Qt=t=>t&&t[t.length-1],xe=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)},nr=t=>{const e=xe(t);return(e&1)===0?-(e>>1):e+1>>1},rr=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Je=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Yt=new TextDecoder,ec=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),tc={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ir=ec(tc),nc={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},sr=ec(nc),rc={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ar=ec(rc),ic=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},e0=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class ba{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 t0=/^[0-9a-fA-F]+$/,As=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),n0=t=>{D(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),xs=(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},Xe=(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=Xe(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}},sc=(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]},ac=(t,e)=>{for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1},r0=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},i0=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},wa=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},s0=(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)},ks=(t,e,n)=>Math.max(e,Math.min(n,t)),qt="und",Ts=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},oc=(t,e)=>Math.round(t/e)*e,ju=(t,e)=>Math.round(t*e)/e,cc=(t,e)=>Math.floor(t/e)*e,a0=t=>{let e=0;for(;t;)e++,t>>=1;return e},lc=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},o0=/^[a-z]{3}$/,qu=t=>o0.test(t),Ii=1e6*(1+Number.EPSILON),Xu=(t,e)=>{const n={...t,...e};if(t.headers||e.headers){const r=t.headers?uc(t.headers):{},i=e.headers?uc(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},uc=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 xa(1e3*o),i())throw a}};class c0{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let fc=null;const dc=()=>fc!==null?fc:fc=!!(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 hc=null;const l0=()=>hc!==null?hc:hc=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let mc=null;const pc=()=>mc!==null?mc:mc=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),u0=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.`,f0=(async()=>{})().constructor,le=t=>t instanceof f0||t instanceof Promise?!0:typeof t?.then=="function",Ri=(t,e)=>t!==-1?t:e,gc=(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},d0=(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},yc=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},va=t=>typeof t=="number"&&!Number.isNaN(t),Nr=(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("/")},Ss=(t,e)=>{let n=0;for(let r=0;r<t.length;r++)e(t[r])&&n++;return n},bc=(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},Aa=t=>{D(Number.isInteger(t.num)),D(Number.isInteger(t.den)),D(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}},wc=(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.`)},xa=t=>new Promise(e=>setTimeout(e,t));class vc{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 On;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(On||(On={}));class Be{constructor(){}static get level(){return Be._level}static set level(e){if(e!==On.Silent&&e!==On.Errors&&e!==On.Warnings&&e!==On.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 vc}static on(e,n,r){return Be._emitter.on(e,n,r)}static _error(...e){Be._emitter._emit("error",e),Be._level>=On.Errors&&console.error(...e)}static _warn(...e){Be._emitter._emit("warn",e),Be._level>=On.Warnings&&console.warn(...e)}static _info(...e){Be._emitter._emit("info",e),Be._level>=On.Info&&console.info(...e)}}Be._level=On.Info,Be._emitterInstance=null;class ka{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 h0{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 or={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class $e{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 $e(this.bytes);return e.pos=this.pos,e}}const Ps=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ac=[-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 $e(t),n=xc(e),{frequencyIndex:r,sampleRate:i}=kc(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=Ac[s]);let o=n,c=!1,u=i;if(n===5||n===29)c=n===29,u=kc(e).sampleRate,o=xc(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}xc(e)===5&&e.readBits(1)&&(u=kc(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}},xc=t=>{const e=t.readBits(5);return e===31?32+t.readBits(6):e},kc=t=>{const e=t.readBits(4);return e===15?{frequencyIndex:e,sampleRate:t.readBits(24)}:{frequencyIndex:e,sampleRate:e<Ps.length?Ps[e]:null}};const Ta=[48e3,44100,32e3],Yu=[24e3,22050,16e3];var Mt;(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"})(Mt||(Mt={}));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 Sa=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):(D(e===4),i=r.getUint32(n,!1)),n+=e,yield{offset:n,length:i},n+=i}},Zu=(t,e)=>{if(e.description){const i=(rr(e.description)[4]&3)+1;return Ku(t,i)}else return Sa(t)},Pa=t=>t&31,_a=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)},Tc=new Uint8Array([0,0,0,1]),Ju=t=>{const e=t.reduce((i,s)=>i+Tc.byteLength+s.byteLength,0),n=new Uint8Array(e);let r=0;for(const i of t)n.set(Tc,r),r+=Tc.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:s0(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},m0=(t,e)=>{if(e.description){const i=(rr(e.description)[4]&3)+1;return ef(t,i)}else return Ju(t)},Sc=t=>{try{const e=[],n=[],r=[];for(const o of Sa(t)){const c=t.subarray(o.offset,o.offset+o.length),u=Pa(c[0]);u===Mt.SPS?e.push(c):u===Mt.PPS?n.push(c):u===Mt.SPS_EXT&&r.push(c)}if(e.length===0||n.length===0)return null;const i=e[0],s=Ea(i);D(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=Je(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}},Ea=t=>{try{const e=new $e(_a(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const r=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();xe(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=xe(e),a===3&&(u=e.readBits(1)),o=xe(e),c=xe(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=nr(e);W=(U+we+256)%256}U=W===0?U:W}}}xe(e);const l=xe(e);if(l===0)xe(e);else if(l===1){e.skipBits(1),nr(e),nr(e);const I=xe(e);for(let B=0;B<I;B++)nr(e)}xe(e),e.skipBits(1);const d=xe(e),f=xe(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=xe(e),B=xe(e),V=xe(e),O=xe(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)&&(xe(e),xe(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),xe(e),xe(e),xe(e),xe(e),S=xe(e),k=xe(e))}if(S===null){D(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)??Qt(wf),W=Math.min(Math.floor(U.maxDpbMbs/(B*O)),16);S=W,k=W}}return D(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=xe(t);t.skipBits(4),t.skipBits(4);for(let n=0;n<=e;n++)xe(t),xe(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},p0=(t,e)=>{if(e.description){const i=(rr(e.description)[21]&3)+1;return ef(t,i)}else return Ju(t)},Ma=(t,e)=>{if(e.description){const i=(rr(e.description)[21]&3)+1;return Ku(t,i)}else return Sa(t)},Bi=t=>t>>1&63,Pc=t=>{try{const e=new $e(_a(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}=g0(e,n);xe(e);const l=xe(e);let d=0;l===3&&(d=e.readBits(1));const f=xe(e),h=xe(e);let p=f,m=h;if(e.readBits(1)){const B=xe(e),V=xe(e),O=xe(e),U=xe(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=xe(e),y=xe(e);xe(e);const A=e.readBits(1)?0:n;let b=0;for(let B=A;B<=n;B++)xe(e),b=xe(e),xe(e);xe(e),xe(e),xe(e),xe(e),xe(e),xe(e),e.readBits(1)&&e.readBits(1)&&y0(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),xe(e),xe(e),e.skipBits(1));const v=xe(e);if(b0(e,v),e.readBits(1)){const B=xe(e);for(let V=0;V<B;V++)xe(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=v0(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}},_c=t=>{try{const e=[],n=[],r=[],i=[];for(const u of Sa(t)){const l=t.subarray(u.offset,u.offset+u.length),d=Bi(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=Pc(n[0]);if(!s)return null;let a=0;if(r.length>0){const u=r[0],l=new $e(_a(u));l.skipBits(16),xe(l),xe(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),xe(l),xe(l),nr(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&xe(l),nr(l),nr(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:Bi(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}},g0=(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}},y0=t=>{for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBits(1))xe(t);else{const i=Math.min(64,1<<4+(e<<1));e>1&&nr(t);for(let s=0;s<i;s++)nr(t)}},b0=(t,e)=>{const n=[];for(let r=0;r<e;r++)n[r]=w0(t,r,e,n)},w0=(t,e,n,r)=>{let i=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===n){const c=xe(t);a=e-(c+1)}else a=e-1;t.readBits(1),xe(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=xe(t),c=xe(t);for(let u=0;u<o;u++)xe(t),t.readBits(1);for(let u=0;u<c;u++)xe(t),t.readBits(1);i=o+c}return i},v0=(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)&&(xe(t),xe(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(xe(t),xe(t),xe(t),xe(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&xe(t),t.readBits(1)&&A0(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=xe(t),xe(t),xe(t),xe(t),xe(t)),{pixelAspectRatio:o,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},A0=(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?xe(t):u=t.readBits(1)===1;let l=1;u||(l=xe(t)+1),r&&sf(t,l,s),i&&sf(t,l,s)}},sf=(t,e,n)=>{for(let r=0;r<e;r++)xe(t),xe(t),n&&(xe(t),xe(t)),t.readBits(1)},x0=t=>{try{const e=Je(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 k0=(t,e)=>{const n=new Set;let r=Nt.audAllowed;for(const s of Ma(t,e)){if(r===Nt.noMoreDataAllowed){n.add(s.offset);continue}const a=Bi(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 Ma(t,e))n.has(s.offset)||i.push(t.subarray(s.offset,s.offset+s.length));return p0(i,e)},T0={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 $e(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=Qt(Di).level;for(const P of Di)if(y<=P.maxPictureSize){w=P.level;break}const A=T0[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}},S0=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,of=function*(t){const e=new $e(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);D(e.pos%8===0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Ec=t=>{for(const{type:e,data:n}of of(t)){if(e!==1)continue;const r=new $e(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},P0=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,cf=t=>{if(t.length<36)return null;const n=Je(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)}},_0=t=>{const e=Je(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}},E0=[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],M0=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:E0[e]*r}},C0=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 $e(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}},Mc=(t,e,n)=>{switch(t){case"avc":{for(const r of Zu(n,e)){const i=n[r.offset],s=Pa(i);if(s>=Mt.NON_IDR_SLICE&&s<=Mt.SLICE_DPC)return"delta";if(s===Mt.IDR)return"key";if(s===Mt.SEI&&!pc()){const a=n.subarray(r.offset,r.offset+r.length),o=_a(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 $e(o);f.pos=8*c;const h=xe(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 Ma(n,e)){const i=Bi(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 $e(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 $e(s);a.skipBits(4),r=!!a.readBits(1)}else if(i===3||i===6||i===7){if(r)return"key";const a=new $e(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:wa(t),D(!1)}};var Fi;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Fi||(Fi={}));const Cc=(t,e)=>{const n=Je(t);let r=0;const i=n.getUint32(r,!0);r+=4;const s=Yt.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=Yt.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=Je(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=Yt.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}}},Ic=[2,1,2,3,3,4,4,5],I0=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;const e=new $e(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}},R0=[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],B0=1536,lf=[1,2,3,6],F0=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;const e=new $e(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=Ta[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}]}},D0=t=>{if(t.length<2)return null;const e=new $e(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 D(e),e.fscod<3?Ta[e.fscod]:e.fscod2!==null&&e.fscod2<3?Yu[e.fscod2]:null},ff=t=>{const e=t.substreams[0];D(e);let n=Ic[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},N0=1683496997,Ca=18,Rc=10,L0=4096,df=32,hf=20,U0=8,O0=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],z0=[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],H0=[16,16,20,20,0,24,24,0],Ia=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],V0=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],W0=8,j0=44646,q0=[32e3,44100,48e3,0],X0=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],$0=[512,1024,2048,4096],mf=t=>{const e=gf(t),n=Je(t);let r=e?Math.ceil(e.frameSize/4)*4:0,i=null;for(;r+4<=t.length&&n.getUint32(r)===N0;){const a=Ra(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<Ca||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;const e=new $e(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%U0!==0)return null;const i=e.readBits(14)+1;if(i<96)return null;const s=e.readBits(6);if(s>=Ia.length)return null;const a=O0[e.readBits(4)];if(a===0)return null;const o=z0[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=H0[e.readBits(3)];if(u===0)return null;const l=c!==0;return{frameSize:i,sampleRate:a,numberOfChannels:Ia[s]+(l?1:0),sampleCount:r*df,channelLayout:V0[s]|(l?W0:0),amode:s,lfePresent:l,bitRate:o,pcmResolution:u}},Ra=t=>{if(t.length<Rc||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;const e=new $e(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=q0[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*lc(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=X0[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}}},G0=t=>{if(t.length<hf)return null;const e=Je(t),n=e.getUint32(0);if(n===0)return null;const r=new $e(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=Q0(o):a<Ia.length&&(c=Ia[a]+s),{sampleRate:n,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:t[12],sampleCount:$0[i],channelLayout:o,numberOfChannels:c}},Q0=t=>lc(t)+lc(t&j0);const yf=["avc","hevc","vp9","av1","vp8","prores"],Ba=["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"],bf=[...["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],...Ba],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}],Di=[{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",Bc=["ap4x","ap4h","apch","apcn","apcs","apco"],xf=["dtsc","dtsh","dtsl","dtse"],Fc=t=>{const{codec:e,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=t;if(e==="avc"){if(D(t.avcType!==null),i){const u=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${As(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}.${As(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=Je(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=Qt(Di).level;for(const b of Di)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=Qt(Di).level;for(const x of Di)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?tc[r.primaries]:1,g=r?.transfer?nc[r.transfer]:1,y=r?.matrix?rc[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&&wa(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=Ea(e);if(n)return{primaries:ir[n.colourPrimaries],transfer:sr[n.transferCharacteristics],matrix:ar[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=x0(t.codecDescription)?.arrays.find(n=>n.nalUnitType===vt.SPS_NUT)?.nalUnits[0]),e){const n=Pc(e);if(n)return{primaries:ir[n.colourPrimaries],transfer:sr[n.transferCharacteristics],matrix:ar[n.matrixCoefficients],fullRange:!!n.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(t.vp9CodecInfo)return{primaries:ir[t.vp9CodecInfo.colourPrimaries],transfer:sr[t.vp9CodecInfo.transferCharacteristics],matrix:ar[t.vp9CodecInfo.matrixCoefficients],fullRange:!!t.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(t.av1CodecInfo)return{primaries:ir[t.av1CodecInfo.colourPrimaries],transfer:sr[t.av1CodecInfo.transferCharacteristics],matrix:ar[t.av1CodecInfo.matrixCoefficients],fullRange:!!t.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(t.proresCodecInfo)return{primaries:ir[t.proresCodecInfo.colourPrimaries],transfer:sr[t.proresCodecInfo.transferCharacteristics],matrix:ar[t.proresCodecInfo.matrixCoefficients],fullRange:t.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Dc=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&&Ba.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Fa=48e3,Tf=/^pcm-([usf])(\d+)(be)?$/,Y0=t=>{if(D(Ba.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);D(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}},_s=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":Bc.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 si=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,Nc=(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}},Lc=t=>{let e=2130706432,n=0;for(;e!==0;)n>>=1,n|=t&e,e>>=8;return n};var Da;(function(t){t[t.FrameCount=1]="FrameCount",t[t.FileSize=2]="FileSize",t[t.Toc=4]="Toc"})(Da||(Da={}));const Es=t=>t===3?1:2;class cr{constructor(e){this.input=e}dispose(){}}const nn=new Uint8Array(0);class xt{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===nn&&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===nn}get microsecondTimestamp(){return Math.trunc(Ii*this.timestamp)}get microsecondDuration(){return Math.trunc(Ii*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 xt(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 xt(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=Je(t);let n=0;const r=e.getUint8(n);n+=1,n+=3;const i=As(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(As(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&&d0(t.data,e.data);const Ni=8,Ms=16,Lr=t=>{let e=ve(t);const n=mt(t,4);let r=8;e===1&&(e=sn(t),r=16);const s=e-r;return s<0?null:{name:n,totalSize:e,headerSize:r,contentSize:s}},ai=t=>di(t)/65536,Uc=t=>di(t)/1073741824,Oc=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},zn=t=>{let e=At(t);return t.skip(2),e=Math.min(e,t.remainingLength),Yt.decode(Pe(t,e))},ng=t=>{const e=Lr(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;const n=ve(t);t.skip(4);const r=Pe(t,e.contentSize-8);switch(n){case 1:return Yt.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new ka(r,"image/jpeg");case 14:return new ka(r,"image/png");case 27:return new ka(r,"image/bmp");default:return r}};const Hn=16,lr=new Uint32Array(256),Li=new Uint32Array(256),Ui=new Uint32Array(256),Oi=new Uint32Array(256),zi=new Uint32Array(256),Ct=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);lr[s]=a<<24|a<<16|a<<8|a,Ct[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;Li[s]=f,Ui[s]=f>>>8|f<<24,Oi[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(Hn/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Hn),this.out=new Uint8Array(Hn),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:n}){D(e.byteLength===16),D(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]^lr[a>>>16&255]&4278190080^lr[a>>>8&255]&16711680^lr[a>>>0&255]&65280^lr[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]=Li[lr[o>>>24&255]&255]^Ui[lr[o>>>16&255]&255]^Oi[lr[o>>>8&255]&255]^zi[lr[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=Li[e>>>24]^Ui[i>>>16&255]^Oi[r>>>8&255]^zi[n&255]^this.roundkey[w],l=Li[n>>>24]^Ui[e>>>16&255]^Oi[i>>>8&255]^zi[r&255]^this.roundkey[w+1],d=Li[r>>>24]^Ui[n>>>16&255]^Oi[e>>>8&255]^zi[i&255]^this.roundkey[w+2],f=Li[i>>>24]^Ui[r>>>16&255]^Oi[n>>>8&255]^zi[e&255]^this.roundkey[w+3],e=u,n=l,r=d,i=f}const h=Ct[e>>>24&255]&4278190080^Ct[i>>>16&255]&16711680^Ct[r>>>8&255]&65280^Ct[n>>>0&255]&255^this.roundkey[40],p=Ct[n>>>24&255]&4278190080^Ct[e>>>16&255]&16711680^Ct[i>>>8&255]&65280^Ct[r>>>0&255]&255^this.roundkey[41],m=Ct[r>>>24&255]&4278190080^Ct[n>>>16&255]&16711680^Ct[e>>>8&255]&65280^Ct[i>>>0&255]&255^this.roundkey[42],g=Ct[i>>>24&255]&4278190080^Ct[r>>>16&255]&16711680^Ct[n>>>8&255]&65280^Ct[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=Pe(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 zc extends cr{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,Ni,Ms);if(le(i)&&(i=await i),!i)break;const s=e,a=Lr(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){D(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);le(i)&&(i=await i),D(i);const s=ve(i),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Ms){let o=this.reader.requestSliceRange(a,Ni,Ms);if(le(o)&&(o=await o),o){const c=Lr(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!==zc)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(D(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;D(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&&Ba.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){D(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=Xe(n.sampleTimingEntries,h,S=>S.startIndex),g=n.sampleTimingEntries[m],y=Xe(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=Qt(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,Ni,Ms);le(n)&&(n=await n),D(n);const r=Lr(n);D(r?.name==="moof");let i=this.reader.requestSlice(e,r.totalSize);le(i)&&(i=await i),D(i),this.traverseBox(i);const s=this.lastReadFragment;D(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)Vc(a,l.timestamp);else{const d=Xe(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];Vc(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const u=Xe(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-Ni&&this.traverseBox(e););}*iterateContiguousBoxes(e){const n=e.filePos;for(;e.filePos-n<=e.length-Ni;){const r=e.filePos,i=Lr(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=r+i.totalSize}}traverseBox(e){const n=e.filePos,r=Lr(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=sn(e)):(e.skip(8),this.movieTimescale=ve(e),this.movieDurationInTimescale=ve(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...or,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=!!(mr(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=sn(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const l=[ai(e),ai(e),Uc(e),ai(e),ai(e),Uc(e),ai(e),ai(e),Uc(e)],d=Jo(oc(cg(l),90));D(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?sn(e):ve(e),h=o===1?H1(e):di(e),p=ai(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=sn(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=Lr(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":Bc.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=Fa;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=As(Pe(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const u=Se(e),l=new Uint8Array(16);l.set(Pe(e,u),0),a.encryptionInfo.defaultConstantIv=l}}break;case"avcC":{const a=this.currentTrack;if(!a||(D(a.info),r.contentSize===0))break;a.info.codecDescription=Pe(e,r.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(D(a.info),r.contentSize===0))break;a.info.codecDescription=Pe(e,r.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;D(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;D(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=Pe(e,r.contentSize-4),b=Ec(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;D(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:ir[c],transfer:sr[u],matrix:ar[l],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;D(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);D(o===3),Oc(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);D(f===4);const h=Oc(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);D(g===5);const y=Oc(e);if(a.info.codecDescription=Pe(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;D(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(At(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;D(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;D(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=Pe(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;D(a.info?.type==="audio"),e.skip(4);const o=127,c=128,u=e.filePos;for(;e.filePos<s;){const p=Se(e),m=mr(e);if((p&o)===Fi.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=Pe(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;D(a.info?.type==="audio");const o=Pe(e,3),c=new $e(o),u=c.readBits(2);c.skipBits(8);const l=c.readBits(3),d=c.readBits(1);u<3&&(a.info.sampleRate=Ta[u]),a.info.numberOfChannels=Ic[l]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;D(a.info?.type==="audio");const o=Pe(e,r.contentSize),c=D0(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;D(a.info?.type==="audio");const o=Pe(e,Math.min(r.contentSize,hf)),c=G0(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=di(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=Pe(e,Math.ceil(c*o/8)),l=new $e(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=sn(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?sn(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,mr,ve],p=h[l],m=h[d],g=h[f],y=ve(e);for(let w=0;w<y;w++){const A=a===1?sn(e):ve(e),b=a===1?sn(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(D(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[Qt(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:u}=this.currentTrack;D(u),u.startTimestamp!==null&&(Vc(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(Pe(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{D(this.currentFragment),e.skip(1);const a=mr(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=sn(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;D(a.currentFragmentState);const o=Se(e);e.skip(3);const c=o===0?ve(e):sn(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;D(this.currentFragment),D(a.currentFragmentState);const o=Se(e),c=mr(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=di(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):(D(a.currentFragmentState.defaultSampleDuration!==null),b=a.currentFragmentState.defaultSampleDuration);let v;f?v=ve(e):(D(a.currentFragmentState.defaultSampleSize!==null),v=a.currentFragmentState.defaultSampleSize);let x;h?x=ve(e):(D(a.currentFragmentState.defaultSampleFlags!==null),x=a.currentFragmentState.defaultSampleFlags),A===0&&y!==null&&(x=y);let P=0;p&&(o===0?P=ve(e):P=di(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),mr(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=Pe(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(mr(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(sn(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;D(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const u=!!(mr(e)&2),l=ve(e),d=a.encryptionInfo.defaultPerSampleIvSize;D(d!==null);for(let f=0;f<Math.min(l,o.samples.length);f++){const h=new Uint8Array(16);d>0?h.set(Pe(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]??=zn(c):this.metadataTags.raw[o.name]??=Pe(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=Yt.decode(Pe(c,o.contentSize)):this.metadataTags.title??=zn(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=zn(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=zn(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=zn(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=zn(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=zn(c));break;case"\xA9day":if(!this.currentTrack){const u=new Date(zn(c));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=zn(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=zn(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=Yt.decode(Pe(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 ka?(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=Je(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=Je(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:(D(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 Ts(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,n){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Hc(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=Xe(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=ac(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 D(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=nn;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(le(u)&&(u=await u),!u)return null;if(s=Pe(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 xt(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];D(s);let a;if(r.metadataOnly)a=nn;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(le(l)&&(l=await l),!l)return null;if(a=Pe(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 xt(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=Xe(this.internalTrack.fragmentLookupTable,r,g=>g.timestamp),d=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,f=Xe(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,Ni,Ms);if(le(g)&&(g=await g),!g)break;const y=m,w=Lr(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];D(!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&&Sc(n.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const n=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=n&&_c(n.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!S0(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||!P0(this.internalTrack.info.av1CodecInfo))){const n=await this.getFirstPacket({}),r=n&&Ec(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(!ic(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:Fc(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:Dc(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const Hc=(t,e)=>{if(t.presentationTimestamps){const n=Xe(t.presentationTimestamps,e,r=>r.presentationTimestamp);return n===-1?-1:t.presentationTimestamps[n].sampleIndex}else{const n=Xe(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 Hc(t,e);if(t.presentationTimestamps){const n=Xe(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(xs(t.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{const n=Hc(t,e),r=Xe(t.keySampleIndices,n,i=>i);return t.keySampleIndices[r]??-1}},ag=(t,e)=>{const n=Xe(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=Xe(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=Xe(t.sampleToChunk,e,y=>y.startSampleIndex),l=t.sampleToChunk[u];D(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];D(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?xs(t.keySampleIndices,e,y=>y)!==-1:!0}},og=(t,e)=>{if(!t.keySampleIndices)return e+1;const n=Xe(t.keySampleIndices,e,r=>r);return t.keySampleIndices[n+1]??-1},Vc=(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{D(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;D(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(Pe(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)=>{D(t.encryptionInfo);const i=t.encryptionInfo;D(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&&t0.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:n0(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);D(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(D(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],Cs=[ce.SeekHead,ce.Info,ce.Cluster,ce.Tracks,ce.Cues,ce.Attachments,ce.Chapters,ce.Tags],Na=[...fg,...Cs],Wc=8,hn=2,ur=2*Wc,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},Is=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},Oe=(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},jc=t=>{const e=Vf(t);return e===null||t.remainingLength<e?null:Oe(t,e)},Wf=t=>{if(t.remainingLength<1)return null;if(Se(t)===255)return;t.skip(-1);const n=Is(t);if(n===null)return null;if(n!==72057594037927940)return n},fr=t=>{D(t.remainingLength>=hn);const e=jc(t);if(e===null)return null;const n=Wf(t);return n===null?null:{id:e,size:n}},Hi=(t,e)=>{const n=Pe(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Rs=(t,e)=>{const n=Pe(t,e);let r=0;for(;r<e&&n[r]!==0;)r+=1;return Yt.decode(n.subarray(0,r))},qc=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?W1(t):Xd(t)},Xc=async(t,e,n,r)=>{const i=new Set(n);let s=e;for(;r===null||s<r;){let a=t.requestSliceRange(s,hn,ur);if(le(a)&&(a=await a),!a)break;const o=fr(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Ur(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<Wc)break;for(let c=0;c<o.length-Wc;c++){o.filePos=a;const u=jc(o);if(u!==null&&s.has(u))return a;a++}}return null},Kt={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 Ur(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 dr;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(dr||(dr={}));var La;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(La||(La={}));var Bs;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Bs||(Bs={}));const $c=[{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 cr{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,hn,ur);if(le(n)&&(n=await n),!n)break;const r=fr(n);if(!r)break;const i=r.id;let s=r.size;const a=n.filePos;if(i===ce.EBML){Ur(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 Xc(this.reader,a,Na,this.reader.fileSize)).pos-a);const o=Qt(this.segments);o&&(o.elementEndPos=a+s)}Ur(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,hn,ur);if(le(o)&&(o=await o),!o)break;const c=r,u=fr(o);if(!u||!Cs.includes(u.id)&&u.id!==ce.Void){const p=await jf(this.reader,c,Cs,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=$c.findIndex(p=>p.id===l);if(h!==-1){const p=$c[h].flag;this.currentSegment[p]=!0,Ur(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,Ur(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=$c.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,hn,ur);if(le(u)&&(u=await u),!u)continue;const l=fr(u);if(!l)continue;const{id:d,size:f}=l;if(d!==c.id)continue;Ur(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,hn,ur);le(r)&&(r=await r),D(r);const i=e,s=fr(r);D(s);const a=s.id;D(a===ce.Cluster);let o=s.size;const c=r.filePos;o===void 0&&(o=(await Xc(this.reader,c,Na,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,Na);l.elementEndPos=d}for(const[,d]of l.trackData){const f=d.track;D(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!==dr.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===dr.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[Qt(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;const g=Xe(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===dr.None)continue;i.decoded||(i.data=this.decodeBlockData(n,i.data),i.decoded=!0);const s=Sn.tempFromBytes(i.data),a=[],o=Se(s)+1;switch(i.lacing){case dr.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 dr.FixedSize:{const u=s.length-1,l=Math.floor(u/o);for(let d=0;d<o;d++)a.push(l)}break;case dr.Ebml:{const u=Is(s);D(u!==null);let l=u;a.push(l);let d=l;for(let f=1;f<o-1;f++){const h=s.bufferPos,p=Is(s);D(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:D(!1)}D(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=Pe(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:dr.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,hn,ur);if(le(r)&&(r=await r),!r)continue;const i=fr(r);if(!i||i.id!==n.id)continue;const{size:s}=i;Ur(s),D(!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>=hn;){const r=e.filePos;if(!this.traverseElement(e,n))return r}return e.filePos}traverseElement(e,n){const r=fr(e);if(!r||n&&n.includes(r.id))return!1;const{id:i,size:s}=r,a=e.filePos;switch(Ur(s),i){case ce.DocType:this.isWebM=Hi(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=Oe(e,s)}break;case ce.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Oe(e,s)}break;case ce.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Oe(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case ce.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=qc(e,s)}break;case ce.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...or,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!==La.Block||o.data.algorithm!==Bs.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===Kt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Kt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===Kt.vp8)this.currentTrack.info.codec="vp8";else if(c===Kt.vp9)this.currentTrack.info.codec="vp9";else if(c===Kt.av1)this.currentTrack.info.codec="av1";else if(c===Kt.prores){const l=this.currentTrack.codecPrivate?Yt.decode(this.currentTrack.codecPrivate):"";Bc.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===Kt.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===Kt.mp3?this.currentTrack.info.codec="mp3":c===Kt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Fa):c===Kt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Kt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Kt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Kt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Kt.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=Oe(e,s)}break;case ce.TrackType:{if(!this.currentTrack)break;const o=Oe(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;Oe(e,s)||(this.currentTrack=null)}break;case ce.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Oe(e,s)}break;case ce.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Oe(e,s)}break;case ce.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Oe(e,s)}break;case ce.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Oe(e,s)}break;case ce.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Oe(e,s)}break;case ce.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Oe(e,s)}break;case ce.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Hi(e,s)}break;case ce.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=Pe(e,s)}break;case ce.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Oe(e,s)}break;case ce.Name:{if(!this.currentTrack)break;this.currentTrack.name=Rs(e,s)}break;case ce.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Hi(e,s),qu(this.currentTrack.languageCode)||(this.currentTrack.languageCode=qt)}break;case ce.LanguageBCP47:{if(!this.currentTrack)break;const c=Hi(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=Oe(e,s)}break;case ce.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Oe(e,s)}break;case ce.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Oe(e,s)}break;case ce.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Oe(e,s)}break;case ce.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Oe(e,s)}break;case ce.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Oe(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=Oe(e,s),c=ar[o];this.currentTrack.info.colorSpace.matrix=c}break;case ce.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=Oe(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=Oe(e,s),c=sr[o];this.currentTrack.info.colorSpace.transfer=c}break;case ce.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=Oe(e,s),c=ir[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=-qc(e,s);try{this.currentTrack.info.rotation=Jo(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=qc(e,s)}break;case ce.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Oe(e,s)}break;case ce.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Oe(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=Oe(e,s);break;case ce.CueTrackPositions:{if(this.currentCueTime===null)break;D(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=Oe(e,s)}break;case ce.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;D(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+Oe(e,s)}break;case ce.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Oe(e,s)}break;case ce.SimpleBlock:{if(!this.currentCluster)break;const o=Is(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=Pe(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=Is(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=Pe(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=Pe(e,s)}break;case ce.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Oe(e,s)}break;case ce.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Oe(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:Oe(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=Rs(e,s);break;case ce.TagString:{if(!this.currentSimpleTagName)break;const o=Rs(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case ce.TagBinary:{if(!this.currentSimpleTagName)break;const o=Pe(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 h0(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=Rs(e,s)}break;case ce.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Hi(e,s)}break;case ce.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=Pe(e,s)}break;case ce.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Rs(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:La.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=Oe(e,s)}break;case ce.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Oe(e,s)}break;case ce.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Bs.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case ce.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Oe(e,s)}break;case ce.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=Pe(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){D(e.decodingInstructions.length>0);let r=n;for(const i of e.decodingInstructions)switch(D(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Bs.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){D(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 Ts(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=Xe(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=ac(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 D(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(D(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);Je(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?nn: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?nn:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);const l=new xt(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=Xe(this.internalTrack.cuePoints,r,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=Xe(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-hn;){if(c){const S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,hn,ur);if(le(y)&&(y=await y),!y)break;const w=g,A=fr(y);if(!A||!Cs.includes(A.id)&&A.id!==ce.Void){const S=await jf(a.reader,w,Cs,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&&(D(b!==ce.Cluster),v=(await Xc(a.reader,x,Na,o.elementEndPos)).pos-x);const P=x+v;if(o.elementEndPos===null){let S=a.reader.requestSliceRange(P,hn,ur);if(le(S)&&(S=await S),!S)break;if(jc(S)===ce.Segment){o.elementEndPos=P;break}}g=P}if(f&&(!u||u.elementStartPos<f.clusterPosition)){const y=this.internalTrack.cuePoints[d-1];D(!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?Sc(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?_c(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?af(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Ec(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?cf(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!ic(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:Fc(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:Dc({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 Gc=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,si,a);if(le(o)&&(o=await o),!o||o.length<si)break;for(;o.remainingLength>=si;){const c=o.filePos,u=ve(o),l=t.fileSize!==null?t.fileSize-s:null,d=Nc(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&Es(d.header.channel)===Es(r.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};class yg extends cr{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 ba,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,mn);if(le(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=pr(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Gc(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=Pe(u,12),d=Je(l),f=d.getUint32(0,!1);this.xingData={frameCount:f&Da.FrameCount?d.getUint32(4,!1):null,fileSize:f&Da.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,mn);if(le(i)&&(i=await i),!i)break;const s=pr(i);if(!s)break;r=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(le(a)&&(a=await a),!a)break;qa(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),D(i),mt(i,3)==="TAG"&&j1(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 D(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(D(e.firstFrameHeader!==null),D(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 D(this.demuxer.firstFrameHeader),Es(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return D(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...or}}async getDecoderConfig(){return D(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Es(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=nn;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(le(s)&&(s=await s),!s)return null;i=Pe(s,r.dataSize)}return new xt(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=xs(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=Xe(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=Je(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"){D(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<a0(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=M0(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 oi=27,Vi=282,kg=Vi+65025,Fs=t=>{const e=t.filePos;if(Gi(t)!==$f)return null;t.skip(1);const r=Se(t),i=V1(t),s=Gi(t),a=Gi(t),o=Gi(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=Gi(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 cr{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,oi,Vi);if(le(n)&&(n=await n),!n)break;const r=Fs(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=Je(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:C0(s.data).modeBlockflags},Cc(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=_0(e.data);n.numberOfChannels=s.outputChannelCount,n.sampleRate=Fa,n.codecInfo.opusInfo={preSkip:s.preSkip},Cc(i.data.subarray(8),this.metadataTags)}async readPacket(e,n){D(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),D(d);const f=Pe(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,oi,Vi);if(le(p)&&(p=await p),!p)return null;const m=Fs(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,oi,Vi);if(le(i)&&(i=await i),!i)return null;const s=Fs(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 ba,this.internalSampleRate=e.codecInfo.codec==="opus"?Fa:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(n=>n.bitstream===this.bitstream);return D(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 D(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{...or,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(D(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 xt(r.metadataOnly?nn: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){D(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(D(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=Ts(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(n);if(r<0)return null;D(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-oi);let x=this.demuxer.reader.requestSlice(b,v-b);if(le(x)&&(x=await x),D(x),!Tg(x,v)){a=A+oi;continue e}let S=this.demuxer.reader.requestSliceRange(x.filePos,oi,Vi);le(S)&&(S=await S),D(S);const k=Fs(S);D(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),D(B);const V=Pe(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,oi,Vi);le(A)&&(A=await A),D(A);const b=Fs(A);D(b),u=b,u.serialNumber===this.bitstream.serialNumber&&l.push(u)}D(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:nn,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(w)){const b=Yf(l,u,d);D(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;){D(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);D(v);let x=this.encodedPacketToMetadata.get(v);if(D(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),D(v),x=this.encodedPacketToMetadata.get(v),D(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=Ts(e*this.internalSampleRate);e=i/this.internalSampleRate;const s=Xe(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);D(u),this.sequentialScanCache.length>0&&D(Qt(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(D(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(D(i!==-1),i===r.lacingValues.length){const s=t[t.indexOf(r)+1];D(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 cr{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),D(e);const n=mt(e,4),r=n!=="RIFX",i=n==="RF64",s=Or(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=Or(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=Ws(i,r);const a=Ws(i,r),o=Or(i,r);i.skip(4);const c=Ws(i,r);let u;if(n===14?u=8:u=Ws(i,r),n>=18&&s!==357){const l=Ws(i,r),d=n-18;if(Math.min(d,l)>=22&&s===Xt.EXTENSIBLE){i.skip(6);const h=Pe(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=Or(i,r),u=Pe(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=pr(r);if(i){const s=n-mn;if(i.size=Math.min(i.size,s),i.size>0){const a=r.slice(e+mn,i.size);qa(a,i,this.metadataTags)}}}getCodec(){if(D(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"}D(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Wi=2048;class Eg{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return D(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(D(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return D(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return D(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return D(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 D(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{...or}}async getPacketAtIndex(e,n){D(e>=0),D(this.demuxer.audioInfo);const r=e*Wi*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(Wi*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=nn;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);le(c)&&(c=await c),D(c),s=Pe(c,i)}const a=e*Wi/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 xt(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,n){D(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Wi,(this.demuxer.dataSize-1)/(Wi*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;D(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){D(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Wi);return this.getPacketAtIndex(r+1,n)}getKeyPacket(e,n){return this.getPacket(e,n)}getNextKeyPacket(e,n){return this.getNextPacket(e,n)}}const Qc=7,ji=9,Ds=t=>{const e=t.filePos,n=Pe(t,9),r=new $e(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 Ua=1024;class Mg extends cr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ba,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();D(this.firstFrameHeader),this.trackBackings=[new Cg(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,mn);if(le(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=pr(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Qc,ji);if(le(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const n=Ds(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=Ps[n.samplingFrequencyIndex];D(r!==void 0);const i=Ua/r,s={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Ua,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,mn);if(le(r)&&(r=await r),!r)break;const i=pr(r);if(!i)break;let s=this.reader.requestSlice(r.filePos,i.size);if(le(s)&&(s=await s),!s)break;qa(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()/Ua}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 D(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){D(this.demuxer.firstFrameHeader);const e=Ac[this.demuxer.firstFrameHeader.channelConfiguration];return D(e!==void 0),e}getSampleRate(){D(this.demuxer.firstFrameHeader);const e=Ps[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return D(e!==void 0),e}getDisposition(){return{...or}}async getDecoderConfig(){return D(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=nn;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(le(s)&&(s=await s),!s)return null;i=Pe(s,r.dataSize)}return new xt(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=xs(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=Xe(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 $e(Pe(t,1));for(;n.readBits(1)===1;)e++;if(e===0)return n.readBits(7);const r=[],i=e-1,s=new $e(Pe(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;wa(e),D(!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 cr{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 ba,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),D(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,mn);if(le(n)&&(n=await n),!n){this.lastSampleLoaded=!0;return}const r=pr(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);le(i)&&(i=await i),D(i),qa(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.`);D(n);const r=Se(n),i=mr(n),s=(r&128)!==0;switch(r&127){case Fi.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(le(o)&&(o=await o),D(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=Pe(o,34),u=new $e(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 Fi.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);le(o)&&(o=await o),D(o),Cc(Pe(o,i),this.metadataTags);break}case Fi.PICTURE:{let o=this.reader.requestSlice(e,i);le(o)&&(o=await o),D(o);const c=ve(o),u=ve(o),l=Yt.decode(Pe(o,u)),d=ve(o),f=Yt.decode(Pe(o,d));o.skip(16);const h=ve(o),p=Pe(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}){D(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=Pe(e,4),s=new $e(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){D(n);const g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(D(!n),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(D(!n),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=Ig(s.readBits(4));if(!o)return null;D(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(Pe(e,h));return p!==m?null:{num:l,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),D(this.lastLoadedPos!==null),D(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 D(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return D(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return qt}getTimeResolution(){return D(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 D(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...or}}async getDecoderConfig(){return D(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(D(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Xe(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=nn;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(le(o)&&(o=await o),!o)return null;i=Pe(o,r.byteSize)}D(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,a=r.blockSize/this.demuxer.audioInfo.sampleRate;return new xt(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 kn=9e4,Yc=2**33,rn=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 cr{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=rn+16+1;let n=this.reader.requestSlice(0,e);le(n)&&(n=await n),D(n);const r=Pe(n,e);if(r[0]===71&&r[rn]===71)this.packetOffset=0,this.packetStride=rn;else if(r[0]===71&&r[rn+16]===71)this.packetOffset=0,this.packetStride=rn+16;else if(r[4]===71&&r[4+rn+4]===71)this.packetOffset=4,this.packetStride=rn+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 $e(l.payload),y=g.readAlignedByte();g.skipBits(8*y),h=g.readBits(8)===2}if(l.pid===0&&!o){const m=new $e(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 $e(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=qi(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 Ns(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=Sc(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;const A=m.info.avcCodecInfo.sequenceParameterSets[0];D(A);const b=Ea(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:ir[b.colourPrimaries],transfer:sr[b.transferCharacteristics],matrix:ar[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=_c(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const b=m.info.hevcCodecInfo.arrays.find(x=>x.nalUnitType===vt.SPS_NUT).nalUnits[0];D(b);const v=Pc(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:ir[v.colourPrimaries],transfer:sr[v.transferCharacteristics],matrix:ar[v.matrixCoefficients],fullRange:!!v.fullRangeFlag},m.info.reorderSize=v.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Fc({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=Sn.tempFromBytes(y.suppliedPacket.data),A=Ds(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=Ac[A.channelConfiguration],m.info.sampleRate=Ps[A.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const w=ve(Sn.tempFromBytes(y.suppliedPacket.data)),A=Nc(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=Es(A.header.channel),m.info.sampleRate=A.header.sampleRate}else if(m.info.codec==="ac3"){const w=I0(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=Ic[w.acmod]+w.lfeon,m.info.sampleRate=Ta[w.fscod]}else if(m.info.codec==="eac3"){const w=F0(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:Dc({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(xs(this.sectionEndPositions,i,y=>y)!==-1){u=!1;break}}if(u){const f=Xe(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,rn);if(le(n)&&(n=await n),!n)return null;const r=Pe(n,rn);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*kn;this.timestampWrapInfo={reference:e-i,offset:e>=Yc-i?-Yc:Yc}}const{reference:n,offset:r}=this.timestampWrapInfo;return r<0&&e>=n||r>0&&e<n?e+r:e}}const ci=(t,e,n)=>{if(e.payload.byteLength<3)return null;const r=new $e(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}},qi=(t,e,n)=>{D(e.endPos!==null);const r=ci(t,e,n);if(!r)return null;const i=new $e(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;D(Number.isInteger(u));const l=e.payload.subarray(u,s>0?a+s:e.payload.byteLength);return{...r,data:l}};class Oa{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++,D(i instanceof Oa),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{...or,primary:!1}}getTimeResolution(){return kn}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 xt(r.metadataOnly?nn:e.data,i,e.pts/kn,Math.max(n/kn,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const n=this.elementaryStream.firstSection;D(n);const r=qi(this.elementaryStream.demuxer,n,!0);D(r);const i=new Ns(this.elementaryStream,r),s=new Zc(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);D(a);const o=qi(s,a,!0);D(o);const c=new Ns(this.elementaryStream,o);r=new Zc(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=Ts(e*kn),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 _=ci(s,k,!1);if(_&&_.pts!==null)return{pesPacketHeader:_,section:k}}P+=s.packetStride}return null},l=this.elementaryStream.firstSection;D(l);const d=ci(s,l,!0);if(D(d),i<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=Xe(h,i,b=>b.pts),m=p!==-1?h[p]:null;if(m&&i-m.pts<kn/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=cc(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=cc(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);D(x);const P=qi(s,x,!0);D(P);const S=new Ns(this.elementaryStream,P),k=new Zc(this,S);for(;!((Qt(k.presentationOrderPackets)?.pts??-1/0)>=i||!await k.readNextPacket()););const _=ac(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();D(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=ci(s,x,!1);if(P&&P.pts!==null){if(P.pts>i)break e;y=P,Kc(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=ci(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{D(_);const U=qi(s,_,!0);D(U);const W=new Ns(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=ci(s,U,!1);if(W&&W.pts!==null){k=W,_=U,Kc(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=ci(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 D(O),O}if(S)return null;v=b,b=Math.max(cc(b-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class qg extends Oa{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 D(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Xg extends Oa{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return D(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Kc=(t,e)=>{const n=t.referencePesPackets,r=Xe(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 Ns{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 D(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=Qt(this.pesPackets).sectionEndPos;for(D(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=qi(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(){D(!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=Pa(S),_=k===Mt.NON_IDR_SLICE||k===Mt.SLICE_DPA||k===Mt.IDR,I=k===Mt.SEI||k===Mt.SPS||k===Mt.PPS||k===Mt.AUD;else{if(k=Bi(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=xe(new $e(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(ji);if(le(c)&&(c=await c),c<ji)return;const u=this.readBytes(ji),l=Ds(Sn.tempFromBytes(u));if(l){this.seekTo(o);let d=this.ensureBuffered(l.frameLength);return le(d)&&(d=await d),this.supplyPacket(d,Math.round(Ua*kn/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(si);if(le(c)&&(c=await c),c<si)return;const u=this.readBytes(si),l=Je(u).getUint32(0),d=Nc(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*kn/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=R0[3*d+l];D(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),le(c)&&(c=await c);const h=Math.round(B0*kn/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*kn/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(Ca);if(le(c)&&(c=await c),c<Ca)return;const u=this.readBytes(Ca),l=gf(u);let d=l?null:Ra(u);if(!l&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);const m=Math.min(d.frameSize,L0);let g=this.ensureBuffered(m);le(g)&&(g=await g),d=Ra(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+Rc;let y=this.ensureBuffered(g);if(le(y)&&(y=await y),y<g)break;this.seekTo(o+m);const w=Ra(this.readBytes(Rc));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*kn/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)D(this.nextPts!==null),i=this.nextPts;else{if(r.pts===null)throw new Error(Kf);i=r.pts,Kc(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=Mc(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 Zc{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(),D(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);D(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(D(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:",Jc="#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 Ls{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=Ss(e,i=>i.getType()==="video")+1;e.push(new hd(this,n,r))}else if(n.type==="audio"){const r=Ss(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=Ss(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=Ss(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(),D(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){D(e.sequenceNumber>=0),D(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(),D(this.firstInputTrack),D(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())}}yc();const pd=0,gd=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});class hr extends vc{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(),D(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 el(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class el{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;D(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Xi extends hr{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 hr||i instanceof el))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=i instanceof hr?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 Xi{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 hr?o.ref():o;return this._root=c,this._rootRequest=null,c};le(s)?this._rootRequest=s.then(a):(a(s),D(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 tl extends Xi{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&&(!va(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 tl(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={...uc(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:ks(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 xa(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 xa(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?(D(l.offset===c.start),c.resolve(l.bytes)):c.resolve(null)},l=>c.reject(l)):(D(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 hr{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&&(!va(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=Xe(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:Je(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:Je(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:r,end:i,bytes:n,view:Je(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(gc(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){D(!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);D(a<=e&&n<=o);let c=null;const u=Xe(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=Xe(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(D(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:Je(f),offset:e}),m.length===0)return D(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=Xe(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}):(D(f),c=g.then(v=>v&&{bytes:v,view:Je(v),offset:e})),c}checkHoleAgainstWorker(e,n,r){if(gc(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)D(a!==null),D(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){D(!e.running),D(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){D(!e.aborted);const r=e.currentPos,i=r+n.length;this.insertIntoCache({start:r,end:i,bytes:n,view:Je(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||gc(r,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a),s--)}}supplyFileSize(e){D(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);D(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=Xe(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=Je(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=Je(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 hr{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:ks(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 xa(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 Wa(b.source).requestEntireFile();D(x),e=$d(x,x.length,{ignore:fd}),b.source instanceof Xi&&(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=Qt(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&&(D(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(Hn),_=Je(k);_.setUint32(8,Math.floor(c/2**32)),_.setUint32(12,c),v={...v,iv:k}}const P={path:Nr(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(Jc)){if(g){m=!0;continue}m||(h===null&&c>0&&p!==null&&(i=c*p),m=!0);const v=b.slice(Jc.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 Ls(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:Nr(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 Ls(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(Hn*2,"0"),S=new Uint8Array(Hn);for(let B=0;B<Hn;B++){const V=-Hn*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:Nr(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=Je(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=Qt(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=Xe(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);D(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 D(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 Va({source:new Kg(n.location.path,async c=>{D(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;D(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 Wa(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},O1),!1),A=await new Wa(y.source).requestSlice(0,Hn);if(!A)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Pe(A,Hn),iv:f.iv}}catch(y){g.error=y,g.hasError=!0}finally{Ad(g)}},()=>{h.free()});l=new wd(m).ref()}else D(!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=bc(this.inputCache,u=>u.age);D(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 cr{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{D(this.input._rootSource instanceof Xi);const e=await this.input._reader.requestEntireFile();D(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=Nr(r,p),g=new Ls(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 Ls(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=Nr(r,p);i.push({fullPath:g,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(rd)){const h=new Ls(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=Nr(r,y)),s.push({fullPath:g,attributes:h,lineNumber:d})}else if(f!==Qg){if(f.startsWith(Jc)){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(_s(k))),A=m.some(k=>bf.includes(_s(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=Nr(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);D(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=Nr(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);D(U!==null),m.push(U)}}m=[...new Set(m)];let b=null,v=null;const x=d.attributes.getAsNumber("bandwidth");D(x!==null);const P=d.attributes.getAsNumber("average-bandwidth"),S=d.attributes.get("name");for(const k of m){const _=_s(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:za(B.attributes),autoselect:za(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:za(B.attributes),autoselect:za(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(),D(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{D(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{...or,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(){D(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 _s(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 _s(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 za=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 Vn{constructor(){this._isIsobmff=!1}}class Ed extends Vn{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 zc(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=sn(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 Vn{async isSupportedEBMLOfDocType(e,n){let r=e._reader.requestSlice(0,ur);if(le(r)&&(r=await r),!r)return!1;const i=Vf(r);if(i===null||i<1||i>8||Oe(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-hn;){const u=fr(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(Oe(o,d)!==1)return!1;break;case ce.EBMLReadVersion:if(Oe(o,d)!==1)return!1;break;case ce.DocType:if(Hi(o,d)!==n)return!1;break;case ce.DocTypeVersion:if(Oe(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 Vn{async _canReadInput(e){let n=0;for(;;){let d=e._reader.requestSlice(n,mn);if(le(d)&&(d=await d),!d)break;const f=pr(d);if(!f)break;n=d.filePos+f.size}const r=await Gc(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 Gc(e._reader,n,n+si);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 Vn{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 Vn{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 Vn{async _canReadInput(e){let n=0;for(;;){let i=e._reader.requestSlice(n,mn);if(le(i)&&(i=await i),!i)break;const s=pr(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 Vn{async _canReadInput(e){let n=0;for(;;){let a=e._reader.requestSlice(n,mn);if(le(a)&&(a=await a),!a)break;const o=pr(a);if(!o)break;n=a.filePos+o.size}let r=e._reader.requestSliceRange(n,Qc,ji);if(le(r)&&(r=await r),!r)return!1;const i=Ds(r);if(!i||(n+=i.frameLength,r=e._reader.requestSliceRange(n,Qc,ji),le(r)&&(r=await r),!r))return!1;const s=Ds(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 Vn{async _canReadInput(e){const n=rn+16+1;let r=e._reader.requestSlice(0,n);if(le(r)&&(r=await r),!r)return!1;const i=Pe(r,n);return i[0]===71&&i[rn]===71||i[0]===71&&i[rn+16]===71?!0:i[4]===71&&i[4+rn+4]===71}_createDemuxer(e){return new jg(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Cd extends Vn{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 Xi))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 Cd,new c1,new l1,new Md,new u1,new d1,new h1,new m1,new f1,new p1,new g1],b1=(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 w1=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},v1=(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});yc();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 li{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"],A1=new Set(rl);class Tn{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(Ii*this.timestamp)}get microsecondDuration(){return Math.trunc(Ii*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||!A1.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&&wc(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??T1(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?rr(e):rr(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&&wc(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&&wc(n.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new Tn(new VideoFrame(e,{timestamp:Math.trunc(n.timestamp*Ii),duration:Math.trunc((n.duration??0)*Ii)||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:l0(),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 li){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=Aa({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 D(this._data!==null),this._data instanceof li?new Tn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Os(this._data)?new Tn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(D(this._layout),new Tn(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 Tn(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 li?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Os(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 Os(this._data)?this._data.allocationSize(e):Ud(this,e).allocationSize}async copyTo(e,n={}){if(!e0(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(D(this._data!==null),Os(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 li){const u={stack:[],error:void 0,hasError:!1};try{const l=w1(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},n.colorSpace??"srgb"),!1);if(!(l instanceof Tn))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{v1(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);D(this.format);const i=rr(e);if(i.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);const s=Ha(this.format);let a;if(this._data instanceof li){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)D(this._layout),D(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");D(l);const d=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:rr(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(D(this._data!==null),this._data instanceof li){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 Os(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(D(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(D(this._data!==null),this._data instanceof li||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=Jo(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=oc(u,e.roundDimensionsTo??1),l=oc(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 x1){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 Tn(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 x1=[],k1=3,Us=[];let Bd=0;const Fd=(t,e)=>{for(const i of Us)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 Us.length>=k1&&Us.splice(bc(Us,i=>i.age),1),Us.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(tc);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(nc);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(rc);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 Os=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 D(s>=0),D(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.")}},T1=(t,e,n)=>{const r=Ha(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},Ha=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:wa(t),D(!1)}},Ud=(t,e)=>{const n={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,i=S1(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 _1(i,a,s)},S1=(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(!P1(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},P1=(t,e)=>{if(t===null)return!0;const n=Ha(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},_1=(t,e,n)=>{const r=Ha(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=[],E1=[];const ui=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.")},$i=t=>{if(!va(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 zs))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(ui(e),this._track.input._disposed)throw new Lt;return sl(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){ui(e);const n=await this.getFirstPacket(e);return n?n.type==="key"?n:this.getNextKeyPacket(n,e):null}async getPacket(e,n={}){if($i(e),ui(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 xt))throw new TypeError("packet must be an EncodedPacket.");if(ui(n),this._track.input._disposed)throw new Lt;return sl(this._track,this._track._backing.getNextPacket(e,n),n)}async getKeyPacket(e,n={}){if($i(e),ui(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&&(D(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 xt))throw new TypeError("packet must be an EncodedPacket.");if(ui(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&&(D(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,n):r)}packets(e,n,r={}){if(e!==void 0&&!(e instanceof xt))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 xt))throw new TypeError("endPacket must be an EncodedPacket.");if(ui(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 M1{constructor(e,n){this.onSample=e,this.onError=n}}class C1{mediaSamplesInRange(e=-1/0,n=1/0,r){$i(e),$i(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){i0(e);const r=r0(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()=>{D(v),D(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);D(I),f.decode(I),k=I}x=-1},S=async()=>{D(f),await f.flush();for(let k=0;k<i.length;k++)m(null);i.length=0};for await(const k of r){if($i(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 D(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 I1 extends M1{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 c0,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 Tn))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();D(d!==void 0),this.mergeAlpha(l,d)}else this.colorQueue.push(l)};if(pc()){if(r==="avc"&&this.decoderConfig.description){const l=tf(rr(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const d=Ea(l.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}ic(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:(D(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(D(this.decoder),dc()||Hu(this.inputTimestamps,e.timestamp,n=>n),pc()&&this.currentPacketIndex===0){if(this.codec==="avc"){const n=[];let r=!1;for(const s of Zu(e.data,this.decoderConfig)){const a=Pa(e.data[s.offset]);if(r||=a>=1&&a<=5,a===Mt.AUD){if(r)break;n.length=0}a>=20&&a<=31||n.push(e.data.subarray(s.offset,s.offset+s.length))}const i=m0(n,this.decoderConfig);e=new xt(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const n=k0(e.data,this.decoderConfig);n&&(e=new xt(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 R1),!this.alphaDecoder){const r=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();D(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();D(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=Mc(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 Ma(e,this.decoderConfig)){const r=Bi(e[n.offset]);if(r===vt.RASL_N||r===vt.RASL_R)return!0}return!1}sampleHandler(e){if(dc()){if(this.sampleQueue.length>0&&e.timestamp>=Qt(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();D(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 Tn(e);else{D(this.merger);const s=await this.merger.merge(e,n);i.sample=new Tn(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){sc(this.finalSamples,i),this.onError(s)}finally{sc(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(D(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),dc()){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()):(D(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 R1{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([`(${B1.toString()})()`],{type:"application/javascript"});ol=URL.createObjectURL(o)}const a=ks(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 B1=()=>{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)}},F1=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 D1 extends C1{constructor(e,n={}){if(!(e instanceof ll))throw new TypeError("videoTrack must be an InputVideoTrack.");F1(n),super(),this._track=e,this._decoderOptions=n}async _createDecoder(e,n){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(u0("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 D(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new I1(e,n,r,s,i,a)}_createPacketSink(){return new al(this._track)}async getSample(e,n={}){$i(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 zs{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 zs))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(fi({filter:n=>n.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(fi({filter:n=>n.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(fi({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(fi({filter:n=>n.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(fi({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 zs{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??=Aa({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Aa({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 D(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 xt))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 D(r),Mc(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&&(!va(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=N1(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:L1(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 zs{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 D(n!==null),E1.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 xt))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Vd=t=>-(t??-1/0),Hs=t=>-t,Vs=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}},fi=(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)},N1=(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 Aa({num:i,den:r})}return null},L1=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};yc();const U1=1,O1=2;class Va extends vc{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 Vn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof hr||e.source instanceof el))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof hr&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Va))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&b1(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof hr?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){D(this._rootSource instanceof Xi);const n=await this._rootSource._resolveRequest(e);return this._emit("source",{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=U1){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(Ss(this._sourceCache,d=>d.cacheGroup===n&&d.sourceRef.source._refCount===1)>=4){const d=bc(this._sourceCache,h=>h.cacheGroup===n&&h.sourceRef.source._refCount===1?h.age:1/0);D(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),sc(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const u=this._sourceCachePromises.findIndex(d=>d.request===e);return D(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 Wa(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(),D(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&&=Vs(e);const r=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return ul(r,e)}async getVideoTracks(e){e&&=Vs(e);const r=(await this.getTracks()).filter(i=>i.isVideoTrack());return ul(r,e)}async getAudioTracks(e){e&&=Vs(e);const r=(await this.getTracks()).filter(i=>i.isAudioTrack());return ul(r,e)}async getPrimaryVideoTrack(e){e&&=Vs(e);const n=fi(e,{sortBy:async i=>[Hs((await i.getDisposition()).default),Hs(await i.hasPairableAudioTrack()),Hs(!await i.hasOnlyKeyPackets()),Vd(await i.getBitrate())]});return(await this.getVideoTracks(n))[0]??null}async getPrimaryAudioTrack(e){e&&=Vs(e);const n=await this.getPrimaryVideoTrack(),r=fi(e,{sortBy:async s=>[Hs(!n||s.canBePairedWith(n)),Hs((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 Wa{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 Sn(s,Je(s),0,e,e)}const r=e+n,i=this.source._read(e,r,pd,gd);return le(i)?i.then(s=>s?new Sn(s.bytes,s.view,s.offset,e,r):null):i?new Sn(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,ks(this.fileSizeNonStrict-e,n,r));{const i=this.requestSlice(e,r),s=a=>a||(D(this.fileSizeNonStrict!==null),this.requestSlice(e,ks(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=Pe(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 Sn(i,Je(i),0,0,r)})()}}class Sn{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 Sn(e,Je(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 Sn(this.bytes,this.view,this.offset,e,e+n)}}const Zt=(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.`)},Pe=(t,e)=>{Zt(t,e);const n=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,n},Se=t=>(Zt(t,1),t.view.getUint8(t.bufferPos++)),Ws=(t,e)=>{Zt(t,2);const n=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,n},At=t=>{Zt(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},mr=t=>{Zt(t,3);const e=Wu(t.view,t.bufferPos);return t.bufferPos+=3,e},fl=t=>{Zt(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},Or=(t,e)=>{Zt(t,4);const n=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,n},ve=t=>{Zt(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},Gi=t=>{Zt(t,4);const e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},di=t=>{Zt(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},z1=t=>{Zt(t,4);const e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},qd=(t,e)=>{let n,r;return e?(n=Or(t,!0),r=Or(t,!0)):(r=Or(t,!1),n=Or(t,!1)),r*4294967296+n},sn=t=>{const e=ve(t),n=ve(t);return e*4294967296+n},H1=t=>{const e=di(t),n=ve(t);return e*4294967296+n},V1=t=>{const e=Gi(t);return z1(t)*4294967296+e},W1=t=>{Zt(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Xd=t=>{Zt(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},mt=(t,e)=>{Zt(t,e);let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t.bytes[t.bufferPos++]);return n},$d=(t,e,n)=>Yt.decode(Pe(t,e)).split(`
|
|
2
|
+
`).map(s=>s.trim()).filter(s=>s.length>0&&!n?.ignore?.(s));var hi;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(hi||(hi={}));var Qi;(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"})(Qi||(Qi={}));const ja=128,mn=10,Yi=["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"],j1=(t,e)=>{const n=t.filePos;e.raw??={},e.raw.TAG??=Pe(t,ja-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=Pe(t,30);let u;if(c[28]===0&&c[29]!==0){const d=c[29];d>0&&(e.trackNumber??=d),t.skip(-30),u=Ki(t,28),t.skip(2)}else t.skip(-30),u=Ki(t,30);u&&(e.comment??=u);const l=Se(t);l<Yi.length&&(e.genre??=Yi[l])},Ki=(t,e)=>{const n=Pe(t,e),r=Ri(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()},pr=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=Lc(a);return s&hi.Footer&&(o+=mn),{majorVersion:r,revision:i,flags:s,size:o}},qa=(t,e,n)=>{if(![2,3,4].includes(e.majorVersion)){Be._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const r=e.flags&hi.Footer?e.size-mn:e.size,i=Pe(t,r),s=new q1(e,i);if(e.flags&hi.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&hi.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&hi.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(Yi[p]!==void 0){n.genre??=Yi[p];break}}if(h=/^\d+$/.exec(f),h){const p=Number.parseInt(h[0]);if(Yi[p]!==void 0){n.genre??=Yi[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 q1{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?Lc(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:Lc(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 Qi.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 Qi.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){const s=new TextDecoder("utf-16le"),a=Ri(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=Ri(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=Ri(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Yt.decode(i.subarray(0,s))}case Qi.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Ri(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 Qi.UTF_8:{const s=Ri(i.findIndex(a=>a===0),i.length);return this.pos=r+Math.min(s+1,i.length),Yt.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 X1(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 Va({source:new tl(t.src),formats:y1});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 D1(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 $1(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=Q1(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 G1(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 Q1(t,e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t.subarray(e,e+n))}catch{return Kd(t,e,n)}}const Y1=Object.freeze(Object.defineProperty({__proto__:null,getEntry:dl,parsePkg:$1,verifyLayout:G1},Symbol.toStringTag,{value:"Module"})),Xa={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 K1(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=$a(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 Z1(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=$a(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 J1(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=$a(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 $a(t,e,n,r){switch(t){case 0:return ey(e,n,r);case 1:return ty(e,n,r);case 2:return ny(e,n,r);case 4:return oy(e,n,r);case 6:return ay(e,n,r);case 7:return sy(e,n,r);case 8:return ry(e,n,r);case 9:return iy(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: "+(Xa[t]||t))}}function ey(t,e,n){return new Uint8Array(t.buffer,t.byteOffset,e*n*4).slice()}function ty(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 ny(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 ry(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 iy(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 sy(t,e,n){return ml(t,e,n,!0,0)}function ay(t,e,n){return ml(t,e,n,!1,3)}function oy(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=cy(o,r),f=ly(o,r),h=i===3?uy(o):i===5?fy(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 cy(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 ly(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 uy(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 fy(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 dy(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 et(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Ga(t,e){return et(t,e)|0}const js=new DataView(new ArrayBuffer(4));function zr(t,e){return js.setUint8(0,t[e]),js.setUint8(1,t[e+1]),js.setUint8(2,t[e+2]),js.setUint8(3,t[e+3]),js.getFloat32(0,!0)}const hy={[$t.PNG]:[137,80,78,71],[$t.JPEG]:[255,216,255],[$t.GIF]:[71,73,70],[$t.WEBP]:[82,73,70,70]};function my(t){let e=0;const n=qs(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=qs(t,e,9);if(e+=9,r!=="TEXI0001\0")throw new Error("\u672A\u77E5 TEXI \u5B50\u5BB9\u5668: "+r);const i=et(t,e);e+=4;const s=et(t,e);e+=4;const a=et(t,e);e+=4;const o=et(t,e);e+=4;let c=46;for(let v=34;v<=64;v++){const x=qs(t,v,9);if(x==="TEXB0001\0"||x==="TEXB0002\0"||x==="TEXB0003\0"||x==="TEXB0004\0"){c=v;break}}const u=et(t,c-12),l=et(t,c-8);e=c;const d=qs(t,e,9);e+=9;const f=et(t,e);e+=4;let h=$t.UNKNOWN,p=0;if(d==="TEXB0004\0"){h=et(t,e)|0,e+=4;const v=et(t,e);e+=4,h===$t.UNKNOWN&&v===1&&(h=$t.MP4),p=v===1?4:3}else if(d==="TEXB0003\0")h=et(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=et(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=et(t,e);e+=4;const _=et(t,e);e+=4;let I=0;if(s&64&&p>=2&&!m){const ie=et(t,e),we=Ga(t,e+8),Y=et(t,e+4),oe=Ga(t,e+12),he=Ce=>{if(!(oe>=0)||Ce+oe>t.length)return!1;const Ue=hy[h];return Ue?Ue.every((Ne,De)=>t[Ce+De]===Ne):!0},Ae=ie<=1&&we>=0&&e+12+we<=t.length,Ee=Y<=1&&he(e+16);!Ae&&Ee&&(I=4)}e+=I;let B=0,V=0;p>=2&&(B=et(t,e),e+=4,V=Ga(t,e),e+=4);const O=Ga(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=qs(t,e,9);if(v.indexOf("TEXS")===0){let x=e+9;const P=et(t,x);x+=4;let S=0,k=0;v==="TEXS0003\0"&&(S=et(t,x),x+=4,k=et(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=zr(t,U+8),ie=zr(t,U+12),we=zr(t,U+16),Y=zr(t,U+20),oe=zr(t,U+24),he=zr(t,U+28),Ae=Math.hypot(we,Y),Ee=Math.hypot(oe,he);B.push({imageId:zr(t,U)|0,duration:zr(t,U+4),x:W,y:ie,width:(Ae>1e-30?Ae:0)||S,height:(Ee>1e-30?Ee: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:Xa[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=et(t,e);e+=4;const r=et(t,e);e+=4;const i=et(t,e);e+=4;const s=et(t,e);e+=4;const a=et(t,e);e+=4;const o=et(t,e);e+=4;const c=et(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=et(t,e);e+=4;const f=et(t,e);e+=4;const h=et(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:Xa[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 qs(t,e,n){let r="";for(let i=e;i<e+n;i++)r+=String.fromCharCode(t[i]);return r}const gy=Object.freeze(Object.defineProperty({__proto__:null,FIF:$t,TEXTURE_FORMATS:Xa,cropBlocks:dy,decodeMip0:K1,decodeMipLevel:Z1,decodeMips:J1,decodePixels:$a,lz4Decompress:Jd,parseTex:my},Symbol.toStringTag,{value:"Module"})),Hr=0,pl=1;function gl(t,e){const n=new Map,r=eh(t)||yy(n),i=eh(e)||null,s=o=>o===pl&&i?i:r,a={LOCATION_SCREEN:Hr,LOCATION_GLOBAL:pl,getItem(o,c=Hr){return s(c).get(String(o))},setItem(o,c,u=Hr){s(u).set(String(o),String(c))},delete(o,c=Hr){s(c).remove(String(o))},removeItem(o,c=Hr){s(c).remove(String(o))},clear(o=Hr){s(o).clear()},key(o,c=Hr){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 yy(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 by(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 wy(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 vy(t,e,n,r){const[i,s,a,o]=th(t,e,n);return Math.max(r,i,s,a,o)}function Ay(t,e,n){return t<=4&&e<=4&&!!n}function xy(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 Zi(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||Zi),t.setTimeout||(t.setTimeout=e.setTimeout||Zi),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 Le{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 Le(e);return new Le(this.x+n.x,this.y+n.y,this.z+n.z)}subtract(e){const n=new Le(e);return new Le(this.x-n.x,this.y-n.y,this.z-n.z)}multiply(e){return e&&typeof e=="object"?new Le(this.x*e.x,this.y*e.y,this.z*e.z):new Le(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 Le(n(this.x,e.x),n(this.y,e.y),n(this.z,e.z)):new Le(n(this.x,e),n(this.y,e),n(this.z,e))}copy(){return new Le(this.x,this.y,this.z)}mix(e,n){const r=new Le(e),i=Number(n),s=Number.isFinite(i)?i:0;return new Le(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 Le(0,0,0):new Le(this.x/e,this.y/e,this.z/e)}dot(e){const n=new Le(e);return this.x*n.x+this.y*n.y+this.z*n.z}toString(){return this.x+" "+this.y+" "+this.z}}const ah=Le;function yl(t){if(t instanceof Le||!t||typeof t!="object"||Array.isArray(t)||!("x"in t)&&!("y"in t)&&!("z"in t)||Object.getPrototypeOf(t)===Le.prototype)return t;try{Object.setPrototypeOf(t,Le.prototype)}catch{}return t}function oh(t){return t&&t.cursorWorldPosition?t:{cursorWorldPosition:new Le(0,0,0),cursorScreenPosition:new Le(0,0,0),cursorPosition:new Le(0,0,0),cursorPositionLast:new Le(0,0,0),cursorLeftDown:!1}}function ky(t,e,n){return new Le(t||0,e||0,n||0)}function Ty(){const t={cursorWorldPosition:new Le(0,0,0),cursorScreenPosition:new Le(0,0,0),cursorPosition:new Le(0,0,0),cursorPositionLast:new Le(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 Le(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 Le(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}),Qa=["mediaPropertiesChanged","mediaThumbnailChanged","mediaPlaybackChanged","mediaTimelineChanged","mediaStatusChanged","mediaLyricsChanged"],Sy=["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"],Py=new RegExp(`(^[ \\t]*|;|\\})[ \\t]*(?:var|let|const)[ \\t]+(?=(?:${Sy.join("|")})\\b)`,"gm"),_y={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 _y[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(Py,"$1")}function Ey(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 Ya(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=Ya(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]=Ya(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 Le(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 My(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]=Ya(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:mi(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||Zi,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||Zi,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:mi(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,`+ia.map(v=>`${v}: typeof ${v} === "function" ? ${v} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,dummy_: 0};')(i,Tf(o),a,u,Ef,Cf,If,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,xe,Pf,d,Mf)}catch(b){return n.onError&&n.onError(b,"parse"),null}const p=!!(h&&ia.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 Ji(){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 c0(t){if(!t)return Ji();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 l0(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 u0(){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 f0(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 xe(k[0],k[1],0)}const w=or(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 xe(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 lc(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 Lf(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 d0(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 h0(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 m0(t){const e=n=>aa(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){d0(Lf(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 Ji()},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):Lf(n,t)||null}}}function aa(t,e){const n=a=>es(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:y0(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?f0(t,r):{getBoneCount:()=>0,getBoneTransform:()=>{const a={translation(o){return o===void 0?new xe(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:aa(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(aa(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]||Ji()}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)]:Ji()},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)]:Ji()},getAnimationLayerCount:()=>(t&&t.animationList||[]).length,getTextureAnimation:()=>c0(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:()=>l0(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 lc(null);if(typeof a=="number"||typeof a=="string"&&/^\d+$/.test(a))return lc(o[Number(a)]||null);const c=String(a);return lc(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=Uf(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 es(o||[0,0,0])},set(o){const c=or(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 p0(t,e,n={}){if(typeof t!="string"||t.length===0)return null;const r=Rf(t),i={};if(e&&typeof e=="object")for(const[A,T]of Object.entries(e))Df(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"&&Af.test(T))return S=>(S&&typeof S=="object"&&typeof S.name=="string"&&!(S.name in i)&&(i[S.name]=sa(S.value)),s)}}),a={registerAsset:A=>A,frametime:1/60,runtime:0,canvasSize:Nf(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||gi,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||gi,clearInterval:n.clearInterval||(()=>{}),openUserShortcut:n.openUserShortcut||(()=>{}),isRunningInEditor:cc(n.isRunningInEditor),isScreensaver:!!n.isScreensaver};Sf(a,n);const o=n.audioViews;a.registerAudioBuffers=A=>{const T=Ff(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:xf()},l=_f(n.inputView),f=n.layer||null,d=n.workshopId!=null?n.workshopId:h0(t),h=aa(f,n),p=m0({...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,`+Qa.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,Le,ah,f,fh,n.storage||gl())}catch(b){return n.onError&&n.onError(b,"parse"),null}const p=!!(h&&Qa.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 Xs(){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 Cy(t){if(!t)return Xs();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 Iy(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 Ry(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 Le(v[0],v[1],0)}const y=gr(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 Le(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 By(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 Fy(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 Dy(t){const e=n=>Ka(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){By(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 Xs()},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 Ka(t,e){const n=o=>mi(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:Uy(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 mi(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?Ry(t,r):{getBoneCount:()=>0,getBoneTransform:()=>{const o={translation(c){return c===void 0?new Le(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:Ka(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(Ka(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]||Xs()}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)]:Xs()},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)]:Xs()},getAnimationLayerCount:()=>(t&&t.animationLayers||[]).length||(t&&t.animationList||[]).length,getTextureAnimation:()=>Cy(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:()=>Iy(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 mi(l||u)},set(c){const u=gr(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 Ny(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]=Ya(_.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||Zi,clearTimeout:n.clearTimeout||(()=>{}),setInterval:n.setInterval||Zi,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:Fy(t),h=Ka(d,n),p=Dy({...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,`+ia.map(T=>`${T}: typeof ${T} === "function" ? ${T} : null,`).join("")+'animationEvent: typeof animationEvent === "function" ? animationEvent : null,dummy_: 0};')(i,Tf(a),Ef,Cf,If,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,xe,Pf,l,h,p,h,u0(),Mf)}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&&ia.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(oc(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(oc(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,oc(T))}catch(S){k.errCount++,n.onError&&n.onError(S,"animationEvent"),k.errCount>=3&&(k.disabled=!0);return}}};return k}function es(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=or(i);return n.x+=s[0],n.y+=s[1],n.z+=s[2],r},subtract(i){const s=or(i);return es([n.x-s[0],n.y-s[1],n.z-s[2]])},multiply(i){if(i&&typeof i=="object"){const s=or(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 xe(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 or(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 oa=Math.PI/180,ca=180/Math.PI;function g0(t){const e=Array.isArray(t)?t:[0,0,0];return{x:(e[0]||0)*ca,y:(e[1]||0)*ca,z:(e[2]||0)*ca}}function Uf(t){const e=or(t);return[e[0]*oa,e[1]*oa,e[2]*oa]}function y0(t){const e={x:0,y:1,z:2},n={add(r){const i=or(r);return n.x+=i[0],n.y+=i[1],n.z+=i[2],n},subtract(r){const i=or(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)*ca},set(i){!t||!Array.isArray(t.angles)||(t.angles[e[r]]=(Number(i)||0)*oa)}});return n}function b0(t,e){return Math.min(256,Math.ceil(Math.max(1,Number(t)||1)*2+8))}function w0(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 v0=Object.freeze(Object.defineProperty({__proto__:null,Vec3:xe,createInputView:n0,drawTextLayer:e0,effectiveTextPadding:Yg,evalObjectScript:p0,evalTextScript:o0,foldVisibleReturn:a0,inkOverflow:kf,layoutText:Kg,makeCursorEventVec:t0,radToScriptAngles:g0,resolveWorkshopAssetPath:Of,rewriteComboStringEq:Bf,scriptAnglesToRad:Uf,shouldGrowMediaPlaceholder:Jg,textCanvasMargin:b0,textCanvasMarginGrow:Zg,textLayerHasTintMask:w0},Symbol.toStringTag,{value:"Module"}));function zf(t){if(t instanceof xe)return t;if(Array.isArray(t))return new xe(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0);const e=String(t??"").trim().split(/\s+/).map(Number);return new xe(e[0]||0,e[1]||0,e[2]||0)}function Hf(t,e){if(!t||typeof e!="string")return null;const n=t[e];return n&&typeof n=="object"?n:null}function uc(t){return typeof t=="string"?t:t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}function k0(t,e){return la(t)&&la(e)?Number(t)===Number(e):String(t)===String(e)}function fc(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 A0(t){switch(t.type){case"bool":return"bool";case"slider":return"num";case"color":return"num";case"textinput":return"text";default:return fc(t.value)}}function Vf(t,e){if(t===null||typeof t!="object")return t;if(t.user&&typeof t.user=="object"&&typeof t.user.name=="string"){const r=Hf(e,t.user.name);if(!r||r.value===void 0||r.value===null)return t.value;const i=r.type==="combo"?dc(r.value,r.options):r.value;return k0(i,t.user.condition)}if(typeof t.user!="string")return t;const n=Hf(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(fc(t.value)==="bool"&&n.type==="slider"){const r=Number(n.value);return Number.isFinite(r)?r!==0:t.value}return fc(t.value)===A0(n)?n.value:t.value}function Rr(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]=Rr(t[r],e,n+1);return t}if(uc(t.user)){let r=Vf(t,e);for(let i=0;i<8&&r!==null&&typeof r=="object"&&uc(r.user);i++)r=Vf(r,e);return t.value=Rr(r,e,n+1),t}for(const r of Object.keys(t))t[r]=Rr(t[r],e,n+1);return t}function x0(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 la(t){return typeof t=="number"?Number.isInteger(t):typeof t=="string"&&/^-?\d+$/.test(t.trim())}function dc(t,e){const n=x0(e);return!(n.length>0?n.every(la):la(t))||typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&/^-?\d+$/.test(t.trim())?Number(t):t}function T0(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"?dc(r.value,r.options):r.type==="color"?zf(r.value):r.value);return e}function yn(t){return t&&typeof t=="object"?uc(t.user):null}function S0(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"?dc(u.value,u.options):u.value,f=u.type==="color"?zf(l):l;s[a]=f,r[a]=f}else s[a]=c,r[a]=c}return r}function yi(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 ts(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 ua(t){return t==null?[1,1,1]:typeof t=="string"?yi(t):typeof t=="object"&&t!==null?yi(t.value):[1,1,1]}function Vt(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 $t(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 hc(t){return t?!t.image&&!t.model&&!t.particle&&t.text==null&&!t.size:!1}function mc(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 P0(t,e){const n=e&&e.general&&e.general.properties||{},r=t.objects||[];Rr(r,n,0),Rr(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:yi(g.origin||"0 0 0"),scale:yi(g.scale||"1 1 1"),angles:yi(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)&&hc(A)),M=mc(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=>Vt(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=ts(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:$t(g.volume,1),playbackmode:g.playbackmode||"single",startsilent:Vt(g.startsilent,!1),maxtime:$t(g.maxtime,0),mintime:$t(g.mintime,0),spatialization:Vt(g.spatialization,!1),muteineditor:Vt(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:$t(g.pointsize,24)||24,textColor:ua(g.color),textAnchor:typeof g.anchor=="string"&&g.anchor!=="none"?g.anchor:"center",textMaxwidth:$t(g.maxwidth,0),textMaxrows:$t(g.maxrows,0),textLimitwidth:Vt(g.limitwidth,!1),textLimitrows:Vt(g.limitrows,!1),textLimituseellipsis:Vt(g.limituseellipsis,!1),textHAlign:g.horizontalalign||"center",textVAlign:g.verticalalign||"center",textSpacing:g.spacing?ts(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:Vt(g.opaquebackground,!1),textBackgroundcolor:ua(g.backgroundcolor),textBackgroundbrightness:$t(g.backgroundbrightness,1),textCastshadow:Vt(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:Vt(A.visible,!0),additive:Vt(A.additive,!1),blend:$t(A.blend,1),rate:$t(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:hc(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:ua(g.color),alpha:$t(g.alpha,1),brightness:$t(g.brightness,1),copybackground:!!g.copybackground,colorBlendMode:g.colorBlendMode||0,parallaxDepth:g.parallaxDepth!==void 0?ts(g.parallaxDepth):null,effects:(g.effects||[]).map(A=>({file:A.file||"",name:typeof A.name=="string"?A.name:"",visible:Vt(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],U=N&&typeof N=="object"&&typeof N.name=="string"?N.name:typeof N=="string"?N:null;U&&(M===S&&(M=S.slice()),M[B]=U)}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 _0(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 E0(t,e){!t||!e||typeof e!="object"||t.isContainer||e.solidlayer===!0&&(t.solid=!0)}function C0(t){return!t||typeof t.material!="string"?null:{materialPath:t.material,autosize:!!t.autosize,cropoffset:t.cropoffset?ts(t.cropoffset):null}}function I0(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=mc({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 M0(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 B0=Object.freeze(Object.defineProperty({__proto__:null,applySolidFromModel:E0,collectTransformDirty:M0,composeChildTransform:mc,isRenderInert:hc,parseBool:Vt,parseColor:ua,parseNum:$t,parseScene:P0,parseVec2:ts,parseVec3:yi,recomposeWorld:I0,recomputeLayerVisibility:_0,resolveMaterial:C0},Symbol.toStringTag,{value:"Module"}));function R0(t,e,n){const r=rc(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=rc(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 F0={"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 Wf(t){if(!t||typeof t!="string")return!0;const e=t.toLowerCase();return e==="generic"||e==="sprite"||e==="flat"||e.startsWith("genericimage")}function D0(t,e){return!t||!e||!e.shader||Wf(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 N0=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_MATERIALS:{"materials/util/solidlayer.json":{passes:[{shader:"flat",blending:"translucent",cullmode:"nocull",depthtest:"disabled",depthwrite:"disabled",textures:[],combos:{}}]}},BUILTIN_MODELS:F0,attachLayerMaterialEffect:D0,isBuiltinAlbedoShader:Wf,resolveEffectChain:R0},Symbol.toStringTag,{value:"Module"}));function L0(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 O0(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=Wn(f);let h=n.body;n.args.forEach((p,m)=>{const g=d[m]!==void 0?d[m].trim():"";h=ns(h,p,g)}),r>0&&(h=jf(h,r-1)),i.push("("+h+")"),s=l+1}return i.join("")}function ns(t,e,n){return t.replace(new RegExp("\\b"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","g"),n)}function Wn(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 jf(t,e){for(let n=0;n<12;n++){const{defs:r,fns:i}=L0(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
|
|
9
|
-
`),!c)break}return t}function
|
|
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,`+Qa.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,Le,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&&Qa.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 mi(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=gr(i);return n.x+=s[0],n.y+=s[1],n.z+=s[2],r},subtract(i){const s=gr(i);return mi([n.x-s[0],n.y-s[1],n.z-s[2]])},divide(i){const s=gr(i),a=(o,c)=>c===0?0:o/c;return mi([a(n.x,s[0]),a(n.y,s[1]),a(n.z,s[2])])},multiply(i){if(i&&typeof i=="object"){const s=gr(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 Le(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 gr(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 Za=Math.PI/180,Ja=180/Math.PI;function Ly(t){const e=Array.isArray(t)?t:[0,0,0];return{x:(e[0]||0)*Ja,y:(e[1]||0)*Ja,z:(e[2]||0)*Ja}}function wh(t){const e=gr(t);return[e[0]*Za,e[1]*Za,e[2]*Za]}function Uy(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=gr(s);return i.x+=a[0],i.y+=a[1],i.z+=a[2],i},subtract(s){const a=gr(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)*Ja:0},set(a){r(n[s],(Number(a)||0)*Za)}});return i}function Oy(t,e){return Math.min(256,Math.ceil(Math.max(1,Number(t)||1)*2+8))}function zy(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 Hy=Object.freeze(Object.defineProperty({__proto__:null,LOCATION_GLOBAL:pl,LOCATION_SCREEN:Hr,Vec3:Le,createInputView:Ty,drawTextLayer:xy,effectiveTextPadding:by,evalObjectScript:Ny,evalTextScript:My,foldVisibleReturn:Ey,inkOverflow:th,layoutText:wy,makeCursorEventVec:ky,makeSandboxStorage:gl,radToScriptAngles:Ly,resolveWorkshopAssetPath:bh,rewriteComboStringEq:dh,scriptAnglesToRad:wh,shouldGrowMediaPlaceholder:Ay,textCanvasMargin:Oy,textCanvasMarginGrow:vy,textLayerHasTintMask:zy},Symbol.toStringTag,{value:"Module"}));function vh(t){if(t instanceof Le)return t;if(Array.isArray(t))return new Le(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0);const e=String(t??"").trim().split(/\s+/).map(Number);return new Le(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 Vy(t,e){return eo(t)&&eo(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 Wy(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 Vy(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)===Wy(n)?n.value:t.value}function pi(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]=pi(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=pi(r,e,n+1),t}for(const r of Object.keys(t))t[r]=pi(t[r],e,n+1);return t}function jy(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 eo(t){return typeof t=="number"?Number.isInteger(t):typeof t=="string"&&/^-?\d+$/.test(t.trim())}function xl(t,e){const n=jy(e);return!(n.length>0?n.every(eo):eo(t))||typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&/^-?\d+$/.test(t.trim())?Number(t):t}function qy(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 Wn(t){return t&&typeof t=="object"?vl(t.user):null}function Xy(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 Ji(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 es(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 to(t){return t==null?[1,1,1]:typeof t=="string"?Ji(t):typeof t=="object"&&t!==null?Ji(t.value):[1,1,1]}function an(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 pn(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 $y(t,e){const n=e&&e.general&&e.general.properties||{},r=t.objects||[];pi(r,n,0),pi(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:Ji(g.origin||"0 0 0"),scale:Ji(g.scale||"1 1 1"),angles:Ji(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=>an(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=es(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:pn(g.volume,1),playbackmode:g.playbackmode||"single",startsilent:an(g.startsilent,!1),maxtime:pn(g.maxtime,0),mintime:pn(g.mintime,0),spatialization:an(g.spatialization,!1),muteineditor:an(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:pn(g.pointsize,24)||24,textColor:to(g.color),textAnchor:typeof g.anchor=="string"&&g.anchor!=="none"?g.anchor:"center",textMaxwidth:pn(g.maxwidth,0),textMaxrows:pn(g.maxrows,0),textLimitwidth:an(g.limitwidth,!1),textLimitrows:an(g.limitrows,!1),textLimituseellipsis:an(g.limituseellipsis,!1),textHAlign:g.horizontalalign||"center",textVAlign:g.verticalalign||"center",textSpacing:g.spacing?es(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:an(g.opaquebackground,!1),textBackgroundcolor:to(g.backgroundcolor),textBackgroundbrightness:pn(g.backgroundbrightness,1),textCastshadow:an(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:an(x.visible,!0),additive:an(x.additive,!1),blend:pn(x.blend,1),rate:pn(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:to(g.color),alpha:pn(g.alpha,1),brightness:pn(g.brightness,1),copybackground:!!g.copybackground,colorBlendMode:g.colorBlendMode||0,perspective:g.perspective===!0?!0:void 0,parallaxDepth:g.parallaxDepth!==void 0?es(g.parallaxDepth):null,parallaxDepthOwn:g.parallaxDepth!==void 0?es(g.parallaxDepth):null,disablePropagation:g.disablepropagation===!0,effects:(g.effects||[]).map(x=>({file:x.file||"",name:typeof x.name=="string"?x.name:"",visible:an(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 Gy(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 Qy(t,e){!t||!e||typeof e!="object"||t.isContainer||e.solidlayer===!0&&(t.solid=!0)}function Yy(t){return!t||typeof t.material!="string"?null:{materialPath:t.material,autosize:!!t.autosize,cropoffset:t.cropoffset?es(t.cropoffset):null}}function Ky(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 Zy(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 Jy=Object.freeze(Object.defineProperty({__proto__:null,applySolidFromModel:Qy,collectTransformDirty:Zy,composeChildTransform:kl,isRenderInert:kh,parseBool:an,parseColor:to,parseNum:pn,parseScene:$y,parseVec2:es,parseVec3:Ji,recomposeWorld:Ky,recomputeLayerVisibility:Gy,resolveMaterial:Yy},Symbol.toStringTag,{value:"Module"}));function eb(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 tb={"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 nb(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 rb=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_MATERIALS:{"materials/util/solidlayer.json":{passes:[{shader:"flat",blending:"translucent",cullmode:"nocull",depthtest:"disabled",depthwrite:"disabled",textures:[],combos:{}}]}},BUILTIN_MODELS:tb,attachLayerMaterialEffect:nb,isBuiltinAlbedoShader:Th,resolveEffectChain:eb},Symbol.toStringTag,{value:"Module"}));function ib(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 sb(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=yr(d);let h=n.body;n.args.forEach((p,m)=>{const g=f[m]!==void 0?f[m].trim():"";h=$s(h,p,g)}),r>0&&(h=Sh(h,r-1)),i.push("("+h+")"),s=l+1}return i.join("")}function $s(t,e,n){return t.replace(new RegExp("\\b"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","g"),n)}function yr(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}=ib(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=$s(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=sb(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
|
|
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(
|
|
14
|
-
`)}function
|
|
15
|
-
`))break}for(;
|
|
16
|
-
`||q===")")break}const U=M.slice(P,N);return/\d\.\d/.test(U)?`${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=ut(l,v,k=>{const T=Wn(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=ut(l,"pow",v=>{const k=Wn(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=ut(l,y,b=>y+"("+b.replace(/(?<![A-Za-z0-9_.])(\d+)(?![.\d])/g,"$1.0")+")");l=ut(l,"clamp",y=>{const b=Wn(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=ut(l,"smoothstep",y=>{const b=Wn(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 U=0;for(let q=P.indexOf("(");q<P.length;q++)if(P[q]==="(")U++;else if(P[q]===")"&&(U--,U===0))return q===P.length-1?Number(N[1]):0;return 0}}if(/^texture(?:Lod)?\s*\(/.test(P)){let N=0;for(let U=P.indexOf("(");U<P.length;U++)if(P[U]==="(")N++;else if(P[U]===")"&&(N--,N===0))return U===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 U=Number(M);return A(N)<=U?S:`${P}vec${M} ${B} = (${N.trim()}).${T[U]};`})}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 U=N.match(new RegExp("^(?:"+S+")\\s*\\("));if(!U)return!1;let q=0;const H=U[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=U[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,U,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),U+q+" = vec"+G+"("+Y+");")}),B.size>0){const N=[...B].sort((U,q)=>q.length-U.length).join("|");l=l.replace(new RegExp(`\\b([A-Za-z_]\\w*)\\s*([*/])\\s*(${N})\\b`,"g"),(U,q,H,G)=>y.has(q)?U:`${q} ${H} ${G}.x`),l=l.replace(new RegExp(`\\b(${N})\\s*([*/])\\s*([A-Za-z_]\\w*)\\b`,"g"),(U,q,H,G)=>y.has(G)?U:`${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=Qf(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=Qf(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=fa(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=fa(l,M,"[","]");if(B<0)break;const N=l.slice(S+1,P),U=l.slice(M+1,B);k+=l.slice(A,T.index),k+=T[1]+"[int(("+N+")) * 4 + int(("+U+"))]",A=B+1,v.lastIndex=A}l=k+l.slice(A)}}l=ut(l,"mix",(y,b)=>{const v=Wn(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 U=/^vec([234])\s*\(/.exec(B);if(U)return Number(U[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=$f(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=fa(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 U of l.slice(0,k.index).matchAll(/\buniform\s+(?:highp|mediump|lowp\s+)?(vec([234]))\s+([A-Za-z_]\w*)/g))B.set(U[3],Number(U[2]));for(const U of M.matchAll(/\b(vec([234]))\s+([A-Za-z_]\w*)/g))B.set(U[3],Number(U[2]));const N=P===2?"xy":"xyz";M=M.replace(/\breturn\s+([A-Za-z_]\w*)\s*;/g,(U,q)=>{const H=B.get(q);return H&&H>P?"return "+q+"."+N+";":U}),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=ut(l,"mul",y=>{const b=Wn(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=ut(l,"atan2",y=>"atan("+y+")"),l=ut(l,"fmod",y=>{const b=Wn(y);if(b.length!==2)return"mod("+y+")";const v=b[0].trim(),k=b[1].trim();return"(("+v+") - ("+k+") * trunc(("+v+") / ("+k+")))"}),l=ut(l,"ddx",y=>"dFdx("+y+")"),l=ut(l,"ddy",y=>"dFdy("+y+")"),l=ut(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,U,q)=>{const H=v.get(U);return!H||T[H]<=T[B]?P:(S.set(U,T[B]),M+H+N+U+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(
|
|
18
|
-
`))}}l=l.replace(/^(\s*in\s+(?:highp|mediump|lowp\s+)?)(vec[234]|float)(\s+)([A-Za-z_]\w*)(\s*;)/gm,(
|
|
19
|
-
`).map(
|
|
20
|
-
`))}const
|
|
21
|
-
`+S.map(
|
|
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(Gs(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(Gs(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")){Gs(a)&&s.push(u);continue}if(l.startsWith("#ifdef")||l.startsWith("#ifndef")||l.startsWith("#if")){const d=Gs(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("#")||Gs(a)&&s.push(u)}return s.join(`
|
|
14
|
+
`)}function Gs(t){return t.every(e=>e.parent&&e.hit)}function no(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 no(t,e,"(",")")}const ab=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 ob(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 ab.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 cb(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 lb(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])||!cb(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 It(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(ob(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=$s(l,v,String(x))}}l=$s(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=It(l,"saturate",w=>"clamp("+w+", 0.0, 1.0)"),l=It(l,"CAST4",w=>"vec4("+w+")"),l=It(l,"CAST3",w=>"vec3("+w+")"),l=It(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=It(l,b,v=>{const P=yr(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=It(l,"pow",b=>{const v=yr(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=It(l,w,A=>w+"("+A.replace(/(?<![A-Za-z0-9_.])(\d+)(?![.\d])/g,"$1.0")+")");l=It(l,"clamp",w=>{const A=yr(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=It(l,"smoothstep",w=>{const A=yr(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=lb(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=no(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=no(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=It(l,"mix",(w,A)=>{const b=yr(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=no(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=It(l,"mul",w=>{const A=yr(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=It(l,"atan2",w=>"atan("+w+")"),l=It(l,"fmod",w=>{const A=yr(w);if(A.length!==2)return"mod("+w+")";const b=A[0].trim(),v=A[1].trim();return"(("+b+") - ("+v+") * trunc(("+b+") / ("+v+")))"}),l=It(l,"ddx",w=>"dFdx("+w+")"),l=It(l,"ddy",w=>"dFdy("+w+")"),l=It(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=It(l,_,I=>{const B=yr(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=$s(P,k,k+"_rw")}S.length>0&&(P=`
|
|
21
|
+
`+S.map(k=>k.replace(/= (\w+)_rw;/,"= $1;")).join(`
|
|
22
22
|
`)+`
|
|
23
|
-
`+
|
|
24
|
-
`).map(
|
|
25
|
-
`)}
|
|
26
|
-
`;return e==="vert"&&(
|
|
27
|
-
`),e==="frag"&&(
|
|
28
|
-
`,/\bgl_FragColor\b/.test(l)&&(
|
|
29
|
-
`,l=l.replace(/\bgl_FragColor\b/g,"fragColor"))),
|
|
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 Ue=/\bfor\s*\(/g;let Ne=-1,De;for(;(De=Ue.exec(ie))!==null;)Ne=De.index;if(Ne>=0){const Re=ie.slice(Ne);let Fe=0,Ge=!1;for(const Qe of Re)Qe==="("?(Fe++,Ge=!0):Qe===")"&&(Fe--,Fe<=0&&(Ge=!1));if(Ge&&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,Ee=!!(Y&&Y[2])||!!(oe&&oe[1]),Ce=(he&&A(he,k)?he:null)||(Ae&&A(Ae,k)?Ae:null);Ee&&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"},ub={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
|
-
}
|
|
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
|
+
}`,fb=`#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
|
-
${
|
|
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
|
-
}`,
|
|
198
|
+
}`,db=`#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
|
-
}`,
|
|
213
|
+
}`,hb=`#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
|
-
}`,
|
|
257
|
+
}`,mb=`#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
|
-
}`,
|
|
270
|
+
}`,pb=`#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
|
-
}`,
|
|
299
|
+
}`,gb=`#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
|
-
}`,
|
|
313
|
+
}`,ts=`#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
|
-
}
|
|
321
|
+
}`,yb=`#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
|
-
}`,
|
|
337
|
+
}`,bb=`#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
|
-
}`,
|
|
348
|
+
}`,wb=`#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 K0(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 Z0(){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 J0(){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 ey={5126:"float",35664:"vec2",35665:"vec3",35666:"vec4",5124:"int",35667:"ivec2",35668:"ivec3",35669:"ivec4",35670:"bool",35676:"mat4",35675:"mat3"};function cr(t,e,n){const r=ed(t,t.VERTEX_SHADER,e),i=ed(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 ed(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 pc(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 gc(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 ty(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 yc(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 ny(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=yc(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,yc(t,e,n,r,s)<i?a=s:o=s;return s}function da(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 da([{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=ny(c,v,k,u,e);return yc(l,A,T,f,S)}function td(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 ry(t){return Array.isArray(t)?t:typeof t=="string"?t.trim().split(/\s+/).map(Number):Number.isFinite(t)?[t]:[]}function nd(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 iy(t,e,n){const r=nd(t._events,e,n,t.frameCount||1,t.mode);for(const i of r)t._eventQueue.push(i)}function rd(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 id(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);iy(p,g,p.frame)},takeEvents(){if(!p._eventQueue.length)return[];const m=p._eventQueue.slice();return p._eventQueue.length=0,m},value(){const m=td(p.parent?p.parent.frame:p.frame,r,i),g=o?{length:r}:void 0;if(c.length===1)return da(c[0],m,g);const w=[];for(const y of c)w.push(da(y,m,g));return w},applyTo(m){const g=p.value();if(!a)return g;const w=ry(m);return Array.isArray(g)?g.map((y,b)=>y+(Number(w[b])||0)):g+(Number(w[0])||0)}};return p}function sy(){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 ay=Object.freeze(Object.defineProperty({__proto__:null,createAnimation:id,createNeutralAnimation:sy,crossedEvents:nd,linkAnimations:rd,sampleChannel:da,wrapFrame:td},Symbol.toStringTag,{value:"Module"}));function oy(t,e,n,r){const i=s=>ha(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)=>sd(s,a));case 12:return i((s,a)=>cy(s,a));case 13:return i((s,a)=>sd(a,s));case 14:return i((s,a)=>[bi(s[0],a[0]),bi(s[1],a[1]),bi(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)=>[bi(s[0],a[0])<.5?0:1,bi(s[1],a[1])<.5?0:1,bi(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)=>ly(s,a));case 27:return i((s,a)=>uy(s,a));case 28:return i((s,a)=>fy(s,a));case 29:return i((s,a)=>dy(s,a));case 30:{const s=Math.max(e[0],Math.max(e[1],e[2]));return ha(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 ha(e,[e[0]+e[0]*n[0],e[1]+e[1]*n[1],e[2]+e[2]*n[2]],r);default:return ha(e,n,r)}}function ha(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 sd(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 cy(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 bi(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 lr(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 bc(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 ma(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[bc(n,e,t[0]+1/3),bc(n,e,t[0]),bc(n,e,t[0]-1/3)]}function ly(t,e){const n=lr(t);return ma([lr(e)[0],n[1],n[2]])}function uy(t,e){const n=lr(t);return ma([n[0],lr(e)[1],n[2]])}function fy(t,e){const n=lr(e);return ma([n[0],n[1],lr(t)[2]])}function dy(t,e){const n=lr(t);return ma([n[0],n[1],lr(e)[2]])}function ad(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 od(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 pa(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),pa(i,e,n))}return n}function wc(t){const e=Zf[t]||"translucent";return{mode:e,prep:H0[e]||0}}function cd(t,e){const n=Number(t);return Number.isFinite(n)&&n!==0?n:e==="additive"?9:Number.isFinite(n)?n:0}function vc(t){const e=Number(t);return!Number.isFinite(e)||e===0?!1:!Zf[e]}function hy(t,e,n,r){if(vc(t))return oy(t,[e,e,e],[n,n,n],r)[0];const{mode:i,prep:s}=wc(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 ld(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 ud(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=pc(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 my(t){const e=Number(t);return!Number.isFinite(e)||e<.001?999:1/e}const ss=-1;function kc(t,e){return!!e&&!t}const py="mix(999.0, 1.0 / max(g_PointerScale, 0.001), step(0.001, g_PointerScale))";function fd(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 *= "+py+" *")}const dd=1;function hd(t,e){return t==="g_PointerScale"?dd:e}function gy(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 U=!1,q=!1,H=0;typeof e.bloomDebugFrames=="number"&&e.bloomDebugFrames;const G=cr(n,is,$0),Y=cr(n,is,Q0),J=cr(n,is,Y0),ne=cr(n,W0,j0),fe=cr(n,q0,X0),Ne=cr(n,is,G0),Ze=cr(n,is,V0),je=n.createVertexArray();n.bindVertexArray(je);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 Pt=1;function Xe(x,_,V){const F=(V||"")+"|"+x+"x"+_;if(Le.has(F)){const D=Le.get(F);return D.stamp=Pt,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:Pt};return Le.set(F,K),K}function Dt(){for(const[x,_]of Le)_.stamp!==Pt&&(_.fbo&&n.deleteFramebuffer(_.fbo),_.tex&&n.deleteTexture(_.tex),Le.delete(x))}const Oe=new Map,qe=new Map,ze=new Map;function st(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?ki(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 vn(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 ki(x){if(x.startsWith('"'))return x.slice(1,-1);const _=Number(x);return Number.isFinite(_)?_:void 0}async function an(x,_,V){let F=ze.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:vn(K)},ze.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(Oe.has(X)){const K=Oe.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=>qe.has(I)?qe.get(I):(D.add(I),null),L=fd(Yf(F.frag,"frag",j,z,F.vert)),E=Yf(F.vert,"vert",j,z,F.frag);if(D.size===0){let I;try{I=cr(n,E,L)}catch(ee){throw Oe.set(X,null),new Error("shader="+x+" "+(ee&&ee.message))}const O=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\]$/,"");O.set(we,{loc:n.getUniformLocation(I,ue.name),type:ey[ue.type]||"unknown",size:ue.size})}const $={...st(F.vert),...st(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:O,matMeta:$,samplerDefaults:se,fragGlsl:L,vertGlsl:E,ndcDirect:Z};return Oe.set(X,te),te}await Promise.all(Array.from(D).map(async I=>{qe.set(I,await r("shaders/"+I)||"")}))}throw new Error("include \u89E3\u6790\u5931\u8D25: "+x)}const _t=gc(n,new Uint8Array([255,255,255,255]),1,1),dt=gc(n,new Uint8Array([0,0,0,0]),1,1);let At=null;function yr(x){At=x||null}function Gn(){if(!At)return null;const x=typeof At=="function"?At():At;return x&&x.state?x.state:x}const Te={x:0,y:0,sx:0,sy:0};let ys=0,on=0,br=0,cn=1/60,Ai=-1;const Ia=typeof e.fadeDuration=="number"&&e.fadeDuration>=0?e.fadeDuration:1,Ma=(x,_)=>{const V=x!==null&&typeof x=="object"?x.value:x;return V===!0||V===1?!0:V===!1||V===0?!1:_},$n=(x,_)=>{const V=x!==null&&typeof x=="object"?x.value:x;return typeof V=="number"&&Number.isFinite(V)?V:_},Et=x=>e.fade!==!1&&Ma(x.camerafade,!1);function bs(x,_){if(!Ma(x.camerashake,!1))return null;const V=$n(x.camerashakeamplitude,0);if(V===0)return null;const F=Math.max(0,Math.min(1,$n(x.camerashakeroughness,0))),j=$n(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 kn(){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 xi(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 Ba(x,_,V){const F=x.get(_);if(!F||F.loc===null)return;const j=V&&V.value!==void 0?V.value:V,X=xi(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,Kt);break;case"mat3":n.uniformMatrix3fv(F.loc,!1,Ur);break}}const ws=()=>new Float32Array([1,0,0,0,1,0,0,0,1]);function Ti(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,kn())),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?Gc(Ei(fn(),te[0]/2,te[1]/2,1)):Kt;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=Gn(),O=kc(!!(I&&I.has),!!x.get("g_PointerScale"));let Q=O?ss:I?I.u:.5,$=O?ss:I?I.v:.5,Z=O?ss:I?I.lastU:.5,se=O?ss: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=tt=>(E.offX+tt*E.viewW-ue)/te,ge=tt=>(E.offY+tt*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,Te.sx*.5+.5,Te.sy*.5+.5)),Be(x,"g_Frametime",te=>n.uniform1f(te,cn)),x.get("g_EffectTextureProjectionMatrixInverse")&&Be(x,"g_EffectTextureProjectionMatrixInverse",te=>n.uniformMatrix4fv(te,!1,Kt));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 qc(x,_,V){for(const[F,j]of Object.entries(_||{})){const X=V&&V[F];X&&Ba(x,X.uniform,j)}for(const[F,j]of Object.entries(V||{}))if(!_||!(F in _)){const X=hd(j.uniform,j.default);X!==void 0&&Ba(x,j.uniform,X)}}function Si(x){const _=Gn();kc(!!(_&&_.has),!!x.get("g_PointerScale"))&&Be(x,"g_PointerScale",V=>n.uniform1f(V,0))}function Nr(x,_){return _?typeof x=="number"&&Number.isFinite(x):!!x&&typeof x=="object"&&Number.isFinite(Number(x.x))&&Number.isFinite(Number(x.y))}function An(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=xi($),se=typeof $=="number",te=se?Z[0]:{x:Z[0],y:Z[1],z:Z[2]},ee=L.init(te);L.__lastConstValue=Nr(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=cn,L.engine.timeOfDay=kn();const $=Gn();$&&$.screenW&&$.screenH&&(L.engine.screenResolution={x:$.screenW,y:$.screenH})}const E=typeof(D.value!==void 0?D.value:D)=="number";if(!Nr(L.__lastConstValue,E)){const $=xi(D.value!==void 0?D.value:D);L.__lastConstValue=E?$[0]:{x:$[0],y:$[1],z:$[2]}}const I=L.__lastConstValue;let O;try{O=L.callUpdate(I)}catch{O=void 0}const Q=O??I;if(Nr(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 Ra(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=id(z.animation),O=z.value!==void 0?z.value:0;I.baseNumeric=Array.isArray(O)?O.slice():O,E={ctrl:I,prevTime:V},S.set(L,E)}K.set(D,E.ctrl)}P.has(_)||(P.add(_),rd(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 O=E.ctrl.takeEvents();O.length&&M.push({layer:F,events:O})}else E.ctrl.takeEvents();X[D]=E.ctrl.applyTo(E.ctrl.baseNumeric)}return X}function vs(x,_,V,F){return x==null||x===""?null:x.startsWith("_rt_")?x.startsWith("_rt_imageLayerComposite")?As&&Wt.has(x)?Wt.get(x):_:V.has(x)?V.get(x):null:V.has(x)?V.get(x):F.get(x)||null}const Lr=Z0(),Or=J0(),wr=new Map;function Qn(x,_){const V=x+"x"+_;let F=wr.get(V);return F===void 0&&(F=K0(x,_),wr.set(V,F)),F}let Ct=null;function Qt(x,_){Ct!==x&&(n.bindBuffer(n.ARRAY_BUFFER,Fe),n.bufferData(n.ARRAY_BUFFER,_,n.DYNAMIC_DRAW),Ct=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")},Yt={mvp:n.getUniformLocation(Y,"u_MVP"),tex:n.getUniformLocation(Y,"u_Tex"),blendPrep:n.getUniformLocation(Y,"u_BlendPrep")},ln={mvp:n.getUniformLocation(J,"u_MVP"),tex:n.getUniformLocation(J,"u_Tex")},xn={mvp:n.getUniformLocation(Ze,"u_MVP"),tex:n.getUniformLocation(Ze,"u_Tex"),backdrop:n.getUniformLocation(Ze,"u_Backdrop"),blendMode:n.getUniformLocation(Ze,"u_BlendMode"),canvasSize:n.getUniformLocation(Ze,"u_CanvasSize"),opacity:n.getUniformLocation(Ze,"u_Opacity")},Tn={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")},Nt={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")},Yn={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")},Kt=fn(),Ur=ws();function Sn(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 zr=0;function Pi(x){const{mode:_,prep:V}=wc(x);zr=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)):Sn("translucent")}function Hr(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($r(x.parallaxDepth[0])*on),L+=Math.abs($r(x.parallaxDepth[1])*br));const E=ad(x),I=L+E[0],O=L+E[1];return D+j+I<_.offX||D-j-I>_.offX+_.viewW||z+X+O<_.offY||z-X-O>_.offY+_.viewH}function ks(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,O=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,O/X,Q/K]}function Vr(x,_){const V=x.size[0]*x.scale[0],F=x.size[1]*x.scale[1];let j=fn();if(_&&_.perspective){const K=vh(x,_);j=Gr(j,K[0],K[1],K[2]);const D=x.angles[0]||0,z=x.angles[1]||0;z&&(j=yh(j,z)),D&&(j=gh(j,D)),j=$c(j,-x.angles[2])}else{if(j=Gr(j,x.origin[0],_.projH-x.origin[1],x.origin[2]),x.parallaxDepth&&(on!==0||br!==0)){const K=$r(x.parallaxDepth[0]),D=$r(x.parallaxDepth[1]);j=Gr(j,K*on,D*br,0)}j=$c(j,-x.angles[2])}const X=Kf[x.alignment]||[.5,.5];return(X[0]!==.5||X[1]!==.5)&&(j=Gr(j,(.5-X[0])*V,(.5-X[1])*F,0)),{m:j,w:V,h:F}}function Wr(x,_,V,F,j,X,K,D,z=!1,L=null,E=null){const I=Vr(F,j);let O=I.m;if(E){const se=(E[0]+E[2]/2)*F.scale[0],te=(E[1]+E[3]/2)*F.scale[1];O=Gr(O,se,-te,0),O=Ei(O,E[2]*F.scale[0],E[3]*F.scale[1],1)}else O=Ei(O,I.w,I.h,1);const Q=dn(X,O);if(!z&&!ht&&vc(F.colorBlendMode)){const se=kr(K,D);n.useProgram(Ze),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,K,D),n.bindVertexArray(je),Qt("local",Or),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,_),n.uniform1i(xn.tex,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,se),n.uniform1i(xn.backdrop,1),n.uniform1i(xn.blendMode,Number(F.colorBlendMode)|0),n.uniform2f(xn.canvasSize,K,D),n.uniform1f(xn.opacity,V[3]),n.uniformMatrix4fv(xn.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?Yt:De;n.useProgram(x),z?(zr=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)):Pi(cd(F.colorBlendMode,F.materialBlending)),Z.blendPrep!==null&&Z.blendPrep!==void 0&&n.uniform1i(Z.blendPrep,zr),ht?(n.bindFramebuffer(n.FRAMEBUFFER,ht.fbo.fbo),n.viewport(0,0,ht.w,ht.h)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,K,D)),n.bindVertexArray(je),Qt("local",Or),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]),un(Z,L),n.drawArrays(n.TRIANGLES,0,6)}function un(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 jr=null,ht=null;const Wt=new Map,qr=new Map;let As=!0;function Fa(x,_){const V=Vr(x,_),F=_&&_.perspective?x.scale[1]:-x.scale[1],j=_&&_.perspective&&x.scale[2]||1;return Ei(V.m,x.scale[0],F,j)}function vr(x,_,V,F,j,X,K){ht?(n.bindFramebuffer(n.FRAMEBUFFER,ht.fbo.fbo),n.viewport(0,0,ht.w,ht.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=dn(V,Fa(x,_));jr(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)),Ct=null}let Pn=null;function kr(x,_){return Pn===null&&(Pn=n.createTexture(),n.bindTexture(n.TEXTURE_2D,Pn),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,Pn),n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB8,0,0,x,_,0),Pn}function Da(x,_,V){const F=kr(_,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(je),Qt("pass",Lr),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(Tn.tex,0),n.uniform2f(Tn.texel,1/_,1/V),n.uniform1f(Tn.damp,x.damp),n.uniform1f(Tn.alpha,x.alpha),n.uniform1f(Tn.strength,x.strength),n.uniform1f(Tn.threshold,x.threshold),n.uniform1i(Tn.metric,x.metric),n.drawArrays(n.TRIANGLES,0,6),n.useProgram(fe);const z=(L,E,I,O)=>{n.bindFramebuffer(n.FRAMEBUFFER,E.fbo),n.viewport(0,0,E.width,E.height),n.bindTexture(n.TEXTURE_2D,L.tex),n.uniform1i(Nt.tex,0),n.uniform2f(Nt.texel,1/L.width,1/L.height),n.uniform2f(Nt.res,L.width,L.height),n.uniform1f(Nt.radius,x.radius),n.uniform2f(Nt.dir,I,O),n.uniform1f(Nt.alpha,x.alpha),n.uniform1f(Nt.strength,x.strength),n.uniform1f(Nt.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(Yn.tex,0),n.uniformMatrix4fv(Yn.mvp,!1,Kt),n.uniform1f(Yn.alpha,x.alpha),n.uniform1f(Yn.strength,x.strength),n.uniform3f(Yn.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 xs(x,_,V,F,j,X,K,D){const z=kr(K,D),L=Vr(x,j);let E=L.m;E=Ei(E,L.w,L.h,1);const I=dn(X,E),O=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]].map(([ee,ue])=>{const we=Ah(I,ee,ue,0);return[we[0]*.5+.5,we[1]*.5+.5]}),[Q,$,Z,se]=O,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),Sn("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(je),n.bindBuffer(n.ARRAY_BUFFER,Fe),n.bufferData(n.ARRAY_BUFFER,te,n.DYNAMIC_DRAW),Ct=null,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,z),n.uniform1i(ln.tex,0),n.uniformMatrix4fv(ln.mvp,!1,Xr(0,V,0,F,-1e4,1e4)),n.drawArrays(n.TRIANGLES,0,6),n.enable(n.BLEND)}function _i(x,_,V,F,j){if(!As||ht)return;const X=qr.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);xs(x,z,K,D,_,V,F,j);for(const L of X)Wt.set(L,z);qr.delete(x.id),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,F,j)}async function Na(x,_,V,F,j,X,K,D){Pt++,n.viewport(0,0,V,F);const z=x.general||{};if(z.clearenabled!==!1){const ee=pc(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),Ai>=0){const ee=j-Ai;cn=ee>0&&ee<1?ee:Math.min(.1,Math.max(.001,ee||1/60))}Ai=j;const L=Ph(x,V,F,X,K,D);let E=dn(L.projection,L.view);const I=z.cameraparallax,O=I===!0||I!==null&&typeof I=="object"&&I.value===!0;on=0,br=0;const Q=Gn();if(Q&&(Te.x=Q.u*2-1,Te.y=Q.v*2-1),!L.perspective&&e.parallax!==!1&&O){const ee=(be,Pe)=>{const ye=be!==null&&typeof be=="object"?be.value:be;return typeof ye=="number"&&Number.isFinite(ye)?ye:Pe},ue=ee(z.cameraparallaxamount,0),we=ee(z.cameraparallaxmouseinfluence,1),ke=ee(z.cameraparallaxdelay,1),ge=j-ys;ys=j;const tt=ge>0?1-Math.exp(-ge/Math.max(.05,ke)):1;Te.sx+=(Te.x-Te.sx)*tt,Te.sy+=(Te.y-Te.sy)*tt;const Re=ue*we,jt=60,Zt=Te.sx*Re*L.viewW,at=Te.sy*Re*L.viewH,xt=Math.max(Math.abs(Zt),Math.abs(at))/jt,_n=xt>1?1/xt:1;on=-(Zt*_n),br=-(at*_n)}if(!L.perspective&&e.shake!==!1){const ee=bs(z,j);if(ee){const ue=ee.x*L.viewW*.02,we=ee.y*L.viewH*.02;(ue!==0||we!==0)&&(E=dn(E,Gr(fn(),ue,we,0)))}}if(At){const ee=typeof At=="function"?At():At;ee&&typeof ee.syncWorld=="function"&&ee.syncWorld(L,0,0)}if(!U){U=!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 La(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||pa(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){qr.has(ee.id)&&_i(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)){_i(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}Hr(ee,L)||await W(ee,_,L,E,V,F,j)}}if(Et(z)&&j<Ia){const ee=Math.max(0,Math.min(1,j/Ia)),ue=1-ee*ee*(3-2*ee);if(ue>.002){const we=pc(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(je),Qt("pass",Lr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,_t),n.uniform1i(De.tex,0),n.uniform4f(De.color,we[0],we[1],we[2],ue),un(De,null),De.blendPrep!==null&&De.blendPrep!==void 0&&n.uniform1i(De.blendPrep,0),n.uniformMatrix4fv(De.mvp,!1,Kt),n.drawArrays(n.TRIANGLES,0,6)}}const te=ud(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&&Da(te,V,F),n.bindVertexArray(null),Dt()}async function La(x,_,V,F,j,X){Wt.clear(),qr.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 O=Number(I[1]);z!==null&&O===z&&D.add(O);let Q=K.get(O);Q||(Q=new Set,K.set(O,Q)),Q.add(E)};for(const E of x.layers||[]){z=E.id;for(const I of E.effects||[])if(I.visible){for(const O of I.passes||[])for(const Q of O.textures||[])L(Q);for(const O of I.materialPasses||[]){for(const Q of O.binds||[])L(Q&&Q.name);for(const Q of O.textures||[])L(Q)}}}if(K.size!==0){for(const[E,I]of K){const O=(x.layers||[]).find(Re=>Re.id===E);if(!O||O.particle||O.isPostProcess||D.has(E))continue;const Q=typeof O.image=="string"?O.image:"";if(O.isContainer&&!O.hasChildren&&Q.indexOf("models/util/composelayer")===0&&!(O.effects||[]).some(Re=>Re.visible)){qr.set(E,I);continue}const Z=Math.max(1,Math.round(Math.abs(O.size[0]*(O.scale[0]||1)))),se=Math.max(1,Math.round(Math.abs(O.size[1]*(O.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:Xr(0,Z,0,se,-1e4,1e4),eye:V.eye,projW:Z,projH:se,offX:0,offY:0,viewW:Z,viewH:se},ue=ht,we=O.origin,ke=O.scale,ge=O.angles,tt=O.visible;ht={fbo:te,w:Z,h:se},O.origin=[Z/2,ee.projH-se/2,we[2]],O.scale=[Math.sign(ke[0])||1,Math.sign(ke[1])||1,ke[2]],O.angles=[0,0,0],O.visible=!0;try{await W(O,_,ee,ee.projection,Z,se,X);for(const Re of I)Wt.set(Re,te)}catch(Re){i(`composite \u6E90\u5C42 ${E} \u6E32\u67D3\u5931\u8D25: ${Re&&Re.message}`)}finally{ht=ue,O.origin=we,O.scale=ke,O.angles=ge,O.visible=tt}}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 O=pa(x,I),Q=_.layers.filter(ge=>O.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:Xr(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);ht={fbo:$,w:z,h:L};try{for(const ge of Q){if(ge.isPostProcess||ge.particle||ge.isContainer&&(ge.childIds||[]).length>0)continue;const tt=ge.origin,Re=ge.scale,jt=ge.angles,Zt=tt[0]-x.origin[0],at=tt[1]-x.origin[1],xt=(Zt*we-at*ke)/te,_n=(Zt*ke+at*we)/ee;ge.origin=[z/2+xt,L/2+_n,tt[2]],ge.scale=[Re[0]/te,Re[1]/ee,Re[2]],ge.angles=[jt[0],jt[1],jt[2]-ue];try{await W(ge,V,Z,se,z,L,D)}finally{ge.origin=tt,ge.scale=Re,ge.angles=jt}}}finally{ht=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&&jr),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 Pe=be.videoWidth||z.width,ye=be.videoHeight||z.height;const He=Math.max(j||0,X||0),Kn=n.getParameter(n.MAX_TEXTURE_SIZE)||0;let ot=c;Kn>0&&(ot=Math.min(ot,Kn)),He>0&&(ot=Math.min(ot,He)),ot=Math.max(ot,u);let Ar=1;Math.max(Pe,ye)>ot&&(Ar=ot/Math.max(Pe,ye));const qt=Math.max(1,Math.round(Pe*Ar)),nt=Math.max(1,Math.round(ye*Ar));let Oa=be;if(s&&qt>0&&nt>0){(s.width!==qt||s.height!==nt)&&(s.width=qt,s.height=nt);const Zn=s.getContext("2d");Zn&&(Zn.clearRect(0,0,qt,nt),Zn.drawImage(be,0,0,qt,nt),Oa=s)}if(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,Oa),n.getError()!==n.NO_ERROR&&s)try{const Lt=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(Lt.data.buffer));n.getError()!==n.NO_ERROR;);}catch{}z.width=qt,z.height=nt,z.lastUploaded=be.currentTime,o!==qt+"x"+nt&&(o=qt+"x"+nt,a=!0,i("video tex ready "+qt+"x"+nt+" (src "+Pe+"x"+ye+", limit "+ot+")"))}catch(Pe){a||(a=!0,i("video upload FAIL: "+(Pe&&Pe.message||Pe))),console.warn("[we-scene] \u89C6\u9891\u5E27\u4E0A\u4F20\u5931\u8D25:",Pe&&Pe.message,"readyState=",be.readyState,"cur=",be.currentTime)}}}const L=x.groupTex?x.groupTex:z&&z.glTex?z.glTex:x.solid?_t:dt,E=(!!x.passthrough||!!x.isPostProcess||od(x))&&!x.groupTex&&!z&&!D;let I,O;if(x.groupTex?(I=x.groupW||x.size[0],O=x.groupH||x.size[1]):D||!z?(I=x.size[0],O=x.size[1]):(I=z.width,O=z.height),!D&&z&&x.spriteSheet){const be=z.frames,Pe=Array.isArray(be)?be:be&&be.list;Pe&&Pe.length&&(I=Pe[0].width||I,O=Pe[0].height||O)}const Q=Math.max(1,Math.round(I)),$=Math.max(1,Math.round(O)),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),Pe=Math.min(Math.abs(x.size[1]*x.scale[1]),V.viewH),ye=be*(j/V.projW),He=Pe*(X/V.projH);if(ye>0&&He>0){const Kn=Math.max(64,Math.round(ye*l)),ot=Math.max(64,Math.round(He*l));Kn<Q&&(te=Kn),ot<$&&(ee=ot)}}if(se.length===0){D?vr(x,V,F,j,X,K):Wr(G,L,Z,x,V,F,j,X,!1,ks(x,z,K));return}const ue=Xe(te,ee,"ping"),we=Xe(te,ee,"pong"),ke=Xr(0,te,0,ee,-1e4,1e4);if(D)n.useProgram(G),Sn("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(je),Ct=null,Qt("layer"+te+"x"+ee,Qn(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),un(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)xs(x,ue,te,ee,V,F,j,X);else{n.useProgram(G),Sn("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(je),Qt("layer"+te+"x"+ee,Qn(te,ee)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,L),n.uniform1i(De.tex,0);const be=se.some(Pe=>Pe&&Pe.layerMaterial)?[1,1,1,Z[3]]:Z;n.uniform4f(De.color,be[0],be[1],be[2],be[3]),un(De,ks(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,tt=we;const Re=new Map;let jt=!1,Zt=ue;const at=[],xt=new Set;for(const be of se){for(const ye of be.fbos||[])if(!Re.has(ye.name)){const[He,Kn]=ld(ye,te,ee),ot=ye.unique?x.id+":"+ye.name:ye.name;Re.set(ye.name,Xe(He,Kn,ot))}const Pe=be.materialPasses||[];for(let ye=0;ye<Pe.length;ye++)at.push({eff:be,mp:Pe[ye],ov:be.passes&&be.passes[ye]})}const _n=[];for(let be=0;be<at.length;be++){const{eff:Pe,mp:ye,ov:He}=at[be];if(xt.has(Pe))continue;const Kn={...ye.combos||{},...He&&He.combos||{}},ot=ye.textures||[],Ar=He&&He.textures||[],qt=[];for(let Me=0;Me<Math.max(ot.length,Ar.length);Me++)Ar[Me]!==void 0&&Ar[Me]!==null?qt[Me]=Ar[Me]:qt[Me]=ot[Me]!==void 0?ot[Me]:null;if(ye.copyCommand){const Me=ye.source?Re.get(ye.source):null,rt=ye.target?Re.get(ye.target):null;Me&&rt&&(n.useProgram(Y),Sn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,rt.fbo),n.viewport(0,0,rt.width,rt.height),n.bindVertexArray(je),Qt("pass",Lr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,Me.tex),n.uniform1i(Yt.tex,0),Yt.blendPrep!==null&&Yt.blendPrep!==void 0&&n.uniform1i(Yt.blendPrep,0),n.uniformMatrix4fv(Yt.mvp,!1,Kt),n.drawArrays(n.TRIANGLES,0,6),n.bindFramebuffer(n.FRAMEBUFFER,null));continue}let nt;try{nt=await an(ye.shader,Kn,qt)}catch(Me){const rt=Me&&Me.message||String(Me);/已缓存/.test(rt)||console.warn("[we-scene] \u8DF3\u8FC7\u6548\u679C\uFF08pass \u7F16\u8BD1\u5931\u8D25\uFF09:",ye.shader,rt),xt.add(Pe);continue}const Oa=nt.prog,Zn=nt.uni;nt.fragGlsl&&_n.push(nt.fragGlsl);let Lt,Ts;ye.target?(jt||(Zt=ge,jt=!0),Lt=Re.get(ye.target)||ge,Ts=Zt):(jt=!1,Lt=tt,Ts=ge),n.useProgram(Oa),Sn(ye.blending||"normal"),n.bindFramebuffer(n.FRAMEBUFFER,Lt.fbo),n.viewport(0,0,Lt.width,Lt.height),n.bindVertexArray(je);const mh=!nt.ndcDirect;mh?Qt("passPx"+Lt.width+"x"+Lt.height,Qn(Lt.width,Lt.height)):Qt("pass",Lr);const iw=mh?Gc(Xr(0,Lt.width,0,Lt.height,-1e4,1e4)):Kt,Xc=ye.textures||[],sw=Math.max(Xc.length,8),ph=new Map,aw=new Set;for(let Me=0;Me<sw;Me++){let rt=Me<Xc.length?Xc[Me]:null;He&&He.textures&&He.textures[Me]!==void 0&&He.textures[Me]!==null&&(rt=He.textures[Me]);for(const Ps of ye.binds||[])Ps.index===Me&&(rt=Ps.name);let En;if(Me===0&&(rt==null||rt===""))En=Ts;else{if((rt==null||rt==="")&&nt.samplerDefaults){const Ps=nt.samplerDefaults.get(Me);Ps&&(rt=Ps)}En=vs(rt,Ts,Re,_)}rt==="previous"&&(En=Ts),En===null&&(En={glTex:_t,width:1,height:1,tex:_t});const Ss=En.fbo?En:{tex:En.glTex||_t,width:En.width||1,height:En.height||1};n.activeTexture(n.TEXTURE0+Me),n.bindTexture(n.TEXTURE_2D,Ss.tex),aw.add(Me),ph.set(Me,[Ss.width,Ss.height,Ss.width,Ss.height])}Ti(Zn,x,K,V.projW,V.projH,iw,ke,Kt,ph,ke,V),qc(Zn,Ra(An({...ye.constants||{},...He&&He.constantshadervalues||{}},(x.id||x.name||"?")+"|"+(ye.shader||"?")+"|"+be,K,x),(x.id||x.name||"?")+"|"+(ye.shader||"?")+"|"+be,K,x),nt.matMeta),Si(Zn),n.drawArrays(n.TRIANGLES,0,6),ye.target||(tt=ge,ge=Lt)}if(x.isContainer&&!x.groupTex&&!E&&x.containerAlphaMeaningful===void 0){let be=!1;for(const Pe of _n){if(typeof Pe!="string")continue;const ye=Pe.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){vr(x,V,F,j,X,K,ge.tex);return}Wr(Y,ge.tex,[1,1,1,1],x,V,F,j,X,!!x.isContainer&&!x.groupTex&&!E,null,null)}return{gl:n,render:Na,getFBO:Xe,getEffectProgram:an,progCache:Oe,shaderResolver:r,whiteTex:_t,resetShaderCaches:function(){Oe.clear(),qe.clear(),ze&&ze.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){As=!!x},compositeStats:function(){const x=[],_=new Uint8Array(4);for(const[V,F]of Wt){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){jr=x},setAudioProvider:m,setPointerProvider:yr,getParallaxOffset:function(){return{x:on,y:br}},dispose:function(){try{const x=n.getExtension("WEBGL_lose_context");x&&x.loseContext()}catch{}}}}const yy=Object.freeze(Object.defineProperty({__proto__:null,ALIGN:Kf,XRAY_IDLE_SCREEN_UV:ss,XRAY_SIZE_FALLBACK:dd,applyColorBlendCPU:hy,bloomPostParams:ud,collectGroupDescendantIds:pa,colorBlendPlan:wc,constantFallback:hd,createRenderer:gy,effectFboSize:ld,layerCompositeBlendMode:cd,layerWantsPreserveBackdrop:od,makeTexture:gc,makeTextureMip:ty,needsShaderBlend:vc,puppetAnimMargin:ad,rewriteXrayFragScale:fd,xrayShouldParkPointer:kc,xrayUvScale:my},Symbol.toStringTag,{value:"Module"}));function by(t=256,e=8){const n=t/e,r=md(1337),i=md(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],U=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(U*255),o[H+1]=Math.round(q*255),o[H+2]=0,o[H+3]=255}}return o}function md(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 wy=Object.freeze(Object.defineProperty({__proto__:null,generateNoiseTexture:by},Symbol.toStringTag,{value:"Module"})),nn=Math.PI*2;function Je(t,e){return t==null?Math.random():e==null?t:t+Math.random()*(e-t)}function pd(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 gd(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 Ac(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 ur(t,e,n){const r=Math.sin(t*127.1+e*311.7+n*74.7)*43758.5453;return r-Math.floor(r)}function vy(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(ur(r,i,s),ur(r+1,i,s),u),p=d(ur(r,i+1,s),ur(r+1,i+1,s),u),m=d(ur(r,i,s+1),ur(r+1,i,s+1),u),g=d(ur(r,i+1,s+1),ur(r+1,i+1,s+1),u);return d(d(h,p,l),d(m,g,l),f)}function xc(t,e,n,r){let i=0,s=.5,a=1,o=0;for(let c=0;c<r;c++)i+=s*vy(t*a,e*a,n*a),o+=s,s*=.5,a*=2;return i/(o||1)}function Tc(t,e,n,r){return[xc(t,e,n,r)*2-1,xc(t+31.7,e+11.3,n+57.1,r)*2-1,xc(t+73.9,e+92.1,n+13.7,r)*2-1]}function ky(t){const e=`#version 300 es
|
|
355
|
+
}`,vb=`#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 Ab(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 xb(){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 kb(){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 Tb={5126:"float",35664:"vec2",35665:"vec3",35666:"vec4",5124:"int",35667:"ivec2",35668:"ivec3",35669:"ivec4",35670:"bool",35676:"mat4",35675:"mat3"};function br(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 ro(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 Sb(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 Pb(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 _b(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 Eb(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 Mb(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 io(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 io([{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=Mb(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 Cb(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 Ib(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);Ib(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 io(c[0],m,g);const y=[];for(const w of c)y.push(io(w,m,g));return y},applyTo(m){const g=p.value();if(!a)return g;const y=Cb(m);return Array.isArray(g)?g.map((w,A)=>w+(Number(y[A])||0)):g+(Number(y[0])||0)}};return p}function Rb(){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 Bb=Object.freeze(Object.defineProperty({__proto__:null,createAnimation:Pl,createNeutralAnimation:Rb,crossedEvents:Lh,linkAnimations:Uh,sampleChannel:io,wrapFrame:Nh},Symbol.toStringTag,{value:"Module"}));function Fb(t,e,n,r){const i=s=>so(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)=>Db(s,a));case 13:return i((s,a)=>Oh(a,s));case 14:return i((s,a)=>[ns(s[0],a[0]),ns(s[1],a[1]),ns(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)=>[ns(s[0],a[0])<.5?0:1,ns(s[1],a[1])<.5?0:1,ns(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)=>Nb(s,a));case 27:return i((s,a)=>Lb(s,a));case 28:return i((s,a)=>Ub(s,a));case 29:return i((s,a)=>Ob(s,a));case 30:{const s=Math.max(e[0],Math.max(e[1],e[2]));return so(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 so(e,[e[0]+e[0]*n[0],e[1]+e[1]*n[1],e[2]+e[2]*n[2]],r);default:return so(e,n,r)}}function so(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 Db(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 ns(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 Vr(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 ao(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 Nb(t,e){const n=Vr(t);return ao([Vr(e)[0],n[1],n[2]])}function Lb(t,e){const n=Vr(t);return ao([n[0],Vr(e)[1],n[2]])}function Ub(t,e){const n=Vr(e);return ao([n[0],n[1],Vr(t)[2]])}function Ob(t,e){const n=Vr(t);return ao([n[0],n[1],Vr(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 oo(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),oo(i,e,n))}return n}function El(t){const e=Bh[t]||"translucent";return{mode:e,prep:ub[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 Fb(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=ro(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 Hb(t){const e=Number(t);return!Number.isFinite(e)||e<.001?999:1/e}const Qs=-1;function Il(t,e){return!!e&&!t}const Vb="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 *= "+Vb+" *")}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 Wb(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 be=n.getInternalformatParameter(n.RENDERBUFFER,n.RGBA8,n.SAMPLES);let fe=0;if(be&&be.length)for(const se of be)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=Et(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(ot),ln("pass",_r),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,te.tex),n.uniform1i(Ze.tex,0),n.uniform4f(Ze.color,1,1,1,1),Er(Ze,null),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,un),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 Ee(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,Ue=!1,Ne=0;typeof e.bloomDebugFrames=="number"&&e.bloomDebugFrames;const De=br(n,ts,yb),Re=br(n,ts,bb),Fe=br(n,ts,wb),Ge=br(n,db,hb),Qe=br(n,mb,pb),Ye=br(n,ts,gb),nt=br(n,ts,fb),yn=br(n,ts,vb),ot=n.createVertexArray();n.bindVertexArray(ot);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 Gt=new Map;let Rn=1;function Et(M,j,te){const Z=(te||"")+"|"+M+"x"+j;if(Gt.has(Z)){const be=Gt.get(Z);return be.stamp=Rn,be}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:Rn};return Gt.set(Z,me),me}function kt(){for(const[M,j]of Gt)j.stamp!==Rn&&(j.fbo&&n.deleteFramebuffer(j.fbo),j.tex&&n.deleteTexture(j.tex),Gt.delete(M))}const on=new Map,Rt=new Map,ss=new Map;function cn(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 be=/"default"\s*:\s*("(?:[^"]*)"|-?\d+(?:\.\d+)?)/.exec(de);j[me[1]]={uniform:ne,default:be?Tr(be[1]):void 0}}return j}function as(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 lt(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 Ro(M,j,te){let Z=ss.get(M);if(Z===void 0){const me=await r("shaders/"+M+".frag")||"",be=await r("shaders/"+M+".vert")||"";Z={frag:me,vert:be,texCombos:lt(me)},ss.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(on.has(de)){const me=on.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 be=new Set,fe=ke=>Rt.has(ke)?Rt.get(ke):(be.add(ke),null),se=Gh(Ih(Z.frag,"frag",ne,fe,Z.vert)),Me=Ih(Z.vert,"vert",ne,fe,Z.frag);if(be.size===0){let ke;try{ke=br(n,Me,se)}catch(L){throw on.set(de,null),new Error("shader="+M+" "+(L&&L.message))}const T=new Map,C=n.getProgramParameter(ke,n.ACTIVE_UNIFORMS);for(let L=0;L<C;L++){const X=n.getActiveUniform(ke,L),Q=X.name.replace(/\[0\]$/,"");T.set(Q,{loc:n.getUniformLocation(ke,X.name),type:Tb[X.type]||"unknown",size:X.size})}const R={...cn(Z.vert),...cn(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([...as(Z.vert),...as(Z.frag)]),H={prog:ke,uni:T,matMeta:R,samplerDefaults:$,fragGlsl:se,vertGlsl:Me,ndcDirect:F};return on.set(de,H),H}await Promise.all(Array.from(be).map(async ke=>{Rt.set(ke,await r("shaders/"+ke)||"")}))}throw new Error("include \u89E3\u6790\u5931\u8D25: "+M)}const bn=Tl(n,new Uint8Array([255,255,255,255]),1,1),Kr=Tl(n,new Uint8Array([0,0,0,0]),1,1);let ut=null;function Qn(M){ut=M||null}function Bn(){if(!ut)return null;const M=typeof ut=="function"?ut():ut;return M&&M.state?M.state:M}const Sr=Ep(e),yt=Sr==="mirage"?{x:.5,y:.5,sx:.5,sy:.5}:{x:0,y:0,sx:0,sy:0},ze={mode:Sr,mx:0,my:0,amount:0,cx:0,cy:0,lx:0,ly:0,active:!1};let Ke=0,os=null,vi=0,Yn=null,Zr=0,Jr=0,Bo=1/60,Ve=-1;const Fo=typeof e.fadeDuration=="number"&&e.fadeDuration>=0?e.fadeDuration:1,Do=(M,j)=>{const te=M!==null&&typeof M=="object"?M.value:M;return te===!0||te===1?!0:te===!1||te===0?!1:j},la=(M,j)=>{const te=M!==null&&typeof M=="object"?M.value:M;return typeof te=="number"&&Number.isFinite(te)?te:j},ua=M=>e.fade===!0&&Do(M.camerafade,!1);function No(M,j){if(!Do(M.camerashake,!1))return null;const te=la(M.camerashakeamplitude,0);if(te===0)return null;const Z=Math.max(0,Math.min(1,la(M.camerashakeroughness,0))),ne=la(M.camerashakespeed,1),de=j*ne,me=Math.sin(de*2.1)*Math.cos(de*.7),be=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:(be*(1-Z)+se*Z)*te}}function Ai(){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 cs(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 Lo(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=cs(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,un);break;case"mat3":n.uniformMatrix3fv(Z.loc,!1,hs);break}}const Uo=()=>new Float32Array([1,0,0,0,1,0,0,0,1]);function ls(M,j,te,Z,ne,de,me,be,fe,se,Me,ke){if(rt(M,"g_Time",L=>n.uniform1f(L,te)),rt(M,"g_Daytime",L=>n.uniform1f(L,Ai())),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,be)),ke&&rt(M,"g_EffectModelViewProjectionMatrix",L=>n.uniformMatrix4fv(L,!1,ke)),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?qo(Rr(Ir(),L[0]/2,L[1]/2,1)):un;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=Bn(),C=Il(!!(T&&T.has),!!M.get("g_PointerScale"));let R=C?Qs:T?T.u:.5,F=C?Qs:T?T.v:.5,$=C?Qs:T?T.lastU:.5,H=C?Qs:T?T.lastV:.5;if(Me&&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=Me.projH-j.origin[1]-X/2,q=N=>(Me.offX+N*Me.viewW-Q)/L,K=N=>(Me.offY+N*Me.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=>{ze.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,Bo)),M.get("g_EffectTextureProjectionMatrixInverse")&&rt(M,"g_EffectTextureProjectionMatrixInverse",L=>n.uniformMatrix4fv(L,!1,un));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 bu(M,j,te){for(const[Z,ne]of Object.entries(j||{})){const de=te&&te[Z];de&&Lo(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&&Lo(M,ne.uniform,de)}}function Kn(M){const j=Bn();Il(!!(j&&j.has),!!M.get("g_PointerScale"))&&rt(M,"g_PointerScale",te=>n.uniform1f(te,0))}function us(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 fa=[1,1,1],Oo=1920,Pr=1080;function Bt(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,be]of Object.entries(M)){if(be===null||typeof be!="object"||typeof be.script!="string")continue;const fe=j+"|"+me;let se=we.get(fe);if(se===void 0){Ae.total++;try{se=_(be.script,be.scriptproperties||be.scriptProperties||null,{userProperties:I||{},screenResolution:{x:Oo,y:Pr},timeOfDay:Ai(),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=be.value!==void 0?be.value:be,F=cs(R),$=typeof R=="number",H=$?F[0]:{x:F[0],y:F[1],z:F[2]},L=se.init(H);se.__lastConstValue=us(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=Bo,se.engine.timeOfDay=Ai();const R=Bn();R&&R.screenW&&R.screenH&&(se.engine.screenResolution={x:R.screenW,y:R.screenH})}const Me=typeof(be.value!==void 0?be.value:be)=="number";if(!us(se.__lastConstValue,Me)){const R=cs(be.value!==void 0?be.value:be);se.__lastConstValue=Me?R[0]:{x:R[0],y:R[1],z:R[2]}}const ke=se.__lastConstValue;let T;try{T=se.callUpdate(ke)}catch{T=void 0}const C=T??ke;if(us(C,Me)&&(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 da(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 be=Pl(ne.animation),fe=ne.value!==void 0?ne.value:0;be.baseNumeric=Array.isArray(fe)?fe.slice():fe,me={ctrl:be,prevTime:te},Y.set(de,me)}}}function Zn(M,j,te,Z){if(!M)return M;let ne=!1;for(const be of Object.values(M))if(be&&typeof be=="object"&&be.animation&&be.animation.options){ne=!0;break}if(!ne)return M;const de={...M},me=new Map;for(const[be,fe]of Object.entries(M)){if(!fe||typeof fe!="object"||!fe.animation||!fe.animation.options)continue;const se=j+"|anim|"+be;let Me=Y.get(se);if(!Me){const ke=Pl(fe.animation),T=fe.value!==void 0?fe.value:0;ke.baseNumeric=Array.isArray(T)?T.slice():T,Me={ctrl:ke,prevTime:te},Y.set(se,Me)}me.set(be,Me.ctrl)}oe.has(j)||(oe.add(j),Uh(me,be=>i(`${j}: ${be}`)));for(const[be,fe]of Object.entries(M)){if(!fe||typeof fe!="object"||!fe.animation||!fe.animation.options)continue;const se=j+"|anim|"+be,Me=Y.get(se),ke=te-Me.prevTime;if(Me.prevTime=te,Me.ctrl.playing&&Me.ctrl.advance(Math.max(0,ke)),he){const T=Me.ctrl.takeEvents();T.length&&he.push({layer:Z,events:T})}else Me.ctrl.takeEvents();de[be]=Me.ctrl.applyTo(Me.ctrl.baseNumeric)}return de}function zo(M,j,te,Z){if(M==null||M==="")return null;if(M==="_rt_FullFrameBuffer"){if(!Yn||Yn.stamp!==vi){const ne=n.getParameter(n.FRAMEBUFFER_BINDING),de=n.getParameter(n.TEXTURE_BINDING_2D);Yn={glTex:Ln(Zr||1,Jr||1),width:Zr||1,height:Jr||1,stamp:vi},n.bindFramebuffer(n.FRAMEBUFFER,ne),n.bindTexture(n.TEXTURE_2D,de)}return Yn}return M.startsWith("_rt_")?M.startsWith("_rt_imageLayerComposite")?gs&&An.has(M)?An.get(M):j:te.has(M)?te.get(M):null:te.has(M)?te.get(M):Z.get(M)||null}const _r=xb(),Ho=kb(),fs=new Map;function ei(M,j){const te=M+"x"+j;let Z=fs.get(te);return Z===void 0&&(Z=Ab(M,j),fs.set(te,Z)),Z}let en=null;function ln(M,j){en!==M&&(n.bindBuffer(n.ARRAY_BUFFER,gt),n.bufferData(n.ARRAY_BUFFER,j,n.DYNAMIC_DRAW),en=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")},Fn={mvp:n.getUniformLocation(Re,"u_MVP"),tex:n.getUniformLocation(Re,"u_Tex"),blendPrep:n.getUniformLocation(Re,"u_BlendPrep")},ds={mvp:n.getUniformLocation(Fe,"u_MVP"),tex:n.getUniformLocation(Fe,"u_Tex")},Jn={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")},er={tex:n.getUniformLocation(Ge,"u_Tex"),texel:n.getUniformLocation(Ge,"u_Texel"),damp:n.getUniformLocation(Ge,"u_Damp"),alpha:n.getUniformLocation(Ge,"u_Alpha"),strength:n.getUniformLocation(Ge,"u_Strength"),threshold:n.getUniformLocation(Ge,"u_Threshold"),metric:n.getUniformLocation(Ge,"u_Metric")},Ft={tex:n.getUniformLocation(Qe,"u_Tex"),texel:n.getUniformLocation(Qe,"u_Texel"),res:n.getUniformLocation(Qe,"u_Res"),radius:n.getUniformLocation(Qe,"u_Radius"),dir:n.getUniformLocation(Qe,"u_Dir"),alpha:n.getUniformLocation(Qe,"u_Alpha"),strength:n.getUniformLocation(Qe,"u_Strength"),iterations:n.getUniformLocation(Qe,"u_Iterations")},ti={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")},xi={mvp:n.getUniformLocation(yn,"u_MVP"),tex:n.getUniformLocation(yn,"u_Tex"),texel:n.getUniformLocation(yn,"u_Texel")},un=Ir(),hs=Uo();function wn(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 tr=0;function Dn(M){const{mode:j,prep:te}=El(M);tr=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)):wn("translucent")}function Vo(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 be=M.origin[0],fe=j.projH-M.origin[1];let se=64;if(M.parallaxDepthOwn||M.parallaxDepth||M.parallaxDepthProp)if(ze.active&&ze.mode==="mirage"){const C=M.parallaxDepthProp||M.parallaxDepth||[0,0],R=M.parallaxAnchor||[be,j.projH-fe],F=Math.abs(R[0]-ze.cx+ze.mx)*Math.abs(C[0])*ze.amount,$=Math.abs(R[1]-ze.cy+ze.my)*Math.abs(C[1])*ze.amount;se+=F+$}else ze.active&&M.parallaxDepth&&(se+=Math.abs(ya(M.parallaxDepth[0])*ze.lx),se+=Math.abs(ya(M.parallaxDepth[1])*ze.ly));const Me=zh(M),ke=se+Me[0],T=se+Me[1];return be+ne+ke<j.offX||be-ne-ke>j.offX+j.viewW||fe+de+T<j.offY||fe-de-T>j.offY+j.viewH}function ms(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 be=0;const fe=M.textureAnimation;if(fe&&fe.frame!==null&&fe.frame!==void 0)be=Math.floor(Number(fe.frame))||0,be>=0||(be=0),be>=ne.length&&(be=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){be=H;break}$-=L,be=H}}}const se=ne[be],Me=se.uDir?se.uDir[0]:se.width,ke=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,Me/de,ke/me,T/de,C/me]}function vn(M,j){const te=M.size[0]*M.scale[0],Z=M.size[1]*M.scale[1];let ne=Ir();if(j&&j.perspective){const me=vp(M,j);ne=ii(ne,me[0],me[1],me[2]);const be=M.angles[0]||0,fe=M.angles[1]||0;fe&&(ne=Tu(ne,fe)),be&&(ne=ku(ne,be)),ne=xu(ne,-M.angles[2])}else{if(ne=ii(ne,M.origin[0],j.projH-M.origin[1],M.origin[2]),M.parallaxDepth&&ze.active){const me=Qo(M,ze);(me[0]!==0||me[1]!==0)&&(ne=ii(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=ii(ne,(.5-de[0])*te,(.5-de[1])*Z,0)),{m:ne,w:te,h:Z}}function Nn(M,j,te,Z,ne,de,me,be,fe=!1,se=null,Me=null){const ke=vn(Z,ne);let T=ke.m;if(Me){const $=(Me[0]+Me[2]/2)*Z.scale[0],H=(Me[1]+Me[3]/2)*Z.scale[1];T=ii(T,$,-H,0),T=Rr(T,Me[2]*Z.scale[0],Me[3]*Z.scale[1],1)}else T=Rr(T,ke.w,ke.h,1);const C=Wt(de,T);if(!fe&&!it&&Ml(Z.colorBlendMode)){const $=Ln(me,be);n.useProgram(nt),n.disable(n.BLEND),g(),n.viewport(0,0,me,be),n.bindVertexArray(ot),ln("local",Ho),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,j),n.uniform1i(Jn.tex,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,$),n.uniform1i(Jn.backdrop,1),n.uniform1i(Jn.blendMode,Number(Z.colorBlendMode)|0),n.uniform2f(Jn.canvasSize,me,be),n.uniform1f(Jn.opacity,te[3]),n.uniformMatrix4fv(Jn.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?Fn:Ze;n.useProgram(M),fe?(tr=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)):Dn(jh(Z.colorBlendMode,Z.materialBlending)),F.blendPrep!==null&&F.blendPrep!==void 0&&n.uniform1i(F.blendPrep,tr),it?(n.bindFramebuffer(n.FRAMEBUFFER,it.fbo.fbo),n.viewport(0,0,it.w,it.h)):(g(),n.viewport(0,0,me,be)),n.bindVertexArray(ot),ln("local",Ho),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]),Er(F,se),n.drawArrays(n.TRIANGLES,0,6)}function Er(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 ps=null,it=null;const An=new Map;let ki=0;const Mr=new Map,Ti=new Map;let gs=!0;function Si(M,j){const te=vn(M,j),Z=j&&j.perspective?M.scale[1]:-M.scale[1],ne=j&&j.perspective&&M.scale[2]||1;return Rr(te.m,M.scale[0],Z,ne)}function ys(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 be=Wt(te,Si(M,j));ps(M,be,{time:de,overrideTex:me||null,ambient:Cl(M.lightingEnabled,fa),keepZ:!!(j&&j.perspective)}),me&&(n.bindTexture(n.TEXTURE_2D,me),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR)),en=null}let Cr=null;function Ln(M,j){if(it)return it.fbo.tex;if(h){const te=Et(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 Cr===null&&(Cr=n.createTexture(),n.bindTexture(n.TEXTURE_2D,Cr),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,Cr),n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB8,0,0,M,j,0),Cr}function Pi(M,j,te){const Z=Ln(j,te),ne=Math.max(1,Math.round(j/4)),de=Math.max(1,Math.round(te/4)),me=Et(ne,de,"bloomA"),be=Et(ne,de,"bloomB");n.bindVertexArray(ot),ln("pass",_r),n.activeTexture(n.TEXTURE0),n.useProgram(Ge),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,me.fbo),n.viewport(0,0,ne,de),n.bindTexture(n.TEXTURE_2D,Z),n.uniform1i(er.tex,0),n.uniform2f(er.texel,1/j,1/te),n.uniform1f(er.damp,M.damp),n.uniform1f(er.alpha,M.alpha),n.uniform1f(er.strength,M.strength),n.uniform1f(er.threshold,M.threshold),n.uniform1i(er.metric,M.metric),n.drawArrays(n.TRIANGLES,0,6),n.useProgram(Qe);const fe=(se,Me,ke,T)=>{n.bindFramebuffer(n.FRAMEBUFFER,Me.fbo),n.viewport(0,0,Me.width,Me.height),n.bindTexture(n.TEXTURE_2D,se.tex),n.uniform1i(Ft.tex,0),n.uniform2f(Ft.texel,1/se.width,1/se.height),n.uniform2f(Ft.res,se.width,se.height),n.uniform1f(Ft.radius,M.radius),n.uniform2f(Ft.dir,ke,T),n.uniform1f(Ft.alpha,M.alpha),n.uniform1f(Ft.strength,M.strength),n.uniform1f(Ft.iterations,M.iterations),n.drawArrays(n.TRIANGLES,0,6)};if(fe(me,be,1,0),fe(be,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(ti.tex,0),n.uniformMatrix4fv(ti.mvp,!1,un),n.uniform1f(ti.alpha,M.alpha),n.uniform1f(ti.strength,M.strength),n.uniform3f(ti.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 ha(M,j,te,Z,ne,de,me,be){const fe=Ln(me,be),se=vn(M,ne);let Me=se.m;Me=Rr(Me,se.w,se.h,1);const ke=Wt(de,Me),T=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]].map(([L,X])=>{const Q=xp(ke,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),wn("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(ot),n.bindBuffer(n.ARRAY_BUFFER,gt),n.bufferData(n.ARRAY_BUFFER,H,n.DYNAMIC_DRAW),en=null,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,fe),n.uniform1i(ds.tex,0),n.uniformMatrix4fv(ds.mvp,!1,Ei(0,te,0,Z,-1e4,1e4)),n.drawArrays(n.TRIANGLES,0,6),n.enable(n.BLEND)}async function bs(M,j,te,Z,ne,de){if(!gs||it)return;const me=Mr.get(M.id);if(!me||me.size===0)return;const be=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(be<=1&&fe<=1)return;const se=Et(be,fe,"lc:"+M.id);if((M.effects||[]).some(ke=>ke.visible)){const ke=it;it={fbo:se,w:be,h:fe};try{_i(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=ke}}else ha(M,se,be,fe,j,te,Z,ne);for(const ke of me)An.set(ke,se);if(Mr.delete(M.id),M.copybackground)for(const ke of me)Ti.set(ke,se);g(),n.viewport(0,0,Z,ne)}async function Wo(M,j,te,Z,ne,de,me,be){Oo=te,Pr=Z,Rn++,y(te,Z),g(),n.viewport(0,0,te,Z);const fe=M.general||{};if(fa=ro(fe.ambientcolor||"1 1 1"),fe.clearenabled!==!1){const Q=ro(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;Bo=Q>0&&Q<1?Q:Math.min(.1,Math.max(.001,Q||1/60))}Ve=ne;const se=Sp(M,te,Z,de,me,be);let Me=Wt(se.projection,se.view);vi++,Zr=te,Jr=Z;const ke=fe.cameraparallax,T=ke===!0||ke!==null&&typeof ke=="object"&&ke.value===!0,C=Bn();if(C&&(ze.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),N=ne-Ke;Ke=ne;const E=N>0?1-Math.exp(-N/Math.max(.05,K)):1;if(yt.sx+=(yt.x-yt.sx)*E,yt.sy+=(yt.y-yt.sy)*E,ze.mode==="mirage")ze.mx=(.5-yt.sx)*se.projW*q,ze.my=(yt.sy-.5)*se.projH*q,ze.amount=re,ze.cx=se.projW/2,ze.cy=se.projH/2,ze.lx=0,ze.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;ze.lx=-(G*ae),ze.ly=-(J*ae),ze.mx=0,ze.my=0,ze.amount=0}ze.active=!0}else ze.active=!1,ze.lx=0,ze.ly=0;let R=null;if(!se.perspective&&e.shake!==!1){const Q=No(fe,ne);if(Q){const re=Q.x*se.viewW*.02,q=Q.y*se.viewH*.02;(re!==0||q!==0)&&(R=ii(Ir(),re,q,0),Me=Wt(Me,R))}}let F=null;if(os=null,!se.perspective)for(const Q of M.layers){if(!Q.perspective||Q.destroyed)continue;const re=Pp(se,fe);re&&(F=R?Wt(re.viewProj,R):re.viewProj,os=re.eye);break}if(ut){const Q=typeof ut=="function"?ut():ut;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(N=>N.visible)&&!K.hasChildren),q=re.filter(K=>(K.effects||[]).some(N=>(N.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 wu(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||oo(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:Me;if(!Q.visible){Mr.has(Q.id)&&await bs(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 bs(Q,se,re,te,Z,ne);continue}if(Q.hasChildren){(Q.childIds||[]).length>0&&await ni(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}Vo(Q,se)||await _i(Q,j,se,re,te,Z,ne)}}if(ua(fe)&&ne<Fo){const Q=Math.max(0,Math.min(1,ne/Fo)),re=1-Q*Q*(3-2*Q);if(re>.002){const q=ro(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(ot),ln("pass",_r),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,bn),n.uniform1i(Ze.tex,0),n.uniform4f(Ze.color,q[0],q[1],q[2],re),Er(Ze,null),Ze.blendPrep!==null&&Ze.blendPrep!==void 0&&n.uniform1i(Ze.blendPrep,0),n.uniformMatrix4fv(Ze.mvp,!1,un),n.drawArrays(n.TRIANGLES,0,6)}}b(te,Z);const X=f?$h(fe):null;if(Ue||(Ue=!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&&Pi(X,te,Z),d==="fxaa"){const Q=Ln(te,Z);n.useProgram(yn),n.disable(n.BLEND),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,te,Z),n.bindVertexArray(ot),ln("pass",_r),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,Q),n.uniform1i(xi.tex,0),n.uniform2f(xi.texel,1/te,1/Z),n.uniformMatrix4fv(xi.mvp,!1,un),n.drawArrays(n.TRIANGLES,0,6)}n.bindVertexArray(null),kt()}async function wu(M,j,te,Z,ne,de){An.clear(),Mr.clear();for(const[ke,T]of Ti)An.set(ke,T);const me=new Map,be=new Set;let fe=null;const se=ke=>{if(typeof ke!="string")return;const T=/^_rt_imageLayerComposite_(\d+)_[a-z]$/.exec(ke);if(!T)return;const C=Number(T[1]);fe!==null&&C===fe&&be.add(C);let R=me.get(C);R||(R=new Set,me.set(C,R)),R.add(ke)};for(const ke of M.layers||[]){fe=ke.id;for(const T of ke.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 ke of[...Ti.keys()]){let T=!1;for(const C of me.values())if(C.has(ke)){T=!0;break}T||Ti.delete(ke)}if(me.size===0)return;const Me=(()=>{const ke=[...me.keys()],T=new Map;for(const $ of ke){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 ke)F($);return C})();for(const ke of Me){const T=me.get(ke),C=(M.layers||[]).find(pe=>pe.id===ke);if(!C||C.particle||C.isPostProcess||be.has(ke))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){Mr.set(ke,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;ki<=0&&(ki=Math.max(1,n.getParameter(n.MAX_TEXTURE_SIZE)||8192));const Q=Xh(L,X,ki),re=Q.width,q=Q.height,K=Q.k,N=Et(re,q,"lc:"+ke);n.bindFramebuffer(n.FRAMEBUFFER,N.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:Ei(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:N,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 _i(C,j,E,E.projection,re,q,de);for(const pe of T)An.set(pe,N)}catch(pe){i(`composite \u6E90\u5C42 ${ke} \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 ni(M,j,te,Z,ne,de,me,be){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 ke=new Map;for(const q of j.layers)q.id!==void 0&&ke.set(q.id,q);const T=oo(M,ke),C=j.layers.filter(q=>T.has(q.id)&&q.visible);if(C.length===0)return;const R=Et(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:Ei(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,N=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=[N[0]/H,N[1]/L,N[2]],q.angles=[E[0],E[1],E[2]-X];try{await _i(q,te,F,$,fe,se,be)}finally{q.origin=K,q.scale=N,q.angles=E}}}finally{it=null}M.groupTex=R.tex,M.groupW=fe,M.groupH=se;try{await _i(M,te,Z,ne,de,me,be)}finally{M.groupTex=null}}async function _i(M,j,te,Z,ne,de,me){const be=!!(M.puppet&&ps),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 St=1;Math.max(ue,pe)>qe&&(St=qe/Math.max(ue,pe));const bt=Math.max(1,Math.round(ue*St)),wt=Math.max(1,Math.round(pe*St));let Un=ae;if(s&&bt>0&&wt>0){(s.width!==bt||s.height!==wt)&&(s.width=bt,s.height=wt);const xn=s.getContext("2d");xn&&(xn.clearRect(0,0,bt,wt),xn.drawImage(ae,0,0,bt,wt),Un=s)}if(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,Un),n.getError()!==n.NO_ERROR&&s)try{const ft=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(ft.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?bn:Kr,Me=(!!M.passthrough||!!M.isPostProcess||Vh(M)||Wh(M))&&!M.groupTex&&!fe&&!be&&!it;let ke,T;if(M.groupTex)ke=M.groupW||M.size[0],T=M.groupH||M.size[1];else if(be||!fe)ke=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));ke=ae>0?ae:fe.width,T=ue>0?ue:fe.height}if(!be&&fe&&M.spriteSheet){const ae=fe.frames,ue=Array.isArray(ae)?ae:ae&&ae.list;ue&&ue.length&&(ke=ue[0].width||ke,T=ue[0].height||T)}const C=Math.max(1,Math.round(ke)),R=Math.max(1,Math.round(T)),F=Cl(M.lightingEnabled,fa),$=[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){be?ys(M,te,Z,ne,de,me):Nn(De,se,$,M,te,Z,ne,de,!1,ms(M,fe,me));return}const Q=Et(L,X,"ping"),re=Et(L,X,"pong"),q=Ei(0,L,0,X,-1e4,1e4);if(be)n.useProgram(De),wn("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(ot),en=null,ln("layer"+L+"x"+X,ei(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),Er(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(Me)ha(M,Q,L,X,te,Z,ne,de);else{n.useProgram(De),wn("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(ot),ln("layer"+L+"x"+X,ei(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]),Er(Ze,ms(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,N=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,Et(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 He=Ie&&Ie.combos||{},tt=pe.combos||{};He.WRITEALPHA===void 0&&tt.WRITEALPHA===void 0&&(je.WRITEALPHA=1),He.TRANSPARENCY===void 0&&tt.TRANSPARENCY===void 0&&(je.TRANSPARENCY=1)}const qe=pe.textures||[],St=Ie&&Ie.textures||[],bt=[];for(let He=0;He<Math.max(qe.length,St.length);He++)St[He]!==void 0&&St[He]!==null?bt[He]=St[He]:bt[He]=qe[He]!==void 0?qe[He]:null;if(Ie&&Array.isArray(Ie.textureFallbacks))for(let He=0;He<bt.length;He++){const tt=bt[He];if(typeof tt!="string"||tt===""||j&&j.get(tt))continue;const dn=Ie.textureFallbacks[He];dn&&(bt[He]=dn)}if(pe.copyCommand){const He=pe.source?E.get(pe.source):null,tt=pe.target?E.get(pe.target):null;He&&tt&&(n.useProgram(Re),wn("normal"),n.bindFramebuffer(n.FRAMEBUFFER,tt.fbo),n.viewport(0,0,tt.width,tt.height),n.bindVertexArray(ot),ln("pass",_r),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,He.tex),n.uniform1i(Fn.tex,0),Fn.blendPrep!==null&&Fn.blendPrep!==void 0&&n.uniform1i(Fn.blendPrep,0),n.uniformMatrix4fv(Fn.mvp,!1,un),n.drawArrays(n.TRIANGLES,0,6),g());continue}let wt;try{wt=await Ro(pe.shader,je,bt)}catch(He){const tt=He&&He.message||String(He);/已缓存/.test(tt)||console.warn("[we-scene] \u8DF3\u8FC7\u6548\u679C\uFF08pass \u7F16\u8BD1\u5931\u8D25\uFF09:",pe.shader,tt),J.add(ue);continue}const Un=wt.prog,xn=wt.uni;wt.fragGlsl&&ge.push(wt.fragGlsl);let ft,tn;pe.target?(z||(ee=K,z=!0),ft=E.get(pe.target)||K,tn=ee):(z=!1,ft=N,tn=K),n.useProgram(Un),wn(pe.blending||"normal"),n.bindFramebuffer(n.FRAMEBUFFER,ft.fbo),n.viewport(0,0,ft.width,ft.height),n.bindVertexArray(ot);const ws=!wt.ndcDirect;ws?ln("passPx"+ft.width+"x"+ft.height,ei(ft.width,ft.height)):ln("pass",_r);const vu=ws?qo(Ei(0,ft.width,0,ft.height,-1e4,1e4)):un,jo=pe.textures||[],ma=Math.max(jo.length,8),fn=new Map,ex=new Set;for(let He=0;He<ma;He++){let tt=bt[He]!==void 0?bt[He]:null;for(const ga of pe.binds||[])ga.index===He&&(tt=ga.name);let dn;if(He===0&&(tt==null||tt===""))dn=tn;else{if((tt==null||tt==="")&&wt.samplerDefaults){const ga=wt.samplerDefaults.get(He);ga&&(tt=ga)}dn=zo(tt,tn,E,j)}tt==="previous"&&(dn=tn),dn===null&&(dn={glTex:bn,width:1,height:1,tex:bn});const pa=dn.fbo?dn:{tex:dn.glTex||bn,width:dn.width||1,height:dn.height||1};n.activeTexture(n.TEXTURE0+He),n.bindTexture(n.TEXTURE_2D,pa.tex),ex.add(He),fn.set(He,[pa.width,pa.height,pa.width,pa.height])}let yp=null;if(xn.get("g_EffectModelViewProjectionMatrix")){const He=vn(M,te);let tt=Rr(He.m,He.w,He.h,1);tt=ws?Wt(tt,Rr(ii(Ir(),-.5,-.5,0),1/ft.width,1/ft.height,1)):Wt(tt,Rr(Ir(),.5,.5,1)),yp=qo(Wt(Z,tt))}ls(xn,M,me,te.projW,te.projH,vu,q,un,fn,q,te,yp);const Au=(M.id||M.name||"?")+"|"+(pe.shader||"?")+"|"+ae,bp={...pe.constants||{},...Ie&&Ie.constantshadervalues||{}};da(bp,Au,me),bu(xn,Zn(Bt(bp,Au,me,M),Au,me,M),wt.matMeta),Kn(xn),n.drawArrays(n.TRIANGLES,0,6),pe.target||(N=K,K=ft)}if(M.isContainer&&!M.groupTex&&!Me&&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"}`)),be){ys(M,te,Z,ne,de,me,K.tex);return}Nn(Re,K.tex,[1,1,1,1],M,te,Z,ne,de,!!M.isContainer&&!M.groupTex&&!Me,null,null)}return{gl:n,render:Wo,getFBO:Et,getEffectProgram:Ro,progCache:on,shaderResolver:r,whiteTex:bn,resetShaderCaches:function(){on.clear(),Rt.clear(),ss&&ss.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 Ln(M,j)},setParticleRenderer:function(M,j){v=typeof M=="function"?M:null,x=typeof j=="function"?j:null},setConstantScriptRuntime:Ee,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){gs=!!M},compositeStats:function(){const M=[],j=new Uint8Array(4);for(const[te,Z]of An){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){ps=M},setAudioProvider:k,setPointerProvider:Qn,getParallaxOffset:function(){return ze},getPerspectiveEye:function(){return os},dispose:function(){try{const M=n.getExtension("WEBGL_lose_context");M&&M.loseContext()}catch{}}}}const jb=Object.freeze(Object.defineProperty({__proto__:null,ALIGN:Rh,XRAY_IDLE_SCREEN_UV:Qs,XRAY_SIZE_FALLBACK:Qh,applyColorBlendCPU:zb,bloomPostParams:$h,chainAlphaMeaningful:Hh,clampCompositeFboSize:Xh,collectGroupDescendantIds:oo,colorBlendPlan:El,compositeSourcePlacement:Zh,compositeSourceQuadSize:Kh,compressedFormatFor:_b,constantFallback:Yh,createRenderer:Wb,effectFboSize:qh,layerColorAmbient:Cl,layerCompositeBlendMode:jh,layerWantsComposeBackdrop:Wh,layerWantsPreserveBackdrop:Vh,makeCompressedTextureMip:Pb,makeR8TextureMip:Eb,makeTexture:Tl,makeTextureMip:Sb,needsShaderBlend:Ml,puppetAnimMargin:zh,rewriteXrayFragScale:Gh,xrayShouldParkPointer:Il,xrayUvScale:Hb},Symbol.toStringTag,{value:"Module"})),Wr=Math.PI*2;function Pt(t,e){return t==null?Math.random():e==null?t:t+Math.random()*(e-t)}function jr(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 wr(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 wr(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 qr(t,e,n){const r=Math.sin(t*127.1+e*311.7+n*74.7)*43758.5453;return r-Math.floor(r)}function qb(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(qr(r,i,s),qr(r+1,i,s),u),p=f(qr(r,i+1,s),qr(r+1,i+1,s),u),m=f(qr(r,i,s+1),qr(r+1,i,s+1),u),g=f(qr(r,i+1,s+1),qr(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*qb(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 Xb(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
|
|
367
|
-
float
|
|
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 *
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
// \
|
|
405
|
-
// \
|
|
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
|
-
// \
|
|
408
|
-
// \
|
|
409
|
-
|
|
410
|
-
// \
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
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
|
-
|
|
418
|
-
|
|
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 yd(t){const e=t&&t.passes&&t.passes[0]&&t.passes[0].combos;return!!(e&&Number(e.REFRACT)===1)}function Ay(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 bd(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 Sc(t,e){return t||e?Math.atan2(e,t)-Math.PI/2:0}function wd(t,e){return t&&t.kind==="ropetrail"?Math.max(1,e||1):1}function vd(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 kd(t){if(!t||t.kind!=="ropetrail")return 0;const e=Number(t.length);return Number.isFinite(e)&&e>0?e:.2}function Pc(t){return t.life>0?t.age/t.life:0}class xy{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 Ty{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 xy)}_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:gd(c.distancemin),distanceMax:gd(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,nn)};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,nn)};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,nn),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=vd(o);this.trailSegments=c,this.trailDuration=kd(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=yd(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]+Je(-f[0],f[0])+(d?d[0]:0),i.y=a[1]+Je(-f[1],f[1])+(d?d[1]:0),i.z=a[2]+Je(-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()*nn,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=Je(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=Je(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)*nn,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,pd(o.life.min,o.life.max,o.life.exp)*this.lifetimeMul):1,i.baseSize=o.size?pd(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?Je(o.alpha.min,o.alpha.max):1)*this.opacityMul,i.alpha=i.baseAlpha,o.velocity&&(i.vx+=Je(o.velocity.min[0],o.velocity.max[0])*c,i.vy+=Je(o.velocity.min[1],o.velocity.max[1])*c,i.vz+=Je(o.velocity.min[2],o.velocity.max[2])*c),o.turbulentVelocity){const f=o.turbulentVelocity,d=f.audioMode?Ac(f.audioBounds,this._audioLevel||0):1,h=Je(f.speedMin,f.speedMax)*c*d,p=this.simTime*(f.timeScale||0),m=Tc(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=Je(o.rotation.min[2],o.rotation.max[2])),o.angularVelocity&&(i.rotVel=Je(o.angularVelocity.min[2],o.angularVelocity.max[2]));const l=this.ops;if(l.oscPos&&(i.oscFreq=Je(l.oscPos.freqMin,l.oscPos.freqMax),i.oscAmp=Je(l.oscPos.scaleMin,l.oscPos.scaleMax),i.oscPhase=Je(l.oscPos.phaseMin,l.oscPos.phaseMax)+i.seed*nn),l.oscAlpha&&(i.oscAFreq=Je(l.oscAlpha.freqMin,l.oscAlpha.freqMax),i.oscAPhase=Math.random()*(l.oscAlpha.phaseMax||nn)),l.oscSize&&(i.oscSFreq=Je(l.oscSize.freqMin,l.oscSize.freqMax),i.oscSPhase=Math.random()*(l.oscSize.phaseMax||nn)),l.turbulence.length){const f=l.turbulence[0];i.turbSpeed=Je(f.speedMin,f.speedMax),i.turbPhase=Je(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=Tc(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?Ac(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=Tc(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*nn+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*nn+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*nn+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=Ac(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=wd(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,U=(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=U(J.x,J.y),Ne=U(ne.x,ne.y),Ze=Ne[0]-fe[0],je=Ne[1]-fe[1],Fe=Math.hypot(Ze,je),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(-Ze,je),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++]=Pc(J),w[y++]=Pc(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,Ze=1,je=1,Fe=J.rot,Le=k,Pt=A,Xe,Dt;if(o&&J.trail){fe=J.trail[ne*3],Ne=J.trail[ne*3+1];const Oe=l>1?ne/(l-1):0;Ze=1-Oe,je=1-Oe*.55;let qe=0,ze=0;ne+1<l?(qe=J.trail[ne*3]-J.trail[(ne+1)*3],ze=J.trail[ne*3+1]-J.trail[(ne+1)*3+1]):ne>0?(qe=J.trail[(ne-1)*3]-J.trail[ne*3],ze=J.trail[(ne-1)*3+1]-J.trail[ne*3+1]):(qe=J.vx,ze=J.vy);const st=U(fe,Ne),ve=U(fe-qe,Ne-ze),vn=st[0]-ve[0],ki=st[1]-ve[1],an=Math.hypot(vn,ki),_t=Math.max(.001,Math.abs(J.size)*v*je);an>.001?(Fe=Sc(vn,ki),Xe=(st[0]+ve[0])*.5,Dt=(st[1]+ve[1])*.5,Pt=Math.max(A,an/_t)):(Xe=st[0],Dt=st[1])}else{const Oe=U(fe,Ne);Xe=Oe[0],Dt=Oe[1]}if(c){const Oe=U(J.x,J.y);Xe=Oe[0],Dt=Oe[1];const qe=U(J.x+J.vx,J.y+J.vy);Fe=Sc(qe[0]-Oe[0],qe[1]-Oe[1]);const ze=bd(Math.hypot(J.vx,J.vy),c.length,c.minLength,c.maxLength);Pt=A*ze}w[y++]=Xe,w[y++]=Dt,w[y++]=0,w[y++]=Math.abs(J.size)*v*je,w[y++]=Fe,w[y++]=J.r*b,w[y++]=J.g*b,w[y++]=J.b*b,w[y++]=J.alpha*Ze,w[y++]=Le,w[y++]=Pt,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=ky(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 Sy=Object.freeze(Object.defineProperty({__proto__:null,ParticleSystem:Ty,particleInstanceSegs:wd,particlePassRefract:yd,rgbaIsBlankWhite:Ay,ropeParticleV:Pc,ropeTrailDuration:kd,ropeTrailHistoryCount:vd,spriteTrailLengthFactor:bd,spriteTrailRotation:Sc},Symbol.toStringTag,{value:"Module"})),as=new Map,_c=new Map;let ga=null;function Py(t,e){const n=String(t);_c.set(n,e),as.delete(n)}function _y(t){ga=typeof t=="function"?t:null}function Ey(){_c.clear(),ga=null,as.clear()}function Cy(){return Object.keys(ds)}function We(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 os(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 cs(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 wi=t=>t*t*(3-2*t),Ad=t=>t*t*t*(t*(t*6-15)+10),Ec=(t,e,n)=>t+(e-t)*n,he=(t,e)=>Math.exp(-(t*t)/(e*e));function fr(t,e,n,r){const i=Math.min(t,e,n-1-t,n-1-e);return i>=r?1:i/r}function ls(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);We(n,(i*t+s)*4,o)}return{width:t,height:t,rgba:n}}function jn(t,e,n){return ls(t,[e,n])}function dr(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*=fr(u,c,t,o),We(s,(c*t+u)*4,m)}return{width:t,height:t,rgba:s}}function bn(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):wi(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);We(a,(o*t+l)*4,d*d*d*u*.55)}}return{width:t,height:e,rgba:a}}const ya=4,Cc=128,Ic=512;function xd(t,e,n,r,i){const s=i===void 0?.85:i,a=new Uint8Array(t*e*4),o=e/ya,c=cs(335009),u=Math.tan(n*Math.PI/180),l=t/2;for(let f=0;f<ya;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||We(a,((f*o+m)*t+b)*4,A)}}}return{width:t,height:e,rgba:a}}function Iy(t){if(t==="particle/nature/rain1"||t==="particle/nature/rain2"){const e=[],n=Ic/ya;for(let r=0;r<ya;r++)e.push({x:0,y:r*n,width:Cc,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*fs,y:n*fs,width:fs,height:fs});return e}return null}function Mc(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);We(r,(s*t+a)*4,he(o-e,n*.6)*Math.max(0,1-o))}return{width:t,height:t,rgba:r}}function Td(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])}We(i,(a*t+o)*4,f)}return os({width:t,height:t,rgba:i},.05)}function us(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=Td(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 Sd(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),We(e,(i*t+s)*4,k)}return os({width:t,height:t,rgba:e},.11)}const fs=256,yt=fs*3;function bt(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=cs(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 U=he(A,.028)*he(T,.72),q=(.8+.2*Math.max(0,1-B))*(1+U*.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 os({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,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 Pd(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;We(e,(r*t+i)*4,Math.min(1,c*.85+u))}return{width:t,height:t,rgba:e}}function My(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));We(e,(r*t+i)*4,u)}return{width:t,height:t,rgba:e}}function _d(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=wi(Math.max(0,Math.cos(u)*.55+.45)),f=he(c-.68,.07)*l+.35*he(c-.78,.12)*he(u-.9,.55);We(e,(i*t+s)*4,Math.min(1,f)*fr(s,i,t,r))}return{width:t,height:t,rgba:e}}function By(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 Ry(t){return!t||!t.rgba?t:By(t.rgba)?rn(t,2.8):t}const Fy={"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 Dy(t){if(!t)return null;const e=String(t);return/normal/i.test(e)?e:Fy[e]||e+"_normal"}function Ny(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 Ly(t){if(ds[t])return ds[t]();const e=String(t).toLowerCase();return/normal/.test(e)?jn(64,{r:.18,w:1},{r:.4,w:.2}):Dd(t)()}function Ed(t,e,n){const r=cs(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=Ad(m),y=Ad(g);return Ec(Ec(a(c,h,p,m,g),a(c,h+1,p,m-1,g),w),Ec(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 Cd(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;We(a,(o*e+d)*4,k/255)}}return{width:e,height:n,rgba:a}}function hr(t,e,n,r,i,s,a){const o=s===void 0?1:s,c=a===void 0?200:a,u=256,l=Ed(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=wi(Math.min(1,P))*S,We(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:Cd(b,t,t)}function Bc(t,e){const n=t,r=Ed(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=wi(Math.min(1,Math.max(0,(w-.18)/.72)))*y;b*=p<.06?p/.06:1,We(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=os({width:n,height:n,rgba:i},.08);return n===t?f:Cd(f,t,t)}function Rc(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);We(i,(o*t+c)*4,m)}return{width:t,height:e,rgba:i}}function Id(t){const e=new Uint8Array(t*t*4),n=cs(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)}We(e,(i*t+s)*4,c)}return{width:t,height:t,rgba:e}}function ba(t,e){const n=e??19,r=cs(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;We(l,(d*t+h)*4,Math.min(1,y)*fr(h,d,t,f))}return{width:t,height:t,rgba:l}}function Fc(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);We(n,(r*t+i)*4,Math.max(o,u))}return{width:t,height:e,rgba:n}}function Oy(t){return jn(t,{r:.1,w:1},{r:.3,w:.16})}function Dc(t,e){const n=new Uint8Array(t*e*4);for(let r=0;r<e;r++){const i=(r+.5)/e,s=wi(Math.min(1,Math.min(i/.08,(1-i)/.08))),a=he(i-.46,.24)*s,o=.5*(1-wi(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);We(n,(r*t+c)*4,he(Math.abs(u)/(o||.01),.5)*a)}}return{width:t,height:e,rgba:n}}function Md(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)*fr(s,i,t,r);We(e,(i*t+s)*4,l)}return{width:t,height:t,rgba:e}}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;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}We(e,(i*t+s)*4,Math.min(1,c)*fr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Rd(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)),We(n,(a*t+o)*4,Math.min(1,f)*fr(o,a,t,i))}return os({width:t,height:t,rgba:n},.03)}function Nc(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 Uy(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*=fr(a,s,t,r),We(e,(s*t+a)*4,l)}return{width:t,height:t,rgba:e}}function Fd(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);We(e,(i*t+s)*4,Math.min(1,u)*fr(s,i,t,r))}return{width:t,height:t,rgba:e}}const ds={"particle/halo_6":()=>jn(256,{r:.14,w:1},{r:.4,w:.17}),"particle/normal_splash":()=>rn(Pd(256),3.2),"particle/drop_normal":()=>rn(Dc(128,512),3.4),"particle/normal_ring_smooth":()=>rn(Mc(256,.55,.12),3.1),"particle/normal_pinch_rotate":()=>rn(My(256),2.8),"particle/water/rain_drops_sheet_normal":()=>rn(Rc(256,512,2,4),3.6),"particle/bubbles/bubble1normal":()=>rn(us(256,1),3.2),"particle/bubbles/bubble2_normal":()=>rn(us(256,2),3.2),"particle/sharp_halo_normal":()=>rn(ls(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),3.4),"particle/beam/beam_0":()=>bn(128,512,.46,!0),"particle/beam/beam_1":()=>bn(128,512,.34,!0),"particle/beam/beam_2":()=>bn(128,512,.22,!0),"particle/beam/beam_2_fade":()=>bn(128,512,.24,!1),"particle/light/light_shafts_0":()=>bn(128,512,.42,!0),"particle/light/light_shafts_1":()=>bn(128,512,.3,!0),"particle/light/light_shafts_3":()=>bn(128,512,.26,!0),"particle/light/light_shafts_5":()=>bn(128,512,.23,!0),"particle/light/light_shafts_6":()=>bn(128,512,.2,!0),"particle/nature/rosepetals":()=>Sd(256),"particle/nature/leaves":()=>bt(yt,0),"particle/nature/leaves1":()=>bt(yt,1),"particle/nature/leaves2":()=>bt(yt,2),"particle/nature/leaves3":()=>bt(yt,3),"particle/nature/leaves5":()=>bt(yt,5),"particle/nature/leaves6":()=>bt(yt,6),"particle/nature/leaves7":()=>bt(yt,7),"particle/nature/leaves8":()=>bt(yt,8),"particle/nature/snow":()=>Bd(256),"particle/halo":()=>jn(256,{r:.12,w:1},{r:.3,w:.15}),"particle/halo_1":()=>jn(256,{r:.1,w:1},{r:.3,w:.13}),"particle/halo_2":()=>jn(256,{r:.2,w:.9},{r:.44,w:.2}),"particle/halo_3":()=>ls(256,[{r:.045,w:1},{r:.13,w:.85},{r:.36,w:.15}]),"particle/halo_4":()=>jn(256,{r:.085,w:1},{r:.28,w:.12}),"particle/halo_5":()=>ls(256,[{r:.04,w:1},{r:.11,w:.8},{r:.34,w:.17}]),"particle/sharp_halo":()=>ls(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),"particle/chromaticdot":()=>Oy(128),"particle/light/flare_0":()=>dr(256,6,.58,10,.08),"particle/light/flare_1":()=>Uy(512),"particle/light/flare_2":()=>Fd(256),"particle/drop":()=>Dc(128,512),"particle/nature/rain1":()=>xd(Cc,Ic,10,1,.78),"particle/nature/rain2":()=>xd(Cc,Ic,10,1.6,.66),"particle/water/rain_drops_sheet":()=>Rc(256,512,2,4),"particle/fog/fog1":()=>hr(512,4,5,1,.4,.9,150),"particle/fog/fog2":()=>hr(512,3,5,2,.45,.8,140),"particle/fog/fog3":()=>hr(512,6,4,3,.36,1,150),"particle/smoke/smoke1":()=>hr(512,3,5,7,.55,1.5,130),"particle/smoke/smoke2":()=>hr(512,2,5,11,.6,1.7,120),"particle/smoke/smoke2light":()=>hr(512,2,5,13,.4,1.7,110),"particle/misc/wave":()=>Mc(512,.72,.085),"particle/misc/star_0":()=>dr(256,5,.62,8,.1),"particle/bubbles/bubble1":()=>us(256,1),"particle/bubbles/bubble2":()=>us(256,2),"particle/bubbles/bubble3":()=>us(256,3),"particle/debris/debris1":()=>Id(128),"particle/lightning/lightning1":()=>ba(256,3),"particle/lightning/lightning2":()=>ba(256,11),"particle/lightning/lightning3":()=>ba(256,19),"particle/fire/fire1":()=>Bc(256,23),"particle/fire/fire2":()=>Bc(256,41),"particle/star":()=>dr(256,4,.58,12,.09),"particle/shape/circle_wind":()=>_d(256),"particle/sickle":()=>Md(256),"particle/magic/glyph_4":()=>Rd(256,4),"@sparkle":()=>dr(256,4,.6,16,.08),"@star":()=>dr(256,5,.62,8,.1),"@trail":()=>Fc(128,256)};function Dd(t){const e=String(t).toLowerCase();if(/normal/.test(e)){const n=Ny(t);return n?()=>rn(Ly(n),2.8):()=>rn(Pd(128),2.6)}return/rosepetal|petal|sakura|blossom/.test(e)?()=>Sd(256):/leaf|leaves|foliage/.test(e)?/leaves8/.test(e)?()=>bt(yt,8):/leaves7/.test(e)?()=>bt(yt,7):/leaves6/.test(e)?()=>bt(yt,6):/leaves5/.test(e)?()=>bt(yt,5):/leaves3/.test(e)?()=>bt(yt,3):/leaves2/.test(e)?()=>bt(yt,2):/leaves1/.test(e)?()=>bt(yt,1):()=>bt(yt,0):/circle_wind|windcircle/.test(e)?()=>_d(256):/fog|cloud|mist|vapor/.test(e)?()=>hr(512,4,5,5,.4,.9,150):/smoke/.test(e)?()=>hr(512,3,5,8,.55,1.5,130):/beam|shaft|ray|godray/.test(e)?()=>bn(128,512,.3,!0):/flare/.test(e)?()=>Fd(256):/bubble/.test(e)?()=>Td(256,1):/ring|wave/.test(e)?()=>Mc(512,.72,.085):/fire|flame|ember|ash/.test(e)?()=>Bc(256,Nc(e)):/sickle|crescent|moon/.test(e)?()=>Md(256):/glyph|magic|rune/.test(e)?()=>Rd(256,Nc(e)):/snowflake|雪花|snow/.test(e)?()=>Bd(256):/流星|meteor|shooting/.test(e)?()=>Fc(128,256):/star|星/.test(e)?()=>dr(256,5,.62,8,.1):/sparkle|glint|twinkle/.test(e)?()=>dr(256,4,.6,16,.08):/rain_drops_sheet|drops_sheet/.test(e)?()=>Rc(256,512,2,4):/drop|rain/.test(e)?()=>Dc(128,512):/debris|dirt|rock/.test(e)?()=>Id(128):/lightning|bolt|arc/.test(e)?()=>ba(256,Nc(e)):/note|music/.test(e)?()=>dr(256,4,.55,8,.12):/trail|streak/.test(e)?()=>Fc(128,256):()=>jn(256,{r:.12,w:1},{r:.3,w:.15})}function zy(t){if(as.has(t))return as.get(t);let e=null;const n=_c.get(t);if(n)try{e=n()}catch{e=null}if(!e&&ga)try{e=ga(t)}catch{e=null}if(!e&&ds[t])try{e=ds[t]()}catch{e=null}if(!e)try{e=Dd(t)()}catch{e=null}return e||(e=jn(256,{r:.12,w:1},{r:.3,w:.15})),as.set(t,e),e}function Hy(t){return typeof t=="string"&&t.indexOf("particle/")===0}const Vy=Object.freeze(Object.defineProperty({__proto__:null,buildBuiltinParticleTexture:zy,builtinParticleFrames:Iy,isBuiltinParticleTextureName:Hy,listBuiltinParticleTextureNames:Cy,particleNormalNameForAlbedo:Dy,prepareParticleNormalTexture:Ry,resetParticleTextureFactories:Ey,setParticleTextureFactory:Py,setParticleTextureProvider:_y},Symbol.toStringTag,{value:"Module"})),Nd=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function mr(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 Ld(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(Nd);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 Lc(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 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 wa(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 Wy(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 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=qy(t,e),k=$y(t,e,v.length),A=Yy(t,e,v),T=jy(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]=Lc(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?mr(G[J],H[Y]):Float32Array.from(H[Y])}for(let Y=0;Y<v.length;Y++)S[Y]=Float64Array.from(Ld(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?mr(Y[ne],A[J]):Float32Array.from(A[J])}for(let J=0;J<v.length;J++)P[J]=mr(Y[J],S[J])}}let B=1/0,N=-1/0,U=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<U&&(U=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:Qy(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:U,maxY:q}}}function jy(t,e,n){const r=wa(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 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 qy(t,e){const n=wa(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=pr(e,s+13+64);i.push({id:o,parent:c>=0&&c<r?c:-1,matrix:u}),s=l.next}return i}function Xy(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 Gy(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 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 $y(t,e,n){const r=wa(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 f=pr(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=Gy(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=Xy(e,w.next,g);if(y<0)break;i=y}return o}function Qy(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 Yy(t,e,n){if(n.length===0)return null;const r=wa(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 Ky(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 Zy(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 Oc(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++){Zy(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;Ky(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?Lc(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],t._local[d]):Lc(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?mr(t._world[h],t._local[d],t._world[d]):t._world[d].set(t._local[d])}for(let d=0;d<s;d++)mr(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:Ld(t.invBindWorld[e])}function Jy(t,e){return mr(t,e)}function Ud(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:mr(t._world[n.bone],n.matrix);return null}function zd(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?mr(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 eb(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=zd(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 tb(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;Oc(c,e,o.parent.animationLayers,l)}const u=Ud(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 nb=128,va=24;function rb(t){const e=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS)||256,n=Math.floor((e-32)/4);return Math.max(va,Math.min(nb,n))}const ib=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 $b(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 Gb(t,e,n){const r=Math.min(1,Math.max(0,(n-t)/(e-t||1)));return r*r*(3-2*r)}function co(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 Qb=32,em=60/112,tm=3.2;function Yb(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=$b(t),n=Yb(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%Qb,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(co(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*co(A*.5+r[Y]*.05,Y%8)),Ee=V*(.5+.3*co(A*.53+r[Y]*.05+31.7,Y%8+16));let Ce=Ae*(.35+.65*oe),Ue=Ee*(.35+.65*oe);if(oe<.2){const nt=O*(1-oe/.2);Ce+=nt,Ue+=nt}if(oe>=.12&&oe<.62){const nt=1-Math.abs(oe-.34)/.28;nt>0&&(Ce+=U*.55*nt,Ue+=U*.35*nt)}if(oe>=.45){const nt=(oe-.45)/.55;Ue+=W*.5*nt,Ce+=W*.3*nt}Ce+=ie*.5,Ue+=ie*.5,Ce*=he,Ue*=he;const Ne=Ce,De=Ue;Ce=Math.min(1,Ce*tm),Ue=Math.min(1,Ue*tm);const Re=.06+oe*.2,Fe=co(A*.13+Y*.35,11)*Re;let Ge=Math.min(1,Math.max(0,Ce*(1-Fe))),Qe=Math.min(1,Math.max(0,Ue*(1+Fe)));const Ye=k?.012:0;s[Y]=Math.max(Ye,Ge),a[Y]=Math.max(Ye,Qe),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 Kb(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=Gb(i[0],i[1],f),f=Math.min(1,Math.max(0,Math.pow(f,s)))*a,f}let rs=1;function Zb(t){const e=Number(t);rs=Number.isFinite(e)&&e>=0?e:1}function Jb(){return rs}const sm={low:3e3,medium:6e3,high:12e3},ew={low:3,medium:5,high:8};let lo="high";function tw(t){lo=sm[t]?t:"high"}function nw(){return lo}const Dl=2048,rw=256,iw=64;let Nl=null;function sw(t){Nl=typeof t=="function"?t:null}let Ll=null;function aw(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 ow(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 cw{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 lw{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)*rs)),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)*rs));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[lo];this.maxCount=Math.max(1,Math.min(c,Math.round(s*o*rs)));const u=ew[lo],l=o<=1?o:Math.min(o,u);this._ov.countMul=l*rs,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 cw);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:wr(c.min)||[0,0,0],max:wr(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:wr(c.min)||[-32,-32,0],max:wr(c.max)||[32,32,0]};break;case"rotationrandom":this.init.rotation={min:wr(c.min)||[0,0,0],max:wr(c.max)||[0,0,Wr],exp:Te(c.exponent,1)};break;case"angularvelocityrandom":this.init.angularVelocity={min:wr(c.min)||[0,0,-5],max:wr(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,Wr)};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>=iw&&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>=rw)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]+Pt(-f[0],f[0])+(h?h[0]:0),s.y=o[1]+Pt(-f[1],f[1])+(h?h[1]:0),s.z=o[2]+Pt(-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()*Wr,I=Math.sqrt(Math.max(0,1-k*k));A=I*Math.cos(_),b=I*Math.sin(_),v=k}else{const k=Math.random()*Wr;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=Pt(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)*Wr,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,jr(c.life.min,c.life.max,c.life.exp)*this.lifetimeMul):1,s.baseSize=c.size?jr(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?Pt(c.alpha.min,c.alpha.max):1)*this.opacityMul,s.alpha=s.baseAlpha,c.velocity&&(s.vx+=Pt(c.velocity.min[0],c.velocity.max[0])*u,s.vy+=Pt(c.velocity.min[1],c.velocity.max[1])*u,s.vz+=Pt(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=Pt(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=jr(c.rotation.min[0],c.rotation.max[0],c.rotation.exp),s.rotY=jr(c.rotation.min[1],c.rotation.max[1],c.rotation.exp),s.rot=jr(c.rotation.min[2],c.rotation.max[2],c.rotation.exp)),c.angularVelocity&&(s.rotVelX=jr(c.angularVelocity.min[0],c.angularVelocity.max[0],c.angularVelocity.exp),s.rotVelY=jr(c.angularVelocity.min[1],c.angularVelocity.max[1],c.angularVelocity.exp),s.rotVel=jr(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]=Pt(d.oscPos.freqMin,d.oscPos.freqMax),s.oscPAmp[f]=Pt(d.oscPos.scaleMin,d.oscPos.scaleMax),s.oscPPhase[f]=Pt(d.oscPos.phaseMin,d.oscPos.phaseMax+Wr));if(d.oscAlpha&&(s.oscAFreq=Pt(d.oscAlpha.freqMin,d.oscAlpha.freqMax),s.oscAAmp=[d.oscAlpha.scaleMin,d.oscAlpha.scaleMax],s.oscAPhase=Pt(d.oscAlpha.phaseMin,d.oscAlpha.phaseMax+Wr)),d.oscSize&&(s.oscSFreq=Pt(d.oscSize.freqMin,d.oscSize.freqMax),s.oscSAmp=[d.oscSize.scaleMin,d.oscSize.scaleMax],s.oscSPhase=Pt(d.oscSize.phaseMin,d.oscSize.phaseMax+Wr)),d.turbulence.length){const f=d.turbulence[0];s.turbSpeed=Pt(f.speedMin,f.speedMax),s.turbPhase=Pt(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=Kb({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),Ee=O(he.x,he.y),Ce=Ee[0]-Ae[0],Ue=Ee[1]-Ae[1],Ne=Math.hypot(Ce,Ue),De=(v(oe.size)+v(he.size))*.5;De>0&&(g[y++]=(Ae[0]+Ee[0])*.5,g[y++]=(Ae[1]+Ee[1])*.5,g[y++]=0,g[y++]=De,g[y++]=Math.atan2(-Ce,Ue),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,Ee,Ce,Ue,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++]=Ee,g[y++]=De,g[y++]=Ce,g[y++]=Ue,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),Ee=O(oe.x+oe.vx,oe.y+oe.vy),Ce=Ee[0]-Ae[0],Ue=Ee[1]-Ae[1],Ne=v(oe.size),De=lm(Ce,Ue),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=Xb(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 uw=Object.freeze(Object.defineProperty({__proto__:null,ParticleSystem:lw,getParticleDensityTier:nw,getParticleQualityScale:Jb,particleInstanceSegs:um,particlePassRefract:om,rgbaIsBlankWhite:ow,ropeParticleV:Ul,ropeTrailDuration:dm,ropeTrailHistoryCount:fm,setParticleDensityTier:tw,setParticleFrameTargetProvider:sw,setParticleQualityScale:Zb,setParticleSceneCapture:aw,spriteTrailLengthFactor:cm,spriteTrailRotation:lm},Symbol.toStringTag,{value:"Module"})),Pn=new Map,Ol=new Map;let uo=null;function fw(t,e){const n=String(t);Ol.set(n,e),Pn.delete(n)}function dw(t){uo=typeof t=="function"?t:null}function hw(){Ol.clear(),uo=null,Pn.clear()}function mw(){return Object.keys(na)}function ct(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 Ys(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 jn(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 qn=t=>t*t*(3-2*t),Ks=t=>t*t*t*(t*(t*6-15)+10),Xn=(t,e,n)=>t+(e-t)*n,_e=(t,e)=>Math.exp(-(t*t)/(e*e));function Xr(t,e,n,r){const i=Math.min(t,e,n-1-t,n-1-e);return i>=r?1:i/r}function Zs(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*_e(a,e[c].r);ct(n,(i*t+s)*4,o)}return{width:t,height:t,rgba:n}}function gi(t,e,n){return Zs(t,[e,n])}function pw(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)}ct(n,(s*t+a)*4,c)}return{width:t,height:t,rgba:n}}function gw(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);ct(e,(r*t+i)*4,Math.pow(1-o,1.6))}return{width:t,height:t,rgba:e}}function $r(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=_e(f,i)+p*_e(f,n);m*=Xr(u,c,t,o),ct(s,(c*t+u)*4,m)}return{width:t,height:t,rgba:s}}function fo(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?_e(c-.5,.27):qn(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=_e(d,n);ct(a,(o*t+l)*4,f*f*f*u*.55)}}return{width:t,height:e,rgba:a}}function yw(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 bw(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=jn(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 yi(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,_n=512,Js=_n*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(Js*Js*4);for(let o=0;o<mm;o++){const c=jn((2654435769^o*2246822507)>>>0),u=o%2*_n,l=(o/2|0)*_n,d=3,f=(h,p,m)=>{if(h<d||p<d||h>=_n-d||p>=_n-d)return;const g=((l+p)*Js+u+h)*4,y=Math.round(Math.min(1,Math.max(0,m))*255);y*255>a[g+3]*255&&ct(a,g,y/255)};for(let h=0;h<n;h++){const p=c()*_n,m=c()*_n,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:Js,height:Js,rgba:a}}function ww(t){if(t==="particle/nature/rain1"||t==="particle/nature/rain2"){const e=[];for(let n=0;n<mm;n++)e.push({x:n%2*_n,y:(n/2|0)*_n,width:_n,height:_n});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=is[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*$n,y:(n/8|0)*$n,width:$n,height:$n});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*Mn,y:(n/8|0)*Mn,width:Mn,height:Mn});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*ea,y:n*ea,width:ea,height:ea});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);ct(r,(s*t+a)*4,_e(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=_e(l-r.r,r.t*.85)*Math.max(0,1.05-l);l<r.r&&(d+=r.inner*_e(l,.5));for(let f=0;f<r.hi.length;f++){const h=r.hi[f];d+=h[3]*_e(Math.hypot(c-h[0],u-h[1]),h[2])}ct(i,(a*t+o)*4,d)}return Ys({width:t,height:t,rgba:i},.05)}function ho(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:_e(b,.48);v=Math.min(1,v+_e(y,.07)*_e(w,.65)*v*.4),ct(e,(i*t+s)*4,v)}return Ys({width:t,height:t,rgba:e},.11)}const ea=256,Ut=ea*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=jn(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=_e(x,.028)*_e(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 Ys({width:i*3,height:i*3,rgba:s},0)}function En(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=_e(o-.62,.11)*.55;ct(e,(r*t+i)*4,Math.min(1,c*.85+u))}return{width:t,height:t,rgba:e}}function vw(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=_e(o,.38)*(.55+.45*Math.cos(c*3+o*6));ct(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=qn(Math.max(0,Math.cos(u)*.55+.45)),d=_e(c-.68,.07)*l+.35*_e(c-.78,.12)*_e(u-.9,.55);ct(e,(i*t+s)*4,Math.min(1,d)*Xr(s,i,t,r))}return{width:t,height:t,rgba:e}}function Aw(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 xw(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 kw(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 Tw(t){return!t||!t.rgba?t:vm(t.rgba)?En(t,2.8):t}const Sw={"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 Pw(t){if(!t)return null;const e=String(t);return/normal/i.test(e)?e:Sw[e]||e+"_normal"}function _w(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 Ew(t){if(na[t])return na[t]();const e=String(t).toLowerCase();return/normal/.test(e)?gi(64,{r:.18,w:1},{r:.4,w:.2}):Mm(t)()}function Hl(t,e,n){const r=jn(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=Ks(m),w=Ks(g);return Xn(Xn(a(c,h,p,m,g),a(c,h+1,p,m-1,g),y),Xn(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=jn(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=Ks(x),_=Ks(P),I=Ks(S),B=Xn(l(f,A,b,v),l(f,A+1,b,v),k),V=Xn(l(f,A,b+1,v),l(f,A+1,b+1,v),k),O=Xn(l(f,A,b,v+1),l(f,A+1,b,v+1),k),U=Xn(l(f,A,b+1,v+1),l(f,A+1,b+1,v+1),k);return Xn(Xn(B,V,_),Xn(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;ct(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));_=qn(Math.min(1,_))*k,_=_<=.02?0:(_-.02)/.98,ct(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=_e(m/(g||.01),.55)*_e(p-.58,.42);let A=qn(Math.min(1,Math.max(0,(y-.18)/.72)))*w;A*=p<.06?p/.06:1,ct(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=Ys({width:n,height:n,rgba:i},.08);return n===t?d:Wl(d,t,t)}function Mw(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:_e(p,.48);ct(i,(o*t+c)*4,m)}return{width:t,height:e,rgba:i}}function Am(t){const e=new Uint8Array(t*t*4),n=jn(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=_e(Math.hypot(p,m),.55);g>c&&(c=g)}ct(e,(i*t+s)*4,c)}return{width:t,height:t,rgba:e}}function mo(t,e){const n=e??19,r=jn(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*_e(g,.012)+.3*_e(g,.05)*y;ct(l,(f*t+h)*4,Math.min(1,w)*Xr(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=_e(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:_e(c,.5);ct(n,(r*t+i)*4,Math.max(o,u))}return{width:t,height:e,rgba:n}}function Cw(t){return gi(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=qn(Math.min(1,Math.min(i/.08,(1-i)/.08))),a=_e(i-.46,.24)*s,o=.5*(1-qn(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);ct(n,(r*t+c)*4,_e(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=_e(Math.hypot(a,o),.42),u=_e(Math.hypot(a-.34,o),.36),l=Math.max(0,c-u*1.08)*Xr(s,i,t,r);ct(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=_e(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+=_e(p,.028)*_e(h,.5)*m,c+=.55*_e(p-(h-.28)*.65,.02)*_e(h-.28,.12)*m,c+=.55*_e(p+(h-.28)*.65,.02)*_e(h-.28,.12)*m,c+=.4*_e(p-(h-.48)*.7,.016)*_e(h-.48,.08)*m,c+=.4*_e(p+(h-.48)*.7,.016)*_e(h-.48,.08)*m}ct(e,(i*t+s)*4,Math.min(1,c)*Xr(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=_e(l,.016);s===0?(d+=_e(c,.012)*_e(u,.38),d+=_e(u,.012)*_e(c,.38)):s===1?(d+=_e(c-u,.012)*_e(c+u,.36),d+=_e(c+u,.012)*_e(c-u,.36)):(d+=_e(Math.hypot(c,u)-.26,.014),d+=_e(c,.012)*_e(u,.22)),ct(n,(a*t+o)*4,Math.min(1,d)*Xr(o,a,t,i))}return Ys({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 Iw(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=_e(u,.05)+.3*_e(u,.15);l+=.9*_e(c,i)*Math.exp(-Math.abs(o)/.3),l+=.9*_e(o,i)*Math.exp(-Math.abs(c)/.3),l*=Xr(a,s,t,r),ct(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=_e(c,.07)+.85*_e(a,.62)*_e(o,.045)+.22*_e(a,.92)*_e(o,.018);ct(e,(i*t+s)*4,Math.min(1,u)*Xr(s,i,t,r))}return{width:t,height:t,rgba:e}}const Rw=1024,Pm=64,$n=128,Bw=[.02,.05,.09,.12,.14,.12,.09,.07,.03,.01,0];function Fw(t){const e={},n=e.gen===void 0?$n>>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||Bw,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?Rw:e.size,P=Math.max(1,Math.round($n/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*$n,O=I*$n;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),Ee=Math.min(10,Math.max(0,Ae*10)),Ce=Math.min(9,Math.floor(Ee)),Ue=(b[Ce]+(b[Ce+1]-b[Ce])*(Ee-Ce))*m,Ne=Math.min(1,Math.max(0,(he-(l-d))/(2*d)));let De=Math.min(1,Math.max(0,f*Ue*Ne));h!==1&&(De=Math.pow(De,h));const Re=Math.min(W,U,n-1-W,n-1-U)/n;Re<p&&(De*=qn(Re/p));const Fe=Math.round(255*De);for(let Ge=0;Ge<P;Ge++)for(let Qe=0;Qe<P;Qe++){const Ye=((O+U*P+Ge)*x+V+W*P+Qe)*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:$n,height:$n})}return S}const Dw=[[.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]],Nw=[[.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]],Lw=[[.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]],Uw=[[.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 ta(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 Ge=Math.max(0,x((Fe+.5)/k,(Re+.5)/_,Y));V[Re*k+Fe]=Ge}const oe=O%r*e,he=(O/r|0)*n,Ae=11,Ee=new Float64Array(Ae),Ce=new Float64Array(Ae),Ue=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 Ge=Re*k+Fe,Qe=Math.hypot((Fe+.5-k/2)/(k/2),(Re+.5-_/2)/(_/2)),Ye=we*Math.exp(-((Qe/.12)**2))+U*Math.exp(-(((Qe-W)/ie)**2)),nt=o*(1-Math.min(1,Ye)),yn=Math.pow(Math.max(0,(V[Ge]-nt)/(1-nt)),a),ot=1-s+s*yn*2.2;let gt=Ye*ot;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[Ge]=gt;const Gt=De(Qe);Ee[Gt]+=Math.min(1,Ye),Ce[Gt]+=gt,Ue[Gt]++}for(let Re=0;Re<Ae;Re++)Ue[Re]>0&&(Ee[Re]/=Ue[Re],Ce[Re]/=Ue[Re]);for(let Re=0;Re<_;Re++)for(let Fe=0;Fe<k;Fe++){const Ge=Re*k+Fe,Qe=Math.hypot((Fe+.5-k/2)/(k/2),(Re+.5-_/2)/(_/2)),Ye=De(Qe),nt=Math.abs(1.2-Qe*10)<.001?Ae-1:Ye,yn=Ee[nt]||Ee[Ae-1],ot=Ce[nt]||Ce[Ae-1];let gt=ot>1e-6?Ne[Ge]*(yn/ot):Ne[Ge];const Gt=Math.min(Fe,Re,k-1-Fe,_-1-Re)/k;Gt<m&&(gt*=qn(Gt/m)),gt=Math.min(1,Math.max(0,gt));const Rn=P(gt),Et=Math.round(255*gt);for(let kt=0;kt<B;kt++)for(let on=0;on<I;on++){const Rt=((he+Re*B+kt)*b.w+oe+Fe*I+on)*4;v[Rt]=Rn,v[Rt+1]=Rn,v[Rt+2]=Rn,v[Rt+3]=Et}}S.frames.push({x:oe,y:he,width:e,height:n})}return S}const is={"particle/water/ripple_single":{fw:32,fh:32,cols:7,frames:14,rows:Uw,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:Lw,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:Dw,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:Nw,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=jn(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 Ow=1024,Ql=64,Mn=128;function zw(t){const{gen:e=Mn>>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=jn(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,Ee=Math.max(0,Math.floor(we-Ae)),Ce=Math.min(e-1,Math.ceil(we+Ae)),Ue=Math.max(0,Math.floor(Y-Ae)),Ne=Math.min(e-1,Math.ceil(Y+Ae)),De=1/(oe*oe);for(let Re=Ue;Re<=Ne;Re++)for(let Fe=Ee;Fe<=Ce;Fe++){const Ge=Fe+.5-we,Qe=Re+.5-Y,Ye=(Ge*Ge+Qe*Qe)*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?Mn>>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=zw({gen:r,frames:i,seed:11,...n}),m=Math.max(1,Math.round(Mn/r)),g=Hl(a,o,u),y=Ow,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*Mn,V=_*Mn,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*=qn(he/f));const Ae=t==="light"?Math.min(1,.8*Math.pow(oe,1.25)):.865+.108*oe,Ee=Math.round(255*Ae),Ce=Math.round(255*oe);for(let Ue=0;Ue<m;Ue++)for(let Ne=0;Ne<m;Ne++){const De=((V+U*m+Ue)*y+B+W*m+Ne)*4;w[De]=Ee,w[De+1]=Ee,w[De+2]=Ee,w[De+3]=Ce}}A.frames.push({x:B,y:V,width:Mn,height:Mn})}return A}const na={"particle/halo_6":()=>gw(128),"particle/normal_splash":()=>En(bm(256),3.2),"particle/drop_normal":()=>En($l(128,512),3.4),"particle/normal_ring_smooth":()=>En(zl(256,.55,.12),3.1),"particle/normal_pinch_rotate":()=>En(vw(256),2.8),"particle/water/rain_drops_sheet_normal":()=>En(Em(),3.6),"particle/bubbles/bubble1normal":()=>En(ho(256,1),3.2),"particle/bubbles/bubble2_normal":()=>En(ho(256,2),3.2),"particle/sharp_halo_normal":()=>En(Zs(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),3.4),"particle/beam/beam_0":()=>fo(128,512,.46,!0),"particle/beam/beam_1":()=>yw(32),"particle/beam/beam_2":()=>fo(128,512,.22,!0),"particle/beam/beam_2_fade":()=>fo(128,512,.24,!1),"particle/light/light_shafts_0":()=>yi(0),"particle/light/light_shafts_1":()=>yi(1),"particle/light/light_shafts_2":()=>yi(2),"particle/light/light_shafts_3":()=>yi(3),"particle/light/light_shafts_4":()=>yi(4),"particle/light/light_shafts_5":()=>yi(5),"particle/light/light_shafts_6":()=>yi(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":()=>pw(256,[234,225,201,164,119,75,41,19,8,3,1].map(t=>t/255)),"particle/halo_1":()=>gi(256,{r:.1,w:1},{r:.3,w:.13}),"particle/halo_2":()=>gi(256,{r:.2,w:.9},{r:.44,w:.2}),"particle/halo_3":()=>Zs(256,[{r:.045,w:1},{r:.13,w:.85},{r:.36,w:.15}]),"particle/halo_4":()=>gi(256,{r:.085,w:1},{r:.28,w:.12}),"particle/halo_5":()=>Zs(256,[{r:.04,w:1},{r:.11,w:.8},{r:.34,w:.17}]),"particle/sharp_halo":()=>Zs(256,[{r:.035,w:1},{r:.09,w:.45},{r:.22,w:.08}]),"particle/chromaticdot":()=>Cw(128),"particle/light/flare_0":()=>$r(256,6,.58,10,.08),"particle/light/flare_1":()=>Iw(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":()=>ta(is["particle/water/splash_1"]),"particle/water/ripple_single":()=>ta(is["particle/water/ripple_single"]),"particle/fog/fog1":()=>Fw(),"particle/fog/fog2":()=>ta(is["particle/fog/fog2"]),"particle/fog/fog3":()=>ta(is["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":()=>$r(256,5,.62,8,.1),"particle/bubbles/bubble1":()=>ho(256,1),"particle/bubbles/bubble2":()=>ho(256,2),"particle/bubbles/bubble3":()=>bw(1024,64,58,11776798),"particle/debris/debris1":()=>Am(128),"particle/lightning/lightning1":()=>mo(256,3),"particle/lightning/lightning2":()=>mo(256,11),"particle/lightning/lightning3":()=>mo(256,19),"particle/fire/fire1":()=>ql(256,23),"particle/fire/fire2":()=>ql(256,41),"particle/star":()=>$r(256,4,.58,12,.09),"particle/shape/circle_wind":()=>wm(256),"particle/sickle":()=>xm(256),"particle/magic/glyph_4":()=>Tm(256,4),"@sparkle":()=>$r(256,4,.6,16,.08),"@star":()=>$r(256,5,.62,8,.1),"@trail":()=>Xl(128,256)};function Mm(t){const e=String(t).toLowerCase();if(/normal/.test(e)){const n=_w(t);return n?()=>En(Ew(n),2.8):()=>En(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)?()=>fo(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)?()=>$r(256,5,.62,8,.1):/sparkle|glint|twinkle/.test(e)?()=>$r(256,4,.6,16,.08):/rain_drops_sheet|drops_sheet/.test(e)?()=>Mw(256,512,2,4):/drop|rain/.test(e)?()=>$l(128,512):/debris|dirt|rock/.test(e)?()=>Am(128):/lightning|bolt|arc/.test(e)?()=>mo(256,Gl(e)):/note|music/.test(e)?()=>$r(256,4,.55,8,.12):/trail|streak/.test(e)?()=>Xl(128,256):()=>gi(256,{r:.12,w:1},{r:.3,w:.15})}function Hw(t){if(Pn.has(t))return Pn.get(t);let e=null;const n=Ol.get(t);if(n)try{e=n()}catch{e=null}if(!e&&uo)try{e=uo(t)}catch{e=null}if(!e&&na[t])try{e=na[t]()}catch{e=null}if(!e)try{e=Mm(t)()}catch{e=null}e||(e=gi(256,{r:.12,w:1},{r:.3,w:.15}));for(const r of Vw)if(r.re.test(t)){Ww(e,r.band);break}return Pn.set(t,e),e}const Vw=[{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 Ww(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=qn(c/i),l=(a*n+o)*4+3;s[l]=Math.round(s[l]*u)}return t}function jw(t){return typeof t=="string"&&t.indexOf("particle/")===0}function qw(t,e,n){const r=jn(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 Xw(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=qw(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 $w(t){return t==="util/clouds_256"?(Pn.has(t)||Pn.set(t,Xw(256)),Pn.get(t)):t==="util/black"?(Pn.has(t)||Pn.set(t,{width:1,height:1,rgba:new Uint8Array([0,0,0,255])}),Pn.get(t)):null}const Gw=Object.freeze(Object.defineProperty({__proto__:null,RING_SHEETS:is,bilinearResize:Wl,buildBuiltinParticleTexture:Hw,buildBuiltinUtilTexture:$w,builtinParticleFrames:ww,convertParticleNormalFormat:xw,convertParticleTexFormat:Aw,isBuiltinParticleTextureName:jw,isPackedNormalTexture:kw,listBuiltinParticleTextureNames:mw,particleNormalNameForAlbedo:Pw,prepareParticleNormalTexture:Tw,resetParticleTextureFactories:hw,rgbaLooksLikeAlbedo:vm,ringSheetAtlas:ta,setParticleTextureFactory:fw,setParticleTextureProvider:dw,smokePuffAtlas:Yl},Symbol.toStringTag,{value:"Module"})),Qw=["util/white","util/black","util/noflow","util/flatnormal","util/noise","util/perlin_256","util/uniform_256","util/fur","util/clouds_256"],Yw=new Set(["util/flatnormal","util/fur","util/noflow","util/noise"]);function Kw(t){return Yw.has(t)}function po(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 Zw(t,e,n,r){const i=po((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=Zw(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 go(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 Jw(){const e=po(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 ev(){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 tv(){const e=po(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 nv(){const e=po(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 rv(){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 iv(t){Zl=typeof t=="function"?t:null}function sv(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:go(32,255,255,255,255)};break;case"util/black":e={width:32,height:32,rgba:go(32,0,0,0,255)};break;case"util/noflow":e={width:32,height:32,rgba:go(32,127,127,0,255)};break;case"util/flatnormal":e={width:16,height:16,rgba:go(16,255,127,0,127)};break;case"util/noise":e=Jw();break;case"util/perlin_256":e={width:256,height:256,rgba:ev()};break;case"util/uniform_256":e=tv();break;case"util/fur":e=nv();break;case"util/clouds_256":e=rv();break}return e&&Kl.set(t,e),e}const av=Object.freeze(Object.defineProperty({__proto__:null,SYSTEM_UTIL_TEXTURES:Qw,buildSystemUtilTexture:sv,isNomipSystemTexture:Kw,setSystemTextureProvider:iv},Symbol.toStringTag,{value:"Module"})),yo=64,Jl=2,ov=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 cv(t){ru=typeof t=="function"?t:null}function lv(){return[...Object.keys(eu).map(t=>"gradient/gradient_"+t),...Object.keys(tu).map(t=>"gradient/"+t)]}function uv(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 bo(t){return t<0?0:t>255?255:t}function fv(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 dv(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 hv(t){const e=new Uint8Array(yo*Jl*4);for(let n=0;n<Jl;n++){const r=n*yo;for(let i=0;i<yo;i++){const[s,a,o]=fv(t.stops,i),c=(r+i)*4;e[c]=bo(Math.round(s)),e[c+1]=bo(Math.round(a)),e[c+2]=bo(Math.round(o)),e[c+3]=255}}return{width:yo,height:Jl,rgba:e}}function mv(t){const e=ov,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=dv(t.stops,a);t.invert&&(o=255-o);const c=(i*e+s)*4;n[c]=n[c+1]=n[c+2]=bo(Math.round(o)),n[c+3]=255}return{width:e,height:e,rgba:n}}function pv(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"?mv(e.spec):hv(e.spec);return nu.set(t,r),r}const gv=Object.freeze(Object.defineProperty({__proto__:null,buildBuiltinGradientTexture:pv,isBuiltinGradientTextureName:uv,listBuiltinGradientTextureNames:lv,setGradientTextureProvider:cv},Symbol.toStringTag,{value:"Module"})),Fm=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gr(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 vr(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 wo(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 yv(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=vr(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=wv(t,e),v=b.bones,x=vv(e,b,v.length),P=kv(t,e,v.length),S=Sv(t,e,v),k=bv(t,e,v.length),_=[],I=[],B=[];if(v.length>0){const Y=v.map((he,Ae)=>{const Ee=he.matrix,Ce=Math.hypot(Ee[0],Ee[1]),Ue=Math.hypot(Ee[4],Ee[5]);return B[Ae]=Float32Array.from([Ee[12],Ee[13],Ee[14],0,0,Math.atan2(Ee[1],Ee[0]),Ce||1,Ue||1,Ee[10]||1]),Float32Array.from(Ee)});for(let he=0;he<v.length;he++){const Ae=B[he],Ee=v[he].matrix;Math.hypot(Ae[0]-Ee[12],Ae[1]-Ee[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?Gr(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 Ee=v[Ae].parent;he[Ae]=Ee>=0&&Ee<Ae?Gr(he[Ee],S[Ae]):Float32Array.from(S[Ae])}for(let Ae=0;Ae<v.length;Ae++)I[Ae]=Gr(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:Tv(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 bv(t,e,n){const r=wo(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=vr(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 wv(t,e){const n=wo(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=vr(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?vr(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 vv(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 Av(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=vr(t,i+8);if(!s.value||s.value.length>64)continue;const a=vr(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 xv(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=vr(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 kv(t,e,n){const r=wo(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=vr(e,i);i=l.next;const d=vr(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=xv(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=Av(e,y.next,g);if(w<0)break;i=w}return o}function Tv(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 Sv(t,e,n){if(n.length===0)return null;const r=wo(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 Pv(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 _v(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?_v(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;Pv(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?Gr(t._world[m],t._local[p],t._world[p]):t._world[p].set(t._local[p])}for(let p=0;p<s;p++)Gr(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 Ev(t,e){return Gr(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:Gr(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?Gr(r,n.matrix):null}return null}function Mv(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 Cv(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"&&Mv(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 Iv(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 Rv=128,vo=24;function Bv(t){const e=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS)||256,n=Math.floor((e-32)/4);return Math.max(vo,Math.min(Rv,n))}const Fv=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,
|
|
556
|
+
gl_Position = u_mvp * vec4(local.xy, local.z * u_keepZ, 1.0);
|
|
449
557
|
v_uv = a_uv;
|
|
450
|
-
}`,
|
|
558
|
+
}`,Dv=`#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 ab(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=rb(t),r=null;for(;;){const u=t.createProgram();let l=!1;try{t.attachShader(u,e(t.VERTEX_SHADER,ib(n))),t.attachShader(u,e(t.FRAGMENT_SHADER,sb)),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<=va)throw new Error("MDL \u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25\uFF08\u9AA8\u6570\u5DF2\u964D\u5230 "+va+"\uFF09");n=Math.max(va,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(Nd,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=Oc(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 ob=Object.freeze(Object.defineProperty({__proto__:null,applyAttachmentBindOrigins:eb,attachmentBind:zd,attachmentWorld:Ud,bindWorldOf:Od,computeSkinMatrices:Oc,createMDLRenderer:ab,followAttachments:tb,mat4MulOut:Jy,parentMeshToWorldDelta:Uc,parseMDL:Wy},Symbol.toStringTag,{value:"Module"}));function cb(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 lb=Object.freeze(Object.defineProperty({__proto__:null,createEngineTimers:cb},Symbol.toStringTag,{value:"Module"}));function ub(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 ka(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 fb=32,Hd=60/112,Vd=3.2;function db(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 Wd(t=20260830){const e=ub(t),n=db(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/Hd,v=b*4,k=(Math.floor(v)%16+16)%16,A=v-Math.floor(v),T=Math.exp(-A*Hd*14),S=y%fb,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,U=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(ka(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),Ze=U*(.5+.3*ka(b*.5+r[ne]*.05,ne%8)),je=U*(.5+.3*ka(b*.53+r[ne]*.05+31.7,ne%8+16));let Fe=Ze*(.35+.65*fe),Le=je*(.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 Pt=Fe,Xe=Le;Fe=Math.min(1,Fe*Vd),Le=Math.min(1,Le*Vd);const Dt=.06+fe*.2,Oe=ka(b*.13+ne*.35,11)*Dt;let qe=Math.min(1,Math.max(0,Fe*(1-Oe))),ze=Math.min(1,Math.max(0,Le*(1+Oe)));const st=P?.012:0;s[ne]=Math.max(st,qe),a[ne]=Math.max(st,ze),o[ne]=Math.max(st,Math.max(0,Pt*(1-Oe))),c[ne]=Math.max(st,Math.max(0,Xe*(1+Oe))),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 hb(t,e){for(const n of t.values()){jd(n.left,e.left64),jd(n.right,e.right64);for(let r=0;r<n.average.length;r++)n.average[r]=(n.left[r]+n.right[r])*.5}}function jd(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 Aa="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=",gr={STOPPED:0,PLAYING:1,PAUSED:2};class et{constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new et(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new et(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){if(e!==null&&typeof e=="object")return new et(this.x*e.x,this.y*e.y,this.z*e.z);const n=Number(e)||0;return new et(this.x*n,this.y*n,this.z*n)}divide(e){const n=Number(e)||1;return new et(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 et(this.x,this.y,this.z)}toArray(){return[this.x,this.y,this.z]}}function mb(t,e,n){return new et(t,e,n)}const xa={primary:[.96,.65,.14],secondary:[.08,.11,.18],tertiary:[.66,.74,.88],text:[.96,.97,1]},pb=[{title:"WebWallGL",artist:"oneincase",album:"Scene",albumArtist:"oneincase",duration:212,colors:xa,thumbnail:Aa,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:xa,thumbnail:Aa,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:xa,thumbnail:Aa,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:xa,thumbnail:Aa,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"]]}],Ta=3;function qd(t=20260901){const e=pb,n=e.reduce((w,y)=>w+y.duration+Ta,0),r={hasMedia:!1,state:gr.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,thumbnail:"",primaryColor:new et(0,0,0),secondaryColor:new et(0,0,0),tertiaryColor:new et(0,0,0),textColor:new et(1,1,1),highContrastColor:new et(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+Ta;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<Ta){b=B,v=N,k=!0;break}y-=Ta}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=gr.PAUSED:k?r.state=gr.STOPPED:T>.7&&T<.76?r.state=gr.PAUSED:r.state=gr.PLAYING,r.hasThumbnail=!k,r.thumbnail=k?"":A.thumbnail||"";const S=A.colors;r.primaryColor=new et(S.primary[0],S.primary[1],S.primary[2]),r.secondaryColor=new et(S.secondary[0],S.secondary[1],S.secondary[2]),r.tertiaryColor=new et(S.tertiary[0],S.tertiary[1],S.tertiary[2]),r.textColor=new et(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 et(0,0,0):new et(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=gr.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:gr,skipNext:d,skipPrevious:h,play:m,pause:p,playPause:g}}function gb(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 yb(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 bb(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 wb=Object.freeze(Object.defineProperty({__proto__:null,MEDIA_PLAYBACK:gr,cloneMediaSnapshot:bb,createSimulatedMedia:qd,diffMediaEvents:yb,mediaVec3:mb,renderThumbnail:gb},Symbol.toStringTag,{value:"Module"})),Xd=14,hs=[{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 Gd(){const t={app:"",title:"",url:"",index:-1};function e(n){const r=Number(n)||0,i=hs.length?Math.floor(r/Xd)%hs.length:0,s=hs[i]||hs[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:hs,hold:Xd}}function $d(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 vb(t){const e=qd(t),n=Gd(),r=$d(null);return{media:e,windowTitle:n,shortcuts:r}}const kb=Object.freeze(Object.defineProperty({__proto__:null,createShortcutHandler:$d,createSimulatedSystem:vb,createSimulatedWindowTitle:Gd},Symbol.toStringTag,{value:"Module"}));function Ab(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 xb=Object.freeze(Object.defineProperty({__proto__:null,createPointerSource:Ab},Symbol.toStringTag,{value:"Module"}));function Qd(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=$r(y[0]),v=$r(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 Tb(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=Qd(l,e,n,r,s,a,o);if(f&&Math.abs(f.lx)<=.5&&Math.abs(f.ly)<=.5)return l}return null}const Sb=Object.freeze(Object.defineProperty({__proto__:null,hitTestLayers:Tb,worldToLayerLocal:Qd},Symbol.toStringTag,{value:"Module"})),wt=t=>t,Ye=wt(Rg),Sa=wt(Qg),vt=wt(B0),wn=wt(N0),ft=wt(yy),Pb=wt(wy),_b=wt(Sy),Fr=wt(Vy),ms=wt(ob),Ke=wt(v0),Eb=wt(lb),Se=wt(wb),Yd=wt(kb),ps=wt(ay),Cb=wt(xb),Ib=wt(Sb);function Mb(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 Bb(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 Rb(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 Fb(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 Db(t,e){Jn(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){Lb(t,e);return}const s=e.canvas instanceof HTMLCanvasElement,a=s?e.canvas:document.createElement("canvas"),o=Es(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}Ub(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=ft.createRenderer(a,{diag:U=>ce(t,e,`renderer: ${U}`),fboCapFactor:0});if(t.renderer=g,f)return;const w="__media",y=new Map;let b,v=0,k=0;{let U=!1;if(i&&typeof window.ImageDecoder=="function")try{const q=await Bb(e.src);if(q&&q.frames.length>1){v=q.width,k=q.height;const H=g.gl,G={glTex:ft.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()},U=!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(!U){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:ft.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=Mb(v,k,w),T=performance.now();let S=0,P=0,M=-1/0;const B=U=>{if(f||t.paused)return;const q=t.cfg.sceneFps||60;if(U-M>=1e3/q){M=U,er(t,U),el(t,a,t.cfg),b?.();const H=t.coverAlign;g.render(A,y,a.width,a.height,(U-T-S)/1e3,xr(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 U=t.video;p=!!(U&&!U.paused&&!U.ended),U?.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 Nb(t,e){if(t.wrap)return t.wrap;const n=e.canvas;return n?n instanceof HTMLCanvasElement?n.parentElement:n:null}function Lb(t,e){if(Jn(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=Nb(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=Ha(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=()=>{er(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,er(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",Ob(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(),Rb(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=rl(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=hf();const p=Fb(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&&hf()){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=Cg({src:e.src,container:n,cssText:i,fit:()=>xr(t.cfg.fit),fps:()=>t.cfg.sceneFps||60,paused:()=>!!t.paused,renderDpr:e.renderDpr,onFirstFrame:u,onFrame:()=>er(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 Ob(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 Ub(t,e){Jn(t);const n=document.createElement("img"),r=Ha(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 zb=["scene.pkg","scenes/scene.pkg","gifscene.pkg"],Hb={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 Kd(t){const e=t.toLowerCase().split(";")[0].trim();return e==="image/gif"?"gif":e.startsWith("video/")?"video":e.startsWith("image/")?"image":null}function zc(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:Hb[i.slice(s+1).toLowerCase()]??null}async function Vb(t,e,n){try{const r=await fetch(t,{...e,method:"HEAD",signal:n});return r.ok?Kd(r.headers.get("content-type")||""):null}catch{return null}}function Zd(t,e){const n=t.replace(/\/+$/,"");return{key:n,async scenePkg(r){let i=null,s=null;for(const o of zb){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 Wb(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 jb(t,e,n){return{key:n,scenePkg:async()=>t,project:async()=>e??null}}function qb(t,e){const n=typeof t!="string",r=t;let i=e?.type??(n?Kd(t.type||""):null)??zc(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 Vb(t,void 0,u)),{url:o(),type:i??void 0}},dispose(){a&&(URL.revokeObjectURL(a),a=null)}}}const Jd=!1,eh=!0,th=!1,Xb=!1,Gb=!1,nh=4,gs=64,rh={STOPPED:0};function $b(){return{left64:new Float32Array(gs),right64:new Float32Array(gs),left32:new Float32Array(32),right32:new Float32Array(32),left16:new Float32Array(16),right16:new Float32Array(16),level:0,silent:!0}}function Pa(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 Qb(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<gs;c++){const u=c/gs,l=(c+1)/gs,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)}Pa(t.left32,t.left64),Pa(t.right32,t.right64),Pa(t.left16,t.left64),Pa(t.right16,t.right64),t.level=Math.min(1,o/(48*1.2)),t.silent=t.level<.02}function Yb(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 Hc(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 Kb(t,e){const n=Yb(e||"empty"),[r,i,s]=Hc(n,72,48),[a,o,c]=Hc((n+40)%360,55,28),[u,l,f]=Hc((n+20)%360,70,72);t.primaryColor=Se.mediaVec3(r,i,s),t.secondaryColor=Se.mediaVec3(a,o,c),t.tertiaryColor=Se.mediaVec3(u,l,f),t.textColor=Se.mediaVec3(.98,.98,1),t.highContrastColor=Se.mediaVec3(1,1,1),t.hasThumbnail=!!e}function Zb(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 Jb(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 e1(){return{hasMedia:!1,state:rh.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,primaryColor:Se.mediaVec3(0,0,0),secondaryColor:Se.mediaVec3(0,0,0),tertiaryColor:Se.mediaVec3(0,0,0),textColor:Se.mediaVec3(1,1,1),highContrastColor:Se.mediaVec3(1,1,1),trackIndex:-1,lyrics:[],lyricLine:"",lyricIndex:-1}}async function t1(){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 ih(t){const e=t?.origin??(typeof location<"u"?location.origin:""),n=t?.onArtwork,r=$b(),i=e1(),s={app:"",title:"",url:"",index:0};let a="off",o="offline",c="offline",u="",l=!1,f="";const d=await t1();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=rh.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,Kb(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),Qb(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 n1={"common.h":`// WE common.h\uFF08\u91CD\u5EFA\u5B50\u96C6\uFF0C\u4F9B we-scene \u6D4F\u89C8\u5668\u6E32\u67D3\uFF09
|
|
567
|
+
}`;function Nv(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=Bv(t),r=null;for(;;){const u=t.createProgram();let l=!1;try{t.attachShader(u,e(t.VERTEX_SHADER,Fv(n))),t.attachShader(u,e(t.FRAGMENT_SHADER,Dv)),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<=vo)throw new Error("MDL \u7740\u8272\u5668\u94FE\u63A5\u5931\u8D25\uFF08\u9AA8\u6570\u5DF2\u964D\u5230 "+vo+"\uFF09");n=Math.max(vo,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 Lv=Object.freeze(Object.defineProperty({__proto__:null,applyAttachmentBindOrigins:Cv,attachmentBind:Om,attachmentWorld:Um,bindWorldOf:Lm,computeSkinMatrices:su,createMDLRenderer:Nv,followAttachments:Iv,mat4MulOut:Ev,parentMeshToWorldDelta:au,parseMDL:yv},Symbol.toStringTag,{value:"Module"}));function Uv(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 Ov=Object.freeze(Object.defineProperty({__proto__:null,createEngineTimers:Uv},Symbol.toStringTag,{value:"Module"})),Ao="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=",Qr={STOPPED:0,PLAYING:1,PAUSED:2};class Tt{constructor(e,n,r){this.x=Number(e)||0,this.y=Number(n)||0,this.z=Number(r)||0}add(e){return new Tt(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new Tt(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){if(e!==null&&typeof e=="object")return new Tt(this.x*e.x,this.y*e.y,this.z*e.z);const n=Number(e)||0;return new Tt(this.x*n,this.y*n,this.z*n)}divide(e){const n=Number(e)||1;return new Tt(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 Tt(this.x,this.y,this.z)}toArray(){return[this.x,this.y,this.z]}}function zv(t,e,n){return new Tt(t,e,n)}const xo={primary:[.96,.65,.14],secondary:[.08,.11,.18],tertiary:[.66,.74,.88],text:[.96,.97,1]},Hv=[{title:"WebWallGL",artist:"oneincase",album:"Scene",albumArtist:"oneincase",duration:212,colors:xo,thumbnail:Ao,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:xo,thumbnail:Ao,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:xo,thumbnail:Ao,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:xo,thumbnail:Ao,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"]]}],ko=3;function zm(t=20260901){const e=Hv,n=e.reduce((y,w)=>y+w.duration+ko,0),r={hasMedia:!1,state:Qr.STOPPED,title:"",artist:"",album:"",albumArtist:"",position:0,duration:0,hasThumbnail:!1,thumbnail:"",primaryColor:new Tt(0,0,0),secondaryColor:new Tt(0,0,0),tertiaryColor:new Tt(0,0,0),textColor:new Tt(1,1,1),highContrastColor:new Tt(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+ko;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<ko){A=I,b=B,v=!0;break}w-=ko}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=Qr.PAUSED:v?r.state=Qr.STOPPED:P>.7&&P<.76?r.state=Qr.PAUSED:r.state=Qr.PLAYING,r.hasThumbnail=!v,r.thumbnail=v?"":x.thumbnail||"";const S=x.colors;r.primaryColor=new Tt(S.primary[0],S.primary[1],S.primary[2]),r.secondaryColor=new Tt(S.secondary[0],S.secondary[1],S.secondary[2]),r.tertiaryColor=new Tt(S.tertiary[0],S.tertiary[1],S.tertiary[2]),r.textColor=new Tt(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 Tt(0,0,0):new Tt(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=Qr.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:Qr,skipNext:f,skipPrevious:h,play:m,pause:p,playPause:g}}function Vv(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 Wv(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 jv(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 qv(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 Xv=Object.freeze(Object.defineProperty({__proto__:null,MEDIA_PLAYBACK:Qr,cloneMediaSnapshot:jv,createSimulatedMedia:zm,createWallpaperAudioMedia:qv,diffMediaEvents:Wv,mediaVec3:zv,renderThumbnail:Vv,songTitleFromLayerName:Hm},Symbol.toStringTag,{value:"Module"})),Vm=14,ra=[{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=ra.length?Math.floor(r/Vm)%ra.length:0,s=ra[i]||ra[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:ra,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 $v(t){const e=zm(t),n=Wm(),r=jm(null);return{media:e,windowTitle:n,shortcuts:r}}const Gv=Object.freeze(Object.defineProperty({__proto__:null,createShortcutHandler:jm,createSimulatedSystem:$v,createSimulatedWindowTitle:Wm},Symbol.toStringTag,{value:"Module"}));function Qv(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 Yv=Object.freeze(Object.defineProperty({__proto__:null,createPointerSource:Qv},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=Qo(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 eA(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 Kv(t){const e=Math.cos(t),n=Math.sin(t);return[e,n,0,-n,e,0,0,0,1]}function Zv(t){const e=Math.cos(t),n=Math.sin(t);return[e,0,-n,0,1,0,n,0,e]}function Jv(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 eA(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=Kv(-(l[2]||0));d=Xm(d,Zv(-(l[1]||0))),d=Xm(d,Jv(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 tA(t,e,n,r,i={}){const s=$m(t,e,n,r,i);return s.length?s[0]:null}const nA=Object.freeze(Object.defineProperty({__proto__:null,hitTestLayers:tA,hitTestLayersAll:$m,worldToLayerLocal:qm},Symbol.toStringTag,{value:"Module"}));function rA(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 iA=Object.freeze(Object.defineProperty({__proto__:null,planCursorDispatch:rA},Symbol.toStringTag,{value:"Module"})),_t=t=>t,st=_t(Y1),Gn=_t(gy),zt=_t(Jy),gn=_t(rb),pt=_t(jb),bi=_t(uw),Jt=_t(Gw),To=_t(av),ou=_t(gv),ia=_t(Lv),at=_t(Hy),sA=_t(Ov),We=_t(Xv),Gm=_t(Gv),sa=_t(Bb),aA=_t(Yv),oA=_t(nA),cA=_t(iA);function lA(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 uA(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 fA(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){ye(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 dA(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){ye(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 hA(t,e){Fr(t);const n=g=>{ye(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){pA(t,e),Ru(t);return}const s=e.canvas instanceof HTMLCanvasElement,a=s?e.canvas:document.createElement("canvas"),o=Mi(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(ye(t,e,`media ${e.type}: WEBGL2_UNAVAILABLE`),s){t.onError?.(new Error("WEBGL2_UNAVAILABLE"));return}yA(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=>{ye(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=>ye(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 uA(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,ye(t,e,`media gif ${b}x${v} ${U.frames.length} \u5E27 \u2192 scene \u6E32\u67D3`)}}catch(U){ye(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}),ye(t,e,`media ${e.type} ${b}x${v} \u2192 scene \u6E32\u67D3`)}}if(d)return;const x=lA(b,v,y),P=performance.now();let S=0,k=0;const _=new Ci(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)){Dr(t,O),Du(t,a,t.cfg),A?.();const W=t.coverAlign;g.render(x,w,a.width,a.height,(O-P-S)/1e3,Br(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 mA(t,e){if(t.wrap)return t.wrap;const n=e.canvas;return n?n instanceof HTMLCanvasElement?n.parentElement:n:null}function pA(t,e){if(Fr(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=mA(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";ye(t,e,`media video \u5931\u8D25: ${f}`),t.onError?.(new Error(`\u5A92\u4F53\u58C1\u7EB8\uFF08video\uFF09${f}`));return}const r=Yo(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`;ye(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=()=>{Dr(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,Dr(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",gA(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(),fA(t,e,f),l(()=>f),ye(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=>ye(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=()=>ye(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=dA(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(),ye(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,ye(t,e,`media video: ${m}\uFF0C\u56DE\u9000 A/B <video>`),d(),g||(t.webcodecsPreferred=!1))};h=X1({src:e.src,container:n,cssText:i,fit:()=>Br(t.cfg.fit),fps:()=>t.cfg.sceneFps||60,paused:()=>!!t.paused,renderDpr:e.renderDpr,onFirstFrame:u,onFrame:()=>Dr(t,performance.now()),onDiag:m=>ye(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,ye(t,e,"media video \u2192 WebCodecs \u9010\u5E27\u8C03\u5EA6\uFF08\u9759\u97F3\u5FAA\u73AF\uFF09");return}d()}function gA(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 yA(t,e){Fr(t);const n=document.createElement("img"),r=Yo(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 bA=["scene.pkg","scenes/scene.pkg","gifscene.pkg"],wA={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:wA[i.slice(s+1).toLowerCase()]??null}async function vA(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 bA){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 AA(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 xA(t,e,n){return{key:n,scenePkg:async()=>t,project:async()=>e??null}}function kA(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 vA(t,void 0,u)),{url:o(),type:i??void 0}},dispose(){a&&(URL.revokeObjectURL(a),a=null)}}}const Km=!1,Zm=!0,Jm=!1,TA=!1,SA=!1,ep=4,uu={antiAliasing:"off",particles:"high",postProcessing:"high"},PA={low:.4,medium:.7,high:1},_A={low:.5,medium:1,high:0},EA=["off","fxaa","msaa2","msaa4"],MA=["off","low","medium","high"],CA=["off","low","medium","high"];function fu(t,e,n){return typeof t=="string"&&e.includes(t)?t:n}function aa(t){const e=t??{};return{antiAliasing:fu(e.antiAliasing,EA,uu.antiAliasing),particles:fu(e.particles,MA,uu.particles),postProcessing:fu(e.postProcessing,CA,uu.postProcessing)}}function IA(t){return t==="off"?0:PA[t]}function RA(t){return t==="off"?0:_A[t]}const oa=64,tp={STOPPED:0};function BA(){return{left64:new Float32Array(oa),right64:new Float32Array(oa),left32:new Float32Array(32),right32:new Float32Array(32),left16:new Float32Array(16),right16:new Float32Array(16),level:0,silent:!0}}function So(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 FA(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<oa;c++){const u=c/oa,l=(c+1)/oa,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)}So(t.left32,t.left64),So(t.right32,t.right64),So(t.left16,t.left64),So(t.right16,t.right64),t.level=Math.min(1,o/(48*1.2)),t.silent=t.level<.02}function DA(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 NA(t,e){const n=DA(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 LA(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 UA(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 OA(){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 zA(){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=BA(),i=OA(),s={app:"",title:"",url:"",index:0};let a="off",o="offline",c="offline",u="",l=!1,d="";const f=await zA();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,NA(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),FA(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 HA=2048,Po=64;function VA(){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=HA,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(Po),y=i.length*.72,w=2;for(let A=0;A<Po;A++){const b=w+Math.floor(y*(A/Po)**2),v=Math.max(b+1,w+Math.floor(y*((A+1)/Po)**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 WA(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)}_o(t.left64,t.left32),_o(t.right64,t.right32),_o(t.left64,t.left16),_o(t.right64,t.right16)}function _o(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 Ar=new Map;let Cn=null,rp=!1,ca=null,hu=null;const mu=new Map,Eo="/api/local-assets";function jA(){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{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ri&&ri.tagName.toUpperCase()==="SCRIPT"&&ri.src||new URL("webwallgl.global.js",document.baseURI).href}<"u"&&!1?"lazy":"off"}async function qA(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!==Gn.FIF?.JPEG&&t.fif!==Gn.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 XA(t){const e=await fetch(t,{cache:"force-cache"});if(!e.ok)return null;const n=new Uint8Array(await e.arrayBuffer()),r=Gn.parseTex(n),i=Gn.decodeMips(r);if(!i.length)return null;const s=await qA(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 $A(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=Ar.get(t);if(e)return e;if(!Cn||!Cn.names.has(t))return null;const n=mu.get(t);if(n)return n;const r=`${Eo}/${encodeURIComponent(Cn.id)}/materials/${t.split("/").map(encodeURIComponent).join("/")}.tex`,i=(async()=>{try{const s=await XA(r);return s&&Ar.set(t,s),s}catch{return null}finally{mu.delete(t)}})();return mu.set(t,i),i}async function GA(){const t=jA();if(t==="off")return null;if(rp)return hu;if(ca)return ca;ca=(async()=>{const e=typeof performance<"u"?performance.now():Date.now();try{const u=await fetch(Eo,{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(`${Eo}/${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;Cn={id:d.id,names:new Set(h.names)}}catch{return null}To.setSystemTextureProvider(u=>Ar.get(u)??null),Jt.setParticleTextureProvider(u=>Ar.get(u)??null),ou.setGradientTextureProvider(u=>Ar.get(u)??null);const n=[...Cn.names].filter(u=>u.startsWith("util/")),r=t==="all"?[...Cn.names]:n;let i=0;await $A(r,8,async u=>{await ip(u)||i++}),rp=!0;let s=0,a=0,o=0;for(const[u,l]of Ar)o+=l.rgba.byteLength,u.startsWith("util/")?s++:u.startsWith("particle/")&&a++;const c={source:Cn.id,available:Cn.names.size,requested:r.length,loaded:Ar.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 ca}finally{ca=null}}async function sp(t){if(typeof t!="string"||!t)return!1;if(Ar.has(t))return!0;if(!Cn)return!1;const e=await ip(t);if(!e)return!1;const n=hu;return n&&(n.loaded=Ar.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 QA(t){if(!Cn||!t||t.includes(".."))return null;const e=ap.get(t);if(e)return e;try{const n=`${Eo}/${encodeURIComponent(Cn.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 YA={"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":`${
|
|
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 r1(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 i1(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 s1(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=i1(e?s1(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 o1={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"},_a=new Map,vi=Ke.foldVisibleReturn;function c1(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 l1(t){for(const e of t){const n=_a.get(e);if(n&&(n.refs--,!(n.refs>0))){_a.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,u1=512*1024*1024;let Ea=0;function f1(t){for(;qn.size>0&&(qn.size>2||Ea>u1);){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);Ea-=r.parsed.fileSize||0,qn.delete(e)}}function d1(t){if(!t)return;const e=qn.get(t);e&&(Ea-=e.parsed.fileSize||0,qn.delete(t))}async function h1(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()}),Ea+=o.fileSize||0,f1(i)),o}function m1(t,e){Jn(t);const n=(e.canvas instanceof HTMLCanvasElement?e.canvas:null)??document.createElement("canvas"),r=Es(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??Zd(`${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 h1(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=vt.parseScene(JSON.parse(Ot(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=T0(b.properties||{});t.liveUserProps=v;const k=()=>vt.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=[];eh&&(b.layers=b.layers.filter(C=>!(eh&&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=_?Ot(_):n1[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=ft.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=Wd(),B=Se.createSimulatedMedia(),N=Yd.createSimulatedWindowTitle();let U=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},Ze=(()=>{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}}})(),je=()=>Ze.active?Ze.snapshot:H.current?H.current.snapshot:M.snapshot;S.setAudioProvider(()=>ne.enabled?je():Ne);const Fe=new Map,Le=new Map,Pt=[],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 Dt=Yd.createShortcutHandler(C=>{ce(t,e,`openUserShortcut: ${C}`)}),Oe={enabled:!t.mediaDisabled,override:null},qe=[];let ze=null,st;q.lastSnap={get:()=>ze,setHasThumbnail:C=>{ze&&(ze.hasThumbnail=C)}};const ve=()=>Y().snapshot,vn=C=>{if(!(!C||!C.hasMediaHook||qe.includes(C))&&(qe.push(C),!!ve().hasMedia))for(const{name:W,event:x}of Se.diffMediaEvents(null,ve()))try{C.callMedia(W,x)}catch{}};window.__mediaStats=()=>({enabled:Oe.enabled,live:!!U,hooks:qe.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=Se.diffMediaEvents(ze,ve());for(const{name:x,event:_}of W)for(const V of qe)V.callMedia(x,_);return ze=Se.cloneMediaSnapshot(ve()),window.__mediaStats()};const ki=()=>{const C=Se.diffMediaEvents(ze,ve());for(const{name:W,event:x}of C)for(const _ of qe)try{_.callMedia(W,x)}catch{}ze=Se.cloneMediaSnapshot(ve())},an=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 ki(),ve()},_t={get snapshot(){return ve()},skipNext:()=>an("skipNext"),skipPrevious:()=>an("skipPrevious"),play:()=>an("play"),pause:()=>an("pause"),playPause:()=>an("playPause")};t.mediaCtl=_t,window.__mediaControl=_t,window.__system={media:_t,windowTitle:J.snapshot,shortcuts:Dt.last,live:null},window.__liveSystem=()=>({audio:"off",media:"offline",window:"offline"});const dt=Cb.createPointerSource(e.canvas?{target:e.canvas,viewport:()=>({w:e.canvas.clientWidth||window.innerWidth||1,h:e.canvas.clientHeight||window.innerHeight||1})}:{});S.setPointerProvider(()=>dt),t.pointerCtl={push:C=>dt.pushExternal(C),leave:()=>dt.pushExternalLeave()};{const C=u;u=()=>{C?.(),dt.dispose()}}const At=Ke.createInputView(),yr=Eb.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)}`))}})()}),Gn={setTimeout:yr.setTimeout,clearTimeout:yr.clearTimeout,setInterval:yr.setInterval,clearInterval:yr.clearInterval};{const C=u;u=()=>{C?.(),yr.dispose()}}window.__pointerStats=()=>{const C=dt.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(dt.normalizedDelta()),counts:{move:C.moveCount,down:C.downCount,up:C.upCount}}};const Te=new Map;Te.set("util/white",{glTex:ft.makeTexture(S.gl,new Uint8Array([255,255,255,255]),1,1),width:1,height:1,rg88:!1}),Te.set("util/noflow",{glTex:ft.makeTexture(S.gl,new Uint8Array([127,127,127,255]),1,1),width:1,height:1,rg88:!1}),Te.set("util/noise",{glTex:ft.makeTexture(S.gl,Pb.generateNoiseTexture(),256,256),width:256,height:256,rg88:!1,mips:null});{const C=x=>{const _=Se.renderThumbnail(x,512);return{glTex:ft.makeTextureMip(S.gl,[_],!1),width:_.width,height:_.height,rg88:!1,mips:[_],generated:!0}},W=B.tracks||[];W.length&&(Te.set("$mediaThumbnail",C(W[0])),Te.set("$mediaPreviousThumbnail",C(W[W.length-1])))}const ys=(C,W,x)=>{const _=Jb(C,W,x,512),V=Zb(C,W,x),F=S.gl,j=Te.get("$mediaThumbnail"),X=!!j?.generated;j&&!X&&Te.set("$mediaPreviousThumbnail",j);const K=Te.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):Te.set("$mediaThumbnail",{glTex:ft.makeTextureMip(F,[_],!1),width:_.width,height:_.height,rg88:!1,mips:[_],generated:!1}),X){const D=Te.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=ys(F,F.width,F.height);F.close?.();const X=Y().snapshot;j&&(X.primaryColor=Se.mediaVec3(...j.primary),X.secondaryColor=Se.mediaVec3(...j.secondary),X.tertiaryColor=Se.mediaVec3(...j.tertiary),X.textColor=Se.mediaVec3(.98,.98,1),X.highContrastColor=Se.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(U=await ih({origin:location.origin,onArtwork:x=>{W(x)}}),C.dead){try{U.dispose()}catch{}U=null}else{if(C.handle=U,G=U.media,J=U.windowTitle,q.mediaDriver=U.media,U.status().audio==="mic"&&(H.current=U.audio),Y().snapshot.hasMedia){for(const{name:_,event:V}of Se.diffMediaEvents(null,Y().snapshot))for(const F of qe)try{F.callMedia(_,V)}catch{}ze=Se.cloneMediaSnapshot(Y().snapshot)}const x=U.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:_t,windowTitle:J.snapshot,shortcuts:Dt.last,live:()=>U.status()},window.__liveSystem=()=>U.status()}}catch(W){ce(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u56DE\u9000\u6A21\u62DF\u6E90 (${W instanceof Error?W.message:W})`),U=null}}{const C=u;u=()=>{C?.(),U?.dispose(),U=null}}const on=new Map,br=async C=>{if(Te.has(C))return Te.get(C);const W=Ye.getEntry(m,`materials/${C}.tex`);if(!W){if(Fr.isBuiltinParticleTextureName(C)){const j=Fr.buildBuiltinParticleTexture(C);if(j){const X={glTex:ft.makeTextureMip(S.gl,[j],!1),width:j.width,height:j.height,rg88:!1,mips:[j],generated:!0};return Te.set(C,X),X}}return null}const x=Sa.parseTex(W),_=Sa.decodeMip0(x),V=x.format===8;let F=null;if(_.video!==void 0){const j=URL.createObjectURL(new Blob([_.video],{type:"video/mp4"})),X=rl(j,{muted:!0,renderDpr:Es(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 O of K)I.addEventListener("ended",O)},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:ft.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)`)},Te.set(C,L),L}else if(_.png!==void 0||_.image!==void 0&&_.fif===Sa.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:ft.makeTexture(S.gl,null,0,0,X),width:X.width,height:X.height,rg88:V}}else{if(_.image!==void 0)return null;{const j=Sa.decodeMip0(x);F={glTex:ft.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 Te.set(C,F),F},cn=C=>{if(Te.has(C))return Promise.resolve(Te.get(C));const W=on.get(C);if(W)return W;const x=br(C);return on.set(C,x),x.finally(()=>{on.get(C)===x&&on.delete(C)}),x},Ai=/uniform\s+sampler2D\s+g_Texture\d+\s*;\s*\/\/[^\n]*"default"\s*:\s*"([^"]+)"/g,Ia=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=Ot(_);Ai.lastIndex=0;let F;for(;(F=Ai.exec(V))!==null;){const j=F[1];!j||j.startsWith("util/")||j.startsWith("_rt_")||Te.has(j)||await cn(j)}}};let Ma=0;const $n=[];for(let C=0;C<b.layers.length;C++){const W=b.layers[C];if(W.image)try{let x;if(wn.BUILTIN_MODELS[W.image])x=wn.BUILTIN_MODELS[W.image];else{const L=Ye.getEntry(m,W.image);if(!L)continue;x=JSON.parse(Ot(L))}vt.applySolidFromModel(W,x);const _=W.srcObject?.instance?.usertextures,V=_?.[0]&&typeof _[0].name=="string"&&_[0].name.startsWith("$")?_[0].name:null,F=V&&Te.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=vt.resolveMaterial(x);if(!j)continue;let X;if(wn.BUILTIN_MATERIALS[j.materialPath])X=wn.BUILTIN_MATERIALS[j.materialPath];else{const L=Ye.getEntry(m,j.materialPath);if(L)X=JSON.parse(Ot(L));else if(W.solid&&wn.BUILTIN_MATERIALS["materials/util/solidlayer.json"])X=wn.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_")||$n.push(cn(E).then(I=>{I&&L===0&&!F&&(W.textureName=E,Ma++,I.videoCtl&&(W.videoCtl=I.videoCtl))}))}K?.shader&&Ye.getEntry(m,`shaders/${K.shader}.frag`)&&wn.attachLayerMaterialEffect(W,K);for(const L of W.effects||[])wn.resolveEffectChain(m,L,Ot);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_")&&$n.push(cn(I));$n.push(Ia(L))}}catch(x){console.warn(`\u56FE\u5C42 ${W.name||C} \u52A0\u8F7D\u5931\u8D25: ${x.message}`)}}if(!th){for(const C of b.layers)if(!(!C.isText||!(C.effects||[]).length))try{for(const W of C.effects||[])wn.resolveEffectChain(m,W,Ot);for(const W of C.effects||[])for(const x of W.passes||[])for(const _ of x.textures||[])typeof _=="string"&&_!==""&&!_.startsWith("util/")&&!_.startsWith("_rt_")&&$n.push(cn(_))}catch(W){console.warn(`\u6587\u5B57\u5C42\u6548\u679C ${C.name} \u89E3\u6790\u5931\u8D25: ${W.message}`)}}await Promise.all($n);for(const[C,W]of Te){if(!W?.videoCtl)continue;b.layers.some(_=>_.textureName===C&&_.visible&&!_.destroyed)&&!t.paused&&W.videoCtl.play()}const Et=[],bs=[],kn=new Map;let Be=0;const xi=async C=>{const W=await cn(C);if(W)return W;const x=Fr.buildBuiltinParticleTexture(C);if(!x)return null;const _={glTex:ft.makeTextureMip(S.gl,[x],!1),width:x.width,height:x.height,rg88:!1,mips:[x],generated:!0,frames:Fr.builtinParticleFrames(C)??void 0};return Te.set(C,_),Be++,_},Ba=C=>{if(!C)return null;const W=C.mips&&C.mips[0];if(W?.rgba&&typeof Fr.prepareParticleNormalTexture=="function"){const x=Fr.prepareParticleNormalTexture(W);if(x&&x!==W)return{glTex:ft.makeTextureMip(S.gl,[x],!1),width:x.width,height:x.height,rg88:!1,mips:[x],generated:!0}}return C},ws=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(Ot(V)),j=new _b.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(Ot(E));j.setMaterial(I);const O=I?.passes?.[0]?.textures||[];X=O[0]||null,K=O[1]||null}}const D=await xi(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?Fr.particleNormalNameForAlbedo(X||"particle/halo"):null);if(z){const E=Ba(await xi(z));E&&j.setNormalTexture({glTex:E.glTex,width:E.width,height:E.height})}j.setVisible(!!W.visible),Et.push(j);const L=W.id;if(L!==void 0){let E=kn.get(L);E||(E=[],kn.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),O=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)*(O[0]||1),(W.scale?.[1]??1)*(O[1]||1),(W.scale?.[2]??1)*(O[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 ws(E.name,se,E.instanceoverride||x,_+1);te&&$&&te.attachFollow(j,$,[I[0]||0,I[1]||0,I[2]||0])}return j};if(!Xb){for(const C of b.layers)if(C.particle)try{await ws(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(Et.length>0){const C=u;u=()=>{C?.();for(const W of Et)W.dispose()}}const Ti=[];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(()=>{}),Ti.push(X);break}}catch(W){console.warn(`\u58F0\u97F3\u56FE\u5C42 ${C.name} \u52A0\u8F7D\u5931\u8D25: ${W.message}`)}const qc=C=>{for(const W of Ti)W.volume=Math.max(0,Math.min(1,C)),W.muted=C<=0};if(t.sceneAudio={setVolume:qc,audios:Ti},a)return;const Si={dt:1/60,t:0};let Nr=0;S.setParticleRenderer(()=>{const C=Math.min(.05,Math.max(0,Si.dt));if(dt.state.has){const{wx:W,wy:x,originY:_}=dt.state,V=_??x;for(const F of Et)F.setPointer(W,V)}if(bs.length)for(const W of bs)W.syncLayerTransform();for(const W of Et)W.layer&&W.layer.runtimeCreated&&W.syncLayerTransform();for(const W of Et)W.advance(C,ne.enabled?je():null);if(Nr<2&&(Nr++,Nr===2)){const W=Et.reduce((x,_)=>x+_.liveCount(),0);ce(t,e,`particles live: ${W} across ${Et.length} systems`)}},(C,W,x,_,V)=>{if(C===void 0)return;const F=kn.get(C);if(F)for(const j of F)j.render(x,_,V,W.projW,W.projH)}),ce(t,e,`particles: ${Et.length} systems, ${Be} builtin tex generated`),window.__particleStats=()=>({t:Si.t,systems:Et.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<Et.length;x++)Et[x].setVisible(W===void 0?C:x===W);return Et.length};const An=[],Ra=new Map,vs=new Map,Lr=C=>{if(!C||!C.puppet)return null;let W=vs.get(C);return W||(W=new Map,vs.set(C,W)),W};for(const C of b.layers)if(C.image)try{if(wn.BUILTIN_MODELS[C.image])continue;const W=Ye.getEntry(m,C.image);if(!W)continue;const x=JSON.parse(Ot(W));if(!x.puppet)continue;const _=Ye.getEntry(m,x.puppet);if(!_)continue;const V=ms.parseMDL(new Uint8Array(_)),F=C.textureName?Te.get(C.textureName):null;if(!F){ce(t,e,`puppet '${C.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}C.puppet=V,An.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=ms.parseMDL(new Uint8Array(W));let _=null;if(x.materialPath){const F=Ye.getEntry(m,x.materialPath);if(F){const X=JSON.parse(Ot(F))?.passes?.[0]?.textures?.[0];typeof X=="string"&&X&&(_=X)}}_&&(await cn(_),C.textureName=_);const V=_?Te.get(_):null;if(!V){ce(t,e,`model '${C.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}C.puppet=x,An.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 Or=null;if(An.length>0)try{Or=ms.createMDLRenderer(S.gl);for(const W of An)Or.upload(W.mdl);const C=new Map;for(const W of An)C.set(W.layer,W);S.setPuppetRenderer((W,x,_)=>{const V=C.get(W);V&&Or.draw(x,V.mdl,{time:_.time,animLayers:W.animationLayers,boneOverrides:vs.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}`),Or=null;for(const W of An)W.layer.puppet=null}if(a)return;ce(t,e,`puppet: ${An.length} meshes`);const wr=ms.applyAttachmentBindOrigins(b.layers);wr.length&&ce(t,e,`attachments: ${wr.length} hanging layers`);const Qn=vt.collectTransformDirty(b.layers,wr.map(C=>C.layer));if(Qn.size){ce(t,e,`transform graph: ${Qn.size} live layers`);for(const[C,W]of kn)if(Qn.has(C))for(const x of W)bs.push(x)}const Ct=[],Qt=[],De=new Map,Yt={};let ln=null,xn=null,Tn=0;if(!th&&b.layers.some(C=>C.isText)){const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=Ua(xr(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=_a.get(L);if(E){E.refs++,j.push(L),F.set(z,E.family);continue}const I=o1[z.toLowerCase()];if(I){F.set(z,I);continue}try{const O=Ye.getEntry(m,z);if(!O)continue;const Q=r1(O instanceof Uint8Array?O:new Uint8Array(O)),$="wefont_"+c1(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,$),_a.set(L,{family:$,refs:1}),j.push(L)}catch(O){console.warn(`\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25 ${z}: ${O.message}`)}}if(j.length){const z=t.sceneCleanup;t.sceneCleanup=()=>{l1(j),z?.()}}ln=document.createElement("canvas"),xn=ln.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:Yt,audioViews:Fe,inputView:At,...Gn,mediaControl:_t,windowTitle:J.snapshot,openUserShortcut:Dt.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&&vn(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=nh*Math.max(1,z.textPointsize),I=Ke.textLayerHasTintMask(z)?8:256,O=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=O,z.size=[L.boxW+O*2,L.boxH+O*2],L.entry={glTex:ft.makeTexture(S.gl,new Uint8Array([0,0,0,0]),1,1),width:1,height:1,rg88:!1},Te.set(L.texName,L.entry),z.textureName=L.texName,z.solid=!1,Ct.push(L)}catch(L){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${z.name} \u521D\u59CB\u5316\u5931\u8D25: ${L.message}`)}if(Ct.length>0){const z=u;u=()=>{z?.();for(const L of Ct)S.gl.deleteTexture(L.entry.glTex)}}const D=z=>{if(!xn||!ln)return;const L=xn;for(const E of Ct){const I=E.layer;let O=String(I.text??"");if(E.sandbox&&E.sandbox.hasUpdate){E.sandbox.engine.runtime=z;const se=E.sandbox.callUpdate(O);se!=null?O=String(se):E.sandbox.thisLayer.text&&(O=String(E.sandbox.thisLayer.text))}else E.sandbox&&typeof E.sandbox.thisLayer?.text=="string"&&(O=String(E.sandbox.thisLayer.text));if(De.set(I.name||"",O),!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=`${O}\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=nh*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(""),tt=(ge.fontBoundingBoxAscent||0)+(ge.fontBoundingBoxDescent||0),Re=I.textSpacing||[0,0],jt=Ke.layoutText(O,{boxW:te,boxH:ee,pointsize:se,lineHeight:(tt>0?tt: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},He=>L.measureText(He).width),Zt=E.margin;if(Ke.shouldGrowMediaPlaceholder(te,ee,!!E.sandbox?.hasMediaHook)){const He=Ke.textCanvasMarginGrow(jt,te,ee,Zt);I.size[0]=te+He*2,I.size[1]=ee+He*2}let at=Math.max(1,Math.round(I.size[0]*ue*E.quality)),xt=Math.max(1,Math.round(I.size[1]*we*E.quality));const _n=Math.min(1,K/Math.max(at,xt));at=Math.max(1,Math.round(at*_n)),xt=Math.max(1,Math.round(xt*_n)),ln.width!==at||ln.height!==xt?(ln.width=at,ln.height=xt):L.clearRect(0,0,at,xt);const be=`${se}px "${ke}", sans-serif`,Pe=Math.min(at/I.size[0],xt/I.size[1]);L.setTransform(Pe,0,0,Pe,0,0),L.translate(Zt,Zt),Ke.drawTextLayer(L,jt,{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,ln),ye.width=at,ye.height=xt}catch(se){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${I.name} \u7ED8\u5236\u5931\u8D25: ${se.message}`),E.lastKey=null}}}};t.sceneTextUpdate=D,window.__textWidgets=Ct,ce(t,e,`text widgets: ${Ct.length} (scripts ${Ct.filter(z=>z.sandbox).length}, fonts ${F.size}, quality ${V.toFixed(2)})`)}if(a)return;const Nt=[],Yn=[],Kt=[],Ur=[],Sn={},zr=[],Pi=[],Hr=new Map,ks=(C,W)=>{if(!W||typeof W.callCursor!="function"||!W.hasCursorHook)return;const x=Hr.get(C);x?x.push(W):Hr.set(C,[W])};for(const C of Ct)C.sandbox&&ks(C.layer,C.sandbox);{const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=v,V=(E,I)=>{const O=b.general||{};if(E==="zoom"&&typeof I=="number"&&Number.isFinite(I)&&I>0){b.cameraTransforms.zoom=I,O.zoom&&typeof O.zoom=="object"?O.zoom.value=I:O.zoom=I;return}O[E]&&typeof O[E]=="object"&&"value"in O[E]?O[E].value=I:O[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(Sn[E])return Sn[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(O=>O.name===I)||null},createSceneLayer:E=>{let I=E&&typeof E=="object"?E:null,O=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,$))O={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,$))O={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,O&&O.kind==="model"){const $=O.path;try{const Z=JSON.parse(Ot(Ye.getEntry(m,$))),se=vt.resolveMaterial(Z),te=se&&Ye.getEntry(m,se.materialPath),ue=(te?JSON.parse(Ot(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_")&&cn(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(O&&O.kind==="particle"){const $=O.path;ws($,Q,null,0).then(Z=>{Z||ce(t,e,`createLayer('${$}') \u7C92\u5B50\u7CFB\u7EDF\u88C5\u914D\u5931\u8D25`)})}return Q},mediaControl:_t,windowTitle:J.snapshot,openUserShortcut:Dt.openUserShortcut,isScreensaver:!1};S.setConstantScriptRuntime?.(Ke.evalObjectScript,{userProperties:_,audioViews:Fe,shared:Yt,inputView:At,timers:yr,animEventQueue:Pt,...j,onSandbox:(E,I)=>{E&&E.hasMediaHook&&vn(E),E&&E.hasAnimEventHook&&Xe(I&&I.layer,{sandbox:E,kind:"const"})}});const X={origin:"localOrigin",scale:"localScale",angles:"localAngles"},K=(E,I)=>{const O=X[I];return O&&E&&Array.isArray(E[O])?O:I};for(const E of b.layers){const I=E.objectAnimations;if(I){E.animations=E.animations||{},E.animationList=E.animationList||[];for(const[O,Q]of Object.entries(I))try{const $=ps.createAnimation(Q.animation);$.field=O,$.baseValue=Q.value;const Z=K(E,O),se=O==="volume"?E.soundprops?.volume:O==="maxwidth"?E.textMaxwidth:O==="zoom"?b.cameraTransforms?.zoom:E[Z];$.baseNumeric=Array.isArray(se)?se.slice():se,$.slot=Z,E.animationList.push($),$.name&&(E.animations[$.name]=$),Yn.push({layer:E,field:O,slot:Z,ctrl:$})}catch($){ce(t,e,`animation '${E.name}.${O}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String($.message).slice(0,80)}`)}if(E.animationList.length){const O=new Map;for(const Q of E.animationList)O.set(Q.field,Q);ps.linkAnimations(O,Q=>ce(t,e,`${E.name}: ${Q}`)),E.animationsByField=Object.fromEntries(O)}}}for(const E of b.layers){const I=E.particleOverrideAnimations;if(I)for(const[O,Q]of Object.entries(I))try{const $=ps.createAnimation(Q.animation);$.baseNumeric=typeof Q.value=="number"?Q.value:Number(Q.value)||0,Kt.push({layer:E,key:O,ctrl:$})}catch($){ce(t,e,`override animation '${E.name}.${O}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String($.message).slice(0,80)}`)}}let D=!1;for(const E of b.layers){for(const[O,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:At,...Gn,layer:E,targetEffect:Q,...j,shared:Yt,onError:ue=>ce(t,e,`effect visible script '${E.name}#${O}' \u5931\u8D25: ${String(ue.message||ue).slice(0,80)}`)});if(!Z)continue;A.push(Z);const se=Z.init(Q.visible),te=vi(se);te!==void 0&&(Q.visible=te),Z.applyUserProperties(_),Z.hasMediaHook&&vn(Z);let ee=null;Z.hasUpdate&&(ee={effect:Q,sandbox:Z,last:se},zr.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}#${O} \u6C42\u503C\u5931\u8D25: ${Z.message}`)}}const I=E.objectScripts;if(I)for(const[O,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:At,layer:E,getAnimationForProperty:()=>E.animationsByField&&E.animationsByField[O]||null,...j,getBoneOverrides:Lr,shared:Yt,...Gn,onError:Z=>ce(t,e,`object script '${E.name}.${O}' \u5931\u8D25: ${String(Z.message||Z).slice(0,90)}`)});if($){A.push($);const Z=K(E,O),se=E[Z],te=O==="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(O==="visible"){const ue=vi(ee);ue!==void 0&&E.visibleSelf!==ue&&(E.visibleSelf=ue,D=!0)}else if(typeof ee=="number"&&Number.isFinite(ee))(O==="alpha"||O==="brightness")&&(E[O]=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]=O==="angles"?Ke.scriptAnglesToRad(ue):[Number(ue.x)||0,Number(ue.y)||0,Number(ue.z)||0])}}$.applyUserProperties(_),ks(E,$),$.hasMediaHook&&vn($),$.hasUpdate&&Nt.push({layer:E,field:O,slot:Z,kind:O==="visible"?"bool":O==="alpha"||O==="brightness"?"scalar":"vec3",sandbox:$,last:O==="visible"?ee:void 0}),$.hasAnimEventHook&&Xe(E,{sandbox:$,kind:O==="visible"?"bool":O==="alpha"||O==="brightness"?"scalar":"vec3",field:O,slot:Z})}}catch($){console.warn(`\u5BF9\u8C61\u811A\u672C ${E.name}.${O} \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 O=Ke.evalObjectScript(I.script,I.scriptproperties,{canvasSize:{width:W,height:x},userProperties:_,audioViews:Fe,inputView:At,...Gn,...j,shared:Yt,onError:$=>ce(t,e,`general script '${E}' \u5931\u8D25: ${String($.message||$).slice(0,80)}`)});if(!O)continue;A.push(O),O.init(I.value),O.applyUserProperties(_),O.hasMediaHook&&vn(O);const Q=$=>V(E,$);O.hasUpdate&&Pi.push({field:E,sandbox:O,write:Q})}catch(O){console.warn(`general \u811A\u672C ${E} \u6C42\u503C\u5931\u8D25: ${O.message}`)}Pi.length&&ce(t,e,`general scripts: ${Pi.map(E=>E.field).join(",")}`)}const L=b.generalAnimations;if(L){for(const[E,I]of Object.entries(L))try{const O=ps.createAnimation(I.animation);O.field=E,O.baseValue=I.value,O.baseNumeric=I.value,O.name&&(Sn[O.name]=O),Ur.push({field:E,ctrl:O,write:Q=>V(E,Q)})}catch(O){ce(t,e,`general animation '${E}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(O.message).slice(0,80)}`)}Ur.length&&ce(t,e,`general animations: ${Ur.map(E=>E.field).join(",")}`)}}Nt.length&&(ce(t,e,`object scripts: ${Nt.length}`),window.__objScripts=Nt,window.__effectScripts=zr),window.__mediaHooks=qe,window.__sceneLayers=b.layers,window.__compositeStats=()=>S.compositeStats?.()??null,window.__compositeEnable=C=>S.setCompositeEnabled?.(C),window.__scene=b,window.__textures=Te;const Vr=Array.from(Hr.keys());Vr.length&&ce(t,e,`cursor hooks: ${Vr.length} layers`);let Wr=null,un=null,jr=!1;const ht=()=>({worldPosition:Ke.makeCursorEventVec(dt.state.wx,dt.state.originY!=null?dt.state.originY:dt.state.wy,0)}),Wt=(C,W,x)=>{const _=Hr.get(C);if(_)for(const V of _)V.callCursor(W,x)},qr=()=>{if(Vr.length===0)return;const C=dt.state;if(!C.has)return;const W=S.getParallaxOffset?S.getParallaxOffset():{x:0,y:0},x=b.general?.orthogonalprojection?.height||n.height,_=Ib.hitTestLayers(b.layers,C.wx,C.wy,x,{parOffX:W.x,parOffY:W.y,alignTable:ft.ALIGN,filter:F=>Hr.has(F)}),V=ht();_!==Wr&&(Wr&&Wt(Wr,"cursorLeave",V),Wr=_,_&&Wt(_,"cursorEnter",V)),_&&Wt(_,"cursorMove",V),C.leftDown&&!jr?(un=_,_&&Wt(_,"cursorDown",V)):!C.leftDown&&jr&&(un&&Wt(un,"cursorUp",V),un&&un===_&&Wt(_,"cursorClick",V),un=null),jr=C.leftDown},As=performance.now();let Fa=0,vr=0;const Pn=[],kr=[];let Da=-1/0,xs=0;const _i=C=>{if(a||t.paused)return;const x=1e3/(t.cfg.sceneFps||60);if(C-Da>=x){Da=C,er(t,C),el(t,n,t.cfg);const _=Math.max(0,(C-As-Fa)/1e3);if(At.update(dt.state),Oe.enabled){if(U?.media)U.media.pump();else{const L=Y();typeof L?.update=="function"&&L.update(_)}const D=ve(),z=Se.diffMediaEvents(ze,D);if(z.length){for(const{name:L,event:E}of z)for(const I of qe)I.disabled||I.callMedia(L,E);ze=Se.cloneMediaSnapshot(D)}if(st!==D.thumbnail&&typeof D.thumbnail=="string"&&D.thumbnail){const L=D.thumbnail;st=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(st!==L){I.close?.();return}const O=I.width,Q=I.height,$=ys(I,O,Q);if(I.close?.(),$){const Z=ve();Z.primaryColor=Se.mediaVec3(...$.primary),Z.secondaryColor=Se.mediaVec3(...$.secondary),Z.tertiaryColor=Se.mediaVec3(...$.tertiary),Z.textColor=Se.mediaVec3(.98,.98,1),Z.highContrastColor=Se.mediaVec3(1,1,1)}ce(t,e,`media: $mediaThumbnail \u5DF2\u66F4\u65B0\uFF08${O}\xD7${Q}\uFF09`)}catch(E){ce(t,e,`media: \u5C01\u9762\u4E0A\u4F20\u5931\u8D25\uFF08${E instanceof Error?E.message:E}\uFF09`)}})()}}U?.windowTitle?U.windowTitle.pump():N.update(_);const V=Math.max(0,_-xs);xs=_,Si.dt=V,Si.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 O of z)I.push({l:String(D&&(D.name||D.id)),f:O.frame,n:O.name}),I.length>400&&I.shift()}for(const E of z)for(const I of L){const O=I.sandbox;if(!(!O||O.disabled))if(I.kind==="text"){const Q=O.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,$=O.callAnimationEvent(E,Q);I.run&&(typeof $=="boolean"||typeof $=="number"&&Number.isFinite($))&&(I.run.last=$);const Z=vi($);Z!==void 0&&(I.effect.visible=Z)}else if(I.kind==="const"){const Q=O.callAnimationEvent(E,O.__lastConstValue);(typeof Q=="number"&&Number.isFinite(Q)||Q&&typeof Q=="object"&&Number.isFinite(Number(Q.x))&&Number.isFinite(Number(Q.y)))&&(O.__lastConstValue=Q)}else if(I.kind==="bool"){const Q=O.callAnimationEvent(E,!!D.visible),$=vi(Q);$!==void 0&&D.visibleSelf!==$&&(D.visibleSelf=$,F=!0)}else if(I.kind==="scalar"){const Q=O.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=O.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 Yn){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 O=0;O<E.length&&O<I.length;O++)I[O]=E[O]}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 Kt){D.ctrl.advance(V);const z=D.ctrl.applyTo(D.ctrl.baseNumeric);if(typeof z!="number"||!Number.isFinite(z))continue;const L=kn.get(D.layer.id);if(L)for(const E of L)E.setOverrideValue(D.key,z)}for(const D of Yn){const z=D.ctrl.takeEvents();z.length&&j(D.layer,z)}for(const D of Kt){const z=D.ctrl.takeEvents();z.length&&j(D.layer,z)}for(const D of Ur)D.ctrl.takeEvents();for(const D of Ur){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 zr){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=vi(z);L!==void 0&&(D.effect.visible=L)}for(const D of Pi){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 Nt){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=vi(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},O=D.sandbox.callUpdate(I),Q=O&&typeof O=="object"&&"x"in O?O:I;D.layer[L]=D.field==="angles"?Ke.scriptAnglesToRad(Q):[Q.x||0,Q.y||0,Q.z||0]}}F&&k(),Qn.size&&vt.recomposeWorld(b.layers,Qn),ne.enabled&&(Ze.pump(),Ze.active||(H.current?H.current.pump():M.update(_)),hb(Fe,je())),wr.length&&ms.followAttachments(wr,_,Lr);for(const D of An){const z=D.mdl,L=D.layer,E=z.animations;if(!E||!E.length||!L.animationLayers||!L.visible||!E.some(O=>O.events&&O.events.length))continue;let I=Ra.get(L);I||(I=new Map,Ra.set(L,I));for(let O=0;O<L.animationLayers.length;O++){const Q=L.animationLayers[O];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(O)?I.get(O):Z,te=ps.crossedEvents($.events,se,Z,$.frameCount,$.mode==="loop"?"loop":$.mode==="mirror"?"mirror":"single");te.length&&j(L,te),I.set(O,Z)}}const K=t.coverAlign;S.render(b,Te,n.width,n.height,_,xr(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(Pt.length){for(const D of Pt)j(D.layer,D.events);Pt.length=0}try{qr()}catch{}dt.beginFrame();try{t.sceneTextUpdate&&C>=Tn&&(Tn=C+100,t.sceneTextUpdate(_))}catch{}t.raf=requestAnimationFrame(_i)}}).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(_i))},Na=()=>{a||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(_i))},La=C=>{if(a)return;const W=b.properties||{},x=S0(W,v,C);if(Object.keys(x).length){Rr(b.general||{},W,0);for(const _ of b.layers){const V=_.srcObject;if(!V)continue;Rr(V,W,0);const F=yn(V.visible);F&&F in x&&(_.visibleSelf=vt.parseBool(V.visible,!0));const j=yn(V.color);j&&j in x&&(_.color=vt.parseColor(V.color),_.isText&&(_.textColor=_.color));const X=yn(V.alpha);X&&X in x&&(_.alpha=vt.parseNum(V.alpha,1));const K=yn(V.brightness);K&&K in x&&(_.brightness=vt.parseNum(V.brightness,1));const D=yn(V.volume);if(D&&D in x){const L=vt.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 O=yn(E.visible);O&&O in x&&(I.visible=vt.parseBool(E.visible,!0));const Q=yn(E.rate);Q&&Q in x&&(I.rate=vt.parseNum(E.rate,1));const $=yn(E.blend);$&&$ in x&&(I.blend=vt.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 O=yn(E.visible);O&&O in x&&!I.visibleScript&&(I.visible=vt.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=yn(z[E]);if(I&&I in x){L=!0;break}}if(L){const E=kn.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=kn.get(_.id);if(V)for(const F of V)F.setVisible(!!_.visible)}S.applyConstUserProperties?.(x);for(const _ of Ct)_.lastKey=null;ce(t,e,`props hot: ${Object.keys(x).join(",")}`)}};d=()=>{t.raf!==void 0&&(cancelAnimationFrame(t.raf),t.raf=void 0),vr||(vr=performance.now()),Pn.length=0;for(const C of Te.values())C?.videoCtl?.isPlaying?.()&&(Pn.push(C.videoCtl),C.videoCtl.pause());kr.length=0;for(const C of Ti)!C.paused&&!C.ended&&(kr.push(C),C.pause())},h=()=>{vr&&(Fa+=performance.now()-vr,vr=0);for(const C of Pn)try{C.play()}catch{}Pn.length=0;for(const C of kr)C.play().catch(()=>{});kr.length=0,Na()},f=La,l&&(La(l),l=null),Na();{const C=b.general?.orthogonalprojection,W=C?.width||n.width,x=C?.height||n.height,_=xr(t.cfg.fit),V=Ua(_,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=Sh(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 p1='data-we-shim="1"',sh="data-we-shim-src";function g1(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 y1(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 ah(t){return t.replace(/<\/script/gi,"<\\/script")}function b1(t,e,n){if(t||(t=""),t.includes(p1)||t.includes(sh))return t;const r=n.baseHref&&!/<base\b/i.test(t)?`<base href="${n.baseHref.replace(/"/g,""")}">`:"",i=`<script ${sh}="1">
|
|
647
|
-
${
|
|
761
|
+
`};function KA(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 ZA(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 JA(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 e2(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=ZA(e?JA(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 t2(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 n2={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"},Mo=new Map,Yr=at.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 r2=1;function i2(t,e){if(t.storageProvider)return at.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 at.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 at.makeSandboxStorage(s(r),s(i))}function s2(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 a2(t){for(const e of t){const n=Mo.get(e);if(n&&(n.refs--,!(n.refs>0))){Mo.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 xr=new Map,o2=512*1024*1024;let Co=0;function c2(t){for(;xr.size>0&&(xr.size>2||Co>o2);){let e=null,n=1/0;for(const[i,s]of xr)i!==t&&s.at<n&&(n=s.at,e=i);if(!e)break;const r=xr.get(e);Co-=r.parsed.fileSize||0,xr.delete(e)}}function l2(t){if(!t)return;const e=xr.get(t);e&&(Co-=e.parsed.fileSize||0,xr.delete(t))}async function u2(t,e,n,r){const i=n.key;if(i){const c=xr.get(i);if(c)return c.at=Date.now(),ye(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))}ye(t,e,`pkg body: ${s.byteLength} bytes`);const a=s instanceof Uint8Array?s:new Uint8Array(s),o=st.parsePkg(a);return i&&(xr.set(i,{parsed:o,at:Date.now()}),Co+=o.fileSize||0,c2(i)),o}function f2(t,e){Fr(t);const n=(e.canvas instanceof HTMLCanvasElement?e.canvas:null)??document.createElement("canvas"),r=Mi(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{ye(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={...aa(t.cfg.quality),...m??{}},p?.(aa(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");ye(t,e,"mountScene start");const g=await u2(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=st.getEntry(g,"scene.json")??st.getEntry(g,"gifscene.json")??st.getEntry(g,"scenes/scene.json")??st.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=qy(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=i2(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=st.getEntry(g,C);let $=F?jt(F):YA[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=>ye(t,e,`renderer: ${T}`),fboCapFactor:0,workshopId:e.src??cu(e.source?.key),parallaxFormula:e.parallaxFormula});if(t.renderer=_,a)return;bi.setParticleFrameTargetProvider(()=>_.getFrameTarget?.()??null),bi.setParticleSceneCapture((T,C)=>_.captureSceneTexture?.(T,C)??null);{const T=u;u=()=>{T?.(),bi.setParticleFrameTargetProvider(null),bi.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 Ee={enabled:I&&!t.audioDisabled},Ce=T=>new Float32Array(T),Ue={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(()=>Ee.enabled?Re||De():Ue);const Fe=new Map,Ge=new Map,Qe=[],Ye=(T,C)=>{if(!T||!C||!C.sandbox)return;let R=Ge.get(T);R||(R=[],Ge.set(T,R)),R.push(C)};window.__audioStats=()=>({enabled:Ee.enabled,live:!!ie.current,level:Ee.enabled?Math.round((ie.current?ie.current.snapshot:B.snapshot).level*1e3)/1e3:0,silent:Ee.enabled?(ie.current?ie.current.snapshot:B.snapshot).silent:!0,bass:Ee.enabled?Math.round((ie.current?ie.current.snapshot:B.snapshot).left64[2]*1e3)/1e3:0}),window.__audioMute=T=>(Ee.enabled=!T,Ee.enabled),ye(t,e,`audio: ${ie.current?"live mic":"simulated"} stream, supportsaudioprocessing=${I}`);const nt=Gm.createShortcutHandler(T=>{ye(t,e,`openUserShortcut: ${T}`)}),yn={enabled:!t.mediaDisabled,override:null},ot=[],gt=new Set;let Gt=0,Rn=0,Et=null,kt=(()=>{const T=new Date;return(T.getHours()*3600+T.getMinutes()*60+T.getSeconds())/86400})(),on=-1;const Rt=T=>{if(!(!T||!T.hasResizeHook||typeof T.callResize!="function")&&!gt.has(T)&&(gt.add(T),Et))try{T.callResize(Et.w,Et.h)}catch{}},ss=(T,C)=>{for(const R of gt)if(!(!R||R.disabled))try{R.callResize(T,C)}catch{}};let cn=null,as;W.lastSnap={get:()=>cn,setHasThumbnail:T=>{cn&&(cn.hasThumbnail=T)}};const lt=()=>he().snapshot,Tr=T=>{if(!(!T||!T.hasMediaHook||ot.includes(T))&&(ot.push(T),!!lt().hasMedia))for(const{name:C,event:R}of We.diffMediaEvents(null,lt()))try{T.callMedia(C,R)}catch{}};window.__mediaStats=()=>({enabled:yn.enabled,live:!!U,hooks:ot.length,title:lt().title,artist:lt().artist,album:lt().album,state:lt().state,position:Math.round(lt().position),duration:lt().duration,hasThumbnail:lt().hasThumbnail,lyric:lt().lyricLine,primaryColor:lt().primaryColor?[lt().primaryColor.x,lt().primaryColor.y,lt().primaryColor.z]:null}),window.__mediaSet=T=>{try{Object.assign(lt(),T||{})}catch{ye(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(cn,lt());for(const{name:R,event:F}of C)for(const $ of ot)$.callMedia(R,F);return cn=We.cloneMediaSnapshot(lt()),window.__mediaStats()};const Ro=()=>{const T=We.diffMediaEvents(cn,lt());for(const{name:C,event:R}of T)for(const F of ot)try{F.callMedia(C,R)}catch{}cn=We.cloneMediaSnapshot(lt())},bn=T=>{const C=he(),R=C?.[T];if(typeof R=="function")try{R.call(C)}catch(F){ye(t,e,`media ${T} \u5931\u8D25: ${F?.message}`)}return Ro(),lt()},Kr={get snapshot(){return lt()},skipNext:()=>bn("skipNext"),skipPrevious:()=>bn("skipPrevious"),play:()=>bn("play"),pause:()=>bn("pause"),playPause:()=>bn("playPause")};t.mediaCtl=Kr,window.__mediaControl=Kr,window.__system={media:Kr,windowTitle:Ae.snapshot,shortcuts:nt.last,live:null},window.__liveSystem=()=>({audio:"off",media:"offline",window:"offline"});const ut=aA.createPointerSource(e.canvas?{target:e.canvas,viewport:()=>({w:e.canvas.clientWidth||window.innerWidth||1,h:e.canvas.clientHeight||window.innerHeight||1})}:{});_.setPointerProvider(()=>ut),t.pointerCtl={push:T=>ut.pushExternal(T),leave:()=>ut.pushExternalLeave()};{const T=u;u=()=>{T?.(),ut.dispose()}}const Qn=at.createInputView(),Bn=sA.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,ye(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)}`))}})()}),Sr={setTimeout:Bn.setTimeout,clearTimeout:Bn.clearTimeout,setInterval:Bn.setInterval,clearInterval:Bn.clearInterval};{const T=u;u=()=>{T?.(),Bn.dispose()}}window.__pointerStats=()=>{const T=ut.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(ut.normalizedDelta()),counts:{move:T.moveCount,down:T.downCount,up:T.upCount}}};const yt=1.15,ze=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=Mi(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(gn.BUILTIN_MODELS[q])K=gn.BUILTIN_MODELS[q];else{const ue=st.getEntry(g,q);ue&&(K=JSON.parse(jt(ue)))}}catch{K=null}if(!K||K.meshes||K.puppet)continue;const N=K.material;if(!N)continue;const E=st.getEntry(g,N);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=Lp(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=ze.get(ue)||0;ae>pe&&ze.set(ue,ae)}}ye(t,e,`[S4] \u56FE\u5C42\u8DB3\u8FF9\u8868 ${ze.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 ye(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,os=Np();let vi="",Yn=!1;const Zr=Rp(t,e),Jr=Bp(t,e),Bo=32,Ve={texCount:0,cpuDecoded:0,cpuReleased:0,gpuUploaded:0,compressed:0,r8Native:0,framesScaled:[],scaled:[],textures:[],pkgBytes:0},Fo=(()=>{if(typeof location>"u")return!0;const T=new URLSearchParams(location.search).get("texr8");return!(T==="0"||T==="off"||T==="native")})(),Do=(()=>{if(typeof location>"u")return!0;const T=new URLSearchParams(location.search).get("texcompress");return!(T==="0"||T==="off"||T==="native")})(),la=()=>{const T=Mi(t,e)||1,C=(n.clientWidth||window.innerWidth||1280)*T,R=(n.clientHeight||window.innerHeight||720)*T;return Math.max(C,R)},ua=T=>Dp(T,Zr,Jr),No=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))},Ai=(T,C)=>{const R=No(C);if(os||Yn)return R;const F=Op(R,T),$=ze.get(vi)||0;return Up(F,R,$)},rt=(T,C,R)=>{if(os||Yn)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=ze.get(vi)||0,re=Q>0?Math.round(Q):Math.max(64,Math.round(la()));return zp(X,C,re)},cs=(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 t2(T,Math.max(1,Math.round(T.width*F)),Math.max(1,Math.round(T.height*F)))},Lo=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 GA()}catch(C){ye(t,e,`local assets \u88C5\u8F7D\u5931\u8D25\uFF08\u5FFD\u7565\uFF09\uFF1A${C?.message}`)}T&&ye(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 To.SYSTEM_UTIL_TEXTURES){const C=To.buildSystemUtilTexture(T);if(!C)continue;const R={wrap:"repeat"};Ke.set(T,To.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&&yn.enabled&&(Ke.set("$mediaThumbnail",T(C[0])),Ke.set("$mediaPreviousThumbnail",T(C[C.length-1])))}const Uo=(T,C,R)=>{const F=UA(T,C,R,512),$=LA(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=Uo(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),ye(t,e,`liveSystem: artwork ${R.title||R.trackKey}`)}catch(F){ye(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 ot)try{H.callMedia(F,$)}catch{}cn=We.cloneMediaSnapshot(he().snapshot)}const R=U.status();ye(t,e,`liveSystem: audio=${R.audio} media=${R.media} window=${R.window}`+(R.title?` title="${R.title}"`:"")+(R.hasArtwork?" artwork=1":"")),ye(t,e,`audio: ${ie.current?"live mic":"simulated"} stream, supportsaudioprocessing=${I}`),window.__system={media:Kr,windowTitle:Ae.snapshot,shortcuts:nt.last,live:()=>U.status()},window.__liveSystem=()=>U.status()}}catch(C){ye(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 ls=new Map,bu=async T=>{if(vi=T,Yn=!1,Ke.has(T))return Ke.get(T);const C=st.getEntry(g,`materials/${T}.tex`);if(!C){if(await sp(T),Jt.isBuiltinParticleTextureName(T)){const L=Jt.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=Gn.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 N=K.width*4,E=new Uint8Array(L*X*4);for(let z=0;z<X;z++)E.set(K.data.subarray(z*N,z*N+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 N=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(N));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),ye(t,e,`tex '${T}': animated multi-image, ${re.length} frames @ ${L}x${X}`),E}}}const F=Gn.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:Mi(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",()=>{ye(t,e,`video tex '${T}': ${X.active.videoWidth}x${X.active.videoHeight}`)}),X.active.addEventListener("error",()=>{ye(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 N=0;return X.onSwap=E=>{K.lastUploaded=-1,re(E),N++,(N===1||N===10||N===100)&&ye(t,e,`video tex '${T}' loop swap ok x${N}`)},X.onFallback=()=>{ye(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===Gn.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));Yn=Q;const re=Q?X:Ai(ua(T),R)||X,q=Math.min(1,re/X),K=await e2(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));Yn=X;const Q=X?1:ua(T),re=Ai(Q,R),q=rt(R,re,Q);{const E=Do?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 St=je===Ie.width&&qe===Ie.height?Ie.data:Gn.cropBlocks(Ie.data,Ie.width,je,qe,E.blockBytes);if(St.length!==Math.ceil(je/4)*Math.ceil(qe/4)*E.blockBytes){G=!1;break}ee.push({width:je,height:qe,data:St})}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:Gn.decodeMipLevel(R,q),N=!H&&Fo&&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=Gn.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&&N&&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($||Vp(E.rgba)){const Ie=$?null:await Lo(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=cs(E,re),ue="resample"):ue="skip-big-alpha"}else E.width*E.height<=16e6?(ge=cs(E,re),ue="resample"):ue="skip-big-alpha";const pe=Jt.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:Jt.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&&(Hp(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?Jt.rgbaLooksLikeAlbedo(L.rgba):!1,H.packedNormal===void 0&&(H.packedNormal=L?.rgba?Jt.isPackedNormalTexture(L):!1),!H.looksAlbedo&&H.cpuMips&&(Ve.cpuReleased+=L?.rgba?L.rgba.byteLength:0,H.cpuMips=null)}H.resourceScale=ua(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:No(R),need:Math.round(ze.get(T)||0),target:Ai(H.resourceScale,R)}),Ke.set(T,H),ye(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},Kn=T=>{if(Ke.has(T))return Promise.resolve(Ke.get(T));const C=ls.get(T);if(C)return C;const R=bu(T);return ls.set(T,R),R.finally(()=>{ls.get(T)===R&&ls.delete(T)}),R},us=/uniform\s+sampler2D\s+g_Texture\d+\s*;\s*\/\/[^\n]*"default"\s*:\s*"([^"]+)"/g,fa=async T=>{for(const C of T.materialPasses||[])if(C.shader)for(const R of["frag","vert"]){const F=st.getEntry(g,`shaders/${C.shader}.${R}`);if(!F)continue;const $=jt(F);us.lastIndex=0;let H;for(;(H=us.exec($))!==null;){const L=H[1];!L||L.startsWith("util/")||L.startsWith("_rt_")||Ke.has(L)||await Kn(L)}}};window.__memStats=()=>({resourceScale:Zr,resourceScaleNormal:Jr,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 Oo=0;const Pr=[];for(let T=0;T<b.layers.length;T++){const C=b.layers[T];if(C.image)try{let R;if(gn.BUILTIN_MODELS[C.image])R=gn.BUILTIN_MODELS[C.image];else{const K=st.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(gn.BUILTIN_MATERIALS[L.materialPath])X=gn.BUILTIN_MATERIALS[L.materialPath];else{const K=st.getEntry(g,L.materialPath);if(K)X=JSON.parse(jt(K));else if(C.solid&&gn.BUILTIN_MATERIALS["materials/util/solidlayer.json"])X=gn.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 N=K.toLowerCase();N==="spritesheet"&&Number(Q.combos[K])===1&&(C.spriteSheet=!0),N==="lighting"&&Number(Q.combos[K])===1&&(C.lightingEnabled=!0)}for(let K=0;K<re.length;K++){const N=re[K];typeof N!="string"||!N||N.startsWith("util/")||N.startsWith("_rt_")||Pr.push(Kn(N).then(E=>{if(E&&K===0&&!H&&(C.textureName=N,Oo++,E.videoCtl&&(C.videoCtl=E.videoCtl),ye(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],ye(t,e,`autosize applied: layer.size=${ae}x${ue}`)):ye(t,e,`autosize skipped: fw=${ee} fh=${G} declared=${E.declaredWidth}x${E.declaredHeight}`)}}))}Q?.shader&&st.getEntry(g,`shaders/${Q.shader}.frag`)&&gn.attachLayerMaterialEffect(C,Q);for(const K of C.effects||[])gn.resolveEffectChain(g,K,jt);for(const K of C.effects||[]){for(const N of K.passes||[]){for(const E of N.textures||[])typeof E=="string"&&E!==""&&!E.startsWith("util/")&&!E.startsWith("_rt_")&&Pr.push(Kn(E));for(const E of N.textureFallbacks||[])typeof E=="string"&&E!==""&&!E.startsWith("util/")&&!E.startsWith("_rt_")&&Pr.push(Kn(E))}Pr.push(fa(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||[])gn.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_")&&Pr.push(Kn(F))}catch(C){console.warn(`\u6587\u5B57\u5C42\u6548\u679C ${T.name} \u89E3\u6790\u5931\u8D25: ${C.message}`)}}await Promise.all(Pr);{const C=(b.general??(b.general={})).orthogonalprojection??null,R=Number(C?.width)>0&&Number(C?.height)>0;if(C){const F=Xo(b.layers);ye(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=Xo(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,ye(t,e,`auto ortho: content ${Math.round($)}x${Math.round(H)}\uFF08orthogonalprojection.auto\uFF09`))}}ye(t,e,`resources R=${Zr}${Jr!==Zr?` (normal R=${Jr})`:""} 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 Bt=[],da=[],Zn=new Map;let zo=0;const _r=async(T,C="albedo")=>{const R=st.getEntry(g,`materials/${T}.tex`)?await Kn(T):null;if(R)return R;await sp(T);let F=Jt.buildBuiltinParticleTexture(T);if(!F)return null;F=C==="normal"?Jt.convertParticleNormalFormat(F,F.format):Jt.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:Jt.builtinParticleFrames(T)??void 0};return Ke.set(T,$),zo++,$},Ho=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 Jt.prepareParticleNormalTexture=="function"){const R=Jt.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},fs=async(T,C,R,F)=>{if(F>3)return null;const $=st.getEntry(g,T);if(!$)return ye(t,e,`particle '${T}' \u4E0D\u5728 pkg\uFF0C\u8DF3\u8FC7`),null;const H=JSON.parse(jt($)),L=new bi.ParticleSystem(_.gl,H,R,C);let X=null,Q=null;if(H.material){const N=st.getEntry(g,H.material);if(N){const E=JSON.parse(jt(N));L.setMaterial(E);const z=E?.passes?.[0]?.textures||[];X=z[0]||null,Q=z[1]||null}}const re=await _r(X||"particle/halo");if(!re)return ye(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?Jt.particleNormalNameForAlbedo(X||"particle/halo"):null);if(q){const N=Ho(await _r(q,"normal"));N&&(N.packed=N.packedNormal===!0,L.setNormalTexture({glTex:N.glTex,width:N.width,height:N.height,packed:!!N.packed}))}L.setVisible(!!C.visible),Bt.push(L);const K=C.id;if(K!==void 0){let N=Zn.get(K);N||(N=[],Zn.set(K,N)),N.push(L)}for(const N of H.children||[]){if(!N||typeof N.name!="string")continue;const E=String(N.origin??"0 0 0").trim().split(/\s+/).map(Number),z=String(N.scale??"1 1 1").trim().split(/\s+/).map(Number),ee=String(N.angles??"0 0 0").trim().split(/\s+/).map(Number),G=N.type==="eventfollow"?"particle":!N.type||N.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 fs(N.name,ge,N.instanceoverride||R,F+1);ae&&G?ae.attachFollow(L,G,[E[0]||0,E[1]||0,E[2]||0]):ae&&(N.type==="eventdeath"||N.type==="eventspawn")&&ae.attachEventParent(L,N.type,[E[0]||0,E[1]||0,E[2]||0])}return L};if(!TA){for(const T of b.layers)if(T.particle)try{await fs(T.particle,T,T.instanceoverride,0)}catch(C){console.warn(`\u7C92\u5B50\u56FE\u5C42 ${T.name} \u52A0\u8F7D\u5931\u8D25: ${C.message}`),ye(t,e,`particle '${T.name}' FAIL: ${C.message.slice(0,80)}`)}}if(Bt.length>0){const T=u;u=()=>{T?.();for(const C of Bt)C.dispose()}}const ei=[],en=VA();en.setVolume(Ko(t,e));const ln=()=>en.dispose();for(const T of b.layers)if(!(!T.sound||!T.sound.length))try{for(const C of T.sound){const R=st.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,en.attach(X),T.soundCtl={play(){if(X.ended)try{X.currentTime=0}catch{}en.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&&(en.resume(),X.play().catch(()=>{})),ei.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 ei)en.routes(R)?(R.volume=1,R.muted=C<=0):(R.volume=C,R.muted=C<=0);en.setVolume(C)};if(t.sceneAudio={setVolume:Ze,audios:ei,dispose:ln},Ru(t),a)return;const Fn={dt:1/60,t:0};let ds=0,Jn=!1;_.setParticleRenderer(()=>{if(Jn)return;const T=Math.min(.05,Math.max(0,Fn.dt));if(ut.state.has){const{wx:C,wy:R,originY:F}=ut.state,$=F??R;for(const H of Bt)H.setPointer(C,$)}if(da.length)for(const C of da)C.syncLayerTransform();for(const C of Bt)C.layer&&C.layer.runtimeCreated&&C.syncLayerTransform();{const C=_.getParallaxOffset?_.getParallaxOffset():null;for(const R of Bt)if(!C||!C.active||!R.layer||!R.layer.parallaxDepth)R.setParallaxOffset(0,0);else{const F=Qo(R.layer,C);R.setParallaxOffset(F[0],F[1])}}for(const C of Bt)C.advance(T,Ee.enabled?De():null);if(ds<2&&(ds++,ds===2)){const C=Bt.reduce((R,F)=>R+F.liveCount(),0);ye(t,e,`particles live: ${C} across ${Bt.length} systems`)}},(T,C,R,F,$)=>{if(Jn||T===void 0)return;const H=Zn.get(T);if(H)for(const L of H)L.render(R,F,$,C.projW,C.projH)});const er=T=>{_.setAntiAliasing?.(T.antiAliasing),_.setEffectsEnabled?.(T.postProcessing!=="off"),_.setFboCapFactor?.(RA(T.postProcessing)),Jn=T.particles==="off",bi.setParticleQualityScale?.(IA(T.particles)),bi.setParticleDensityTier?.(T.particles==="off"?"high":T.particles);for(const C of Bt)C._applyOverride?.();ye(t,e,`quality: aa=${T.antiAliasing} particles=${T.particles} post=${T.postProcessing}`)};p=er,er(aa(e.quality)),ye(t,e,`particles: ${Bt.length} systems, ${zo} builtin tex generated`),window.__particleStats=()=>({t:Fn.t,systems:Bt.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 N=Math.abs(re.size)*T.sysScale;N<L&&(L=N),N>X&&(X=N)}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<Bt.length;R++)Bt[R].setVisible(C===void 0?T:R===C);return Bt.length};const Ft=[],ti=new Map,xi=new Map,un=T=>{if(!T||!T.puppet)return null;let C=xi.get(T);return C||(C=new Map,xi.set(T,C)),C};for(const T of b.layers)if(T.image)try{if(gn.BUILTIN_MODELS[T.image])continue;const C=st.getEntry(g,T.image);if(!C)continue;const R=JSON.parse(jt(C));if(!R.puppet)continue;const F=st.getEntry(g,R.puppet);if(!F)continue;const $=ia.parseMDL(new Uint8Array(F)),H=T.textureName?Ke.get(T.textureName):null;if(!H){ye(t,e,`puppet '${T.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}T.puppet=$,Ft.push({mdl:$,tex:H,layer:T});const L=$.animations[0];ye(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}`),ye(t,e,`puppet '${T.name}' \u5931\u8D25: ${C.message}`)}for(const T of b.layers)if(T.model&&!T.puppet)try{const C=st.getEntry(g,T.model);if(!C)continue;const R=ia.parseMDL(new Uint8Array(C));let F=null;if(R.materialPath){const H=st.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 Kn(F),T.textureName=F}catch(H){ye(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(!$){ye(t,e,`model '${T.name}' \u65E0\u8D34\u56FE\uFF0C\u8DF3\u8FC7`);continue}T.puppet=R,Ft.push({mdl:R,tex:$,layer:T}),ye(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}`),ye(t,e,`model '${T.name}' \u5931\u8D25: ${C.message}`)}let hs=null;if(Ft.length>0)try{hs=ia.createMDLRenderer(_.gl);for(const C of Ft)hs.upload(C.mdl);const T=new Map;for(const C of Ft)T.set(C.layer,C);_.setPuppetRenderer((C,R,F)=>{const $=T.get(C);$&&hs.draw(R,$.mdl,{time:F.time,animLayers:C.animationLayers,boneOverrides:xi.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}`),ye(t,e,`puppet renderer \u5931\u8D25: ${T.message}`),hs=null;for(const C of Ft)C.layer.puppet=null}if(a)return;ye(t,e,`puppet: ${Ft.length} meshes`);const wn=ia.applyAttachmentBindOrigins(b.layers);wn.length&&ye(t,e,`attachments: ${wn.length} hanging layers`);const tr=zt.collectTransformDirty(b.layers,wn.map(T=>T.layer));if(tr.size){ye(t,e,`transform graph: ${tr.size} live layers`);for(const[T,C]of Zn)if(tr.has(T))for(const R of C)da.push(R)}const Dn=[],Vo=[],ms=new Map,vn={};let Nn=null,Er=null,ps=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=$o(Br(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}`,N=Mo.get(K);if(N){N.refs++,L.push(K),H.set(q,N.family);continue}const E=n2[q.toLowerCase()];if(E){H.set(q,E);continue}try{const z=st.getEntry(g,q),ee=z?z instanceof Uint8Array?z:new Uint8Array(z):await QA(q);if(!ee)continue;const G=KA(ee),J="wefont_"+s2(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),Mo.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=()=>{a2(L),q?.()}}Nn=document.createElement("canvas"),Er=Nn.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=at.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:kt,userProperties:v,shared:vn,storage:S,audioViews:Fe,inputView:Qn,...Sr,mediaControl:Kr,windowTitle:Ae.snapshot,openUserShortcut:nt.openUserShortcut,getLayerText:ee=>ms.get(ee),onError:ee=>{ye(t,e,`text script '${q.name}' \u5931\u8D25: ${String(ee.message||ee).slice(0,120)}`)}}),K.sandbox&&(P.push(K.sandbox),Vo.push({sandbox:K.sandbox,layer:q}),K.sandbox.hasMediaHook&&Tr(K.sandbox),Rt(K.sandbox),K.sandbox.hasAnimEventHook&&Ye(q,{sandbox:K.sandbox,kind:"text"}))),ms.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 N=ep*Math.max(1,q.textPointsize),E=at.textLayerHasTintMask(q)?8:256,z=Math.min(E,at.textCanvasMargin(N,0));K.boxW=q.size[0]>0?q.size[0]:N*4,K.boxH=q.size[1]>0?q.size[1]:N*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,Dn.push(K)}catch(K){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${q.name} \u521D\u59CB\u5316\u5931\u8D25: ${K.message}`)}if(Dn.length>0){const q=u;u=()=>{q?.();for(const K of Dn)_.gl.deleteTexture(K.entry.glTex)}}const re=q=>{if(!Er||!Nn)return;const K=Er;for(const N of Dn){const E=N.layer;let z=String(E.text??"");if(N.sandbox&&N.sandbox.hasUpdate){N.sandbox.engine.runtime=q,N.sandbox.engine.timeOfDay=kt;const ge=N.sandbox.callUpdate(z);ge!=null?z=String(ge):N.sandbox.thisLayer.text&&(z=String(N.sandbox.thisLayer.text))}else N.sandbox&&typeof N.sandbox.thisLayer?.text=="string"&&(z=String(N.sandbox.thisLayer.text));if(ms.set(E.name||"",z),!E.visible)continue;const ee=Math.max(1,N.sandbox?N.sandbox.thisLayer.pointsize:E.textPointsize),G=N.sandbox&&N.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(N.lastKey!==J){N.lastKey=J;try{const ge=ep*ee,ae=N.boxW,ue=N.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(""),St=(qe.fontBoundingBoxAscent||0)+(qe.fontBoundingBoxDescent||0),bt=E.textSpacing||[0,0],wt=at.layoutText(z,{boxW:ae,boxH:ue,pointsize:ge,lineHeight:(St>0?St: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},fn=>K.measureText(fn).width);let Un=N.margin;const xn=!E.textAnchor||E.textAnchor==="center"||E.textAnchor==="none";if(N.sandbox?.hasMediaHook&&!at.textLayerHasTintMask(E)&&xn){const fn=at.textCanvasMarginGrow(wt,ae,ue,Un);(at.shouldGrowMediaPlaceholder(ae,ue,!0)||fn>Un)&&(E.size[0]=ae+fn*2,E.size[1]=ue+fn*2),fn!==Un&&(N.margin=fn,Un=fn)}let ft=Math.max(1,Math.round(E.size[0]*pe*N.quality)),tn=Math.max(1,Math.round(E.size[1]*Ie*N.quality));const ws=Math.min(1,Q/Math.max(ft,tn));ft=Math.max(1,Math.round(ft*ws)),tn=Math.max(1,Math.round(tn*ws)),Nn.width!==ft||Nn.height!==tn?(Nn.width=ft,Nn.height=tn):K.clearRect(0,0,ft,tn);const vu=`${ge}px "${je}", sans-serif`,jo=Math.min(ft/E.size[0],tn/E.size[1]);K.setTransform(jo,0,0,jo,0,0),K.translate(Un,Un),at.drawTextLayer(K,wt,{font:vu,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 ma=N.entry;_.gl.bindTexture(_.gl.TEXTURE_2D,ma.glTex),_.gl.texImage2D(_.gl.TEXTURE_2D,0,_.gl.RGBA,_.gl.RGBA,_.gl.UNSIGNED_BYTE,Nn),ma.width=ft,ma.height=tn}catch(ge){console.warn(`\u6587\u5B57\u5BF9\u8C61 ${E.name} \u7ED8\u5236\u5931\u8D25: ${ge.message}`),N.lastKey=null}}}};t.sceneTextUpdate=re,window.__textWidgets=Dn,ye(t,e,`text widgets: ${Dn.length} (scripts ${Dn.filter(q=>q.sandbox).length}, fonts ${H.size}, quality ${$.toFixed(2)})`)}if(a)return;const it=[],An=new Set,ki=[],Mr=[],Ti=[],gs=[],Si=[],ys={},Cr=[],Ln=[],Pi=new Map,ha=(T,C)=>{if(!C||typeof C.callCursor!="function"||!C.hasCursorHook)return;const R=Pi.get(T);R?R.push(C):Pi.set(T,[C])};for(const T of Dn)T.sandbox&&ha(T.layer,T.sandbox);{const T=b.general?.orthogonalprojection,C=T?.width||n.width,R=T?.height||n.height,F=v,$=(N,E)=>{const z=b.general||{};if(N==="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[N]&&typeof z[N]=="object"&&"value"in z[N]?z[N].value=E:z[N]=E};let H=1+Math.max(0,...b.layers.map(N=>Number(N.id)||0));const L={recomputeVisibility:x,markTransformDirty:N=>{N&&N.id!==void 0&&N.id!==null&&An.add(N.id)},getSceneLayer:N=>b.layers.find(E=>E.name===N&&!E.destroyed)||null,getSceneLayerById:N=>b.layers.find(E=>E.id===N&&!E.destroyed)||null,enumerateSceneLayers:()=>b.layers.filter(N=>!N.destroyed),getSceneAnimation:N=>{if(N==null||N==="")return null;if(ys[N])return ys[N];for(const E of b.layers)if(E.animations&&E.animations[N])return E.animations[N];return null},cameraTransforms:b.cameraTransforms,getInitialLayerConfig:N=>{const E=N&&typeof N=="object"?N.name:String(N||"");return b.layers.find(z=>z.name===E)||null},createSceneLayer:N=>{let E=N&&typeof N=="object"?N:null,z=null;if(typeof N=="string"){const G=N;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)&&st.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)&&st.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 ye(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(st.getEntry(g,G))),ge=zt.resolveMaterial(J),ae=ge&&st.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_")&&Kn(Ie).then(je=>{if(je&&(ee.textureName=Ie,ee.size[0]===0||ee.size[1]===0)){const qe=je.geomFrame,St=je.frames&&Array.isArray(je.frames)?je.frames[0]:null;ee.size=[qe&&qe.width||St&&St.width||je.declaredWidth||je.width,qe&&qe.height||St&&St.height||je.declaredHeight||je.height]}})}catch(J){ye(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;fs(G,ee,null,0).then(J=>{J||ye(t,e,`createLayer('${G}') \u7C92\u5B50\u7CFB\u7EDF\u88C5\u914D\u5931\u8D25`)})}return ee},mediaControl:Kr,windowTitle:Ae.snapshot,openUserShortcut:nt.openUserShortcut,isScreensaver:!1};_.setConstantScriptRuntime?.(at.evalObjectScript,{userProperties:F,audioViews:Fe,shared:vn,storage:S,inputView:Qn,timers:Bn,animEventQueue:Qe,...L,onSandbox:(N,E)=>{N&&N.hasMediaHook&&Tr(N),Rt(N),N&&N.hasAnimEventHook&&Ye(E&&E.layer,{sandbox:N,kind:"const"})}});const X={origin:"localOrigin",scale:"localScale",angles:"localAngles"},Q=(N,E)=>{const z=X[E];return z&&N&&Array.isArray(N[z])?z:E};for(const N of b.layers){const E=N.objectAnimations;if(E){N.animations=N.animations||{},N.animationList=N.animationList||[];for(const[z,ee]of Object.entries(E))try{const G=sa.createAnimation(ee.animation);G.field=z,G.baseValue=ee.value;const J=Q(N,z),ge=z==="volume"?N.soundprops?.volume:z==="maxwidth"?N.textMaxwidth:z==="zoom"?b.cameraTransforms?.zoom:N[J];G.baseNumeric=Array.isArray(ge)?ge.slice():ge,G.slot=J,N.animationList.push(G),G.name&&(N.animations[G.name]=G),ki.push({layer:N,field:z,slot:J,ctrl:G})}catch(G){ye(t,e,`animation '${N.name}.${z}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(G.message).slice(0,80)}`)}if(N.animationList.length){const z=new Map;for(const ee of N.animationList)z.set(ee.field,ee);sa.linkAnimations(z,ee=>ye(t,e,`${N.name}: ${ee}`)),N.animationsByField=Object.fromEntries(z)}}}for(const N of b.layers){const E=N.particleOverrideAnimations;if(E)for(const[z,ee]of Object.entries(E))try{const G=sa.createAnimation(ee.animation);G.baseNumeric=typeof ee.value=="number"?ee.value:Number(ee.value)||0,Mr.push({layer:N,key:z,ctrl:G})}catch(G){ye(t,e,`override animation '${N.name}.${z}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(G.message).slice(0,80)}`)}}for(const N of b.layers)(Array.isArray(N.animationLayers)?N.animationLayers:[]).forEach((z,ee)=>{const G=z.visibleScript;if(G)try{const J=at.evalObjectScript(G.script,G.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:kt,userProperties:F,audioViews:Fe,inputView:Qn,layer:N,...Sr,...L,shared:vn,storage:S,onError:ue=>ye(t,e,`animationlayer visible script '${N.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=Yr(ge);ae!==void 0&&(z.visible=ae),J.applyUserProperties(F),J.hasMediaHook&&Tr(J),Rt(J),gs.push({layer:N,index:ee,sandbox:J}),J.hasAnimEventHook&&Ye(N,{sandbox:J,kind:"animLayer",animLayerIndex:ee})}catch(J){ye(t,e,`animationlayer script '${N.name}[${ee}]' \u6C42\u503C\u5931\u8D25: ${String(J.message).slice(0,80)}`)}});for(const N of b.layers){const E=N.particleOverrideScripts;if(E)for(const[z,ee]of Object.entries(E))try{const G=at.evalObjectScript(ee.script,ee.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:kt,userProperties:F,audioViews:Fe,inputView:Qn,layer:N,...Sr,...L,shared:vn,storage:S,onError:J=>ye(t,e,`override script '${N.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),Rt(G),G.hasUpdate&&Ti.push({layer:N,key:z,sandbox:G})}catch(G){ye(t,e,`override script '${N.name}.${z}' \u6C42\u503C\u5931\u8D25: ${String(G.message).slice(0,80)}`)}}let re=!1;for(const N of b.layers){for(const[z,ee]of(N.effects||[]).entries()){const G=ee.visibleScript;if(G)try{const J=at.evalObjectScript(G.script,G.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:kt,userProperties:F,audioViews:Fe,inputView:Qn,...Sr,layer:N,targetEffect:ee,...L,shared:vn,storage:S,onError:pe=>ye(t,e,`effect visible script '${N.name}#${z}' \u5931\u8D25: ${String(pe.message||pe).slice(0,80)}`)});if(!J)continue;P.push(J);const ge=J.init(ee.visible),ae=Yr(ge);ae!==void 0&&(ee.visible=ae),J.applyUserProperties(F),J.hasMediaHook&&Tr(J),Rt(J);let ue=null;J.hasUpdate&&(ue={effect:ee,sandbox:J,last:ge},Cr.push(ue)),J.hasAnimEventHook&&Ye(N,{sandbox:J,kind:"effectVisible",effect:ee,run:ue})}catch(J){console.warn(`\u6548\u679C\u5F00\u5173\u811A\u672C ${N.name}#${z} \u6C42\u503C\u5931\u8D25: ${J.message}`)}}const E=N.objectScripts;if(E)for(const[z,ee]of Object.entries(E))try{const G=at.evalObjectScript(ee.script,ee.scriptproperties,{canvasSize:{width:C,height:R},screenResolution:{x:n.clientWidth||window.innerWidth||1,y:n.clientHeight||window.innerHeight||1},timeOfDay:kt,userProperties:F,audioViews:Fe,inputView:Qn,layer:N,getAnimationForProperty:()=>N.animationsByField&&N.animationsByField[z]||null,...L,getBoneOverrides:un,shared:vn,storage:S,...Sr,onError:J=>ye(t,e,`object script '${N.name}.${z}' \u5931\u8D25: ${String(J.message||J).slice(0,90)}`)});if(G){P.push(G);const J=Q(N,z),ge=N[J],ae=z==="angles"&&Array.isArray(ge)?at.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=Yr(ue);pe!==void 0&&N.visibleSelf!==pe&&(N.visibleSelf=pe,re=!0)}else if(typeof ue=="number"&&Number.isFinite(ue))["alpha","brightness","maxwidth","pointsize","volume","intensity","exponent"].includes(z)&&op(N,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))&&(N[J]=z==="angles"?at.scriptAnglesToRad(pe):[Number(pe.x)||0,Number(pe.y)||0,Number(pe.z)||0])}}G.applyUserProperties(F),ha(N,G),G.hasMediaHook&&Tr(G),Rt(G),G.hasUpdate&&it.push({layer:N,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(N,{sandbox:G,kind:z==="visible"?"bool":z==="alpha"||z==="brightness"?"scalar":"vec3",field:z,slot:J})}}catch(G){console.warn(`\u5BF9\u8C61\u811A\u672C ${N.name}.${z} \u6C42\u503C\u5931\u8D25: ${G.message}`)}}for(const N of Vo){const E=N.sandbox.init(N.layer.text??"");typeof E=="string"&&(N.layer.text=E),N.sandbox.applyUserProperties(v)}re&&x();const q=b.generalScripts;if(q){for(const[N,E]of Object.entries(q))try{const z=at.evalObjectScript(E.script,E.scriptproperties,{canvasSize:{width:C,height:R},timeOfDay:kt,userProperties:F,audioViews:Fe,inputView:Qn,...Sr,...L,shared:vn,storage:S,onError:G=>ye(t,e,`general script '${N}' \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),Rt(z);const ee=G=>$(N,G);z.hasUpdate&&Ln.push({field:N,sandbox:z,write:ee})}catch(z){console.warn(`general \u811A\u672C ${N} \u6C42\u503C\u5931\u8D25: ${z.message}`)}Ln.length&&ye(t,e,`general scripts: ${Ln.map(N=>N.field).join(",")}`)}const K=b.generalAnimations;if(K){for(const[N,E]of Object.entries(K))try{const z=sa.createAnimation(E.animation);z.field=N,z.baseValue=E.value,z.baseNumeric=E.value,z.name&&(ys[z.name]=z),Si.push({field:N,ctrl:z,write:ee=>$(N,ee)})}catch(z){ye(t,e,`general animation '${N}' \u5EFA\u63A7\u5236\u5668\u5931\u8D25: ${String(z.message).slice(0,80)}`)}Si.length&&ye(t,e,`general animations: ${Si.map(N=>N.field).join(",")}`)}}it.length&&(ye(t,e,`object scripts: ${it.length}`),window.__objScripts=it,window.__effectScripts=Cr),window.__mediaHooks=ot,window.__sceneLayers=b.layers,window.__compositeStats=()=>_.compositeStats?.()??null,window.__compositeEnable=T=>_.setCompositeEnabled?.(T),window.__scene=b,window.__textures=Ke;const bs=Array.from(Pi.keys());bs.length&&ye(t,e,`cursor hooks: ${bs.length} layers`);let Wo={hovered:[],pressed:[],lastLeftDown:!1};const wu=()=>({worldPosition:at.makeCursorEventVec(ut.state.wx,ut.state.originY!=null?ut.state.originY:ut.state.wy,0)}),ni=(T,C,R)=>{const F=Pi.get(T);if(F)for(const $ of F)$.callCursor(C,R)},_i=()=>{if(bs.length===0)return;const T=ut.state;if(!T.has)return;const C=_.getParallaxOffset?_.getParallaxOffset():null,R=b.general?.orthogonalprojection?.height||n.height,F=oA.hitTestLayersAll(b.layers,T.wx,T.wy,R,{parallaxCtx:C,alignTable:pt.ALIGN,perspEye:_.getPerspectiveEye?_.getPerspectiveEye():null,filter:L=>Pi.has(L)}),$=cA.planCursorDispatch(Wo,F,T.leftDown);Wo=$.next;const H=wu();for(const L of $.leave)ni(L,"cursorLeave",H);for(const L of $.enter)ni(L,"cursorEnter",H);for(const L of $.move)ni(L,"cursorMove",H);for(const L of $.down)ni(L,"cursorDown",H);for(const L of $.up)ni(L,"cursorUp",H);for(const L of $.click)ni(L,"cursorClick",H)},M=performance.now();let j=0,te=0;const Z=[],ne=[],de=new Ci(t.cfg.sceneFps||60);let me=t.cfg.sceneFps||60,be=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)){Dr(t,T),Du(t,n,t.cfg);const R=n.clientWidth||window.innerWidth||1,F=n.clientHeight||window.innerHeight||1;(R!==Gt||F!==Rn)&&(Gt=R,Rn=F,Et={w:R,h:F},ss(R,F));const $=Math.max(0,(T-M-j)/1e3);if(Qn.update(ut.state),yn.enabled){if(U?.media)U.media.pump();else{const ee=he();typeof ee?.update=="function"&&ee.update($)}const E=lt(),z=We.diffMediaEvents(cn,E);if(z.length){for(const{name:ee,event:G}of z)for(const J of ot)J.disabled||J.callMedia(ee,G);cn=We.cloneMediaSnapshot(E)}if(as!==E.thumbnail&&typeof E.thumbnail=="string"&&E.thumbnail){const ee=E.thumbnail;as=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(as!==ee){J.close?.();return}const ge=J.width,ae=J.height,ue=Uo(J,ge,ae);if(J.close?.(),ue){const pe=lt();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)}ye(t,e,`media: $mediaThumbnail \u5DF2\u66F4\u65B0\uFF08${ge}\xD7${ae}\uFF09`)}catch(G){ye(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,$-be);be=$;const L=H,X=Math.min(H,fe);Fn.dt=L,Fn.t=$;let Q=!1;const re=(E,z)=>{const ee=Ge.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=Yr(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=Yr(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"?at.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"?at.scriptAnglesToRad(Ie):[Number(Ie.x)||0,Number(Ie.y)||0,Number(Ie.z)||0]}}}};for(const E of ki){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 Mr){E.ctrl.advance(L);const z=E.ctrl.applyTo(E.ctrl.baseNumeric);if(typeof z!="number"||!Number.isFinite(z))continue;const ee=Zn.get(E.layer.id);if(ee)for(const G of ee)G.setOverrideValue(E.key,z)}for(const E of gs){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=kt;const z=E.layer.animationLayers?.[E.index];if(!z)continue;const ee=E.sandbox.callUpdate(z.visible!==!1),G=Yr(ee);G!==void 0&&(z.visible=G)}for(const E of Ti){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=kt;const z=E.sandbox.callUpdate(void 0),ee=Zn.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 ki){const z=E.ctrl.takeEvents();z.length&&re(E.layer,z)}for(const E of Mr){const z=E.ctrl.takeEvents();z.length&&re(E.layer,z)}for(const E of Si)E.ctrl.takeEvents();for(const E of Si){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!==on){on=q;const E=new Date;kt=(E.getHours()*3600+E.getMinutes()*60+E.getSeconds())/86400}for(const E of Cr){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=kt;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=Yr(z);ee!==void 0&&(E.effect.visible=ee)}for(const E of Ln){if(E.sandbox.disabled)continue;E.sandbox.engine.frametime=X,E.sandbox.engine.runtime=$,E.sandbox.engine.timeOfDay=kt;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=kt);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=kt;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=Yr(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"?at.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"?at.scriptAnglesToRad(ae):[ae.x||0,ae.y||0,ae.z||0]}}if(Q&&x(),An.size){for(const E of An)tr.add(E);An.clear()}if(tr.size&&zt.recomposeWorld(b.layers,tr),Ee.enabled){Ne.pump(),Ne.active||(ie.current?ie.current.pump():B.update($));const E=en.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};WA(ee,E,r2),Re=ee,rm(Fe,ee)}else Re=z,rm(Fe,z)}wn.length&&ia.followAttachments(wn,$,un);for(const E of Ft){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=ti.get(ee);J||(J=new Map,ti.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=sa.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 N=t.coverAlign;_.render(b,Ke,n.width,n.height,$,Br(t.cfg.fit),N.x,N.y).then(()=>{if(t.onFirstFrame){const E=t.onFirstFrame;t.onFirstFrame=void 0;try{E()}catch{}}if(!(a||t.paused)){if(Qe.length){for(const E of Qe)re(E.layer,E.events);Qe.length=0}try{_i()}catch{}ut.beginFrame();try{t.sceneTextUpdate&&T>=ps&&(ps=T+100,t.sceneTextUpdate($))}catch{}t.raf=requestAnimationFrame(se)}}).catch(E=>{console.warn("scene render error:",E),ye(t,e,`render: ${String(E.message||E).slice(0,200)}`),a=!0})}else t.paused||(t.raf=requestAnimationFrame(se))},Me=()=>{a||t.paused||t.raf===void 0&&(t.raf=requestAnimationFrame(se))},ke=T=>{if(a)return;const C=b.properties||{},R=Xy(C,v,T);if(Object.keys(R).length){pi(b.general||{},C,0);for(const F of b.layers){const $=F.srcObject;if(!$)continue;pi($,C,0);const H=Wn($.visible);H&&H in R&&(F.visibleSelf=zt.parseBool($.visible,!0));const L=Wn($.color);L&&L in R&&(F.color=zt.parseColor($.color),F.isText&&(F.textColor=F.color));const X=Wn($.alpha);X&&X in R&&(F.alpha=zt.parseNum($.alpha,1));const Q=Wn($.brightness);Q&&Q in R&&(F.brightness=zt.parseNum($.brightness,1));const re=Wn($.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 N=$.animationlayers[K],E=F.animationLayers?.[K];if(!N||!E)continue;const z=Wn(N.visible);z&&z in R&&(E.visible=zt.parseBool(N.visible,!0));const ee=Wn(N.rate);ee&&ee in R&&(E.rate=zt.parseNum(N.rate,1));const G=Wn(N.blend);G&&G in R&&(E.blend=zt.parseNum(N.blend,1))}for(let K=0;K<($.effects||[]).length;K++){const N=$.effects[K],E=F.effects?.[K];if(!N||!E)continue;const z=Wn(N.visible);z&&z in R&&!E.visibleScript&&(E.visible=zt.parseBool(N.visible,!0))}const q=$.instanceoverride;if(q&&typeof q=="object"&&F.particle){let K=!1;for(const N of Object.keys(q)){if(N==="id")continue;const E=Wn(q[N]);if(E&&E in R){K=!0;break}}if(K){const N=Zn.get(F.id);if(N)for(const E of N)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 $=Zn.get(F.id);if($)for(const H of $)H.setVisible(!!F.visible)}_.applyConstUserProperties?.(R);for(const F of Dn)F.lastKey=null;ye(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 ei)!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(),Me()},d=ke,l&&(ke(l),l=null),Me();{const T=b.general?.orthogonalprojection,C=T?.width||n.width,R=T?.height||n.height,F=Br(t.cfg.fit),$=$o(F,C,R,n.width,n.height);ye(t,e,`fit ${F}: view ${Math.round($.viewW)}x${Math.round($.viewH)} scene ${C}x${R} canvas ${n.width}x${n.height}`);{const H=Xo(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},ye(t,e,`cover peek gate: content ${Math.round(H.maxX-H.minX)}x${Math.round(H.maxY-H.minY)}`))}}ye(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));ye(t,e,`failed: ${String(g.message||g).slice(0,200)}`),t.onError?t.onError(g):t.fallbackPage?.()}})()}const d2='data-we-shim="1"',cp="data-we-shim-src";function h2(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 m2(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 p2(t,e,n){if(t||(t=""),t.includes(d2)||t.includes(cp))return t;const r=n.baseHref&&!/<base\b/i.test(t)?`<base href="${n.baseHref.replace(/"/g,""")}">`:"",i=`<script ${cp}="1">
|
|
762
|
+
${lp(e)}
|
|
648
763
|
<\/script>`,s=n.seedScript&&n.seedScript.trim()?`<script>
|
|
649
|
-
${
|
|
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
|
|
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 g2=`/**
|
|
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 @@ ${ah(n.seedScript)}
|
|
|
674
789
|
w.document.documentElement.setAttribute("data-we-shim", "1");
|
|
675
790
|
}
|
|
676
791
|
} catch (_) {
|
|
677
|
-
|
|
792
|
+
|
|
678
793
|
}
|
|
679
794
|
|
|
680
795
|
var audioListener = null;
|
|
@@ -1151,6 +1266,7 @@ ${ah(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 @@ ${ah(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 @@ ${ah(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 @@ ${ah(n.seedScript)}
|
|
|
2063
2200
|
installRafThrottle();
|
|
2064
2201
|
})(window);
|
|
2065
2202
|
|
|
2066
|
-
`;function
|
|
2067
|
-
`)}function M1(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=xr(t.cfg.fit)==="cover";i();const g=m&&h>0&&p>0?U1(d):null,w=g?O1(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 B1(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 R1(t,e,n){const r=(i,s)=>{if(!e.isConnected)return null;const a=n.getBoundingClientRect(),o=e.getBoundingClientRect();return B1(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&&kt(t,a=>a.__wePushPointer?.(s.x,s.y,Number(i.buttons)||0,Number(i.mods)||0))},leave(){kt(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;kt(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 Vc(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),M1(t,s,n),i.injected&&R1(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),er(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||v1(t,s,l)}catch{}kt(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 F1=.005,D1=.01,N1=.2,L1=6;function O1(t,e,n){if(!(t>0)||!(e>0)||!(n>0))return null;const r=t/e;if(Math.abs(r-n)<=F1)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 U1(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*D1)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<N1||u>L1))return{contentAspect:u}}return null}function Dr(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 z1(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,Dr(i)),a.addColorStop(1,Dr(s)),r.fillStyle=a,r.fillRect(0,0,64,64),n.toDataURL("image/jpeg",.85)}catch{return""}}function H1(){return Se.createSimulatedMedia()}function V1(t,e,n){const r=Se.diffMediaEvents(e,n);for(const{name:i,event:s}of r)if(i==="mediaStatusChanged")kt(t,a=>a.__wePushMedia?.({op:"status",enabled:!!s.enabled}));else if(i==="mediaPropertiesChanged")kt(t,a=>a.__wePushMedia?.({op:"properties",title:s.title??"",artist:s.artist??"",album:s.album??"",albumArtist:s.albumArtist??""}));else if(i==="mediaThumbnailChanged"){const a=z1(n);kt(t,o=>o.__wePushMedia?.({op:"thumbnail",thumbnail:a,hasThumbnail:!!s.hasThumbnail||!!a,primaryColor:Dr(s.primaryColor),secondaryColor:Dr(s.secondaryColor),tertiaryColor:Dr(s.tertiaryColor),textColor:Dr(s.textColor),highContrastColor:Dr(s.highContrastColor)}))}else i==="mediaPlaybackChanged"?kt(t,a=>a.__wePushMedia?.({op:"playback",state:Number(s.state)||0})):i==="mediaTimelineChanged"&&kt(t,a=>a.__wePushMedia?.({op:"timeline",position:Number(s.position)||0,duration:Number(s.duration)||0}));return Se.cloneMediaSnapshot(n)}function ch(t,e,n,r={driver:null}){if(!e)return;const i=_1(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),S1);if(!(l-o<h*.85)){o=l;try{const p=s();p.tick?.(l);const m=p.snapshot(),g=A1(k1,m.left,m.right);kt(t,w=>w.__wePushAudio?.(g)),n&&l-n.last>200&&er(t,l)}catch{}}};a=requestAnimationFrame(c);const u=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(a);try{u?.()}catch{}}}function lh(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=V1(t,i,u.snapshot)}catch{}}};r=requestAnimationFrame(a);const o=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(r);try{o?.()}catch{}}}function W1(t){t.sceneCtl={pause(){t.paused=!0,kt(t,e=>e.__weSetPaused?.(!0))},resume(){t.paused=!1,kt(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,kt(t,r=>r.__weApplyProps?.(e))}}}function j1(t){try{return new URL(t,location.href).origin===location.origin}catch{return!1}}function q1(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 X1(t){try{const e=new URL("project.json",new URL(t,location.href)),n=await fetch(e.href,{credentials:"same-origin"});return n.ok?q1(await n.json()):{}}catch{return{}}}function G1(t,e){const n={...t};if(e)for(const[r,i]of Object.entries(e))n[r]={value:i};return n}function $1(t,e){Jn(t),t.cfg=e;const n=C1(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}W1(t);const i=e,s=i._webAudio===null||t.audioDisabled?null:i._webAudio??P1(),a=i._webMedia===null||t.mediaDisabled?null:i._webMedia??H1(),o=f=>{ce(t,e,`\u7F51\u9875\u58C1\u7EB8 shim \u6CE8\u5165\u5931\u8D25\uFF08${f}\uFF09\uFF0C\u9000\u56DE\u88F8 iframe`),Vc(t,e,n,r,{injected:!1}),ch(t,null),lh(t,null);let d=0;const h=p=>{t.iframe&&(d=requestAnimationFrame(h),!t.paused&&er(t,p))};d=requestAnimationFrame(h),(t.wallpaperDisposers??=[]).push(()=>cancelAnimationFrame(d))},c={last:0},u={driver:null},l=()=>{if(ch(t,s,c,u),lh(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 ih({origin:location.origin});if(f.dead){try{d.dispose()}catch{}return}f.handle=d;const h=d.status();h.audio==="mic"?(u.driver=E1(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 X1(r),d=G1(f,t.liveUserProps);if(t.liveUserProps=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.value])),j1(r)){Vc(t,e,n,r,{injected:!0,frameClock:c}),l(),t.iframe?.addEventListener("load",()=>{let p=!1;kt(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(y1(p)){o("CSP \u963B\u6B62 inline script");return}const m=b1(p,w1,{baseHref:g1(r),seedScript:I1(d,e.sceneFps,e.muted===!1?1:0)}),g=new Blob([m],{type:"text/html;charset=utf-8"}),w=URL.createObjectURL(g);Vc(t,e,n,w,{blobUrl:w,injected:!0,frameClock:c}),l()}catch(h){o(h instanceof Error?h.message:String(h))}})()}function Wc(t,e){const n=String(e.type??"").toLowerCase();e={...e,type:n},t.cfg=e,(n==="video"||n==="gif"||n==="image")&&e.src?Db(t,e):n==="scene"&&(e.source||e.src)?m1(t,e):n==="web"&&e.src?$1(t,e):t.onUnhandledType?.(e)}class Xn{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 Xn(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new Xn(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return typeof e=="number"?new Xn(this.x*e,this.y*e,this.z*e):new Xn(this.x*e.x,this.y*e.y,this.z*e.z)}toString(){return`${this.x} ${this.y} ${this.z}`}}function sn(t,e,n){if(t instanceof Xn)return t;if(Array.isArray(t))return new Xn(t[0]??0,t[1]??0,t[2]??0);if(typeof t=="object"&&t!==null){const r=t;return new Xn(r.x??0,r.y??0,r.z??0)}return new Xn(t,e??0,n??0)}const Q1=[.35,.38,.45],Y1=[.12,.13,.17],K1=[.72,.76,.84],uh=[.95,.96,.98];function Z1(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 fh(t){const e=Number(t.position)||0,n=Array.isArray(t.lyrics)?t.lyrics:[],{line:r,index:i}=Z1(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:sn(t.primaryColor??Q1),secondaryColor:sn(t.secondaryColor??Y1),tertiaryColor:sn(t.tertiaryColor??K1),textColor:sn(t.textColor??uh),highContrastColor:sn(t.highContrastColor??t.textColor??uh),trackIndex:Number(t.trackIndex)||0,lyrics:n,lyricLine:r,lyricIndex:i}}function J1(t={},e={}){let n={...t},r=fh(n);return{get snapshot(){return r},set(i){n={...n,...i},r=fh(n)},update(){},skipNext:e.skipNext,skipPrevious:e.skipPrevious,play:e.play,pause:e.pause,playPause:e.playPause}}function ew(t){return t==="fit"?"contain":t==="fill"?"cover":t==="contain"||t==="stretch"?t:"cover"}function tw(t){const e=t?.type;return typeof e=="string"&&e.toLowerCase()==="web"}const jc=new Set(["video","gif","image"]);function nw(t){const e=t?.type;if(typeof e!="string")return null;const n=e.toLowerCase();return jc.has(n)?n:null}function Ca(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 dh(t,e){const n={fit:ew(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(tw(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=nw(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=jc.has(String(c).toLowerCase())?String(c).toLowerCase():i,l=u==="video"?t:Ca(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=(jc.has(String(c).toLowerCase())?String(c).toLowerCase():null)??(o?zc(o):null);if(o&&u){const l=u==="video"?t:Ca(t);return{...n,type:u,src:o,canvas:l,source:e.source}}}const a=Ca(t);return{...n,type:"scene",canvas:a,source:e.source}}function hh(t,e){const n=_h(),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(Jn(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=Ca(t,!1);m!==n.cfg.canvas&&(n.cfg={...n.cfg,canvas:m},s=m)}Wc(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,Jc(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,Va(n),n.webRelayout?.();const m=Ha(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,kt(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),kt(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:sn(0,0,0),secondaryColor:sn(0,0,0),tertiaryColor:sn(0,0,0),textColor:sn(1,1,1),highContrastColor:sn(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 dh(s,i);g.type!=="web"&&g.canvas instanceof HTMLCanvasElement&&(s=g.canvas),n.cfg=g,n.paused=!1,n.info=void 0,Va(n),i.properties&&(n.liveUserProps={...i.properties});const w=u(),y=l();Wc(n,g);try{await Promise.race([w,y.promise])}finally{y.off()}},release(){Jn(n)},restore(){f()},destroy(p){Eh(n),p?.releasePkgCache&&d1(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 Ih(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 dh(t,p);m.type!=="web"&&m.canvas instanceof HTMLCanvasElement&&(s=m.canvas),n.cfg=m,n.paused=!1,n.info=void 0,Va(n),p.properties&&Object.keys(p.properties).length&&(n.liveUserProps={...p.properties});const g=u(),w=l();Wc(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 rw(t,e){const n=hh(t,e);return await n.__applyOptions(e),n}It.bytesSource=jb,It.createMediaSource=J1,It.createScene=hh,It.fileSource=Wb,It.httpSource=Zd,It.mediaColor=sn,It.mediaSource=qb,It.mount=rw,It.sniffMediaType=zc,Object.defineProperty(It,Symbol.toStringTag,{value:"Module"})});
|
|
2203
|
+
`;function Ht(t,e){try{const n=t.iframe?.contentWindow;n&&e(n)}catch{}}function y2(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 b2=new Float32Array(128);function w2(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 v2=1.8,A2=1.8,x2=30;function up(t){const e=Number(t)||0;return e<=0?0:Math.min(1,Math.pow(e,A2)*v2)}function k2(){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 T2(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 S2(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 P2(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?(ye(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 _2(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 E2(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=Br(t.cfg.fit)==="cover";i();const g=m&&h>0&&p>0?N2(f):null,y=g?D2(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,ye(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 M2(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 C2(t,e,n){const r=(i,s)=>{if(!e.isConnected)return null;const a=n.getBoundingClientRect(),o=e.getBoundingClientRect();return M2(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),E2(t,s,n),i.injected&&C2(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),Dr(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||y2(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?.(Ko(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 I2=.005,R2=.01,B2=.2,F2=6;function D2(t,e,n){if(!(t>0)||!(e>0)||!(n>0))return null;const r=t/e;if(Math.abs(r-n)<=I2)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 N2(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*R2)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<B2||u>F2))return{contentAspect:u}}return null}function wi(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 L2(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,wi(i)),a.addColorStop(1,wi(s)),r.fillStyle=a,r.fillRect(0,0,64,64),n.toDataURL("image/jpeg",.85)}catch{return""}}function U2(){return We.createSimulatedMedia()}function O2(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=L2(n);Ht(t,o=>o.__wePushMedia?.({op:"thumbnail",thumbnail:a,hasThumbnail:!!s.hasThumbnail||!!a,primaryColor:wi(s.primaryColor),secondaryColor:wi(s.secondaryColor),tertiaryColor:wi(s.tertiaryColor),textColor:wi(s.textColor),highContrastColor:wi(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=T2(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),x2);if(!(l-o<h*.85)){o=l;try{const p=s();p.tick?.(l);const m=p.snapshot(),g=w2(b2,m.left,m.right);Ht(t,y=>y.__wePushAudio?.(g)),n&&l-n.last>200&&Dr(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=O2(t,i,u.snapshot)}catch{}}};r=requestAnimationFrame(a);const o=t.sceneCleanup;t.sceneCleanup=()=>{cancelAnimationFrame(r);try{o?.()}catch{}}}function z2(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 H2(t){try{return new URL(t,location.href).origin===location.origin}catch{return!1}}function V2(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 W2(t){try{const e=new URL("project.json",new URL(t,location.href)),n=await fetch(e.href,{credentials:"same-origin"});return n.ok?V2(await n.json()):{}}catch{return{}}}function j2(t,e){const n={...t};if(e)for(const[r,i]of Object.entries(e))n[r]={value:i};return n}function q2(t,e){Fr(t),t.cfg=e;const n=P2(t,e);if(!n){ye(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){ye(t,e,"\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"),t.onError?.(new Error("\u7F51\u9875\u58C1\u7EB8\uFF1A\u7F3A\u5C11 src"));return}z2(t);const i=e,s=i._webAudio===null||t.audioDisabled?null:i._webAudio??k2(),a=i._webMedia===null||t.mediaDisabled?null:i._webMedia??U2(),o=d=>{ye(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&&Dr(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=S2(f),ye(t,e,"liveSystem: \u7F51\u9875\u58C1\u7EB8\u97F3\u9891\u6539\u7528\u9EA6\u514B\u98CE")):ye(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){ye(t,e,`liveSystem: \u542F\u52A8\u5931\u8D25\uFF0C\u7F51\u9875\u58C1\u7EB8\u6CBF\u7528\u6A21\u62DF\u6E90 (${f?.message??f})`)}})()}};(async()=>{const d=await W2(r),f=j2(d,t.liveUserProps);if(t.liveUserProps=Object.fromEntries(Object.entries(f).map(([h,p])=>[h,p.value])),H2(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||ye(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(m2(p)){o("CSP \u963B\u6B62 inline script");return}const m=p2(p,g2,{baseHref:h2(r),seedScript:_2(f,e.sceneFps,Ko(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?hA(t,e):n==="scene"&&(e.source||e.src)?f2(t,e):n==="web"&&e.src?q2(t,e):t.onUnhandledType?.(e)}class kr{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 kr(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new kr(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return typeof e=="number"?new kr(this.x*e,this.y*e,this.z*e):new kr(this.x*e.x,this.y*e.y,this.z*e.z)}toString(){return`${this.x} ${this.y} ${this.z}`}}function In(t,e,n){if(t instanceof kr)return t;if(Array.isArray(t))return new kr(t[0]??0,t[1]??0,t[2]??0);if(typeof t=="object"&&t!==null){const r=t;return new kr(r.x??0,r.y??0,r.z??0)}return new kr(t,e??0,n??0)}const X2=[.35,.38,.45],$2=[.12,.13,.17],G2=[.72,.76,.84],hp=[.95,.96,.98];function Q2(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}=Q2(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:In(t.primaryColor??X2),secondaryColor:In(t.secondaryColor??$2),tertiaryColor:In(t.tertiaryColor??G2),textColor:In(t.textColor??hp),highContrastColor:In(t.highContrastColor??t.textColor??hp),trackIndex:Number(t.trackIndex)||0,lyrics:n,lyricLine:r,lyricIndex:i}}function Y2(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 K2(t){const e=t?.type;return typeof e=="string"&&e.toLowerCase()==="web"}const yu=new Set(["video","gif","image"]);function Z2(t){const e=t?.type;if(typeof e!="string")return null;const n=e.toLowerCase();return yu.has(n)?n:null}function Io(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:Br(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(K2(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=Z2(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:Io(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:Io(t);return{...n,type:l,src:c,canvas:d,source:e.source}}}const a=Io(t),o=cu(e.source.key);return{...n,type:"scene",canvas:a,source:e.source,...o?{src:o}:{}}}function gp(t,e){const n=jp(),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(Fr(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=Io(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,Zo(n),n.webRelayout?.();const m=Yo(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={...aa(i.quality??n.cfg.quality),...p??{}};i={...i,quality:m},n.cfg.quality=m,n.sceneCtl?.setQuality?.(p??{})},getQuality(){return aa(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:In(0,0,0),secondaryColor:In(0,0,0),tertiaryColor:In(0,0,0),textColor:In(1,1,1),highContrastColor:In(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,Zo(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(){Fr(n)},restore(){d()},destroy(p){qp(n),p?.releasePkgCache&&l2(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 $p(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,Zo(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 J2(t,e){const n=gp(t,e);return await n.__applyOptions(e),n}Vt.bytesSource=xA,Vt.createMediaSource=Y2,Vt.createScene=gp,Vt.fileSource=AA,Vt.httpSource=Ym,Vt.mediaColor=In,Vt.mediaSource=kA,Vt.mount=J2,Vt.sniffMediaType=lu,Vt.workshopIdFromSourceKey=cu,Object.defineProperty(Vt,Symbol.toStringTag,{value:"Module"})});
|
|
2068
2205
|
|
|
2069
2206
|
//# sourceMappingURL=webwallgl.global.min.js.map
|