vuer 0.0.40__py3-none-any.whl → 0.0.42rc1__py3-none-any.whl
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.
Potentially problematic release.
This version of vuer might be problematic. Click here for more details.
- vuer/__pycache__/types.cpython-38.pyc +0 -0
- vuer/client_build/404.html +1 -1
- vuer/client_build/assets/chunks/chunk-B0wKlVcO.js +269 -0
- vuer/client_build/assets/chunks/chunk-B0wKlVcO.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-C5hUn4Av.js +7724 -0
- vuer/client_build/assets/chunks/chunk-C5hUn4Av.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-CdlMBVEj.js +102 -0
- vuer/client_build/assets/chunks/chunk-CdlMBVEj.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-Cl9s_LKx.js +4660 -0
- vuer/client_build/assets/chunks/chunk-Cl9s_LKx.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-GQfId1da.js +3 -0
- vuer/client_build/assets/chunks/chunk-GQfId1da.js.map +1 -0
- vuer/client_build/assets/entries/entry-client-routing.CByy54Oc.js +5 -0
- vuer/client_build/assets/entries/entry-client-routing.CByy54Oc.js.map +1 -0
- vuer/client_build/assets/entries/entry-client-routing.DigTvBcB.js +5 -0
- vuer/client_build/assets/entries/entry-client-routing.DigTvBcB.js.map +1 -0
- vuer/client_build/assets/entries/pages_editor.BbTGXxse.js +2 -0
- vuer/client_build/assets/entries/pages_editor.BbTGXxse.js.map +1 -0
- vuer/client_build/assets/entries/pages_editor.DFf94zHo.js +2 -0
- vuer/client_build/assets/entries/pages_editor.DFf94zHo.js.map +1 -0
- vuer/client_build/assets/entries/pages_index.DR3iYtUX.js +2 -0
- vuer/client_build/assets/entries/pages_index.DR3iYtUX.js.map +1 -0
- vuer/client_build/assets/entries/pages_simple.CICNNOAI.js +2 -0
- vuer/client_build/assets/entries/pages_simple.CICNNOAI.js.map +1 -0
- vuer/client_build/editor/index.html +4 -4
- vuer/client_build/editor.html +18 -0
- vuer/client_build/index.html +4 -4
- vuer/client_build/simple/index.html +3 -3
- vuer/schemas/__pycache__/__init__.cpython-38.pyc +0 -0
- vuer/schemas/__pycache__/drei_components.cpython-38.pyc +0 -0
- vuer/schemas/__pycache__/html_components.cpython-38.pyc +0 -0
- vuer/schemas/__pycache__/physics_components.cpython-38.pyc +0 -0
- vuer/schemas/__pycache__/scene_components.cpython-38.pyc +0 -0
- vuer/schemas/__pycache__/vuer_components.cpython-38.pyc +0 -0
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/METADATA +1 -1
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/RECORD +40 -11
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/LICENSE +0 -0
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/WHEEL +0 -0
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/entry_points.txt +0 -0
- {vuer-0.0.40.dist-info → vuer-0.0.42rc1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import{f as mn,g as P,i as Qe,j as xu,u as $,k as vu,l as Ie,m as he,o as be,p as Vi,C as we,s as vt,E as Zt,S as Po,t as Ue,v as bl,T as Zf,w as ko,x as Oo,y as le,B as pi,G as Xe,J as Br,K as ls,U as Ei,X as Ws,Y as Ct,a0 as ms,a1 as mt,a2 as Wt,a3 as ie,a4 as Ce,a5 as ps,a6 as Ss,a7 as pn,a8 as Ru,a9 as Kr,aa as Zs,ab as Qo,ac as Tr,ad as Vr,ae as ke,af as st,ag as eg,ah as Sr,ai as ei,aj as ds,ak as wu,al as $a,am as Du,an as Kt,ao as tg,ap as sg,aq as ig,ar as Lu,as as ng,at as ti,au as rg,av as oi,aw as Go,ax as li,ay as ag,az as Yr,aA as bu,aB as Wi,aC as Mu,aD as Ml,aE as og,aF as lg,aG as cg,aH as Fu,aI as Pu,aJ as Xa,aK as ku,aL as ja,aM as hg,aN as ug,aO as dg,aP as Zi,aQ as Ag,aR as fg,aS as gg,aT as mg,aU as ci,aV as pg,aW as Eg,aX as Wa,aY as Za,aZ as eo,a_ as Cg,a$ as Ig,b0 as Jr,b1 as yg,b2 as Bg,b3 as Tg,b4 as Sg,b5 as _g,b6 as xg,b7 as _r,b8 as vg,b9 as Xs,ba as Rg,bb as wg,bc as Dg,bd as Lg,be as bg,bf as Mg,bg as Fg,bh as Pg,bi as kg,bj as St,bk as Yn,bl as Yi,bm as Og,bn as Ni,bo as Hi,bp as Fl,bq as Ou,br as wt,bs as Uo,bt as Qg,bu as No,bv as Gg,bw as Ug,bx as Qu,by as to,bz as Ci,bA as Ng,bB as Gu,bC as Uu,bD as Nu,bE as Hu,bF as Ku,bG as Hg,bH as Kg,bI as Vg,bJ as Vu,bK as Yu,bL as Yg,bM as Pl,bN as Jg,bO as Ho,bP as Ju,bQ as zg,bR as qg,bS as zu,bT as qu,bU as $g,bV as $u,bW as Xg,bX as jg,bY as Wg,bZ as Zg,b_ as em,b$ as tm,c0 as sm,c1 as im,c2 as nm,c3 as rm,c4 as am,c5 as om,c6 as lm,c7 as cm,c8 as hm,c9 as um,ca as dm,cb as Am,cc as fm,cd as gm,ce as mm,cf as pm,cg as Em,ch as Cm,ci as Im,cj as ym,ck as Bm,cl as Tm,cm as Sm,cn as _m,co as xm,cp as vm,cq as Rm,cr as wm,cs as Dm,ct as Lm,cu as bm,cv as Mm,cw as Fm,cx as Pm,cy as km,cz as Om,cA as Qm,cB as Gm,cC as Um,cD as Nm,cE as Hm,cF as Km,cG as Vm,cH as Ym,cI as Jm,cJ as zm,cK as qm,cL as $m,cM as Xm,cN as jm,cO as Wm,cP as Zm,cQ as ep,cR as tp,cS as sp,cT as ip,cU as np,cV as rp,cW as ap,cX as op,cY as lp,cZ as cp,c_ as hp,c$ as up,d0 as dp,d1 as Ap,d2 as fp,d3 as gp,d4 as mp,d5 as pp,d6 as Ep,d7 as Cp,d8 as Ip,d9 as yp,da as Bp,db as Tp,dc as Sp,dd as _p,de as xp,df as vp,dg as Rp,dh as wp,di as Dp,dj as Lp,dk as bp,dl as Mp,dm as Fp,dn as Pp,dp as kp,dq as Op,dr as Qp,ds as Gp,dt as Up,du as Np,dv as Hp,dw as Kp,dx as Vp,dy as Yp,dz as Jp,dA as zp,dB as qp,dC as $p,dD as Xp,dE as jp,dF as Wp,dG as Zp,dH as eE,dI as tE,dJ as sE,dK as iE,dL as nE,dM as rE,dN as aE,dO as oE,dP as lE,dQ as cE,dR as hE,dS as uE,dT as dE,dU as AE,dV as fE,dW as gE,dX as mE,dY as pE,dZ as EE,d_ as CE,d$ as IE,e0 as yE,e1 as BE,e2 as TE,e3 as SE,e4 as _E,e5 as xE,e6 as vE,e7 as RE,e8 as wE,e9 as DE,ea as LE,eb as bE,ec as ME,ed as FE,ee as PE,ef as kE,eg as Ko,eh as Vo,ei as xr,ej as Yo,ek as OE,el as QE,em as GE,en as UE,eo as NE,ep as HE,eq as KE,er as VE,es as YE,et as JE,eu as zE,ev as qE,ew as $E,ex as XE,ey as jE,ez as WE,eA as ZE,eB as e0,eC as t0,eD as s0,eE as i0,eF as n0,eG as r0,eH as a0,eI as o0,eJ as l0,eK as c0,eL as h0,eM as u0,eN as d0,eO as A0,eP as f0,eQ as g0,eR as m0,eS as p0,eT as E0,eU as C0,eV as I0,eW as y0,eX as B0,eY as T0,eZ as S0,e_ as _0,e$ as x0,f0 as v0,f1 as R0,f2 as w0,f3 as D0,f4 as L0,f5 as b0,f6 as M0,f7 as F0,f8 as P0,f9 as k0,fa as O0,fb as Q0,fc as G0,fd as U0,fe as N0,ff as H0,fg as K0,fh as V0,fi as Y0,fj as J0,fk as z0,fl as q0,fm as $0,fn as X0,fo as j0,fp as W0,fq as Z0,fr as eC,fs as tC,ft as sC,fu as iC,fv as nC,fw as rC,fx as aC,fy as oC,fz as lC,fA as cC,fB as hC}from"./chunk-C5hUn4Av.js";import{r as T,o as kl,e as uC,f as dC,g as AC,j as ts}from"./chunk-11bBwnOQ.js";import{_ as fC}from"./chunk-D7HrI6pR.js";function gC(n,e="pointer",t="auto",s=document.body){T.useEffect(()=>{if(n)return s.style.cursor=e,()=>void(s.style.cursor=t)},[n])}const Ol=n=>{let e;const t=new Set,s=(c,h)=>{const u=typeof c=="function"?c(e):c;if(!Object.is(u,e)){const d=e;e=h??(typeof u!="object"||u===null)?u:Object.assign({},e,u),t.forEach(A=>A(e,d))}},i=()=>e,o={setState:s,getState:i,getInitialState:()=>l,subscribe:c=>(t.add(c),()=>t.delete(c))},l=e=n(s,i,o);return o},mC=n=>n?Ol(n):Ol,pC=n=>n;function EC(n,e=pC){const t=kl.useSyncExternalStore(n.subscribe,()=>e(n.getState()),()=>e(n.getInitialState()));return kl.useDebugValue(t),t}const Ql=n=>{const e=mC(n),t=s=>EC(e,s);return Object.assign(t,e),t},Xu=n=>n?Ql(n):Ql;let yi=0;const Jo=Xu(n=>(mn.onStart=(e,t,s)=>{n({active:!0,item:e,loaded:t,total:s,progress:(t-yi)/(s-yi)*100})},mn.onLoad=()=>{n({active:!1})},mn.onError=e=>n(t=>({errors:[...t.errors,e]})),mn.onProgress=(e,t,s)=>{t===s&&(yi=s),n({active:!0,item:e,loaded:t,total:s,progress:(t-yi)/(s-yi)*100||100})},{errors:[],active:!1,progress:0,item:"",loaded:0,total:0}));function CC({children:n}){const e=Jo();return T.createElement(T.Fragment,null,n==null?void 0:n(e))}const IC=n=>`Loading ${n.toFixed(2)}%`;function yC({containerStyles:n,innerStyles:e,barStyles:t,dataStyles:s,dataInterpolation:i=IC,initialState:r=a=>a}){const{active:a,progress:o}=Jo(),l=T.useRef(0),c=T.useRef(0),h=T.useRef(null),[u,d]=T.useState(r(a));T.useEffect(()=>{let f;return a!==u&&(f=setTimeout(()=>d(a),300)),()=>clearTimeout(f)},[u,a]);const A=T.useCallback(()=>{h.current&&(l.current+=(o-l.current)/2,(l.current>.95*o||o===100)&&(l.current=o),h.current.innerText=i(l.current),l.current<o&&(c.current=requestAnimationFrame(A)))},[i,o]);return T.useEffect(()=>(A(),()=>cancelAnimationFrame(c.current)),[A]),u?T.createElement("div",{style:{...En.container,opacity:a?1:0,...n}},T.createElement("div",null,T.createElement("div",{style:{...En.inner,...e}},T.createElement("div",{style:{...En.bar,transform:`scaleX(${o/100})`,...t}}),T.createElement("span",{ref:h,style:{...En.data,...s}})))):null}const En={container:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"#171717",display:"flex",alignItems:"center",justifyContent:"center",transition:"opacity 300ms ease",zIndex:1e3},inner:{width:100,height:3,background:"#272727",textAlign:"center"},bar:{height:3,width:"100%",background:"white",transition:"transform 200ms",transformOrigin:"left center"},data:{display:"inline-block",position:"relative",fontVariantNumeric:"tabular-nums",marginTop:"0.8em",color:"#f0f0f0",fontSize:"0.6em",fontFamily:'-apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Helvetica Neue", Helvetica, Arial, Roboto, Ubuntu, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',whiteSpace:"nowrap"}},zr=new P,Gl=new Qe,Es=new P,Cn=new P,Bi=new P,Ul=new xu,BC=T.forwardRef(({autoTransform:n=!0,matrix:e,axisLock:t,dragLimits:s,onHover:i,onDragStart:r,onDrag:a,onDragEnd:o,children:l,dragConfig:c,...h},u)=>{const d=$(E=>E.controls),{camera:A,size:f,raycaster:g,invalidate:p}=$(),m=T.useRef(null),C=vu({onHover:({hovering:E})=>i&&i(E??!1),onDragStart:({event:E})=>{d&&(d.enabled=!1);const{point:B}=E;m.current.matrix.decompose(zr,new Ie,new P),Es.copy(B),Cn.copy(Es).sub(zr),r&&r(zr),p()},onDrag:({xy:[E,B],intentional:I})=>{if(!I)return;const _=(E-f.left)/f.width*2-1,S=-((B-f.top)/f.height)*2+1;if(Gl.set(_,S),g.setFromCamera(Gl,A),!t)A.getWorldDirection(Bi).negate();else switch(t){case"x":Bi.set(1,0,0);break;case"y":Bi.set(0,1,0);break;case"z":Bi.set(0,0,1);break}Ul.setFromNormalAndCoplanarPoint(Bi,Es),g.ray.intersectPlane(Ul,Es);const x=m.current.matrix.clone(),b=m.current.matrixWorld.clone(),v=new P(Es.x-Cn.x,Es.y-Cn.y,Es.z-Cn.z);if(s&&(v.x=s[0]?Math.max(Math.min(v.x,s[0][1]),s[0][0]):v.x,v.y=s[1]?Math.max(Math.min(v.y,s[1][1]),s[1][0]):v.y,v.z=s[2]?Math.max(Math.min(v.z,s[2][1]),s[2][0]):v.z),n){m.current.matrix.setPosition(v);const D=m.current.matrix.clone().multiply(x.invert()),U=m.current.matrix.clone().multiply(b.invert());a&&a(m.current.matrix,D,m.current.matrixWorld,U)}else{const D=new he().copy(m.current.matrix);D.setPosition(v);const U=D.clone().multiply(x.invert()),Q=D.clone().multiply(b.invert());a&&a(D,U,m.current.matrixWorld,Q)}p()},onDragEnd:()=>{d&&(d.enabled=!0),o&&o(),p()}},{drag:{filterTaps:!0,threshold:1,...typeof c=="object"?c:{}}});return T.useImperativeHandle(u,()=>m.current,[]),T.useLayoutEffect(()=>{e&&(m.current.matrix=e)},[e]),T.createElement("group",be({ref:m},C(),{matrix:e,matrixAutoUpdate:!1},h),l)});function Ji(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function so(n,e){return so=Object.setPrototypeOf||function(s,i){return s.__proto__=i,s},so(n,e)}function TC(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function SC(){for(var n=arguments.length,e=new Array(n),t=0;t<n;t++)e[t]=arguments[t];var s=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=e[5],c=e[6],h=e[7],u=e[8];return s*o*u+i*l*c+r*a*h-r*o*c-i*a*u-s*l*h}function Nl(n,e){for(var t=[],s=n.toArray(),i=e.toArray(),r=0;r<s.length;r++)t[r]=s[r]+i[r];return new Vi().fromArray(t)}function _C(n){if(Array.isArray(n))return n}function xC(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var s=[],i=!0,r=!1,a,o;try{for(t=t.call(n);!(i=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));i=!0);}catch(l){r=!0,o=l}finally{try{!i&&t.return!=null&&t.return()}finally{if(r)throw o}}return s}}function io(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=n[t];return s}function ju(n,e){if(n){if(typeof n=="string")return io(n,e);var t=Object.prototype.toString.call(n).slice(8,-1);if(t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set")return Array.from(n);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return io(n,e)}}function vC(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ut(n,e){return _C(n)||xC(n,e)||ju(n,e)||vC()}function RC(n){if(Array.isArray(n))return io(n)}function wC(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function DC(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
3
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sr(n){return RC(n)||wC(n)||ju(n)||DC()}function Jn(n,e,t){return TC()?Jn=Reflect.construct:Jn=function(i,r,a){var o=[null];o.push.apply(o,r);var l=Function.bind.apply(i,o),c=new l;return a&&so(c,a.prototype),c},Jn.apply(null,arguments)}function LC(n){var e=Ut(n[0],2),t=e[0],s=e[1],i=Ut(n[1],2),r=i[0],a=i[1],o=Ut(n[2],2),l=o[0],c=o[1];return SC(t,s,1,r,a,1,l,c,1)}function bC(n){return LC(n)===0}var MC=new Qe,FC=new Qe;function Hl(n){var e=n.map(function(c){return Array.isArray(c)?Jn(Qe,sr(c)):c}),t=Ut(e,3),s=t[0],i=t[1],r=t[2];if(bC(n))return!1;var a=MC.subVectors(i,s),o=FC.subVectors(r,s),l=o.cross(a);return l>0}function Wu(n,e,t){return Math.max(e,Math.min(t,n))}function Zu(n,e){return Wu(n-Math.floor(n/e)*e,0,e)}function ed(n,e){var t=Zu(e-n,Math.PI*2);return t>Math.PI&&(t-=Math.PI*2),t}function PC(n){return n/180*Math.PI}function kC(n){return n*180/Math.PI}function OC(n,e){for(var t=e.radius,s=t===void 0?1:t,i=n.length/3,r=2/i,a=Math.PI*(3-2.2360679775),o=0;o<n.length;o+=3){var l=o*r-1+r/2,c=Math.sqrt(1-Math.pow(l,2)),h=o%i*a,u=Math.cos(h)*c,d=Math.sin(h)*c;n[o]=u*s,n[o+1]=l*s,n[o+2]=d*s}}function QC(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Number.EPSILON;return Math.abs(n.x-e.x)<t&&Math.abs(n.y-e.y)<t&&Math.abs(n.z-e.z)<t}function td(n,e){return n.x===e.x?typeof n.z<"u"&&n.y===e.y?n.z-e.z:n.y-e.y:n.x-e.x}function GC(n){for(var e=n.sort(td),t=[e[0],e[1]],s=2;s<e.length;s++)for(t.push(e[s]);t.length>2&&Hl(sr(t.slice(-3)));)t.splice(t.length-2,1);for(var i=[e[e.length-1],e[e.length-2]],r=e.length-3;r>=0;r--)for(i.push(e[r]);i.length>2&&Hl(sr(i.slice(-3)));)i.splice(i.length-2,1);i.splice(0,1),i.splice(i.length-1,1);var a=[].concat(t,i);return a}function UC(n,e,t){var s=Ut(e,2),i=s[0],r=s[1],a=Ut(t,2),o=a[0],l=a[1];return o+(n-i)*(l-o)/(r-i)}function NC(n){return n*n*n*(n*(n*6-15)+10)}function HC(n,e,t){return n*(1-t)+e*t}function sd(n,e,t){return(t-n)/(e-n)}function KC(n,e,t){var s=Math.sqrt(n*n+e*e+t*t);return[n/s,e/s,t/s]}function VC(n,e,t){var s=n*n,i=e*e,r=t*t,a=n*Math.sqrt(1-(i+r)/2+i*r/3),o=e*Math.sqrt(1-(r+s)/2+r*s/3),l=t*Math.sqrt(1-(s+i)/2+s*i/3);return[a,o,l]}function id(n,e){var t=new P().crossVectors(n,e),s=n.dot(e),i=new Vi().identity(),r=new Vi().set(0,-t.z,t.y,t.z,0,-t.x,-t.y,t.x,0),a=new Vi().multiplyMatrices(r,r).multiplyScalar(1/(1+s)),o=Nl(Nl(i,r),a);return o}function YC(n,e,t){var s=Math.asin(e),i=Math.atan2(n,-t);return[s,i]}function JC(n,e){var t=Math.sin(n),s=Math.cos(n),i=Math.sin(e)*s,r=-Math.cos(e)*s;return[i,t,r]}function zC(n,e){var t=Ut(e,2),s=t[0],i=t[1],r=id(n.normal,new P(0,1,0)),a=sd(s.clone().applyMatrix3(r).y,i.clone().applyMatrix3(r).y,0);return new P().lerpVectors(s,i,a)}function qC(n,e){var t=e.normal.dot(n);return t}function $C(n,e){var t=Ut(n,3),s=t[0],i=t[1],r=t[2],a=Ut(e,2),o=a[0],l=a[1];return r*o*l+i*o+s}function XC(n,e){var t=Ut(e,2),s=t[0],i=t[1],r=s*i,a=n/r,o=n-r*a,l=o/s,c=o%s;return[c,l,a]}function jC(n,e){return n[0]+e[0]*n[1]}function WC(n,e){var t=n%e,s=Math.floor(n/e);return[t,s]}var qr=Object.freeze({__proto__:null,clamp:Wu,repeat:Zu,deltaAngle:ed,degToRad:PC,radToDeg:kC,fibonacciOnSphere:OC,vectorEquals:QC,lexicographic:td,convexHull:GC,remap:UC,fade:NC,lerp:HC,inverseLerp:sd,normalize:KC,pointOnCubeToPointOnSphere:VC,rotateVectorOnVector:id,pointToCoordinate:YC,coordinateToPoint:JC,planeSegmentIntersection:zC,pointToPlaneDistance:qC,getIndexFrom3D:$C,get3DFromIndex:XC,getIndexFrom2D:jC,get2DFromIndex:WC});function nd(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}var at=function n(e,t,s){var i=this;nd(this,n),Ji(this,"dot2",function(r,a){return i.x*r+i.y*a}),Ji(this,"dot3",function(r,a,o){return i.x*r+i.y*a+i.z*o}),this.x=e,this.y=t,this.z=s},ZC=[new at(1,1,0),new at(-1,1,0),new at(1,-1,0),new at(-1,-1,0),new at(1,0,1),new at(-1,0,1),new at(1,0,-1),new at(-1,0,-1),new at(0,1,1),new at(0,-1,1),new at(0,1,-1),new at(0,-1,-1)],Kl=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],Vl=new Array(512),Yl=new Array(512),eI=function(e){e>0&&e<1&&(e*=65536),e=Math.floor(e),e<256&&(e|=e<<8);for(var t=0;t<256;t++){var s;t&1?s=Kl[t]^e&255:s=Kl[t]^e>>8&255,Vl[t]=Vl[t+256]=s,Yl[t]=Yl[t+256]=ZC[s%12]}};eI(0);function tI(n){if(typeof n=="number")n=Math.abs(n);else if(typeof n=="string"){var e=n;n=0;for(var t=0;t<e.length;t++)n=(n+(t+1)*(e.charCodeAt(t)%96))%2147483647}return n===0&&(n=311),n}function Jl(n){var e=tI(n);return function(){var t=e*48271%2147483647;return e=t,t/2147483647}}var sI=function n(e){var t=this;nd(this,n),Ji(this,"seed",0),Ji(this,"init",function(s){t.seed=s,t.value=Jl(s)}),Ji(this,"value",Jl(this.seed)),this.init(e)};new sI(Math.random());var iI=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return s/Math.atan(1/t)*Math.atan(Math.sin(2*Math.PI*e*i)/t)},rd=function(e){return 1/(1+e+.48*e*e+.235*e*e*e)},nI=function(e){return e},rI={in:function(e){return 1-Math.cos(e*Math.PI/2)},out:function(e){return Math.sin(e*Math.PI/2)},inOut:function(e){return-(Math.cos(Math.PI*e)-1)/2}},aI={in:function(e){return e*e*e},out:function(e){return 1-Math.pow(1-e,3)},inOut:function(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}},oI={in:function(e){return e*e*e*e*e},out:function(e){return 1-Math.pow(1-e,5)},inOut:function(e){return e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2}},lI={in:function(e){return 1-Math.sqrt(1-Math.pow(e,2))},out:function(e){return Math.sqrt(1-Math.pow(e-1,2))},inOut:function(e){return e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2}},cI={in:function(e){return e*e*e*e},out:function(e){return 1- --e*e*e*e},inOut:function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e}},hI={in:function(e){return e===0?0:Math.pow(2,10*e-10)},out:function(e){return e===1?1:1-Math.pow(2,-10*e)},inOut:function(e){return e===0?0:e===1?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2}};function Ye(n,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,r=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:rd,o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,l="velocity_"+e;if(n.__damp===void 0&&(n.__damp={}),n.__damp[l]===void 0&&(n.__damp[l]=0),Math.abs(n[e]-t)<=o)return n[e]=t,!1;s=Math.max(1e-4,s);var c=2/s,h=a(c*i),u=n[e]-t,d=t,A=r*s;u=Math.min(Math.max(u,-A),A),t=n[e]-u;var f=(n.__damp[l]+c*u)*i;n.__damp[l]=(n.__damp[l]-c*f)*h;var g=t+(u+f)*h;return d-n[e]>0==g>d&&(g=d,n.__damp[l]=(g-d)/i),n[e]=g,!0}var uI=function(e){return e&&e.isCamera},dI=function(e){return e&&e.isLight},Ti=new P,zl=new Ie,ql=new Ie,Si=new he,$r=new P;function AI(n,e,t,s,i,r,a){typeof e=="number"?Ti.setScalar(e):Array.isArray(e)?Ti.set(e[0],e[1],e[2]):Ti.copy(e);var o=n.parent;n.updateWorldMatrix(!0,!1),$r.setFromMatrixPosition(n.matrixWorld),uI(n)||dI(n)?Si.lookAt($r,Ti,n.up):Si.lookAt(Ti,$r,n.up),ir(n.quaternion,ql.setFromRotationMatrix(Si),t,s,i,r,a),o&&(Si.extractRotation(o.matrixWorld),zl.setFromRotationMatrix(Si),ir(n.quaternion,ql.copy(n.quaternion).premultiply(zl.invert()),t,s,i,r,a))}function si(n,e,t,s,i,r,a,o){return Ye(n,e,n[e]+ed(n[e],t),s,i,r,a,o)}var _i=new Qe,$l,Xl;function fI(n,e,t,s,i,r,a){return typeof e=="number"?_i.setScalar(e):Array.isArray(e)?_i.set(e[0],e[1]):_i.copy(e),$l=Ye(n,"x",_i.x,t,s,i,r,a),Xl=Ye(n,"y",_i.y,t,s,i,r,a),$l||Xl}var Ms=new P,jl,Wl,Zl;function no(n,e,t,s,i,r,a){return typeof e=="number"?Ms.setScalar(e):Array.isArray(e)?Ms.set(e[0],e[1],e[2]):Ms.copy(e),jl=Ye(n,"x",Ms.x,t,s,i,r,a),Wl=Ye(n,"y",Ms.y,t,s,i,r,a),Zl=Ye(n,"z",Ms.z,t,s,i,r,a),jl||Wl||Zl}var Cs=new vt,ec,tc,sc,ic;function gI(n,e,t,s,i,r,a){return typeof e=="number"?Cs.setScalar(e):Array.isArray(e)?Cs.set(e[0],e[1],e[2],e[3]):Cs.copy(e),ec=Ye(n,"x",Cs.x,t,s,i,r,a),tc=Ye(n,"y",Cs.y,t,s,i,r,a),sc=Ye(n,"z",Cs.z,t,s,i,r,a),ic=Ye(n,"w",Cs.w,t,s,i,r,a),ec||tc||sc||ic}var xi=new Zt,nc,rc,ac;function mI(n,e,t,s,i,r,a){return Array.isArray(e)?xi.set(e[0],e[1],e[2],e[3]):xi.copy(e),nc=si(n,"x",xi.x,t,s,i,r,a),rc=si(n,"y",xi.y,t,s,i,r,a),ac=si(n,"z",xi.z,t,s,i,r,a),nc||rc||ac}var Fs=new we,oc,lc,cc;function pI(n,e,t,s,i,r,a){return e instanceof we?Fs.copy(e):Array.isArray(e)?Fs.setRGB(e[0],e[1],e[2]):Fs.set(e),oc=Ye(n,"r",Fs.r,t,s,i,r,a),lc=Ye(n,"g",Fs.g,t,s,i,r,a),cc=Ye(n,"b",Fs.b,t,s,i,r,a),oc||lc||cc}var It=new Ie,Vt=new vt,hc=new vt,vi=new vt,uc,dc,Ac,fc;function ir(n,e,t,s,i,r,a){var o=n;Array.isArray(e)?It.set(e[0],e[1],e[2],e[3]):It.copy(e);var l=n.dot(It)>0?1:-1;return It.x*=l,It.y*=l,It.z*=l,It.w*=l,uc=Ye(n,"x",It.x,t,s,i,r,a),dc=Ye(n,"y",It.y,t,s,i,r,a),Ac=Ye(n,"z",It.z,t,s,i,r,a),fc=Ye(n,"w",It.w,t,s,i,r,a),Vt.set(n.x,n.y,n.z,n.w).normalize(),hc.set(o.__damp.velocity_x,o.__damp.velocity_y,o.__damp.velocity_z,o.__damp.velocity_w),vi.copy(Vt).multiplyScalar(hc.dot(Vt)/Vt.dot(Vt)),o.__damp.velocity_x-=vi.x,o.__damp.velocity_y-=vi.y,o.__damp.velocity_z-=vi.z,o.__damp.velocity_w-=vi.w,n.set(Vt.x,Vt.y,Vt.z,Vt.w),uc||dc||Ac||fc}var Ri=new Po,gc,mc,pc;function EI(n,e,t,s,i,r,a){return Array.isArray(e)?Ri.set(e[0],e[1],e[2]):Ri.copy(e),gc=Ye(n,"radius",Ri.radius,t,s,i,r,a),mc=si(n,"phi",Ri.phi,t,s,i,r,a),pc=si(n,"theta",Ri.theta,t,s,i,r,a),gc||mc||pc}var In=new he,Ec=new P,Cc=new Ie,Ic=new P,yc,Bc,Tc;function CI(n,e,t,s,i,r,a){var o=n;return o.__damp===void 0&&(o.__damp={position:new P,rotation:new Ie,scale:new P},n.decompose(o.__damp.position,o.__damp.rotation,o.__damp.scale)),Array.isArray(e)?In.set.apply(In,sr(e)):In.copy(e),In.decompose(Ec,Cc,Ic),yc=no(o.__damp.position,Ec,t,s,i,r,a),Bc=ir(o.__damp.rotation,Cc,t,s,i,r,a),Tc=no(o.__damp.scale,Ic,t,s,i,r,a),n.compose(o.__damp.position,o.__damp.rotation,o.__damp.scale),yc||Bc||Tc}var hi=Object.freeze({__proto__:null,rsqw:iI,exp:rd,linear:nI,sine:rI,cubic:aI,quint:oI,circ:lI,quart:cI,expo:hI,damp:Ye,dampLookAt:AI,dampAngle:si,damp2:fI,damp3:no,damp4:gI,dampE:mI,dampC:pI,dampQ:ir,dampS:EI,dampM:CI});const zo=T.createContext(null);function qo(){return T.useContext(zo)}function II({eps:n=1e-5,enabled:e=!0,infinite:t,horizontal:s,pages:i=1,distance:r=1,damping:a=.25,maxSpeed:o=1/0,prepend:l=!1,style:c={},children:h}){const{get:u,setEvents:d,gl:A,size:f,invalidate:g,events:p}=$(),[m]=T.useState(()=>document.createElement("div")),[C]=T.useState(()=>document.createElement("div")),[E]=T.useState(()=>document.createElement("div")),B=A.domElement.parentNode,I=T.useRef(0),_=T.useMemo(()=>({el:m,eps:n,fill:C,fixed:E,horizontal:s,damping:a,offset:0,delta:0,scroll:I,pages:i,range(b,v,D=0){const U=b-D,Q=U+v+D*2;return this.offset<U?0:this.offset>Q?1:(this.offset-U)/(Q-U)},curve(b,v,D=0){return Math.sin(this.range(b,v,D)*Math.PI)},visible(b,v,D=0){const U=b-D,Q=U+v+D*2;return this.offset>=U&&this.offset<=Q}}),[n,a,s,i]);T.useEffect(()=>{m.style.position="absolute",m.style.width="100%",m.style.height="100%",m.style[s?"overflowX":"overflowY"]="auto",m.style[s?"overflowY":"overflowX"]="hidden",m.style.top="0px",m.style.left="0px";for(const v in c)m.style[v]=c[v];E.style.position="sticky",E.style.top="0px",E.style.left="0px",E.style.width="100%",E.style.height="100%",E.style.overflow="hidden",m.appendChild(E),C.style.height=s?"100%":`${i*r*100}%`,C.style.width=s?`${i*r*100}%`:"100%",C.style.pointerEvents="none",m.appendChild(C),l?B.prepend(m):B.appendChild(m),m[s?"scrollLeft":"scrollTop"]=1;const x=p.connected||A.domElement;requestAnimationFrame(()=>p.connect==null?void 0:p.connect(m));const b=u().events.compute;return d({compute(v,D){const{left:U,top:Q}=B.getBoundingClientRect(),j=v.clientX-U,V=v.clientY-Q;D.pointer.set(j/D.size.width*2-1,-(V/D.size.height)*2+1),D.raycaster.setFromCamera(D.pointer,D.camera)}}),()=>{B.removeChild(m),d({compute:b}),p.connect==null||p.connect(x)}},[i,r,s,m,C,E,B]),T.useEffect(()=>{if(p.connected===m){const x=f[s?"width":"height"],b=m[s?"scrollWidth":"scrollHeight"],v=b-x;let D=0,U=!0,Q=!0;const j=()=>{if(!(!e||Q)&&(g(),D=m[s?"scrollLeft":"scrollTop"],I.current=D/v,t)){if(!U){if(D>=v){const X=1-_.offset;m[s?"scrollLeft":"scrollTop"]=1,I.current=_.offset=-X,U=!0}else if(D<=0){const X=1+_.offset;m[s?"scrollLeft":"scrollTop"]=b,I.current=_.offset=X,U=!0}}U&&setTimeout(()=>U=!1,40)}};m.addEventListener("scroll",j,{passive:!0}),requestAnimationFrame(()=>Q=!1);const V=X=>m.scrollLeft+=X.deltaY/2;return s&&m.addEventListener("wheel",V,{passive:!0}),()=>{m.removeEventListener("scroll",j),s&&m.removeEventListener("wheel",V)}}},[m,p,f,t,_,g,s,e]);let S=0;return Ue((x,b)=>{S=_.offset,hi.damp(_,"offset",I.current,a,b,o,void 0,n),hi.damp(_,"delta",Math.abs(S-_.offset),a,b,o,void 0,n),_.delta>n&&g()}),T.createElement(zo.Provider,{value:_},h)}const yI=T.forwardRef(({children:n},e)=>{const t=T.useRef(null);T.useImperativeHandle(e,()=>t.current,[]);const s=qo(),{width:i,height:r}=$(a=>a.viewport);return Ue(()=>{t.current.position.x=s.horizontal?-i*(s.pages-1)*s.offset:0,t.current.position.y=s.horizontal?0:r*(s.pages-1)*s.offset}),T.createElement("group",{ref:t},n)}),BI=T.forwardRef(({children:n,style:e,...t},s)=>{const i=qo(),r=T.useRef(null);T.useImperativeHandle(s,()=>r.current,[]);const{width:a,height:o}=$(h=>h.size),l=T.useContext(bl),c=T.useMemo(()=>uC(i.fixed),[i.fixed]);return Ue(()=>{i.delta>i.eps&&(r.current.style.transform=`translate3d(${i.horizontal?-a*(i.pages-1)*i.offset:0}px,${i.horizontal?0:o*(i.pages-1)*-i.offset}px,0)`)}),c.render(T.createElement("div",be({ref:r,style:{...e,position:"absolute",top:0,left:0,willChange:"transform"}},t),T.createElement(zo.Provider,{value:i},T.createElement(bl.Provider,{value:l},n)))),null}),TI=T.forwardRef(({html:n,...e},t)=>{const s=n?BI:yI;return T.createElement(s,be({ref:t},e))});var $o=un(),Ae=n=>hn(n,$o),Xo=un();Ae.write=n=>hn(n,Xo);var vr=un();Ae.onStart=n=>hn(n,vr);var jo=un();Ae.onFrame=n=>hn(n,jo);var Wo=un();Ae.onFinish=n=>hn(n,Wo);var ii=[];Ae.setTimeout=(n,e)=>{const t=Ae.now()+e,s=()=>{const r=ii.findIndex(a=>a.cancel==s);~r&&ii.splice(r,1),hs-=~r?1:0},i={time:t,handler:n,cancel:s};return ii.splice(ad(t),0,i),hs+=1,od(),i};var ad=n=>~(~ii.findIndex(e=>e.time>n)||~ii.length);Ae.cancel=n=>{vr.delete(n),jo.delete(n),Wo.delete(n),$o.delete(n),Xo.delete(n)};Ae.sync=n=>{ro=!0,Ae.batchedUpdates(n),ro=!1};Ae.throttle=n=>{let e;function t(){try{n(...e)}finally{e=null}}function s(...i){e=i,Ae.onStart(t)}return s.handler=n,s.cancel=()=>{vr.delete(t),e=null},s};var Zo=typeof window<"u"?window.requestAnimationFrame:()=>{};Ae.use=n=>Zo=n;Ae.now=typeof performance<"u"?()=>performance.now():Date.now;Ae.batchedUpdates=n=>n();Ae.catch=console.error;Ae.frameLoop="always";Ae.advance=()=>{Ae.frameLoop!=="demand"?console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"):cd()};var cs=-1,hs=0,ro=!1;function hn(n,e){ro?(e.delete(n),n(0)):(e.add(n),od())}function od(){cs<0&&(cs=0,Ae.frameLoop!=="demand"&&Zo(ld))}function SI(){cs=-1}function ld(){~cs&&(Zo(ld),Ae.batchedUpdates(cd))}function cd(){const n=cs;cs=Ae.now();const e=ad(cs);if(e&&(hd(ii.splice(0,e),t=>t.handler()),hs-=e),!hs){SI();return}vr.flush(),$o.flush(n?Math.min(64,cs-n):16.667),jo.flush(),Xo.flush(),Wo.flush()}function un(){let n=new Set,e=n;return{add(t){hs+=e==n&&!n.has(t)?1:0,n.add(t)},delete(t){return hs-=e==n&&n.has(t)?1:0,n.delete(t)},flush(t){e.size&&(n=new Set,hs-=e.size,hd(e,s=>s(t)&&n.add(s)),hs+=n.size,e=n)}}}function hd(n,e){n.forEach(t=>{try{e(t)}catch(s){Ae.catch(s)}})}var _I=Object.defineProperty,xI=(n,e)=>{for(var t in e)_I(n,t,{get:e[t],enumerable:!0})},Rt={};xI(Rt,{assign:()=>RI,colors:()=>As,createStringInterpolator:()=>tl,skipAnimation:()=>dd,to:()=>ud,willAdvance:()=>sl});function ao(){}var vI=(n,e,t)=>Object.defineProperty(n,e,{value:t,writable:!0,configurable:!0}),q={arr:Array.isArray,obj:n=>!!n&&n.constructor.name==="Object",fun:n=>typeof n=="function",str:n=>typeof n=="string",num:n=>typeof n=="number",und:n=>n===void 0};function qt(n,e){if(q.arr(n)){if(!q.arr(e)||n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}return n===e}var _e=(n,e)=>n.forEach(e);function ss(n,e,t){if(q.arr(n)){for(let s=0;s<n.length;s++)e.call(t,n[s],`${s}`);return}for(const s in n)n.hasOwnProperty(s)&&e.call(t,n[s],s)}var pt=n=>q.und(n)?[]:q.arr(n)?n:[n];function zi(n,e){if(n.size){const t=Array.from(n);n.clear(),_e(t,e)}}var Ki=(n,...e)=>zi(n,t=>t(...e)),el=()=>typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),tl,ud,As=null,dd=!1,sl=ao,RI=n=>{n.to&&(ud=n.to),n.now&&(Ae.now=n.now),n.colors!==void 0&&(As=n.colors),n.skipAnimation!=null&&(dd=n.skipAnimation),n.createStringInterpolator&&(tl=n.createStringInterpolator),n.requestAnimationFrame&&Ae.use(n.requestAnimationFrame),n.batchedUpdates&&(Ae.batchedUpdates=n.batchedUpdates),n.willAdvance&&(sl=n.willAdvance),n.frameLoop&&(Ae.frameLoop=n.frameLoop)},qi=new Set,gt=[],Xr=[],nr=0,Rr={get idle(){return!qi.size&&!gt.length},start(n){nr>n.priority?(qi.add(n),Ae.onStart(wI)):(Ad(n),Ae(oo))},advance:oo,sort(n){if(nr)Ae.onFrame(()=>Rr.sort(n));else{const e=gt.indexOf(n);~e&&(gt.splice(e,1),fd(n))}},clear(){gt=[],qi.clear()}};function wI(){qi.forEach(Ad),qi.clear(),Ae(oo)}function Ad(n){gt.includes(n)||fd(n)}function fd(n){gt.splice(DI(gt,e=>e.priority>n.priority),0,n)}function oo(n){const e=Xr;for(let t=0;t<gt.length;t++){const s=gt[t];nr=s.priority,s.idle||(sl(s),s.advance(n),s.idle||e.push(s))}return nr=0,Xr=gt,Xr.length=0,gt=e,gt.length>0}function DI(n,e){const t=n.findIndex(e);return t<0?n.length:t}var LI=(n,e,t)=>Math.min(Math.max(t,n),e),bI={transparent:0,aliceblue:4042850303,antiquewhite:4209760255,aqua:16777215,aquamarine:2147472639,azure:4043309055,beige:4126530815,bisque:4293182719,black:255,blanchedalmond:4293643775,blue:65535,blueviolet:2318131967,brown:2771004159,burlywood:3736635391,burntsienna:3934150143,cadetblue:1604231423,chartreuse:2147418367,chocolate:3530104575,coral:4286533887,cornflowerblue:1687547391,cornsilk:4294499583,crimson:3692313855,cyan:16777215,darkblue:35839,darkcyan:9145343,darkgoldenrod:3095792639,darkgray:2846468607,darkgreen:6553855,darkgrey:2846468607,darkkhaki:3182914559,darkmagenta:2332068863,darkolivegreen:1433087999,darkorange:4287365375,darkorchid:2570243327,darkred:2332033279,darksalmon:3918953215,darkseagreen:2411499519,darkslateblue:1211993087,darkslategray:793726975,darkslategrey:793726975,darkturquoise:13554175,darkviolet:2483082239,deeppink:4279538687,deepskyblue:12582911,dimgray:1768516095,dimgrey:1768516095,dodgerblue:512819199,firebrick:2988581631,floralwhite:4294635775,forestgreen:579543807,fuchsia:4278255615,gainsboro:3705462015,ghostwhite:4177068031,gold:4292280575,goldenrod:3668254975,gray:2155905279,green:8388863,greenyellow:2919182335,grey:2155905279,honeydew:4043305215,hotpink:4285117695,indianred:3445382399,indigo:1258324735,ivory:4294963455,khaki:4041641215,lavender:3873897215,lavenderblush:4293981695,lawngreen:2096890111,lemonchiffon:4294626815,lightblue:2916673279,lightcoral:4034953471,lightcyan:3774873599,lightgoldenrodyellow:4210742015,lightgray:3553874943,lightgreen:2431553791,lightgrey:3553874943,lightpink:4290167295,lightsalmon:4288707327,lightseagreen:548580095,lightskyblue:2278488831,lightslategray:2005441023,lightslategrey:2005441023,lightsteelblue:2965692159,lightyellow:4294959359,lime:16711935,limegreen:852308735,linen:4210091775,magenta:4278255615,maroon:2147483903,mediumaquamarine:1724754687,mediumblue:52735,mediumorchid:3126187007,mediumpurple:2473647103,mediumseagreen:1018393087,mediumslateblue:2070474495,mediumspringgreen:16423679,mediumturquoise:1221709055,mediumvioletred:3340076543,midnightblue:421097727,mintcream:4127193855,mistyrose:4293190143,moccasin:4293178879,navajowhite:4292783615,navy:33023,oldlace:4260751103,olive:2155872511,olivedrab:1804477439,orange:4289003775,orangered:4282712319,orchid:3664828159,palegoldenrod:4008225535,palegreen:2566625535,paleturquoise:2951671551,palevioletred:3681588223,papayawhip:4293907967,peachpuff:4292524543,peru:3448061951,pink:4290825215,plum:3718307327,powderblue:2967529215,purple:2147516671,rebeccapurple:1714657791,red:4278190335,rosybrown:3163525119,royalblue:1097458175,saddlebrown:2336560127,salmon:4202722047,sandybrown:4104413439,seagreen:780883967,seashell:4294307583,sienna:2689740287,silver:3233857791,skyblue:2278484991,slateblue:1784335871,slategray:1887473919,slategrey:1887473919,snow:4294638335,springgreen:16744447,steelblue:1182971135,tan:3535047935,teal:8421631,thistle:3636451583,tomato:4284696575,turquoise:1088475391,violet:4001558271,wheat:4125012991,white:4294967295,whitesmoke:4126537215,yellow:4294902015,yellowgreen:2597139199},xt="[-+]?\\d*\\.?\\d+",rr=xt+"%";function wr(...n){return"\\(\\s*("+n.join(")\\s*,\\s*(")+")\\s*\\)"}var MI=new RegExp("rgb"+wr(xt,xt,xt)),FI=new RegExp("rgba"+wr(xt,xt,xt,xt)),PI=new RegExp("hsl"+wr(xt,rr,rr)),kI=new RegExp("hsla"+wr(xt,rr,rr,xt)),OI=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,QI=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,GI=/^#([0-9a-fA-F]{6})$/,UI=/^#([0-9a-fA-F]{8})$/;function NI(n){let e;return typeof n=="number"?n>>>0===n&&n>=0&&n<=4294967295?n:null:(e=GI.exec(n))?parseInt(e[1]+"ff",16)>>>0:As&&As[n]!==void 0?As[n]:(e=MI.exec(n))?(Ps(e[1])<<24|Ps(e[2])<<16|Ps(e[3])<<8|255)>>>0:(e=FI.exec(n))?(Ps(e[1])<<24|Ps(e[2])<<16|Ps(e[3])<<8|xc(e[4]))>>>0:(e=OI.exec(n))?parseInt(e[1]+e[1]+e[2]+e[2]+e[3]+e[3]+"ff",16)>>>0:(e=UI.exec(n))?parseInt(e[1],16)>>>0:(e=QI.exec(n))?parseInt(e[1]+e[1]+e[2]+e[2]+e[3]+e[3]+e[4]+e[4],16)>>>0:(e=PI.exec(n))?(Sc(_c(e[1]),yn(e[2]),yn(e[3]))|255)>>>0:(e=kI.exec(n))?(Sc(_c(e[1]),yn(e[2]),yn(e[3]))|xc(e[4]))>>>0:null}function jr(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*(2/3-t)*6:n}function Sc(n,e,t){const s=t<.5?t*(1+e):t+e-t*e,i=2*t-s,r=jr(i,s,n+1/3),a=jr(i,s,n),o=jr(i,s,n-1/3);return Math.round(r*255)<<24|Math.round(a*255)<<16|Math.round(o*255)<<8}function Ps(n){const e=parseInt(n,10);return e<0?0:e>255?255:e}function _c(n){return(parseFloat(n)%360+360)%360/360}function xc(n){const e=parseFloat(n);return e<0?0:e>1?255:Math.round(e*255)}function yn(n){const e=parseFloat(n);return e<0?0:e>100?1:e/100}function vc(n){let e=NI(n);if(e===null)return n;e=e||0;const t=(e&4278190080)>>>24,s=(e&16711680)>>>16,i=(e&65280)>>>8,r=(e&255)/255;return`rgba(${t}, ${s}, ${i}, ${r})`}var en=(n,e,t)=>{if(q.fun(n))return n;if(q.arr(n))return en({range:n,output:e,extrapolate:t});if(q.str(n.output[0]))return tl(n);const s=n,i=s.output,r=s.range||[0,1],a=s.extrapolateLeft||s.extrapolate||"extend",o=s.extrapolateRight||s.extrapolate||"extend",l=s.easing||(c=>c);return c=>{const h=KI(c,r);return HI(c,r[h],r[h+1],i[h],i[h+1],l,a,o,s.map)}};function HI(n,e,t,s,i,r,a,o,l){let c=l?l(n):n;if(c<e){if(a==="identity")return c;a==="clamp"&&(c=e)}if(c>t){if(o==="identity")return c;o==="clamp"&&(c=t)}return s===i?s:e===t?n<=e?s:i:(e===-1/0?c=-c:t===1/0?c=c-e:c=(c-e)/(t-e),c=r(c),s===-1/0?c=-c:i===1/0?c=c+s:c=c*(i-s)+s,c)}function KI(n,e){for(var t=1;t<e.length-1&&!(e[t]>=n);++t);return t-1}var VI=(n,e="end")=>t=>{t=e==="end"?Math.min(t,.999):Math.max(t,.001);const s=t*n,i=e==="end"?Math.floor(s):Math.ceil(s);return LI(0,1,i/n)},ar=1.70158,Bn=ar*1.525,Rc=ar+1,wc=2*Math.PI/3,Dc=2*Math.PI/4.5,Tn=n=>n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375,YI={linear:n=>n,easeInQuad:n=>n*n,easeOutQuad:n=>1-(1-n)*(1-n),easeInOutQuad:n=>n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2,easeInCubic:n=>n*n*n,easeOutCubic:n=>1-Math.pow(1-n,3),easeInOutCubic:n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,easeInQuart:n=>n*n*n*n,easeOutQuart:n=>1-Math.pow(1-n,4),easeInOutQuart:n=>n<.5?8*n*n*n*n:1-Math.pow(-2*n+2,4)/2,easeInQuint:n=>n*n*n*n*n,easeOutQuint:n=>1-Math.pow(1-n,5),easeInOutQuint:n=>n<.5?16*n*n*n*n*n:1-Math.pow(-2*n+2,5)/2,easeInSine:n=>1-Math.cos(n*Math.PI/2),easeOutSine:n=>Math.sin(n*Math.PI/2),easeInOutSine:n=>-(Math.cos(Math.PI*n)-1)/2,easeInExpo:n=>n===0?0:Math.pow(2,10*n-10),easeOutExpo:n=>n===1?1:1-Math.pow(2,-10*n),easeInOutExpo:n=>n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2,easeInCirc:n=>1-Math.sqrt(1-Math.pow(n,2)),easeOutCirc:n=>Math.sqrt(1-Math.pow(n-1,2)),easeInOutCirc:n=>n<.5?(1-Math.sqrt(1-Math.pow(2*n,2)))/2:(Math.sqrt(1-Math.pow(-2*n+2,2))+1)/2,easeInBack:n=>Rc*n*n*n-ar*n*n,easeOutBack:n=>1+Rc*Math.pow(n-1,3)+ar*Math.pow(n-1,2),easeInOutBack:n=>n<.5?Math.pow(2*n,2)*((Bn+1)*2*n-Bn)/2:(Math.pow(2*n-2,2)*((Bn+1)*(n*2-2)+Bn)+2)/2,easeInElastic:n=>n===0?0:n===1?1:-Math.pow(2,10*n-10)*Math.sin((n*10-10.75)*wc),easeOutElastic:n=>n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n*10-.75)*wc)+1,easeInOutElastic:n=>n===0?0:n===1?1:n<.5?-(Math.pow(2,20*n-10)*Math.sin((20*n-11.125)*Dc))/2:Math.pow(2,-20*n+10)*Math.sin((20*n-11.125)*Dc)/2+1,easeInBounce:n=>1-Tn(1-n),easeOutBounce:Tn,easeInOutBounce:n=>n<.5?(1-Tn(1-2*n))/2:(1+Tn(2*n-1))/2,steps:VI},tn=Symbol.for("FluidValue.get"),ui=Symbol.for("FluidValue.observers"),kt=n=>!!(n&&n[tn]),At=n=>n&&n[tn]?n[tn]():n,Lc=n=>n[ui]||null;function JI(n,e){n.eventObserved?n.eventObserved(e):n(e)}function or(n,e){const t=n[ui];t&&t.forEach(s=>{JI(s,e)})}var zI=class{constructor(n){if(!n&&!(n=this.get))throw Error("Unknown getter");qI(this,n)}},qI=(n,e)=>gd(n,tn,e);function dn(n,e){if(n[tn]){let t=n[ui];t||gd(n,ui,t=new Set),t.has(e)||(t.add(e),n.observerAdded&&n.observerAdded(t.size,e))}return e}function lr(n,e){const t=n[ui];if(t&&t.has(e)){const s=t.size-1;s?t.delete(e):n[ui]=null,n.observerRemoved&&n.observerRemoved(s,e)}}var gd=(n,e,t)=>Object.defineProperty(n,e,{value:t,writable:!0,configurable:!0}),zn=/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,$I=/(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi,bc=new RegExp(`(${zn.source})(%|[a-z]+)`,"i"),XI=/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi,Dr=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/,md=n=>{const[e,t]=jI(n);if(!e||el())return n;const s=window.getComputedStyle(document.documentElement).getPropertyValue(e);if(s)return s.trim();if(t&&t.startsWith("--")){const i=window.getComputedStyle(document.documentElement).getPropertyValue(t);return i||n}else{if(t&&Dr.test(t))return md(t);if(t)return t}return n},jI=n=>{const e=Dr.exec(n);if(!e)return[,];const[,t,s]=e;return[t,s]},Wr,WI=(n,e,t,s,i)=>`rgba(${Math.round(e)}, ${Math.round(t)}, ${Math.round(s)}, ${i})`,pd=n=>{Wr||(Wr=As?new RegExp(`(${Object.keys(As).join("|")})(?!\\w)`,"g"):/^\b$/);const e=n.output.map(r=>At(r).replace(Dr,md).replace($I,vc).replace(Wr,vc)),t=e.map(r=>r.match(zn).map(Number)),i=t[0].map((r,a)=>t.map(o=>{if(!(a in o))throw Error('The arity of each "output" value must be equal');return o[a]})).map(r=>en({...n,output:r}));return r=>{var l;const a=!bc.test(e[0])&&((l=e.find(c=>bc.test(c)))==null?void 0:l.replace(zn,""));let o=0;return e[0].replace(zn,()=>`${i[o++](r)}${a||""}`).replace(XI,WI)}},il="react-spring: ",Ed=n=>{const e=n;let t=!1;if(typeof e!="function")throw new TypeError(`${il}once requires a function parameter`);return(...s)=>{t||(e(...s),t=!0)}},ZI=Ed(console.warn);function ey(){ZI(`${il}The "interpolate" function is deprecated in v9 (use "to" instead)`)}var ty=Ed(console.warn);function sy(){ty(`${il}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`)}function Lr(n){return q.str(n)&&(n[0]=="#"||/\d/.test(n)||!el()&&Dr.test(n)||n in(As||{}))}var nl=el()?T.useEffect:T.useLayoutEffect,iy=()=>{const n=T.useRef(!1);return nl(()=>(n.current=!0,()=>{n.current=!1}),[]),n};function Cd(){const n=T.useState()[1],e=iy();return()=>{e.current&&n(Math.random())}}function ny(n,e){const[t]=T.useState(()=>({inputs:e,result:n()})),s=T.useRef(),i=s.current;let r=i;return r?r.inputs&&ry(e,r.inputs)||(r={inputs:e,result:n()}):r=t,T.useEffect(()=>{s.current=r,i==t&&(t.inputs=t.result=void 0)},[r]),r.result}function ry(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}var Id=n=>T.useEffect(n,ay),ay=[];function Mc(n){const e=T.useRef();return T.useEffect(()=>{e.current=n}),e.current}var sn=Symbol.for("Animated:node"),oy=n=>!!n&&n[sn]===n,Ft=n=>n&&n[sn],rl=(n,e)=>vI(n,sn,e),br=n=>n&&n[sn]&&n[sn].getPayload(),yd=class{constructor(){rl(this,this)}getPayload(){return this.payload||[]}},An=class extends yd{constructor(n){super(),this._value=n,this.done=!0,this.durationProgress=0,q.num(this._value)&&(this.lastPosition=this._value)}static create(n){return new An(n)}getPayload(){return[this]}getValue(){return this._value}setValue(n,e){return q.num(n)&&(this.lastPosition=n,e&&(n=Math.round(n/e)*e,this.done&&(this.lastPosition=n))),this._value===n?!1:(this._value=n,!0)}reset(){const{done:n}=this;this.done=!1,q.num(this._value)&&(this.elapsedTime=0,this.durationProgress=0,this.lastPosition=this._value,n&&(this.lastVelocity=null),this.v0=null)}},nn=class extends An{constructor(n){super(0),this._string=null,this._toString=en({output:[n,n]})}static create(n){return new nn(n)}getValue(){const n=this._string;return n??(this._string=this._toString(this._value))}setValue(n){if(q.str(n)){if(n==this._string)return!1;this._string=n,this._value=1}else if(super.setValue(n))this._string=null;else return!1;return!0}reset(n){n&&(this._toString=en({output:[this.getValue(),n]})),this._value=0,super.reset()}},cr={dependencies:null},al=class extends yd{constructor(n){super(),this.source=n,this.setValue(n)}getValue(n){const e={};return ss(this.source,(t,s)=>{oy(t)?e[s]=t.getValue(n):kt(t)?e[s]=At(t):n||(e[s]=t)}),e}setValue(n){this.source=n,this.payload=this._makePayload(n)}reset(){this.payload&&_e(this.payload,n=>n.reset())}_makePayload(n){if(n){const e=new Set;return ss(n,this._addToPayload,e),Array.from(e)}}_addToPayload(n){cr.dependencies&&kt(n)&&cr.dependencies.add(n);const e=br(n);e&&_e(e,t=>this.add(t))}},Bd=class extends al{constructor(n){super(n)}static create(n){return new Bd(n)}getValue(){return this.source.map(n=>n.getValue())}setValue(n){const e=this.getPayload();return n.length==e.length?e.map((t,s)=>t.setValue(n[s])).some(Boolean):(super.setValue(n.map(ly)),!0)}};function ly(n){return(Lr(n)?nn:An).create(n)}function lo(n){const e=Ft(n);return e?e.constructor:q.arr(n)?Bd:Lr(n)?nn:An}var Fc=(n,e)=>{const t=!q.fun(n)||n.prototype&&n.prototype.isReactComponent;return T.forwardRef((s,i)=>{const r=T.useRef(null),a=t&&T.useCallback(f=>{r.current=uy(i,f)},[i]),[o,l]=hy(s,e),c=Cd(),h=()=>{const f=r.current;if(t&&!f)return;(f?e.applyAnimatedValues(f,o.getValue(!0)):!1)===!1&&c()},u=new cy(h,l),d=T.useRef();nl(()=>(d.current=u,_e(l,f=>dn(f,u)),()=>{d.current&&(_e(d.current.deps,f=>lr(f,d.current)),Ae.cancel(d.current.update))})),T.useEffect(h,[]),Id(()=>()=>{const f=d.current;_e(f.deps,g=>lr(g,f))});const A=e.getComponentProps(o.getValue());return T.createElement(n,{...A,ref:a})})},cy=class{constructor(n,e){this.update=n,this.deps=e}eventObserved(n){n.type=="change"&&Ae.write(this.update)}};function hy(n,e){const t=new Set;return cr.dependencies=t,n.style&&(n={...n,style:e.createAnimatedStyle(n.style)}),n=new al(n),cr.dependencies=null,[n,t]}function uy(n,e){return n&&(q.fun(n)?n(e):n.current=e),e}var Pc=Symbol.for("AnimatedComponent"),dy=(n,{applyAnimatedValues:e=()=>!1,createAnimatedStyle:t=i=>new al(i),getComponentProps:s=i=>i}={})=>{const i={applyAnimatedValues:e,createAnimatedStyle:t,getComponentProps:s},r=a=>{const o=kc(a)||"Anonymous";return q.str(a)?a=r[a]||(r[a]=Fc(a,i)):a=a[Pc]||(a[Pc]=Fc(a,i)),a.displayName=`Animated(${o})`,a};return ss(n,(a,o)=>{q.arr(n)&&(o=kc(a)),r[o]=r(a)}),{animated:r}},kc=n=>q.str(n)?n:n&&q.str(n.displayName)?n.displayName:q.fun(n)&&n.name||null;function xs(n,...e){return q.fun(n)?n(...e):n}var $i=(n,e)=>n===!0||!!(e&&n&&(q.fun(n)?n(e):pt(n).includes(e))),Td=(n,e)=>q.obj(n)?e&&n[e]:n,Sd=(n,e)=>n.default===!0?n[e]:n.default?n.default[e]:void 0,Ay=n=>n,ol=(n,e=Ay)=>{let t=fy;n.default&&n.default!==!0&&(n=n.default,t=Object.keys(n));const s={};for(const i of t){const r=e(n[i],i);q.und(r)||(s[i]=r)}return s},fy=["config","onProps","onStart","onChange","onPause","onResume","onRest"],gy={config:1,from:1,to:1,ref:1,loop:1,reset:1,pause:1,cancel:1,reverse:1,immediate:1,default:1,delay:1,onProps:1,onStart:1,onChange:1,onPause:1,onResume:1,onRest:1,onResolve:1,items:1,trail:1,sort:1,expires:1,initial:1,enter:1,update:1,leave:1,children:1,onDestroyed:1,keys:1,callId:1,parentId:1};function my(n){const e={};let t=0;if(ss(n,(s,i)=>{gy[i]||(e[i]=s,t++)}),t)return e}function _d(n){const e=my(n);if(e){const t={to:e};return ss(n,(s,i)=>i in e||(t[i]=s)),t}return{...n}}function rn(n){return n=At(n),q.arr(n)?n.map(rn):Lr(n)?Rt.createStringInterpolator({range:[0,1],output:[n,n]})(1):n}function py(n){for(const e in n)return!0;return!1}function co(n){return q.fun(n)||q.arr(n)&&q.obj(n[0])}function Ey(n,e){var t;(t=n.ref)==null||t.delete(n),e==null||e.delete(n)}function Cy(n,e){var t;e&&n.ref!==e&&((t=n.ref)==null||t.delete(n),e.add(n),n.ref=e)}var Iy={default:{tension:170,friction:26},gentle:{tension:120,friction:14},wobbly:{tension:180,friction:12},stiff:{tension:210,friction:20},slow:{tension:280,friction:60},molasses:{tension:280,friction:120}},ho={...Iy.default,mass:1,damping:1,easing:YI.linear,clamp:!1},yy=class{constructor(){this.velocity=0,Object.assign(this,ho)}};function By(n,e,t){t&&(t={...t},Oc(t,e),e={...t,...e}),Oc(n,e),Object.assign(n,e);for(const a in ho)n[a]==null&&(n[a]=ho[a]);let{frequency:s,damping:i}=n;const{mass:r}=n;return q.und(s)||(s<.01&&(s=.01),i<0&&(i=0),n.tension=Math.pow(2*Math.PI/s,2)*r,n.friction=4*Math.PI*i*r/s),n}function Oc(n,e){if(!q.und(e.decay))n.duration=void 0;else{const t=!q.und(e.tension)||!q.und(e.friction);(t||!q.und(e.frequency)||!q.und(e.damping)||!q.und(e.mass))&&(n.duration=void 0,n.decay=void 0),t&&(n.frequency=void 0)}}var Qc=[],Ty=class{constructor(){this.changed=!1,this.values=Qc,this.toValues=null,this.fromValues=Qc,this.config=new yy,this.immediate=!1}};function xd(n,{key:e,props:t,defaultProps:s,state:i,actions:r}){return new Promise((a,o)=>{let l,c,h=$i(t.cancel??(s==null?void 0:s.cancel),e);if(h)A();else{q.und(t.pause)||(i.paused=$i(t.pause,e));let f=s==null?void 0:s.pause;f!==!0&&(f=i.paused||$i(f,e)),l=xs(t.delay||0,e),f?(i.resumeQueue.add(d),r.pause()):(r.resume(),d())}function u(){i.resumeQueue.add(d),i.timeouts.delete(c),c.cancel(),l=c.time-Ae.now()}function d(){l>0&&!Rt.skipAnimation?(i.delayed=!0,c=Ae.setTimeout(A,l),i.pauseQueue.add(u),i.timeouts.add(c)):A()}function A(){i.delayed&&(i.delayed=!1),i.pauseQueue.delete(u),i.timeouts.delete(c),n<=(i.cancelId||0)&&(h=!0);try{r.start({...t,callId:n,cancel:h},a)}catch(f){o(f)}}})}var ll=(n,e)=>e.length==1?e[0]:e.some(t=>t.cancelled)?ni(n.get()):e.every(t=>t.noop)?vd(n.get()):_t(n.get(),e.every(t=>t.finished)),vd=n=>({value:n,noop:!0,finished:!0,cancelled:!1}),_t=(n,e,t=!1)=>({value:n,finished:e,cancelled:t}),ni=n=>({value:n,cancelled:!0,finished:!1});function Rd(n,e,t,s){const{callId:i,parentId:r,onRest:a}=e,{asyncTo:o,promise:l}=t;return!r&&n===o&&!e.reset?l:t.promise=(async()=>{t.asyncId=i,t.asyncTo=n;const c=ol(e,(p,m)=>m==="onRest"?void 0:p);let h,u;const d=new Promise((p,m)=>(h=p,u=m)),A=p=>{const m=i<=(t.cancelId||0)&&ni(s)||i!==t.asyncId&&_t(s,!1);if(m)throw p.result=m,u(p),p},f=(p,m)=>{const C=new Gc,E=new Uc;return(async()=>{if(Rt.skipAnimation)throw an(t),E.result=_t(s,!1),u(E),E;A(C);const B=q.obj(p)?{...p}:{...m,to:p};B.parentId=i,ss(c,(_,S)=>{q.und(B[S])&&(B[S]=_)});const I=await s.start(B);return A(C),t.paused&&await new Promise(_=>{t.resumeQueue.add(_)}),I})()};let g;if(Rt.skipAnimation)return an(t),_t(s,!1);try{let p;q.arr(n)?p=(async m=>{for(const C of m)await f(C)})(n):p=Promise.resolve(n(f,s.stop.bind(s))),await Promise.all([p.then(h),d]),g=_t(s.get(),!0,!1)}catch(p){if(p instanceof Gc)g=p.result;else if(p instanceof Uc)g=p.result;else throw p}finally{i==t.asyncId&&(t.asyncId=r,t.asyncTo=r?o:void 0,t.promise=r?l:void 0)}return q.fun(a)&&Ae.batchedUpdates(()=>{a(g,s,s.item)}),g})()}function an(n,e){zi(n.timeouts,t=>t.cancel()),n.pauseQueue.clear(),n.resumeQueue.clear(),n.asyncId=n.asyncTo=n.promise=void 0,e&&(n.cancelId=e)}var Gc=class extends Error{constructor(){super("An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise.")}},Uc=class extends Error{constructor(){super("SkipAnimationSignal")}},uo=n=>n instanceof cl,Sy=1,cl=class extends zI{constructor(){super(...arguments),this.id=Sy++,this._priority=0}get priority(){return this._priority}set priority(n){this._priority!=n&&(this._priority=n,this._onPriorityChange(n))}get(){const n=Ft(this);return n&&n.getValue()}to(...n){return Rt.to(this,n)}interpolate(...n){return ey(),Rt.to(this,n)}toJSON(){return this.get()}observerAdded(n){n==1&&this._attach()}observerRemoved(n){n==0&&this._detach()}_attach(){}_detach(){}_onChange(n,e=!1){or(this,{type:"change",parent:this,value:n,idle:e})}_onPriorityChange(n){this.idle||Rr.sort(this),or(this,{type:"priority",parent:this,priority:n})}},Ls=Symbol.for("SpringPhase"),wd=1,Dd=2,Ld=4,Zr=n=>(n[Ls]&wd)>0,is=n=>(n[Ls]&Dd)>0,wi=n=>(n[Ls]&Ld)>0,Nc=(n,e)=>e?n[Ls]|=Dd|wd:n[Ls]&=-3,Hc=(n,e)=>e?n[Ls]|=Ld:n[Ls]&=-5,_y=class extends cl{constructor(n,e){if(super(),this.animation=new Ty,this.defaultProps={},this._state={paused:!1,delayed:!1,pauseQueue:new Set,resumeQueue:new Set,timeouts:new Set},this._pendingCalls=new Set,this._lastCallId=0,this._lastToId=0,this._memoizedDuration=0,!q.und(n)||!q.und(e)){const t=q.obj(n)?{...n}:{...e,from:n};q.und(t.default)&&(t.default=!0),this.start(t)}}get idle(){return!(is(this)||this._state.asyncTo)||wi(this)}get goal(){return At(this.animation.to)}get velocity(){const n=Ft(this);return n instanceof An?n.lastVelocity||0:n.getPayload().map(e=>e.lastVelocity||0)}get hasAnimated(){return Zr(this)}get isAnimating(){return is(this)}get isPaused(){return wi(this)}get isDelayed(){return this._state.delayed}advance(n){let e=!0,t=!1;const s=this.animation;let{toValues:i}=s;const{config:r}=s,a=br(s.to);!a&&kt(s.to)&&(i=pt(At(s.to))),s.values.forEach((c,h)=>{if(c.done)return;const u=c.constructor==nn?1:a?a[h].lastPosition:i[h];let d=s.immediate,A=u;if(!d){if(A=c.lastPosition,r.tension<=0){c.done=!0;return}let f=c.elapsedTime+=n;const g=s.fromValues[h],p=c.v0!=null?c.v0:c.v0=q.arr(r.velocity)?r.velocity[h]:r.velocity;let m;const C=r.precision||(g==u?.005:Math.min(1,Math.abs(u-g)*.001));if(q.und(r.duration))if(r.decay){const E=r.decay===!0?.998:r.decay,B=Math.exp(-(1-E)*f);A=g+p/(1-E)*(1-B),d=Math.abs(c.lastPosition-A)<=C,m=p*B}else{m=c.lastVelocity==null?p:c.lastVelocity;const E=r.restVelocity||C/10,B=r.clamp?0:r.bounce,I=!q.und(B),_=g==u?c.v0>0:g<u;let S,x=!1;const b=1,v=Math.ceil(n/b);for(let D=0;D<v&&(S=Math.abs(m)>E,!(!S&&(d=Math.abs(u-A)<=C,d)));++D){I&&(x=A==u||A>u==_,x&&(m=-m*B,A=u));const U=-r.tension*1e-6*(A-u),Q=-r.friction*.001*m,j=(U+Q)/r.mass;m=m+j*b,A=A+m*b}}else{let E=1;r.duration>0&&(this._memoizedDuration!==r.duration&&(this._memoizedDuration=r.duration,c.durationProgress>0&&(c.elapsedTime=r.duration*c.durationProgress,f=c.elapsedTime+=n)),E=(r.progress||0)+f/this._memoizedDuration,E=E>1?1:E<0?0:E,c.durationProgress=E),A=g+r.easing(E)*(u-g),m=(A-c.lastPosition)/n,d=E==1}c.lastVelocity=m,Number.isNaN(A)&&(console.warn("Got NaN while animating:",this),d=!0)}a&&!a[h].done&&(d=!1),d?c.done=!0:e=!1,c.setValue(A,r.round)&&(t=!0)});const o=Ft(this),l=o.getValue();if(e){const c=At(s.to);(l!==c||t)&&!r.decay?(o.setValue(c),this._onChange(c)):t&&r.decay&&this._onChange(l),this._stop()}else t&&this._onChange(l)}set(n){return Ae.batchedUpdates(()=>{this._stop(),this._focus(n),this._set(n)}),this}pause(){this._update({pause:!0})}resume(){this._update({pause:!1})}finish(){if(is(this)){const{to:n,config:e}=this.animation;Ae.batchedUpdates(()=>{this._onStart(),e.decay||this._set(n,!1),this._stop()})}return this}update(n){return(this.queue||(this.queue=[])).push(n),this}start(n,e){let t;return q.und(n)?(t=this.queue||[],this.queue=[]):t=[q.obj(n)?n:{...e,to:n}],Promise.all(t.map(s=>this._update(s))).then(s=>ll(this,s))}stop(n){const{to:e}=this.animation;return this._focus(this.get()),an(this._state,n&&this._lastCallId),Ae.batchedUpdates(()=>this._stop(e,n)),this}reset(){this._update({reset:!0})}eventObserved(n){n.type=="change"?this._start():n.type=="priority"&&(this.priority=n.priority+1)}_prepareNode(n){const e=this.key||"";let{to:t,from:s}=n;t=q.obj(t)?t[e]:t,(t==null||co(t))&&(t=void 0),s=q.obj(s)?s[e]:s,s==null&&(s=void 0);const i={to:t,from:s};return Zr(this)||(n.reverse&&([t,s]=[s,t]),s=At(s),q.und(s)?Ft(this)||this._set(t):this._set(s)),i}_update({...n},e){const{key:t,defaultProps:s}=this;n.default&&Object.assign(s,ol(n,(a,o)=>/^on/.test(o)?Td(a,t):a)),Vc(this,n,"onProps"),Li(this,"onProps",n,this);const i=this._prepareNode(n);if(Object.isFrozen(this))throw Error("Cannot animate a `SpringValue` object that is frozen. Did you forget to pass your component to `animated(...)` before animating its props?");const r=this._state;return xd(++this._lastCallId,{key:t,props:n,defaultProps:s,state:r,actions:{pause:()=>{wi(this)||(Hc(this,!0),Ki(r.pauseQueue),Li(this,"onPause",_t(this,Di(this,this.animation.to)),this))},resume:()=>{wi(this)&&(Hc(this,!1),is(this)&&this._resume(),Ki(r.resumeQueue),Li(this,"onResume",_t(this,Di(this,this.animation.to)),this))},start:this._merge.bind(this,i)}}).then(a=>{if(n.loop&&a.finished&&!(e&&a.noop)){const o=bd(n);if(o)return this._update(o,!0)}return a})}_merge(n,e,t){if(e.cancel)return this.stop(!0),t(ni(this));const s=!q.und(n.to),i=!q.und(n.from);if(s||i)if(e.callId>this._lastToId)this._lastToId=e.callId;else return t(ni(this));const{key:r,defaultProps:a,animation:o}=this,{to:l,from:c}=o;let{to:h=l,from:u=c}=n;i&&!s&&(!e.default||q.und(h))&&(h=u),e.reverse&&([h,u]=[u,h]);const d=!qt(u,c);d&&(o.from=u),u=At(u);const A=!qt(h,l);A&&this._focus(h);const f=co(e.to),{config:g}=o,{decay:p,velocity:m}=g;(s||i)&&(g.velocity=0),e.config&&!f&&By(g,xs(e.config,r),e.config!==a.config?xs(a.config,r):void 0);let C=Ft(this);if(!C||q.und(h))return t(_t(this,!0));const E=q.und(e.reset)?i&&!e.default:!q.und(u)&&$i(e.reset,r),B=E?u:this.get(),I=rn(h),_=q.num(I)||q.arr(I)||Lr(I),S=!f&&(!_||$i(a.immediate||e.immediate,r));if(A){const D=lo(h);if(D!==C.constructor)if(S)C=this._set(I);else throw Error(`Cannot animate between ${C.constructor.name} and ${D.name}, as the "to" prop suggests`)}const x=C.constructor;let b=kt(h),v=!1;if(!b){const D=E||!Zr(this)&&d;(A||D)&&(v=qt(rn(B),I),b=!v),(!qt(o.immediate,S)&&!S||!qt(g.decay,p)||!qt(g.velocity,m))&&(b=!0)}if(v&&is(this)&&(o.changed&&!E?b=!0:b||this._stop(l)),!f&&((b||kt(l))&&(o.values=C.getPayload(),o.toValues=kt(h)?null:x==nn?[1]:pt(I)),o.immediate!=S&&(o.immediate=S,!S&&!E&&this._set(l)),b)){const{onRest:D}=o;_e(vy,Q=>Vc(this,e,Q));const U=_t(this,Di(this,l));Ki(this._pendingCalls,U),this._pendingCalls.add(t),o.changed&&Ae.batchedUpdates(()=>{var Q;o.changed=!E,D==null||D(U,this),E?xs(a.onRest,U):(Q=o.onStart)==null||Q.call(o,U,this)})}E&&this._set(B),f?t(Rd(e.to,e,this._state,this)):b?this._start():is(this)&&!A?this._pendingCalls.add(t):t(vd(B))}_focus(n){const e=this.animation;n!==e.to&&(Lc(this)&&this._detach(),e.to=n,Lc(this)&&this._attach())}_attach(){let n=0;const{to:e}=this.animation;kt(e)&&(dn(e,this),uo(e)&&(n=e.priority+1)),this.priority=n}_detach(){const{to:n}=this.animation;kt(n)&&lr(n,this)}_set(n,e=!0){const t=At(n);if(!q.und(t)){const s=Ft(this);if(!s||!qt(t,s.getValue())){const i=lo(t);!s||s.constructor!=i?rl(this,i.create(t)):s.setValue(t),s&&Ae.batchedUpdates(()=>{this._onChange(t,e)})}}return Ft(this)}_onStart(){const n=this.animation;n.changed||(n.changed=!0,Li(this,"onStart",_t(this,Di(this,n.to)),this))}_onChange(n,e){e||(this._onStart(),xs(this.animation.onChange,n,this)),xs(this.defaultProps.onChange,n,this),super._onChange(n,e)}_start(){const n=this.animation;Ft(this).reset(At(n.to)),n.immediate||(n.fromValues=n.values.map(e=>e.lastPosition)),is(this)||(Nc(this,!0),wi(this)||this._resume())}_resume(){Rt.skipAnimation?this.finish():Rr.start(this)}_stop(n,e){if(is(this)){Nc(this,!1);const t=this.animation;_e(t.values,i=>{i.done=!0}),t.toValues&&(t.onChange=t.onPause=t.onResume=void 0),or(this,{type:"idle",parent:this});const s=e?ni(this.get()):_t(this.get(),Di(this,n??t.to));Ki(this._pendingCalls,s),t.changed&&(t.changed=!1,Li(this,"onRest",s,this))}}};function Di(n,e){const t=rn(e),s=rn(n.get());return qt(s,t)}function bd(n,e=n.loop,t=n.to){const s=xs(e);if(s){const i=s!==!0&&_d(s),r=(i||n).reverse,a=!i||i.reset;return on({...n,loop:e,default:!1,pause:void 0,to:!r||co(t)?t:void 0,from:a?n.from:void 0,reset:a,...i})}}function on(n){const{to:e,from:t}=n=_d(n),s=new Set;return q.obj(e)&&Kc(e,s),q.obj(t)&&Kc(t,s),n.keys=s.size?Array.from(s):null,n}function xy(n){const e=on(n);return q.und(e.default)&&(e.default=ol(e)),e}function Kc(n,e){ss(n,(t,s)=>t!=null&&e.add(s))}var vy=["onStart","onRest","onChange","onPause","onResume"];function Vc(n,e,t){n.animation[t]=e[t]!==Sd(e,t)?Td(e[t],n.key):void 0}function Li(n,e,...t){var s,i,r,a;(i=(s=n.animation)[e])==null||i.call(s,...t),(a=(r=n.defaultProps)[e])==null||a.call(r,...t)}var Ry=["onStart","onChange","onRest"],wy=1,Dy=class{constructor(n,e){this.id=wy++,this.springs={},this.queue=[],this._lastAsyncId=0,this._active=new Set,this._changed=new Set,this._started=!1,this._state={paused:!1,pauseQueue:new Set,resumeQueue:new Set,timeouts:new Set},this._events={onStart:new Map,onChange:new Map,onRest:new Map},this._onFrame=this._onFrame.bind(this),e&&(this._flush=e),n&&this.start({default:!0,...n})}get idle(){return!this._state.asyncTo&&Object.values(this.springs).every(n=>n.idle&&!n.isDelayed&&!n.isPaused)}get item(){return this._item}set item(n){this._item=n}get(){const n={};return this.each((e,t)=>n[t]=e.get()),n}set(n){for(const e in n){const t=n[e];q.und(t)||this.springs[e].set(t)}}update(n){return n&&this.queue.push(on(n)),this}start(n){let{queue:e}=this;return n?e=pt(n).map(on):this.queue=[],this._flush?this._flush(this,e):(Od(this,e),Ao(this,e))}stop(n,e){if(n!==!!n&&(e=n),e){const t=this.springs;_e(pt(e),s=>t[s].stop(!!n))}else an(this._state,this._lastAsyncId),this.each(t=>t.stop(!!n));return this}pause(n){if(q.und(n))this.start({pause:!0});else{const e=this.springs;_e(pt(n),t=>e[t].pause())}return this}resume(n){if(q.und(n))this.start({pause:!1});else{const e=this.springs;_e(pt(n),t=>e[t].resume())}return this}each(n){ss(this.springs,n)}_onFrame(){const{onStart:n,onChange:e,onRest:t}=this._events,s=this._active.size>0,i=this._changed.size>0;(s&&!this._started||i&&!this._started)&&(this._started=!0,zi(n,([o,l])=>{l.value=this.get(),o(l,this,this._item)}));const r=!s&&this._started,a=i||r&&t.size?this.get():null;i&&e.size&&zi(e,([o,l])=>{l.value=a,o(l,this,this._item)}),r&&(this._started=!1,zi(t,([o,l])=>{l.value=a,o(l,this,this._item)}))}eventObserved(n){if(n.type=="change")this._changed.add(n.parent),n.idle||this._active.add(n.parent);else if(n.type=="idle")this._active.delete(n.parent);else return;Ae.onFrame(this._onFrame)}};function Ao(n,e){return Promise.all(e.map(t=>Md(n,t))).then(t=>ll(n,t))}async function Md(n,e,t){const{keys:s,to:i,from:r,loop:a,onRest:o,onResolve:l}=e,c=q.obj(e.default)&&e.default;a&&(e.loop=!1),i===!1&&(e.to=null),r===!1&&(e.from=null);const h=q.arr(i)||q.fun(i)?i:void 0;h?(e.to=void 0,e.onRest=void 0,c&&(c.onRest=void 0)):_e(Ry,g=>{const p=e[g];if(q.fun(p)){const m=n._events[g];e[g]=({finished:C,cancelled:E})=>{const B=m.get(p);B?(C||(B.finished=!1),E&&(B.cancelled=!0)):m.set(p,{value:null,finished:C||!1,cancelled:E||!1})},c&&(c[g]=e[g])}});const u=n._state;e.pause===!u.paused?(u.paused=e.pause,Ki(e.pause?u.pauseQueue:u.resumeQueue)):u.paused&&(e.pause=!0);const d=(s||Object.keys(n.springs)).map(g=>n.springs[g].start(e)),A=e.cancel===!0||Sd(e,"cancel")===!0;(h||A&&u.asyncId)&&d.push(xd(++n._lastAsyncId,{props:e,state:u,actions:{pause:ao,resume:ao,start(g,p){A?(an(u,n._lastAsyncId),p(ni(n))):(g.onRest=o,p(Rd(h,g,u,n)))}}})),u.paused&&await new Promise(g=>{u.resumeQueue.add(g)});const f=ll(n,await Promise.all(d));if(a&&f.finished&&!(t&&f.noop)){const g=bd(e,a,i);if(g)return Od(n,[g]),Md(n,g,!0)}return l&&Ae.batchedUpdates(()=>l(f,n,n.item)),f}function Yc(n,e){const t={...n.springs};return e&&_e(pt(e),s=>{q.und(s.keys)&&(s=on(s)),q.obj(s.to)||(s={...s,to:void 0}),kd(t,s,i=>Pd(i))}),Fd(n,t),t}function Fd(n,e){ss(e,(t,s)=>{n.springs[s]||(n.springs[s]=t,dn(t,n))})}function Pd(n,e){const t=new _y;return t.key=n,e&&dn(t,e),t}function kd(n,e,t){e.keys&&_e(e.keys,s=>{(n[s]||(n[s]=t(s)))._prepareNode(e)})}function Od(n,e){_e(e,t=>{kd(n.springs,t,s=>Pd(s,n))})}var Mr=({children:n,...e})=>{const t=T.useContext(hr),s=e.pause||!!t.pause,i=e.immediate||!!t.immediate;e=ny(()=>({pause:s,immediate:i}),[s,i]);const{Provider:r}=hr;return T.createElement(r,{value:e},n)},hr=Ly(Mr,{});Mr.Provider=hr.Provider;Mr.Consumer=hr.Consumer;function Ly(n,e){return Object.assign(n,T.createContext(e)),n.Provider._context=n,n.Consumer._context=n,n}var by=()=>{const n=[],e=function(s){sy();const i=[];return _e(n,(r,a)=>{if(q.und(s))i.push(r.start());else{const o=t(s,r,a);o&&i.push(r.start(o))}}),i};e.current=n,e.add=function(s){n.includes(s)||n.push(s)},e.delete=function(s){const i=n.indexOf(s);~i&&n.splice(i,1)},e.pause=function(){return _e(n,s=>s.pause(...arguments)),this},e.resume=function(){return _e(n,s=>s.resume(...arguments)),this},e.set=function(s){_e(n,(i,r)=>{const a=q.fun(s)?s(r,i):s;a&&i.set(a)})},e.start=function(s){const i=[];return _e(n,(r,a)=>{if(q.und(s))i.push(r.start());else{const o=this._getProps(s,r,a);o&&i.push(r.start(o))}}),i},e.stop=function(){return _e(n,s=>s.stop(...arguments)),this},e.update=function(s){return _e(n,(i,r)=>i.update(this._getProps(s,i,r))),this};const t=function(s,i,r){return q.fun(s)?s(r,i):s};return e._getProps=t,e};function My(n,e,t){const s=q.fun(e)&&e;s&&!t&&(t=[]);const i=T.useMemo(()=>s||arguments.length==3?by():void 0,[]),r=T.useRef(0),a=Cd(),o=T.useMemo(()=>({ctrls:[],queue:[],flush(m,C){const E=Yc(m,C);return r.current>0&&!o.queue.length&&!Object.keys(E).some(I=>!m.springs[I])?Ao(m,C):new Promise(I=>{Fd(m,E),o.queue.push(()=>{I(Ao(m,C))}),a()})}}),[]),l=T.useRef([...o.ctrls]),c=[],h=Mc(n)||0;T.useMemo(()=>{_e(l.current.slice(n,h),m=>{Ey(m,i),m.stop(!0)}),l.current.length=n,u(h,n)},[n]),T.useMemo(()=>{u(0,Math.min(h,n))},t);function u(m,C){for(let E=m;E<C;E++){const B=l.current[E]||(l.current[E]=new Dy(null,o.flush)),I=s?s(E,B):e[E];I&&(c[E]=xy(I))}}const d=l.current.map((m,C)=>Yc(m,c[C])),A=T.useContext(Mr),f=Mc(A),g=A!==f&&py(A);nl(()=>{r.current++,o.ctrls=l.current;const{queue:m}=o;m.length&&(o.queue=[],_e(m,C=>C())),_e(l.current,(C,E)=>{i==null||i.add(C),g&&C.start({default:A});const B=c[E];B&&(Cy(C,B.ref),C.ref?C.queue.push(B):C.start(B))})}),Id(()=>()=>{_e(o.ctrls,m=>m.stop(!0))});const p=d.map(m=>({...m}));return i?[p,i]:p}function Fy(n,e){const t=q.fun(n),[[s],i]=My(1,t?n:[n],t?[]:e);return t||arguments.length==2?[s,i]:s}var Py=class extends cl{constructor(n,e){super(),this.source=n,this.idle=!0,this._active=new Set,this.calc=en(...e);const t=this._get(),s=lo(t);rl(this,s.create(t))}advance(n){const e=this._get(),t=this.get();qt(e,t)||(Ft(this).setValue(e),this._onChange(e,this.idle)),!this.idle&&Jc(this._active)&&ea(this)}_get(){const n=q.arr(this.source)?this.source.map(At):pt(At(this.source));return this.calc(...n)}_start(){this.idle&&!Jc(this._active)&&(this.idle=!1,_e(br(this),n=>{n.done=!1}),Rt.skipAnimation?(Ae.batchedUpdates(()=>this.advance()),ea(this)):Rr.start(this))}_attach(){let n=1;_e(pt(this.source),e=>{kt(e)&&dn(e,this),uo(e)&&(e.idle||this._active.add(e),n=Math.max(n,e.priority+1))}),this.priority=n,this._start()}_detach(){_e(pt(this.source),n=>{kt(n)&&lr(n,this)}),this._active.clear(),ea(this)}eventObserved(n){n.type=="change"?n.idle?this.advance():(this._active.add(n.parent),this._start()):n.type=="idle"?this._active.delete(n.parent):n.type=="priority"&&(this.priority=pt(this.source).reduce((e,t)=>Math.max(e,(uo(t)?t.priority:0)+1),0))}};function ky(n){return n.idle!==!1}function Jc(n){return!n.size||Array.from(n).every(ky)}function ea(n){n.idle||(n.idle=!0,_e(br(n),e=>{e.done=!0}),or(n,{type:"idle",parent:n}))}Rt.assign({createStringInterpolator:pd,to:(n,e)=>new Py(n,e)});var Oy=["primitive"].concat(Object.keys(Zf).filter(n=>/^[A-Z]/.test(n)).map(n=>n[0].toLowerCase()+n.slice(1)));Rt.assign({createStringInterpolator:pd,colors:bI,frameLoop:"demand"});ko(()=>{Ae.advance()});var Qy=dy(Oy,{applyAnimatedValues:Oo}),Gy=Qy.animated;function Uy({enabled:n=!0,snap:e,global:t,domElement:s,cursor:i=!0,children:r,speed:a=1,rotation:o=[0,0,0],zoom:l=1,polar:c=[0,Math.PI/2],azimuth:h=[-1/0,1/0],config:u={mass:1,tension:170,friction:26}}){const d=$(_=>_.events),A=$(_=>_.gl),f=s||d.connected||A.domElement,{size:g}=$(),p=T.useMemo(()=>[o[0]+c[0],o[0]+c[1]],[o[0],c[0],c[1]]),m=T.useMemo(()=>[o[1]+h[0],o[1]+h[1]],[o[1],h[0],h[1]]),C=T.useMemo(()=>[le.clamp(o[0],...p),le.clamp(o[1],...m),o[2]],[o[0],o[1],o[2],p,m]),[E,B]=Fy(()=>({scale:1,rotation:C,config:u}));T.useEffect(()=>void B.start({scale:1,rotation:C,config:u}),[C]),T.useEffect(()=>{if(t&&i&&n)return f.style.cursor="grab",A.domElement.style.cursor="",()=>{f.style.cursor="default",A.domElement.style.cursor="default"}},[t,i,f,n]);const I=vu({onHover:({last:_})=>{i&&!t&&n&&(f.style.cursor=_?"auto":"grab")},onDrag:({down:_,delta:[S,x],memo:[b,v]=E.rotation.animation.to||C})=>{if(!n)return[x,S];i&&(f.style.cursor=_?"grabbing":"grab"),S=le.clamp(v+S/g.width*Math.PI*a,...m),x=le.clamp(b+x/g.height*Math.PI*a,...p);const D=e&&!_&&typeof e!="boolean"?e:u;return B.start({scale:_&&x>p[1]/2?l:1,rotation:e&&!_?C:[x,S,0],config:U=>U==="scale"?{...D,friction:D.friction*3}:D}),[x,S]}},{target:t?f:void 0});return T.createElement(Gy.group,be({},I==null?void 0:I(),E),r)}const Ny=n=>(e,t,s)=>{const i=s.subscribe;return s.subscribe=(a,o,l)=>{let c=a;if(o){const h=(l==null?void 0:l.equalityFn)||Object.is;let u=a(s.getState());c=d=>{const A=a(d);if(!h(u,A)){const f=u;o(u=A,f)}},l!=null&&l.fireImmediately&&o(u,u)}return i(c)},n(e,t,s)},Hy=Ny,Qd=T.createContext(null);function Ky({map:n,children:e,onChange:t,domElement:s}){const i=n.map(l=>l.name+l.keys).join("-"),r=T.useMemo(()=>Xu(Hy(()=>n.reduce((l,c)=>({...l,[c.name]:!1}),{}))),[i]),a=T.useMemo(()=>[r.subscribe,r.getState,r],[i]),o=r.setState;return T.useEffect(()=>{const c=n.map(({name:A,keys:f,up:g})=>({keys:f,up:g,fn:p=>{o({[A]:p}),t&&t(A,p,a[1]())}})).reduce((A,{keys:f,fn:g,up:p=!0})=>(f.forEach(m=>A[m]={fn:g,pressed:!1,up:p}),A),{}),h=({key:A,code:f})=>{const g=c[A]||c[f];if(!g)return;const{fn:p,pressed:m,up:C}=g;g.pressed=!0,(C||!m)&&p(!0)},u=({key:A,code:f})=>{const g=c[A]||c[f];if(!g)return;const{fn:p,up:m}=g;g.pressed=!1,m&&p(!1)},d=s||window;return d.addEventListener("keydown",h,{passive:!0}),d.addEventListener("keyup",u,{passive:!0}),()=>{d.removeEventListener("keydown",h),d.removeEventListener("keyup",u)}},[s,i]),T.createElement(Qd.Provider,{value:a,children:e})}function Vy(n){const[e,t,s]=T.useContext(Qd);return n?s(n):[e,t]}var Yy=Object.defineProperty,Jy=(n,e,t)=>e in n?Yy(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,de=(n,e,t)=>(Jy(n,typeof e!="symbol"?e+"":e,t),t);const zc=new P;let zy=class extends pi{constructor(e,t){super(),de(this,"object"),de(this,"domElement"),de(this,"enabled",!0),de(this,"movementSpeed",1),de(this,"lookSpeed",.005),de(this,"lookVertical",!0),de(this,"autoForward",!1),de(this,"activeLook",!0),de(this,"heightSpeed",!1),de(this,"heightCoef",1),de(this,"heightMin",0),de(this,"heightMax",1),de(this,"constrainVertical",!1),de(this,"verticalMin",0),de(this,"verticalMax",Math.PI),de(this,"mouseDragOn",!1),de(this,"autoSpeedFactor",0),de(this,"mouseX",0),de(this,"mouseY",0),de(this,"moveForward",!1),de(this,"moveBackward",!1),de(this,"moveLeft",!1),de(this,"moveRight",!1),de(this,"moveUp",!1),de(this,"moveDown",!1),de(this,"viewHalfX",0),de(this,"viewHalfY",0),de(this,"lat",0),de(this,"lon",0),de(this,"lookDirection",new P),de(this,"spherical",new Po),de(this,"target",new P),de(this,"connect",s=>{s.setAttribute("tabindex","-1"),s.style.touchAction="none",s.addEventListener("contextmenu",this.contextmenu),s.addEventListener("mousemove",this.onMouseMove),s.addEventListener("mousedown",this.onMouseDown),s.addEventListener("mouseup",this.onMouseUp),this.domElement=s,window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),this.handleResize()}),de(this,"dispose",()=>{var s,i,r,a;(s=this.domElement)==null||s.removeEventListener("contextmenu",this.contextmenu),(i=this.domElement)==null||i.removeEventListener("mousedown",this.onMouseDown),(r=this.domElement)==null||r.removeEventListener("mousemove",this.onMouseMove),(a=this.domElement)==null||a.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}),de(this,"handleResize",()=>{this.domElement&&(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}),de(this,"onMouseDown",s=>{var i;if((i=this.domElement)==null||i.focus(),this.activeLook)switch(s.button){case 0:this.moveForward=!0;break;case 2:this.moveBackward=!0;break}this.mouseDragOn=!0}),de(this,"onMouseUp",s=>{if(this.activeLook)switch(s.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}),de(this,"onMouseMove",s=>{this.domElement&&(this.mouseX=s.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=s.pageY-this.domElement.offsetTop-this.viewHalfY)}),de(this,"onKeyDown",s=>{switch(s.code){case"ArrowUp":case"KeyW":this.moveForward=!0;break;case"ArrowLeft":case"KeyA":this.moveLeft=!0;break;case"ArrowDown":case"KeyS":this.moveBackward=!0;break;case"ArrowRight":case"KeyD":this.moveRight=!0;break;case"KeyR":this.moveUp=!0;break;case"KeyF":this.moveDown=!0;break}}),de(this,"onKeyUp",s=>{switch(s.code){case"ArrowUp":case"KeyW":this.moveForward=!1;break;case"ArrowLeft":case"KeyA":this.moveLeft=!1;break;case"ArrowDown":case"KeyS":this.moveBackward=!1;break;case"ArrowRight":case"KeyD":this.moveRight=!1;break;case"KeyR":this.moveUp=!1;break;case"KeyF":this.moveDown=!1;break}}),de(this,"lookAt",(s,i,r)=>(s instanceof P?this.target.copy(s):i&&r&&this.target.set(s,i,r),this.object.lookAt(this.target),this.setOrientation(),this)),de(this,"update",s=>{if(!this.enabled)return;if(this.heightSpeed){const u=le.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=s*(u*this.heightCoef)}else this.autoSpeedFactor=0;const i=s*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(i+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(i),this.moveLeft&&this.object.translateX(-i),this.moveRight&&this.object.translateX(i),this.moveUp&&this.object.translateY(i),this.moveDown&&this.object.translateY(-i);let r=s*this.lookSpeed;this.activeLook||(r=0);let a=1;this.constrainVertical&&(a=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.mouseX*r,this.lookVertical&&(this.lat-=this.mouseY*r*a),this.lat=Math.max(-85,Math.min(85,this.lat));let o=le.degToRad(90-this.lat);const l=le.degToRad(this.lon);this.constrainVertical&&(o=le.mapLinear(o,0,Math.PI,this.verticalMin,this.verticalMax));const c=this.object.position;zc.setFromSphericalCoords(1,o,l).add(c),this.object.lookAt(zc)}),de(this,"contextmenu",s=>s.preventDefault()),de(this,"setOrientation",()=>{this.lookDirection.set(0,0,-1).applyQuaternion(this.object.quaternion),this.spherical.setFromVector3(this.lookDirection),this.lat=90-le.radToDeg(this.spherical.phi),this.lon=le.radToDeg(this.spherical.theta)}),this.object=e,this.domElement=t,this.setOrientation(),t&&this.connect(t)}};var qy=Object.defineProperty,$y=(n,e,t)=>e in n?qy(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,k=(n,e,t)=>($y(n,typeof e!="symbol"?e+"":e,t),t);let Xy=class extends Xe{constructor(e,t){super(),k(this,"isTransformControls",!0),k(this,"visible",!1),k(this,"domElement"),k(this,"raycaster",new Br),k(this,"gizmo"),k(this,"plane"),k(this,"tempVector",new P),k(this,"tempVector2",new P),k(this,"tempQuaternion",new Ie),k(this,"unit",{X:new P(1,0,0),Y:new P(0,1,0),Z:new P(0,0,1)}),k(this,"pointStart",new P),k(this,"pointEnd",new P),k(this,"offset",new P),k(this,"rotationAxis",new P),k(this,"startNorm",new P),k(this,"endNorm",new P),k(this,"rotationAngle",0),k(this,"cameraPosition",new P),k(this,"cameraQuaternion",new Ie),k(this,"cameraScale",new P),k(this,"parentPosition",new P),k(this,"parentQuaternion",new Ie),k(this,"parentQuaternionInv",new Ie),k(this,"parentScale",new P),k(this,"worldPositionStart",new P),k(this,"worldQuaternionStart",new Ie),k(this,"worldScaleStart",new P),k(this,"worldPosition",new P),k(this,"worldQuaternion",new Ie),k(this,"worldQuaternionInv",new Ie),k(this,"worldScale",new P),k(this,"eye",new P),k(this,"positionStart",new P),k(this,"quaternionStart",new Ie),k(this,"scaleStart",new P),k(this,"camera"),k(this,"object"),k(this,"enabled",!0),k(this,"axis",null),k(this,"mode","translate"),k(this,"translationSnap",null),k(this,"rotationSnap",null),k(this,"scaleSnap",null),k(this,"space","world"),k(this,"size",1),k(this,"dragging",!1),k(this,"showX",!0),k(this,"showY",!0),k(this,"showZ",!0),k(this,"changeEvent",{type:"change"}),k(this,"mouseDownEvent",{type:"mouseDown",mode:this.mode}),k(this,"mouseUpEvent",{type:"mouseUp",mode:this.mode}),k(this,"objectChangeEvent",{type:"objectChange"}),k(this,"intersectObjectWithRay",(i,r,a)=>{const o=r.intersectObject(i,!0);for(let l=0;l<o.length;l++)if(o[l].object.visible||a)return o[l];return!1}),k(this,"attach",i=>(this.object=i,this.visible=!0,this)),k(this,"detach",()=>(this.object=void 0,this.visible=!1,this.axis=null,this)),k(this,"reset",()=>this.enabled?(this.dragging&&this.object!==void 0&&(this.object.position.copy(this.positionStart),this.object.quaternion.copy(this.quaternionStart),this.object.scale.copy(this.scaleStart),this.dispatchEvent(this.changeEvent),this.dispatchEvent(this.objectChangeEvent),this.pointStart.copy(this.pointEnd)),this):this),k(this,"updateMatrixWorld",()=>{this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this.parentPosition,this.parentQuaternion,this.parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this.worldScale),this.parentQuaternionInv.copy(this.parentQuaternion).invert(),this.worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this.cameraScale),this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld()}),k(this,"pointerHover",i=>{if(this.object===void 0||this.dragging===!0)return;this.raycaster.setFromCamera(i,this.camera);const r=this.intersectObjectWithRay(this.gizmo.picker[this.mode],this.raycaster);r?this.axis=r.object.name:this.axis=null}),k(this,"pointerDown",i=>{if(!(this.object===void 0||this.dragging===!0||i.button!==0)&&this.axis!==null){this.raycaster.setFromCamera(i,this.camera);const r=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(r){let a=this.space;if(this.mode==="scale"?a="local":(this.axis==="E"||this.axis==="XYZE"||this.axis==="XYZ")&&(a="world"),a==="local"&&this.mode==="rotate"){const o=this.rotationSnap;this.axis==="X"&&o&&(this.object.rotation.x=Math.round(this.object.rotation.x/o)*o),this.axis==="Y"&&o&&(this.object.rotation.y=Math.round(this.object.rotation.y/o)*o),this.axis==="Z"&&o&&(this.object.rotation.z=Math.round(this.object.rotation.z/o)*o)}this.object.updateMatrixWorld(),this.object.parent&&this.object.parent.updateMatrixWorld(),this.positionStart.copy(this.object.position),this.quaternionStart.copy(this.object.quaternion),this.scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this.worldScaleStart),this.pointStart.copy(r.point).sub(this.worldPositionStart)}this.dragging=!0,this.mouseDownEvent.mode=this.mode,this.dispatchEvent(this.mouseDownEvent)}}),k(this,"pointerMove",i=>{const r=this.axis,a=this.mode,o=this.object;let l=this.space;if(a==="scale"?l="local":(r==="E"||r==="XYZE"||r==="XYZ")&&(l="world"),o===void 0||r===null||this.dragging===!1||i.button!==-1)return;this.raycaster.setFromCamera(i,this.camera);const c=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(c){if(this.pointEnd.copy(c.point).sub(this.worldPositionStart),a==="translate")this.offset.copy(this.pointEnd).sub(this.pointStart),l==="local"&&r!=="XYZ"&&this.offset.applyQuaternion(this.worldQuaternionInv),r.indexOf("X")===-1&&(this.offset.x=0),r.indexOf("Y")===-1&&(this.offset.y=0),r.indexOf("Z")===-1&&(this.offset.z=0),l==="local"&&r!=="XYZ"?this.offset.applyQuaternion(this.quaternionStart).divide(this.parentScale):this.offset.applyQuaternion(this.parentQuaternionInv).divide(this.parentScale),o.position.copy(this.offset).add(this.positionStart),this.translationSnap&&(l==="local"&&(o.position.applyQuaternion(this.tempQuaternion.copy(this.quaternionStart).invert()),r.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(o.position.z=Math.round(o.position.z/this.translationSnap)*this.translationSnap),o.position.applyQuaternion(this.quaternionStart)),l==="world"&&(o.parent&&o.position.add(this.tempVector.setFromMatrixPosition(o.parent.matrixWorld)),r.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(o.position.z=Math.round(o.position.z/this.translationSnap)*this.translationSnap),o.parent&&o.position.sub(this.tempVector.setFromMatrixPosition(o.parent.matrixWorld))));else if(a==="scale"){if(r.search("XYZ")!==-1){let h=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(h*=-1),this.tempVector2.set(h,h,h)}else this.tempVector.copy(this.pointStart),this.tempVector2.copy(this.pointEnd),this.tempVector.applyQuaternion(this.worldQuaternionInv),this.tempVector2.applyQuaternion(this.worldQuaternionInv),this.tempVector2.divide(this.tempVector),r.search("X")===-1&&(this.tempVector2.x=1),r.search("Y")===-1&&(this.tempVector2.y=1),r.search("Z")===-1&&(this.tempVector2.z=1);o.scale.copy(this.scaleStart).multiply(this.tempVector2),this.scaleSnap&&this.object&&(r.search("X")!==-1&&(this.object.scale.x=Math.round(o.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Y")!==-1&&(o.scale.y=Math.round(o.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Z")!==-1&&(o.scale.z=Math.round(o.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(a==="rotate"){this.offset.copy(this.pointEnd).sub(this.pointStart);const h=20/this.worldPosition.distanceTo(this.tempVector.setFromMatrixPosition(this.camera.matrixWorld));r==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this.startNorm.copy(this.pointStart).normalize(),this.endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this.endNorm.cross(this.startNorm).dot(this.eye)<0?1:-1):r==="XYZE"?(this.rotationAxis.copy(this.offset).cross(this.eye).normalize(),this.rotationAngle=this.offset.dot(this.tempVector.copy(this.rotationAxis).cross(this.eye))*h):(r==="X"||r==="Y"||r==="Z")&&(this.rotationAxis.copy(this.unit[r]),this.tempVector.copy(this.unit[r]),l==="local"&&this.tempVector.applyQuaternion(this.worldQuaternion),this.rotationAngle=this.offset.dot(this.tempVector.cross(this.eye).normalize())*h),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),l==="local"&&r!=="E"&&r!=="XYZE"?(o.quaternion.copy(this.quaternionStart),o.quaternion.multiply(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this.parentQuaternionInv),o.quaternion.copy(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),o.quaternion.multiply(this.quaternionStart).normalize())}this.dispatchEvent(this.changeEvent),this.dispatchEvent(this.objectChangeEvent)}}),k(this,"pointerUp",i=>{i.button===0&&(this.dragging&&this.axis!==null&&(this.mouseUpEvent.mode=this.mode,this.dispatchEvent(this.mouseUpEvent)),this.dragging=!1,this.axis=null)}),k(this,"getPointer",i=>{var r;if(this.domElement&&((r=this.domElement.ownerDocument)!=null&&r.pointerLockElement))return{x:0,y:0,button:i.button};{const a=i.changedTouches?i.changedTouches[0]:i,o=this.domElement.getBoundingClientRect();return{x:(a.clientX-o.left)/o.width*2-1,y:-(a.clientY-o.top)/o.height*2+1,button:i.button}}}),k(this,"onPointerHover",i=>{if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this.getPointer(i));break}}),k(this,"onPointerDown",i=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="none",this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.pointerHover(this.getPointer(i)),this.pointerDown(this.getPointer(i)))}),k(this,"onPointerMove",i=>{this.enabled&&this.pointerMove(this.getPointer(i))}),k(this,"onPointerUp",i=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="",this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.pointerUp(this.getPointer(i)))}),k(this,"getMode",()=>this.mode),k(this,"setMode",i=>{this.mode=i}),k(this,"setTranslationSnap",i=>{this.translationSnap=i}),k(this,"setRotationSnap",i=>{this.rotationSnap=i}),k(this,"setScaleSnap",i=>{this.scaleSnap=i}),k(this,"setSize",i=>{this.size=i}),k(this,"setSpace",i=>{this.space=i}),k(this,"update",()=>{console.warn("THREE.TransformControls: update function has no more functionality and therefore has been deprecated.")}),k(this,"connect",i=>{i===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.domElement=i,this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("pointermove",this.onPointerHover),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp)}),k(this,"dispose",()=>{var i,r,a,o,l,c;(i=this.domElement)==null||i.removeEventListener("pointerdown",this.onPointerDown),(r=this.domElement)==null||r.removeEventListener("pointermove",this.onPointerHover),(o=(a=this.domElement)==null?void 0:a.ownerDocument)==null||o.removeEventListener("pointermove",this.onPointerMove),(c=(l=this.domElement)==null?void 0:l.ownerDocument)==null||c.removeEventListener("pointerup",this.onPointerUp),this.traverse(h=>{const u=h;u.geometry&&u.geometry.dispose(),u.material&&u.material.dispose()})}),this.domElement=t,this.camera=e,this.gizmo=new jy,this.add(this.gizmo),this.plane=new Wy,this.add(this.plane);const s=(i,r)=>{let a=r;Object.defineProperty(this,i,{get:function(){return a!==void 0?a:r},set:function(o){a!==o&&(a=o,this.plane[i]=o,this.gizmo[i]=o,this.dispatchEvent({type:i+"-changed",value:o}),this.dispatchEvent(this.changeEvent))}}),this[i]=r,this.plane[i]=r,this.gizmo[i]=r};s("camera",this.camera),s("object",this.object),s("enabled",this.enabled),s("axis",this.axis),s("mode",this.mode),s("translationSnap",this.translationSnap),s("rotationSnap",this.rotationSnap),s("scaleSnap",this.scaleSnap),s("space",this.space),s("size",this.size),s("dragging",this.dragging),s("showX",this.showX),s("showY",this.showY),s("showZ",this.showZ),s("worldPosition",this.worldPosition),s("worldPositionStart",this.worldPositionStart),s("worldQuaternion",this.worldQuaternion),s("worldQuaternionStart",this.worldQuaternionStart),s("cameraPosition",this.cameraPosition),s("cameraQuaternion",this.cameraQuaternion),s("pointStart",this.pointStart),s("pointEnd",this.pointEnd),s("rotationAxis",this.rotationAxis),s("rotationAngle",this.rotationAngle),s("eye",this.eye),t!==void 0&&this.connect(t)}};class jy extends Xe{constructor(){super(),k(this,"isTransformControlsGizmo",!0),k(this,"type","TransformControlsGizmo"),k(this,"tempVector",new P(0,0,0)),k(this,"tempEuler",new Zt),k(this,"alignVector",new P(0,1,0)),k(this,"zeroVector",new P(0,0,0)),k(this,"lookAtMatrix",new he),k(this,"tempQuaternion",new Ie),k(this,"tempQuaternion2",new Ie),k(this,"identityQuaternion",new Ie),k(this,"unitX",new P(1,0,0)),k(this,"unitY",new P(0,1,0)),k(this,"unitZ",new P(0,0,1)),k(this,"gizmo"),k(this,"picker"),k(this,"helper"),k(this,"rotationAxis",new P),k(this,"cameraPosition",new P),k(this,"worldPositionStart",new P),k(this,"worldQuaternionStart",new Ie),k(this,"worldPosition",new P),k(this,"worldQuaternion",new Ie),k(this,"eye",new P),k(this,"camera",null),k(this,"enabled",!0),k(this,"axis",null),k(this,"mode","translate"),k(this,"space","world"),k(this,"size",1),k(this,"dragging",!1),k(this,"showX",!0),k(this,"showY",!0),k(this,"showZ",!0),k(this,"updateMatrixWorld",()=>{let G=this.space;this.mode==="scale"&&(G="local");const H=G==="local"?this.worldQuaternion:this.identityQuaternion;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let J=[];J=J.concat(this.picker[this.mode].children),J=J.concat(this.gizmo[this.mode].children),J=J.concat(this.helper[this.mode].children);for(let K=0;K<J.length;K++){const R=J[K];R.visible=!0,R.rotation.set(0,0,0),R.position.copy(this.worldPosition);let te;if(this.camera.isOrthographicCamera?te=(this.camera.top-this.camera.bottom)/this.camera.zoom:te=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),R.scale.set(1,1,1).multiplyScalar(te*this.size/7),R.tag==="helper"){R.visible=!1,R.name==="AXIS"?(R.position.copy(this.worldPositionStart),R.visible=!!this.axis,this.axis==="X"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,0)),R.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Y"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,Math.PI/2)),R.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Z"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),R.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="XYZE"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),this.alignVector.copy(this.rotationAxis),R.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.zeroVector,this.alignVector,this.unitY)),R.quaternion.multiply(this.tempQuaternion),R.visible=this.dragging),this.axis==="E"&&(R.visible=!1)):R.name==="START"?(R.position.copy(this.worldPositionStart),R.visible=this.dragging):R.name==="END"?(R.position.copy(this.worldPosition),R.visible=this.dragging):R.name==="DELTA"?(R.position.copy(this.worldPositionStart),R.quaternion.copy(this.worldQuaternionStart),this.tempVector.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),this.tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()),R.scale.copy(this.tempVector),R.visible=this.dragging):(R.quaternion.copy(H),this.dragging?R.position.copy(this.worldPositionStart):R.position.copy(this.worldPosition),this.axis&&(R.visible=this.axis.search(R.name)!==-1));continue}R.quaternion.copy(H),this.mode==="translate"||this.mode==="scale"?((R.name==="X"||R.name==="XYZX")&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),(R.name==="Y"||R.name==="XYZY")&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),(R.name==="Z"||R.name==="XYZZ")&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="XY"&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="YZ"&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="XZ"&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name.search("X")!==-1&&(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.x*=-1:R.tag==="bwd"&&(R.visible=!1)),R.name.search("Y")!==-1&&(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.y*=-1:R.tag==="bwd"&&(R.visible=!1)),R.name.search("Z")!==-1&&(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.z*=-1:R.tag==="bwd"&&(R.visible=!1))):this.mode==="rotate"&&(this.tempQuaternion2.copy(H),this.alignVector.copy(this.eye).applyQuaternion(this.tempQuaternion.copy(H).invert()),R.name.search("E")!==-1&&R.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.eye,this.zeroVector,this.unitY)),R.name==="X"&&(this.tempQuaternion.setFromAxisAngle(this.unitX,Math.atan2(-this.alignVector.y,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion)),R.name==="Y"&&(this.tempQuaternion.setFromAxisAngle(this.unitY,Math.atan2(this.alignVector.x,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion)),R.name==="Z"&&(this.tempQuaternion.setFromAxisAngle(this.unitZ,Math.atan2(this.alignVector.y,this.alignVector.x)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion))),R.visible=R.visible&&(R.name.indexOf("X")===-1||this.showX),R.visible=R.visible&&(R.name.indexOf("Y")===-1||this.showY),R.visible=R.visible&&(R.name.indexOf("Z")===-1||this.showZ),R.visible=R.visible&&(R.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),R.material.tempOpacity=R.material.tempOpacity||R.material.opacity,R.material.tempColor=R.material.tempColor||R.material.color.clone(),R.material.color.copy(R.material.tempColor),R.material.opacity=R.material.tempOpacity,this.enabled?this.axis&&(R.name===this.axis?(R.material.opacity=1,R.material.color.lerp(new we(1,1,1),.5)):this.axis.split("").some(function(oe){return R.name===oe})?(R.material.opacity=1,R.material.color.lerp(new we(1,1,1),.5)):(R.material.opacity*=.25,R.material.color.lerp(new we(1,1,1),.5))):(R.material.opacity*=.5,R.material.color.lerp(new we(1,1,1),.5))}super.updateMatrixWorld()});const e=new ls({depthTest:!1,depthWrite:!1,transparent:!0,side:Ei,fog:!1,toneMapped:!1}),t=new Ws({depthTest:!1,depthWrite:!1,transparent:!0,linewidth:1,fog:!1,toneMapped:!1}),s=e.clone();s.opacity=.15;const i=e.clone();i.opacity=.33;const r=e.clone();r.color.set(16711680);const a=e.clone();a.color.set(65280);const o=e.clone();o.color.set(255);const l=e.clone();l.opacity=.25;const c=l.clone();c.color.set(16776960);const h=l.clone();h.color.set(65535);const u=l.clone();u.color.set(16711935),e.clone().color.set(16776960);const A=t.clone();A.color.set(16711680);const f=t.clone();f.color.set(65280);const g=t.clone();g.color.set(255);const p=t.clone();p.color.set(65535);const m=t.clone();m.color.set(16711935);const C=t.clone();C.color.set(16776960);const E=t.clone();E.color.set(7895160);const B=C.clone();B.opacity=.25;const I=new Ct(0,.05,.2,12,1,!1),_=new ms(.125,.125,.125),S=new mt;S.setAttribute("position",new Wt([0,0,0,1,0,0],3));const x=(G,H)=>{const J=new mt,K=[];for(let R=0;R<=64*H;++R)K.push(0,Math.cos(R/32*Math.PI)*G,Math.sin(R/32*Math.PI)*G);return J.setAttribute("position",new Wt(K,3)),J},b=()=>{const G=new mt;return G.setAttribute("position",new Wt([0,0,0,1,1,1],3)),G},v={X:[[new ie(I,r),[1,0,0],[0,0,-Math.PI/2],null,"fwd"],[new ie(I,r),[1,0,0],[0,0,Math.PI/2],null,"bwd"],[new Ce(S,A)]],Y:[[new ie(I,a),[0,1,0],null,null,"fwd"],[new ie(I,a),[0,1,0],[Math.PI,0,0],null,"bwd"],[new Ce(S,f),null,[0,0,Math.PI/2]]],Z:[[new ie(I,o),[0,0,1],[Math.PI/2,0,0],null,"fwd"],[new ie(I,o),[0,0,1],[-Math.PI/2,0,0],null,"bwd"],[new Ce(S,g),null,[0,-Math.PI/2,0]]],XYZ:[[new ie(new ps(.1,0),l.clone()),[0,0,0],[0,0,0]]],XY:[[new ie(new Ss(.295,.295),c.clone()),[.15,.15,0]],[new Ce(S,C),[.18,.3,0],null,[.125,1,1]],[new Ce(S,C),[.3,.18,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new ie(new Ss(.295,.295),h.clone()),[0,.15,.15],[0,Math.PI/2,0]],[new Ce(S,p),[0,.18,.3],[0,0,Math.PI/2],[.125,1,1]],[new Ce(S,p),[0,.3,.18],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new ie(new Ss(.295,.295),u.clone()),[.15,0,.15],[-Math.PI/2,0,0]],[new Ce(S,m),[.18,0,.3],null,[.125,1,1]],[new Ce(S,m),[.3,0,.18],[0,-Math.PI/2,0],[.125,1,1]]]},D={X:[[new ie(new Ct(.2,0,1,4,1,!1),s),[.6,0,0],[0,0,-Math.PI/2]]],Y:[[new ie(new Ct(.2,0,1,4,1,!1),s),[0,.6,0]]],Z:[[new ie(new Ct(.2,0,1,4,1,!1),s),[0,0,.6],[Math.PI/2,0,0]]],XYZ:[[new ie(new ps(.2,0),s)]],XY:[[new ie(new Ss(.4,.4),s),[.2,.2,0]]],YZ:[[new ie(new Ss(.4,.4),s),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new ie(new Ss(.4,.4),s),[.2,0,.2],[-Math.PI/2,0,0]]]},U={START:[[new ie(new ps(.01,2),i),null,null,null,"helper"]],END:[[new ie(new ps(.01,2),i),null,null,null,"helper"]],DELTA:[[new Ce(b(),i),null,null,null,"helper"]],X:[[new Ce(S,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Ce(S,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Ce(S,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},Q={X:[[new Ce(x(1,.5),A)],[new ie(new ps(.04,0),r),[0,0,.99],null,[1,3,1]]],Y:[[new Ce(x(1,.5),f),null,[0,0,-Math.PI/2]],[new ie(new ps(.04,0),a),[0,0,.99],null,[3,1,1]]],Z:[[new Ce(x(1,.5),g),null,[0,Math.PI/2,0]],[new ie(new ps(.04,0),o),[.99,0,0],null,[1,3,1]]],E:[[new Ce(x(1.25,1),B),null,[0,Math.PI/2,0]],[new ie(new Ct(.03,0,.15,4,1,!1),B),[1.17,0,0],[0,0,-Math.PI/2],[1,1,.001]],[new ie(new Ct(.03,0,.15,4,1,!1),B),[-1.17,0,0],[0,0,Math.PI/2],[1,1,.001]],[new ie(new Ct(.03,0,.15,4,1,!1),B),[0,-1.17,0],[Math.PI,0,0],[1,1,.001]],[new ie(new Ct(.03,0,.15,4,1,!1),B),[0,1.17,0],[0,0,0],[1,1,.001]]],XYZE:[[new Ce(x(1,1),E),null,[0,Math.PI/2,0]]]},j={AXIS:[[new Ce(S,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},V={X:[[new ie(new pn(1,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ie(new pn(1,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ie(new pn(1,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ie(new pn(1.25,.1,2,24),s)]],XYZE:[[new ie(new Ru(.7,10,8),s)]]},X={X:[[new ie(_,r),[.8,0,0],[0,0,-Math.PI/2]],[new Ce(S,A),null,null,[.8,1,1]]],Y:[[new ie(_,a),[0,.8,0]],[new Ce(S,f),null,[0,0,Math.PI/2],[.8,1,1]]],Z:[[new ie(_,o),[0,0,.8],[Math.PI/2,0,0]],[new Ce(S,g),null,[0,-Math.PI/2,0],[.8,1,1]]],XY:[[new ie(_,c),[.85,.85,0],null,[2,2,.2]],[new Ce(S,C),[.855,.98,0],null,[.125,1,1]],[new Ce(S,C),[.98,.855,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new ie(_,h),[0,.85,.85],null,[.2,2,2]],[new Ce(S,p),[0,.855,.98],[0,0,Math.PI/2],[.125,1,1]],[new Ce(S,p),[0,.98,.855],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new ie(_,u),[.85,0,.85],null,[2,.2,2]],[new Ce(S,m),[.855,0,.98],null,[.125,1,1]],[new Ce(S,m),[.98,0,.855],[0,-Math.PI/2,0],[.125,1,1]]],XYZX:[[new ie(new ms(.125,.125,.125),l.clone()),[1.1,0,0]]],XYZY:[[new ie(new ms(.125,.125,.125),l.clone()),[0,1.1,0]]],XYZZ:[[new ie(new ms(.125,.125,.125),l.clone()),[0,0,1.1]]]},Z={X:[[new ie(new Ct(.2,0,.8,4,1,!1),s),[.5,0,0],[0,0,-Math.PI/2]]],Y:[[new ie(new Ct(.2,0,.8,4,1,!1),s),[0,.5,0]]],Z:[[new ie(new Ct(.2,0,.8,4,1,!1),s),[0,0,.5],[Math.PI/2,0,0]]],XY:[[new ie(_,s),[.85,.85,0],null,[3,3,.2]]],YZ:[[new ie(_,s),[0,.85,.85],null,[.2,3,3]]],XZ:[[new ie(_,s),[.85,0,.85],null,[3,.2,3]]],XYZX:[[new ie(new ms(.2,.2,.2),s),[1.1,0,0]]],XYZY:[[new ie(new ms(.2,.2,.2),s),[0,1.1,0]]],XYZZ:[[new ie(new ms(.2,.2,.2),s),[0,0,1.1]]]},ae={X:[[new Ce(S,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Ce(S,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Ce(S,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},Y=G=>{const H=new Xe;for(let J in G)for(let K=G[J].length;K--;){const R=G[J][K][0].clone(),te=G[J][K][1],oe=G[J][K][2],ue=G[J][K][3],Je=G[J][K][4];R.name=J,R.tag=Je,te&&R.position.set(te[0],te[1],te[2]),oe&&R.rotation.set(oe[0],oe[1],oe[2]),ue&&R.scale.set(ue[0],ue[1],ue[2]),R.updateMatrix();const rt=R.geometry.clone();rt.applyMatrix4(R.matrix),R.geometry=rt,R.renderOrder=1/0,R.position.set(0,0,0),R.rotation.set(0,0,0),R.scale.set(1,1,1),H.add(R)}return H};this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=Y(v)),this.add(this.gizmo.rotate=Y(Q)),this.add(this.gizmo.scale=Y(X)),this.add(this.picker.translate=Y(D)),this.add(this.picker.rotate=Y(V)),this.add(this.picker.scale=Y(Z)),this.add(this.helper.translate=Y(U)),this.add(this.helper.rotate=Y(j)),this.add(this.helper.scale=Y(ae)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}}class Wy extends ie{constructor(){super(new Ss(1e5,1e5,2,2),new ls({visible:!1,wireframe:!0,side:Ei,transparent:!0,opacity:.1,toneMapped:!1})),k(this,"isTransformControlsPlane",!0),k(this,"type","TransformControlsPlane"),k(this,"unitX",new P(1,0,0)),k(this,"unitY",new P(0,1,0)),k(this,"unitZ",new P(0,0,1)),k(this,"tempVector",new P),k(this,"dirVector",new P),k(this,"alignVector",new P),k(this,"tempMatrix",new he),k(this,"identityQuaternion",new Ie),k(this,"cameraQuaternion",new Ie),k(this,"worldPosition",new P),k(this,"worldQuaternion",new Ie),k(this,"eye",new P),k(this,"axis",null),k(this,"mode","translate"),k(this,"space","world"),k(this,"updateMatrixWorld",()=>{let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),this.unitX.set(1,0,0).applyQuaternion(e==="local"?this.worldQuaternion:this.identityQuaternion),this.unitY.set(0,1,0).applyQuaternion(e==="local"?this.worldQuaternion:this.identityQuaternion),this.unitZ.set(0,0,1).applyQuaternion(e==="local"?this.worldQuaternion:this.identityQuaternion),this.alignVector.copy(this.unitY),this.mode){case"translate":case"scale":switch(this.axis){case"X":this.alignVector.copy(this.eye).cross(this.unitX),this.dirVector.copy(this.unitX).cross(this.alignVector);break;case"Y":this.alignVector.copy(this.eye).cross(this.unitY),this.dirVector.copy(this.unitY).cross(this.alignVector);break;case"Z":this.alignVector.copy(this.eye).cross(this.unitZ),this.dirVector.copy(this.unitZ).cross(this.alignVector);break;case"XY":this.dirVector.copy(this.unitZ);break;case"YZ":this.dirVector.copy(this.unitX);break;case"XZ":this.alignVector.copy(this.unitZ),this.dirVector.copy(this.unitY);break;case"XYZ":case"E":this.dirVector.set(0,0,0);break}break;case"rotate":default:this.dirVector.set(0,0,0)}this.dirVector.length()===0?this.quaternion.copy(this.cameraQuaternion):(this.tempMatrix.lookAt(this.tempVector.set(0,0,0),this.dirVector,this.alignVector),this.quaternion.setFromRotationMatrix(this.tempMatrix)),super.updateMatrixWorld()})}}var Zy=Object.defineProperty,eB=(n,e,t)=>e in n?Zy(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ne=(n,e,t)=>(eB(n,typeof e!="symbol"?e+"":e,t),t);const ks=new Zt(0,0,0,"YXZ"),Os=new P,tB={type:"change"},sB={type:"lock"},iB={type:"unlock"},qc=Math.PI/2;let nB=class extends pi{constructor(e,t){super(),Ne(this,"camera"),Ne(this,"domElement"),Ne(this,"isLocked"),Ne(this,"minPolarAngle"),Ne(this,"maxPolarAngle"),Ne(this,"pointerSpeed"),Ne(this,"onMouseMove",s=>{!this.domElement||this.isLocked===!1||(ks.setFromQuaternion(this.camera.quaternion),ks.y-=s.movementX*.002*this.pointerSpeed,ks.x-=s.movementY*.002*this.pointerSpeed,ks.x=Math.max(qc-this.maxPolarAngle,Math.min(qc-this.minPolarAngle,ks.x)),this.camera.quaternion.setFromEuler(ks),this.dispatchEvent(tB))}),Ne(this,"onPointerlockChange",()=>{this.domElement&&(this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(sB),this.isLocked=!0):(this.dispatchEvent(iB),this.isLocked=!1))}),Ne(this,"onPointerlockError",()=>{console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}),Ne(this,"connect",s=>{this.domElement=s||this.domElement,this.domElement&&(this.domElement.ownerDocument.addEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.addEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.addEventListener("pointerlockerror",this.onPointerlockError))}),Ne(this,"disconnect",()=>{this.domElement&&(this.domElement.ownerDocument.removeEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.removeEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.removeEventListener("pointerlockerror",this.onPointerlockError))}),Ne(this,"dispose",()=>{this.disconnect()}),Ne(this,"getObject",()=>this.camera),Ne(this,"direction",new P(0,0,-1)),Ne(this,"getDirection",s=>s.copy(this.direction).applyQuaternion(this.camera.quaternion)),Ne(this,"moveForward",s=>{Os.setFromMatrixColumn(this.camera.matrix,0),Os.crossVectors(this.camera.up,Os),this.camera.position.addScaledVector(Os,s)}),Ne(this,"moveRight",s=>{Os.setFromMatrixColumn(this.camera.matrix,0),this.camera.position.addScaledVector(Os,s)}),Ne(this,"lock",()=>{this.domElement&&this.domElement.requestPointerLock()}),Ne(this,"unlock",()=>{this.domElement&&this.domElement.ownerDocument.exitPointerLock()}),this.camera=e,this.domElement=t,this.isLocked=!1,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.pointerSpeed=1,t&&this.connect(t)}};var rB=Object.defineProperty,aB=(n,e,t)=>e in n?rB(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,He=(n,e,t)=>(aB(n,typeof e!="symbol"?e+"":e,t),t);let oB=class extends pi{constructor(e){super(),He(this,"object"),He(this,"changeEvent",{type:"change"}),He(this,"EPS",1e-6),He(this,"enabled",!0),He(this,"deviceOrientation",{alpha:0,beta:0,gamma:0}),He(this,"screenOrientation",0),He(this,"alphaOffset",0),He(this,"onDeviceOrientationChangeEvent",t=>{this.deviceOrientation=t}),He(this,"onScreenOrientationChangeEvent",()=>{this.screenOrientation=window.orientation||0}),He(this,"zee",new P(0,0,1)),He(this,"euler",new Zt),He(this,"q0",new Ie),He(this,"q1",new Ie(-Math.sqrt(.5),0,0,Math.sqrt(.5))),He(this,"setObjectQuaternion",(t,s,i,r,a)=>{this.euler.set(i,s,-r,"YXZ"),t.setFromEuler(this.euler),t.multiply(this.q1),t.multiply(this.q0.setFromAxisAngle(this.zee,-a))}),He(this,"connect",()=>{this.onScreenOrientationChangeEvent(),window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission=="function"?window.DeviceOrientationEvent.requestPermission().then(t=>{t=="granted"&&(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent))}).catch(t=>{console.error("THREE.DeviceOrientationControls: Unable to use DeviceOrientation API:",t)}):(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent)),this.enabled=!0}),He(this,"disconnect",()=>{window.removeEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.removeEventListener("deviceorientation",this.onDeviceOrientationChangeEvent),this.enabled=!1}),He(this,"lastQuaternion",new Ie),He(this,"update",()=>{if(this.enabled===!1)return;const t=this.deviceOrientation;if(t){const s=t.alpha?le.degToRad(t.alpha)+this.alphaOffset:0,i=t.beta?le.degToRad(t.beta):0,r=t.gamma?le.degToRad(t.gamma):0,a=this.screenOrientation?le.degToRad(this.screenOrientation):0;this.setObjectQuaternion(this.object.quaternion,s,i,r,a),8*(1-this.lastQuaternion.dot(this.object.quaternion))>this.EPS&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(this.changeEvent))}}),He(this,"dispose",()=>this.disconnect()),this.object=e,this.object.rotation.reorder("YXZ"),this.connect()}};var lB=Object.defineProperty,cB=(n,e,t)=>e in n?lB(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,z=(n,e,t)=>(cB(n,typeof e!="symbol"?e+"":e,t),t);let hB=class extends pi{constructor(e,t){super(),z(this,"enabled",!0),z(this,"screen",{left:0,top:0,width:0,height:0}),z(this,"rotateSpeed",1),z(this,"zoomSpeed",1.2),z(this,"panSpeed",.3),z(this,"noRotate",!1),z(this,"noZoom",!1),z(this,"noPan",!1),z(this,"staticMoving",!1),z(this,"dynamicDampingFactor",.2),z(this,"minDistance",0),z(this,"maxDistance",1/0),z(this,"keys",["KeyA","KeyS","KeyD"]),z(this,"mouseButtons",{LEFT:Kr.ROTATE,MIDDLE:Kr.DOLLY,RIGHT:Kr.PAN}),z(this,"object"),z(this,"domElement"),z(this,"cursorZoom",!1),z(this,"target",new P),z(this,"mousePosition",new Qe),z(this,"STATE",{NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4}),z(this,"EPS",1e-6),z(this,"lastZoom",1),z(this,"lastPosition",new P),z(this,"cursorVector",new P),z(this,"targetVector",new P),z(this,"_state",this.STATE.NONE),z(this,"_keyState",this.STATE.NONE),z(this,"_eye",new P),z(this,"_movePrev",new Qe),z(this,"_moveCurr",new Qe),z(this,"_lastAxis",new P),z(this,"_lastAngle",0),z(this,"_zoomStart",new Qe),z(this,"_zoomEnd",new Qe),z(this,"_touchZoomDistanceStart",0),z(this,"_touchZoomDistanceEnd",0),z(this,"_panStart",new Qe),z(this,"_panEnd",new Qe),z(this,"target0"),z(this,"position0"),z(this,"up0"),z(this,"zoom0"),z(this,"changeEvent",{type:"change"}),z(this,"startEvent",{type:"start"}),z(this,"endEvent",{type:"end"}),z(this,"onScreenVector",new Qe),z(this,"getMouseOnScreen",(s,i)=>(this.onScreenVector.set((s-this.screen.left)/this.screen.width,(i-this.screen.top)/this.screen.height),this.onScreenVector)),z(this,"onCircleVector",new Qe),z(this,"getMouseOnCircle",(s,i)=>(this.onCircleVector.set((s-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-i))/this.screen.width),this.onCircleVector)),z(this,"axis",new P),z(this,"quaternion",new Ie),z(this,"eyeDirection",new P),z(this,"objectUpDirection",new P),z(this,"objectSidewaysDirection",new P),z(this,"moveDirection",new P),z(this,"angle",0),z(this,"rotateCamera",()=>{this.moveDirection.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0),this.angle=this.moveDirection.length(),this.angle?(this._eye.copy(this.object.position).sub(this.target),this.eyeDirection.copy(this._eye).normalize(),this.objectUpDirection.copy(this.object.up).normalize(),this.objectSidewaysDirection.crossVectors(this.objectUpDirection,this.eyeDirection).normalize(),this.objectUpDirection.setLength(this._moveCurr.y-this._movePrev.y),this.objectSidewaysDirection.setLength(this._moveCurr.x-this._movePrev.x),this.moveDirection.copy(this.objectUpDirection.add(this.objectSidewaysDirection)),this.axis.crossVectors(this.moveDirection,this._eye).normalize(),this.angle*=this.rotateSpeed,this.quaternion.setFromAxisAngle(this.axis,this.angle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion),this._lastAxis.copy(this.axis),this._lastAngle=this.angle):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),this.quaternion.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion)),this._movePrev.copy(this._moveCurr)}),z(this,"zoomCamera",()=>{let s;if(this._state===this.STATE.TOUCH_ZOOM_PAN)s=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(s):this.object.isOrthographicCamera?(this.object.zoom/=s,this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type");else{if(s=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,Math.abs(s-1)>this.EPS&&s>0&&(this.object.isPerspectiveCamera?(s>1&&this._eye.length()>=this.maxDistance-this.EPS&&(s=1),this._eye.multiplyScalar(s)):this.object.isOrthographicCamera?(s>1&&this.object.zoom<this.maxDistance*this.maxDistance&&(s=1),this.object.zoom/=s):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor,this.cursorZoom){this.targetVector.copy(this.target).project(this.object);let i=this.cursorVector.set(this.mousePosition.x,this.mousePosition.y,this.targetVector.z).unproject(this.object);this.target.lerpVectors(i,this.target,s)}this.object.isOrthographicCamera&&this.object.updateProjectionMatrix()}}),z(this,"mouseChange",new Qe),z(this,"objectUp",new P),z(this,"pan",new P),z(this,"panCamera",()=>{if(this.domElement&&(this.mouseChange.copy(this._panEnd).sub(this._panStart),this.mouseChange.lengthSq()>this.EPS)){if(this.object.isOrthographicCamera){const s=this.object,i=(s.right-s.left)/this.object.zoom,r=(s.top-s.bottom)/this.object.zoom;this.mouseChange.x*=i,this.mouseChange.y*=r}else this.mouseChange.multiplyScalar(this._eye.length()*this.panSpeed);this.pan.copy(this._eye).cross(this.object.up).setLength(this.mouseChange.x),this.pan.add(this.objectUp.copy(this.object.up).setLength(this.mouseChange.y)),this.object.position.add(this.pan),this.target.add(this.pan),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(this.mouseChange.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}),z(this,"checkDistances",()=>{(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}),z(this,"handleResize",()=>{if(!this.domElement)return;const s=this.domElement.getBoundingClientRect(),i=this.domElement.ownerDocument.documentElement;this.screen.left=s.left+window.pageXOffset-i.clientLeft,this.screen.top=s.top+window.pageYOffset-i.clientTop,this.screen.width=s.width,this.screen.height=s.height}),z(this,"update",()=>{this._eye.subVectors(this.object.position,this.target),this.noRotate||this.rotateCamera(),this.noZoom||this.zoomCamera(),this.noPan||this.panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this.checkDistances(),this.object.lookAt(this.target),this.lastPosition.distanceToSquared(this.object.position)>this.EPS&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this.lastPosition.distanceToSquared(this.object.position)>this.EPS||this.lastZoom!==this.object.zoom)&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type")}),z(this,"reset",()=>{this._state=this.STATE.NONE,this._keyState=this.STATE.NONE,this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.up.copy(this.up0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom}),z(this,"keydown",s=>{this.enabled!==!1&&(window.removeEventListener("keydown",this.keydown),this._keyState===this.STATE.NONE&&(s.code===this.keys[this.STATE.ROTATE]&&!this.noRotate?this._keyState=this.STATE.ROTATE:s.code===this.keys[this.STATE.ZOOM]&&!this.noZoom?this._keyState=this.STATE.ZOOM:s.code===this.keys[this.STATE.PAN]&&!this.noPan&&(this._keyState=this.STATE.PAN)))}),z(this,"onPointerDown",s=>{if(this.enabled!==!1)switch(s.pointerType){case"mouse":case"pen":this.onMouseDown(s);break}}),z(this,"onPointerMove",s=>{if(this.enabled!==!1)switch(s.pointerType){case"mouse":case"pen":this.onMouseMove(s);break}}),z(this,"onPointerUp",s=>{if(this.enabled!==!1)switch(s.pointerType){case"mouse":case"pen":this.onMouseUp();break}}),z(this,"keyup",()=>{this.enabled!==!1&&(this._keyState=this.STATE.NONE,window.addEventListener("keydown",this.keydown))}),z(this,"onMouseDown",s=>{if(!this.domElement)return;if(this._state===this.STATE.NONE)switch(s.button){case this.mouseButtons.LEFT:this._state=this.STATE.ROTATE;break;case this.mouseButtons.MIDDLE:this._state=this.STATE.ZOOM;break;case this.mouseButtons.RIGHT:this._state=this.STATE.PAN;break}const i=this._keyState!==this.STATE.NONE?this._keyState:this._state;i===this.STATE.ROTATE&&!this.noRotate?(this._moveCurr.copy(this.getMouseOnCircle(s.pageX,s.pageY)),this._movePrev.copy(this._moveCurr)):i===this.STATE.ZOOM&&!this.noZoom?(this._zoomStart.copy(this.getMouseOnScreen(s.pageX,s.pageY)),this._zoomEnd.copy(this._zoomStart)):i===this.STATE.PAN&&!this.noPan&&(this._panStart.copy(this.getMouseOnScreen(s.pageX,s.pageY)),this._panEnd.copy(this._panStart)),this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.startEvent)}),z(this,"onMouseMove",s=>{if(this.enabled===!1)return;const i=this._keyState!==this.STATE.NONE?this._keyState:this._state;i===this.STATE.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(s.pageX,s.pageY))):i===this.STATE.ZOOM&&!this.noZoom?this._zoomEnd.copy(this.getMouseOnScreen(s.pageX,s.pageY)):i===this.STATE.PAN&&!this.noPan&&this._panEnd.copy(this.getMouseOnScreen(s.pageX,s.pageY))}),z(this,"onMouseUp",()=>{this.domElement&&this.enabled!==!1&&(this._state=this.STATE.NONE,this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.endEvent))}),z(this,"mousewheel",s=>{if(this.enabled!==!1&&this.noZoom!==!0){switch(s.preventDefault(),s.deltaMode){case 2:this._zoomStart.y-=s.deltaY*.025;break;case 1:this._zoomStart.y-=s.deltaY*.01;break;default:this._zoomStart.y-=s.deltaY*25e-5;break}this.mousePosition.x=s.offsetX/this.screen.width*2-1,this.mousePosition.y=-(s.offsetY/this.screen.height)*2+1,this.dispatchEvent(this.startEvent),this.dispatchEvent(this.endEvent)}}),z(this,"touchstart",s=>{if(this.enabled!==!1){switch(s.preventDefault(),s.touches.length){case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(s.touches[0].pageX,s.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this._state=this.STATE.TOUCH_ZOOM_PAN;const i=s.touches[0].pageX-s.touches[1].pageX,r=s.touches[0].pageY-s.touches[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(i*i+r*r);const a=(s.touches[0].pageX+s.touches[1].pageX)/2,o=(s.touches[0].pageY+s.touches[1].pageY)/2;this._panStart.copy(this.getMouseOnScreen(a,o)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(this.startEvent)}}),z(this,"touchmove",s=>{if(this.enabled!==!1)switch(s.preventDefault(),s.touches.length){case 1:this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(s.touches[0].pageX,s.touches[0].pageY));break;default:const i=s.touches[0].pageX-s.touches[1].pageX,r=s.touches[0].pageY-s.touches[1].pageY;this._touchZoomDistanceEnd=Math.sqrt(i*i+r*r);const a=(s.touches[0].pageX+s.touches[1].pageX)/2,o=(s.touches[0].pageY+s.touches[1].pageY)/2;this._panEnd.copy(this.getMouseOnScreen(a,o));break}}),z(this,"touchend",s=>{if(this.enabled!==!1){switch(s.touches.length){case 0:this._state=this.STATE.NONE;break;case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(s.touches[0].pageX,s.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break}this.dispatchEvent(this.endEvent)}}),z(this,"contextmenu",s=>{this.enabled!==!1&&s.preventDefault()}),z(this,"connect",s=>{s===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.domElement=s,this.domElement.addEventListener("contextmenu",this.contextmenu),this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("wheel",this.mousewheel),this.domElement.addEventListener("touchstart",this.touchstart),this.domElement.addEventListener("touchend",this.touchend),this.domElement.addEventListener("touchmove",this.touchmove),this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.keydown),window.addEventListener("keyup",this.keyup),this.handleResize()}),z(this,"dispose",()=>{this.domElement&&(this.domElement.removeEventListener("contextmenu",this.contextmenu),this.domElement.removeEventListener("pointerdown",this.onPointerDown),this.domElement.removeEventListener("wheel",this.mousewheel),this.domElement.removeEventListener("touchstart",this.touchstart),this.domElement.removeEventListener("touchend",this.touchend),this.domElement.removeEventListener("touchmove",this.touchmove),this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.keydown),window.removeEventListener("keyup",this.keyup))}),this.object=e,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.up0=this.object.up.clone(),this.zoom0=this.object.zoom,t!==void 0&&this.connect(t),this.update()}};var uB=Object.defineProperty,dB=(n,e,t)=>e in n?uB(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,M=(n,e,t)=>(dB(n,typeof e!="symbol"?e+"":e,t),t);const ee={IDLE:Symbol(),ROTATE:Symbol(),PAN:Symbol(),SCALE:Symbol(),FOV:Symbol(),FOCUS:Symbol(),ZROTATE:Symbol(),TOUCH_MULTI:Symbol(),ANIMATION_FOCUS:Symbol(),ANIMATION_ROTATE:Symbol()},xe={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()},ge={x:0,y:0},nt={camera:new he,gizmos:new he},Me={type:"change"},yt={type:"start"},ot={type:"end"};let AB=class extends pi{constructor(e,t=null,s=null){super(),M(this,"camera"),M(this,"domElement"),M(this,"scene"),M(this,"mouseActions"),M(this,"_mouseOp"),M(this,"_v2_1"),M(this,"_v3_1"),M(this,"_v3_2"),M(this,"_m4_1"),M(this,"_m4_2"),M(this,"_quat"),M(this,"_translationMatrix"),M(this,"_rotationMatrix"),M(this,"_scaleMatrix"),M(this,"_rotationAxis"),M(this,"_cameraMatrixState"),M(this,"_cameraProjectionState"),M(this,"_fovState"),M(this,"_upState"),M(this,"_zoomState"),M(this,"_nearPos"),M(this,"_farPos"),M(this,"_gizmoMatrixState"),M(this,"_up0"),M(this,"_zoom0"),M(this,"_fov0"),M(this,"_initialNear"),M(this,"_nearPos0"),M(this,"_initialFar"),M(this,"_farPos0"),M(this,"_cameraMatrixState0"),M(this,"_gizmoMatrixState0"),M(this,"_button"),M(this,"_touchStart"),M(this,"_touchCurrent"),M(this,"_input"),M(this,"_switchSensibility"),M(this,"_startFingerDistance"),M(this,"_currentFingerDistance"),M(this,"_startFingerRotation"),M(this,"_currentFingerRotation"),M(this,"_devPxRatio"),M(this,"_downValid"),M(this,"_nclicks"),M(this,"_downEvents"),M(this,"_clickStart"),M(this,"_maxDownTime"),M(this,"_maxInterval"),M(this,"_posThreshold"),M(this,"_movementThreshold"),M(this,"_currentCursorPosition"),M(this,"_startCursorPosition"),M(this,"_grid"),M(this,"_gridPosition"),M(this,"_gizmos"),M(this,"_curvePts"),M(this,"_timeStart"),M(this,"_animationId"),M(this,"focusAnimationTime"),M(this,"_timePrev"),M(this,"_timeCurrent"),M(this,"_anglePrev"),M(this,"_angleCurrent"),M(this,"_cursorPosPrev"),M(this,"_cursorPosCurr"),M(this,"_wPrev"),M(this,"_wCurr"),M(this,"adjustNearFar"),M(this,"scaleFactor"),M(this,"dampingFactor"),M(this,"wMax"),M(this,"enableAnimations"),M(this,"enableGrid"),M(this,"cursorZoom"),M(this,"minFov"),M(this,"maxFov"),M(this,"enabled"),M(this,"enablePan"),M(this,"enableRotate"),M(this,"enableZoom"),M(this,"minDistance"),M(this,"maxDistance"),M(this,"minZoom"),M(this,"maxZoom"),M(this,"target"),M(this,"_currentTarget"),M(this,"_tbRadius"),M(this,"_state"),M(this,"onWindowResize",()=>{const i=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3;if(this.camera){const c=this.calculateTbRadius(this.camera);c!==void 0&&(this._tbRadius=c)}const r=this._tbRadius/i,o=new Vr(0,0,r,r).getPoints(this._curvePts),l=new mt().setFromPoints(o);for(const c in this._gizmos.children){const h=this._gizmos.children[c];h.geometry=l}this.dispatchEvent(Me)}),M(this,"onContextMenu",i=>{if(this.enabled){for(let r=0;r<this.mouseActions.length;r++)if(this.mouseActions[r].mouse==2){i.preventDefault();break}}}),M(this,"onPointerCancel",()=>{this._touchStart.splice(0,this._touchStart.length),this._touchCurrent.splice(0,this._touchCurrent.length),this._input=xe.NONE}),M(this,"onPointerDown",i=>{if(i.button==0&&i.isPrimary?(this._downValid=!0,this._downEvents.push(i)):this._downValid=!1,i.pointerType=="touch"&&this._input!=xe.CURSOR)switch(this._touchStart.push(i),this._touchCurrent.push(i),this._input){case xe.NONE:this._input=xe.ONE_FINGER,this.onSinglePanStart(i,"ROTATE"),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp);break;case xe.ONE_FINGER:case xe.ONE_FINGER_SWITCHED:this._input=xe.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case xe.TWO_FINGER:this._input=xe.MULT_FINGER,this.onTriplePanStart();break}else if(i.pointerType!="touch"&&this._input==xe.NONE){let r=null;i.ctrlKey||i.metaKey?r="CTRL":i.shiftKey&&(r="SHIFT"),this._mouseOp=this.getOpFromAction(i.button,r),this._mouseOp&&(window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),this._input=xe.CURSOR,this._button=i.button,this.onSinglePanStart(i,this._mouseOp))}}),M(this,"onPointerMove",i=>{if(i.pointerType=="touch"&&this._input!=xe.CURSOR)switch(this._input){case xe.ONE_FINGER:this.updateTouchEvent(i),this.onSinglePanMove(i,ee.ROTATE);break;case xe.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],i)*this._devPxRatio>=this._switchSensibility){this._input=xe.ONE_FINGER,this.updateTouchEvent(i),this.onSinglePanStart(i,"ROTATE");break}break;case xe.TWO_FINGER:this.updateTouchEvent(i),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case xe.MULT_FINGER:this.updateTouchEvent(i),this.onTriplePanMove();break}else if(i.pointerType!="touch"&&this._input==xe.CURSOR){let r=null;i.ctrlKey||i.metaKey?r="CTRL":i.shiftKey&&(r="SHIFT");const a=this.getOpStateFromAction(this._button,r);a&&this.onSinglePanMove(i,a)}this._downValid&&this.calculatePointersDistance(this._downEvents[this._downEvents.length-1],i)*this._devPxRatio>this._movementThreshold&&(this._downValid=!1)}),M(this,"onPointerUp",i=>{if(i.pointerType=="touch"&&this._input!=xe.CURSOR){const r=this._touchCurrent.length;for(let a=0;a<r;a++)if(this._touchCurrent[a].pointerId==i.pointerId){this._touchCurrent.splice(a,1),this._touchStart.splice(a,1);break}switch(this._input){case xe.ONE_FINGER:case xe.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=xe.NONE,this.onSinglePanEnd();break;case xe.TWO_FINGER:this.onDoublePanEnd(),this.onPinchEnd(),this.onRotateEnd(),this._input=xe.ONE_FINGER_SWITCHED;break;case xe.MULT_FINGER:this._touchCurrent.length==0&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=xe.NONE,this.onTriplePanEnd());break}}else i.pointerType!="touch"&&this._input==xe.CURSOR&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=xe.NONE,this.onSinglePanEnd(),this._button=-1);if(i.isPrimary)if(this._downValid)if(i.timeStamp-this._downEvents[this._downEvents.length-1].timeStamp<=this._maxDownTime)if(this._nclicks==0)this._nclicks=1,this._clickStart=performance.now();else{const a=i.timeStamp-this._clickStart,o=this.calculatePointersDistance(this._downEvents[1],this._downEvents[0])*this._devPxRatio;a<=this._maxInterval&&o<=this._posThreshold?(this._nclicks=0,this._downEvents.splice(0,this._downEvents.length),this.onDoubleTap(i)):(this._nclicks=1,this._downEvents.shift(),this._clickStart=performance.now())}else this._downValid=!1,this._nclicks=0,this._downEvents.splice(0,this._downEvents.length);else this._nclicks=0,this._downEvents.splice(0,this._downEvents.length)}),M(this,"onWheel",i=>{var r,a;if(this.enabled&&this.enableZoom&&this.domElement){let o=null;i.ctrlKey||i.metaKey?o="CTRL":i.shiftKey&&(o="SHIFT");const l=this.getOpFromAction("WHEEL",o);if(l){i.preventDefault(),this.dispatchEvent(yt);const c=125;let h=i.deltaY/c,u=1;switch(h>0?u=1/this.scaleFactor:h<0&&(u=this.scaleFactor),l){case"ZOOM":if(this.updateTbState(ee.SCALE,!0),h>0?u=1/Math.pow(this.scaleFactor,h):h<0&&(u=Math.pow(this.scaleFactor,-h)),this.cursorZoom&&this.enablePan){let d;this.camera instanceof st&&(d=(r=this.unprojectOnTbPlane(this.camera,i.clientX,i.clientY,this.domElement))==null?void 0:r.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position)),this.camera instanceof ke&&(d=(a=this.unprojectOnTbPlane(this.camera,i.clientX,i.clientY,this.domElement))==null?void 0:a.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)),d!==void 0&&this.applyTransformMatrix(this.applyScale(u,d))}else this.applyTransformMatrix(this.applyScale(u,this._gizmos.position));this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(ee.IDLE,!1),this.dispatchEvent(Me),this.dispatchEvent(ot);break;case"FOV":if(this.camera instanceof ke){this.updateTbState(ee.FOV,!0),i.deltaX!=0&&(h=i.deltaX/c,u=1,h>0?u=1/Math.pow(this.scaleFactor,h):h<0&&(u=Math.pow(this.scaleFactor,-h))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const d=this._v3_1.distanceTo(this._gizmos.position);let A=d/u;A=le.clamp(A,this.minDistance,this.maxDistance);const f=d*Math.tan(le.DEG2RAD*this.camera.fov*.5);let g=le.RAD2DEG*(Math.atan(f/A)*2);g>this.maxFov?g=this.maxFov:g<this.minFov&&(g=this.minFov);const p=f/Math.tan(le.DEG2RAD*(g/2));u=d/p,this.setFov(g),this.applyTransformMatrix(this.applyScale(u,this._gizmos.position,!1))}this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(ee.IDLE,!1),this.dispatchEvent(Me),this.dispatchEvent(ot);break}}}}),M(this,"onSinglePanStart",(i,r)=>{if(this.enabled&&this.domElement)switch(this.dispatchEvent(yt),this.setCenter(i.clientX,i.clientY),r){case"PAN":if(!this.enablePan)return;if(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(Me)),this.camera){this.updateTbState(ee.PAN,!0);const a=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement);a!==void 0&&this._startCursorPosition.copy(a),this.enableGrid&&(this.drawGrid(),this.dispatchEvent(Me))}break;case"ROTATE":if(!this.enableRotate)return;if(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1),this.camera){this.updateTbState(ee.ROTATE,!0);const a=this.unprojectOnTbSurface(this.camera,ge.x,ge.y,this.domElement,this._tbRadius);a!==void 0&&this._startCursorPosition.copy(a),this.activateGizmos(!0),this.enableAnimations&&(this._timePrev=this._timeCurrent=performance.now(),this._angleCurrent=this._anglePrev=0,this._cursorPosPrev.copy(this._startCursorPosition),this._cursorPosCurr.copy(this._cursorPosPrev),this._wCurr=0,this._wPrev=this._wCurr)}this.dispatchEvent(Me);break;case"FOV":if(!this.enableZoom)return;this.camera instanceof ke&&(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(Me)),this.updateTbState(ee.FOV,!0),this._startCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition));break;case"ZOOM":if(!this.enableZoom)return;this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(Me)),this.updateTbState(ee.SCALE,!0),this._startCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition);break}}),M(this,"onSinglePanMove",(i,r)=>{if(this.enabled&&this.domElement){const a=r!=this._state;switch(this.setCenter(i.clientX,i.clientY),r){case ee.PAN:if(this.enablePan&&this.camera)if(a){this.dispatchEvent(ot),this.dispatchEvent(yt),this.updateTbState(r,!0);const o=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement);o!==void 0&&this._startCursorPosition.copy(o),this.enableGrid&&this.drawGrid(),this.activateGizmos(!1)}else{const o=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement);o!==void 0&&this._currentCursorPosition.copy(o),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition))}break;case ee.ROTATE:if(this.enableRotate&&this.camera)if(a){this.dispatchEvent(ot),this.dispatchEvent(yt),this.updateTbState(r,!0);const o=this.unprojectOnTbSurface(this.camera,ge.x,ge.y,this.domElement,this._tbRadius);o!==void 0&&this._startCursorPosition.copy(o),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!0)}else{const o=this.unprojectOnTbSurface(this.camera,ge.x,ge.y,this.domElement,this._tbRadius);o!==void 0&&this._currentCursorPosition.copy(o);const l=this._startCursorPosition.distanceTo(this._currentCursorPosition),c=this._startCursorPosition.angleTo(this._currentCursorPosition),h=Math.max(l/this._tbRadius,c);this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition,this._currentCursorPosition),h)),this.enableAnimations&&(this._timePrev=this._timeCurrent,this._timeCurrent=performance.now(),this._anglePrev=this._angleCurrent,this._angleCurrent=h,this._cursorPosPrev.copy(this._cursorPosCurr),this._cursorPosCurr.copy(this._currentCursorPosition),this._wPrev=this._wCurr,this._wCurr=this.calculateAngularSpeed(this._anglePrev,this._angleCurrent,this._timePrev,this._timeCurrent))}break;case ee.SCALE:if(this.enableZoom)if(a)this.dispatchEvent(ot),this.dispatchEvent(yt),this.updateTbState(r,!0),this._startCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let c=1;l<0?c=1/Math.pow(this.scaleFactor,-l*8):l>0&&(c=Math.pow(this.scaleFactor,l*8)),this.applyTransformMatrix(this.applyScale(c,this._gizmos.position))}break;case ee.FOV:if(this.enableZoom&&this.camera instanceof ke)if(a)this.dispatchEvent(ot),this.dispatchEvent(yt),this.updateTbState(r,!0),this._startCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let c=1;l<0?c=1/Math.pow(this.scaleFactor,-l*8):l>0&&(c=Math.pow(this.scaleFactor,l*8)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const h=this._v3_1.distanceTo(this._gizmos.position);let u=h/c;u=le.clamp(u,this.minDistance,this.maxDistance);const d=h*Math.tan(le.DEG2RAD*this._fovState*.5);let A=le.RAD2DEG*(Math.atan(d/u)*2);A=le.clamp(A,this.minFov,this.maxFov);const f=d/Math.tan(le.DEG2RAD*(A/2));c=h/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(A),this.applyTransformMatrix(this.applyScale(c,this._v3_2,!1));const g=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(f/h);this._m4_1.makeTranslation(g.x,g.y,g.z)}break}this.dispatchEvent(Me)}}),M(this,"onSinglePanEnd",()=>{if(this._state==ee.ROTATE){if(!this.enableRotate)return;if(this.enableAnimations)if(performance.now()-this._timeCurrent<120){const r=Math.abs((this._wPrev+this._wCurr)/2),a=this;this._animationId=window.requestAnimationFrame(function(o){a.updateTbState(ee.ANIMATION_ROTATE,!0);const l=a.calculateRotationAxis(a._cursorPosPrev,a._cursorPosCurr);a.onRotationAnim(o,l,Math.min(r,a.wMax))})}else this.updateTbState(ee.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Me);else this.updateTbState(ee.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Me)}else(this._state==ee.PAN||this._state==ee.IDLE)&&(this.updateTbState(ee.IDLE,!1),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1),this.dispatchEvent(Me));this.dispatchEvent(ot)}),M(this,"onDoubleTap",i=>{if(this.enabled&&this.enablePan&&this.scene&&this.camera&&this.domElement){this.dispatchEvent(yt),this.setCenter(i.clientX,i.clientY);const r=this.unprojectOnObj(this.getCursorNDC(ge.x,ge.y,this.domElement),this.camera);if(r&&this.enableAnimations){const a=this;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),this._timeStart=-1,this._animationId=window.requestAnimationFrame(function(o){a.updateTbState(ee.ANIMATION_FOCUS,!0),a.onFocusAnim(o,r,a._cameraMatrixState,a._gizmoMatrixState)})}else r&&!this.enableAnimations&&(this.updateTbState(ee.FOCUS,!0),this.focus(r,this.scaleFactor),this.updateTbState(ee.IDLE,!1),this.dispatchEvent(Me))}this.dispatchEvent(ot)}),M(this,"onDoublePanStart",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.dispatchEvent(yt),this.updateTbState(ee.PAN,!0),this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2);const i=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement,!0);i!==void 0&&this._startCursorPosition.copy(i),this._currentCursorPosition.copy(this._startCursorPosition),this.activateGizmos(!1)}}),M(this,"onDoublePanMove",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2),this._state!=ee.PAN&&(this.updateTbState(ee.PAN,!0),this._startCursorPosition.copy(this._currentCursorPosition));const i=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement,!0);i!==void 0&&this._currentCursorPosition.copy(i),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition,!0)),this.dispatchEvent(Me)}}),M(this,"onDoublePanEnd",()=>{this.updateTbState(ee.IDLE,!1),this.dispatchEvent(ot)}),M(this,"onRotateStart",()=>{var i;this.enabled&&this.enableRotate&&(this.dispatchEvent(yt),this.updateTbState(ee.ZROTATE,!0),this._startFingerRotation=this.getAngle(this._touchCurrent[1],this._touchCurrent[0])+this.getAngle(this._touchStart[1],this._touchStart[0]),this._currentFingerRotation=this._startFingerRotation,(i=this.camera)==null||i.getWorldDirection(this._rotationAxis),!this.enablePan&&!this.enableZoom&&this.activateGizmos(!0))}),M(this,"onRotateMove",()=>{var i;if(this.enabled&&this.enableRotate&&this.camera&&this.domElement){this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2);let r;this._state!=ee.ZROTATE&&(this.updateTbState(ee.ZROTATE,!0),this._startFingerRotation=this._currentFingerRotation),this._currentFingerRotation=this.getAngle(this._touchCurrent[1],this._touchCurrent[0])+this.getAngle(this._touchStart[1],this._touchStart[0]),this.enablePan?this.camera&&(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),r=(i=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement))==null?void 0:i.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._v3_2)):r=new P().setFromMatrixPosition(this._gizmoMatrixState);const a=le.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);r!==void 0&&this.applyTransformMatrix(this.zRotate(r,a)),this.dispatchEvent(Me)}}),M(this,"onRotateEnd",()=>{this.updateTbState(ee.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(ot)}),M(this,"onPinchStart",()=>{this.enabled&&this.enableZoom&&(this.dispatchEvent(yt),this.updateTbState(ee.SCALE,!0),this._startFingerDistance=this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),this._currentFingerDistance=this._startFingerDistance,this.activateGizmos(!1))}),M(this,"onPinchMove",()=>{var i,r;if(this.enabled&&this.enableZoom&&this.domElement){this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2);const a=12;this._state!=ee.SCALE&&(this._startFingerDistance=this._currentFingerDistance,this.updateTbState(ee.SCALE,!0)),this._currentFingerDistance=Math.max(this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),a*this._devPxRatio);const o=this._currentFingerDistance/this._startFingerDistance;let l;this.enablePan?this.camera instanceof st?l=(i=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement))==null?void 0:i.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position):this.camera instanceof ke&&(l=(r=this.unprojectOnTbPlane(this.camera,ge.x,ge.y,this.domElement))==null?void 0:r.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)):l=this._gizmos.position,l!==void 0&&this.applyTransformMatrix(this.applyScale(o,l)),this.dispatchEvent(Me)}}),M(this,"onPinchEnd",()=>{this.updateTbState(ee.IDLE,!1),this.dispatchEvent(ot)}),M(this,"onTriplePanStart",()=>{if(this.enabled&&this.enableZoom&&this.domElement){this.dispatchEvent(yt),this.updateTbState(ee.SCALE,!0);let i=0,r=0;const a=this._touchCurrent.length;for(let o=0;o<a;o++)i+=this._touchCurrent[o].clientX,r+=this._touchCurrent[o].clientY;this.setCenter(i/a,r/a),this._startCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition)}}),M(this,"onTriplePanMove",()=>{if(this.enabled&&this.enableZoom&&this.camera&&this.domElement){let i=0,r=0;const a=this._touchCurrent.length;for(let p=0;p<a;p++)i+=this._touchCurrent[p].clientX,r+=this._touchCurrent[p].clientY;this.setCenter(i/a,r/a);const o=8;this._currentCursorPosition.setY(this.getCursorNDC(ge.x,ge.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let c=1;l<0?c=1/Math.pow(this.scaleFactor,-l*o):l>0&&(c=Math.pow(this.scaleFactor,l*o)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const h=this._v3_1.distanceTo(this._gizmos.position);let u=h/c;u=le.clamp(u,this.minDistance,this.maxDistance);const d=h*Math.tan(le.DEG2RAD*this._fovState*.5);let A=le.RAD2DEG*(Math.atan(d/u)*2);A=le.clamp(A,this.minFov,this.maxFov);const f=d/Math.tan(le.DEG2RAD*(A/2));c=h/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(A),this.applyTransformMatrix(this.applyScale(c,this._v3_2,!1));const g=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(f/h);this._m4_1.makeTranslation(g.x,g.y,g.z),this.dispatchEvent(Me)}}),M(this,"onTriplePanEnd",()=>{this.updateTbState(ee.IDLE,!1),this.dispatchEvent(ot)}),M(this,"setCenter",(i,r)=>{ge.x=i,ge.y=r}),M(this,"initializeMouseActions",()=>{this.setMouseAction("PAN",0,"CTRL"),this.setMouseAction("PAN",2),this.setMouseAction("ROTATE",0),this.setMouseAction("ZOOM","WHEEL"),this.setMouseAction("ZOOM",1),this.setMouseAction("FOV","WHEEL","SHIFT"),this.setMouseAction("FOV",1,"SHIFT")}),M(this,"setMouseAction",(i,r,a=null)=>{const o=["PAN","ROTATE","ZOOM","FOV"],l=[0,1,2,"WHEEL"],c=["CTRL","SHIFT",null];let h;if(!o.includes(i)||!l.includes(r)||!c.includes(a)||r=="WHEEL"&&i!="ZOOM"&&i!="FOV")return!1;switch(i){case"PAN":h=ee.PAN;break;case"ROTATE":h=ee.ROTATE;break;case"ZOOM":h=ee.SCALE;break;case"FOV":h=ee.FOV;break}const u={operation:i,mouse:r,key:a,state:h};for(let d=0;d<this.mouseActions.length;d++)if(this.mouseActions[d].mouse==u.mouse&&this.mouseActions[d].key==u.key)return this.mouseActions.splice(d,1,u),!0;return this.mouseActions.push(u),!0}),M(this,"getOpFromAction",(i,r)=>{let a;for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==i&&a.key==r)return a.operation;if(r){for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==i&&a.key==null)return a.operation}return null}),M(this,"getOpStateFromAction",(i,r)=>{let a;for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==i&&a.key==r)return a.state;if(r){for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==i&&a.key==null)return a.state}return null}),M(this,"getAngle",(i,r)=>Math.atan2(r.clientY-i.clientY,r.clientX-i.clientX)*180/Math.PI),M(this,"updateTouchEvent",i=>{for(let r=0;r<this._touchCurrent.length;r++)if(this._touchCurrent[r].pointerId==i.pointerId){this._touchCurrent.splice(r,1,i);break}}),M(this,"calculateAngularSpeed",(i,r,a,o)=>{const l=r-i,c=(o-a)/1e3;return c==0?0:l/c}),M(this,"calculatePointersDistance",(i,r)=>Math.sqrt(Math.pow(r.clientX-i.clientX,2)+Math.pow(r.clientY-i.clientY,2))),M(this,"calculateRotationAxis",(i,r)=>(this._rotationMatrix.extractRotation(this._cameraMatrixState),this._quat.setFromRotationMatrix(this._rotationMatrix),this._rotationAxis.crossVectors(i,r).applyQuaternion(this._quat),this._rotationAxis.normalize().clone())),M(this,"calculateTbRadius",i=>{const a=i.position.distanceTo(this._gizmos.position);if(i instanceof ke){const o=le.DEG2RAD*i.fov*.5,l=Math.atan(i.aspect*Math.tan(o));return Math.tan(Math.min(o,l))*a*.67}else if(i instanceof st)return Math.min(i.top,i.right)*.67}),M(this,"focus",(i,r,a=1)=>{if(this.camera){const o=i.clone();o.sub(this._gizmos.position).multiplyScalar(a),this._translationMatrix.makeTranslation(o.x,o.y,o.z);const l=this._gizmoMatrixState.clone();this._gizmoMatrixState.premultiply(this._translationMatrix),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale);const c=this._cameraMatrixState.clone();this._cameraMatrixState.premultiply(this._translationMatrix),this._cameraMatrixState.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.enableZoom&&this.applyTransformMatrix(this.applyScale(r,this._gizmos.position)),this._gizmoMatrixState.copy(l),this._cameraMatrixState.copy(c)}}),M(this,"drawGrid",()=>{if(this.scene){let a,o,l,c;if(this.camera instanceof st){const h=this.camera.right-this.camera.left,u=this.camera.bottom-this.camera.top;l=Math.max(h,u),c=l/20,a=l/this.camera.zoom*3,o=a/c*this.camera.zoom}else if(this.camera instanceof ke){const h=this.camera.position.distanceTo(this._gizmos.position),u=le.DEG2RAD*this.camera.fov*.5,d=Math.atan(this.camera.aspect*Math.tan(u));l=Math.tan(Math.max(u,d))*h*2,c=l/20,a=l*3,o=a/c}this._grid==null&&this.camera&&(this._grid=new eg(a,o,8947848,8947848),this._grid.position.copy(this._gizmos.position),this._gridPosition.copy(this._grid.position),this._grid.quaternion.copy(this.camera.quaternion),this._grid.rotateX(Math.PI*.5),this.scene.add(this._grid))}}),M(this,"connect",i=>{i===document&&console.error('THREE.ArcballControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.domElement=i,this.domElement.style.touchAction="none",this.domElement.addEventListener("contextmenu",this.onContextMenu),this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("pointercancel",this.onPointerCancel),this.domElement.addEventListener("wheel",this.onWheel)}),M(this,"dispose",()=>{var i,r,a,o,l;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),(i=this.domElement)==null||i.removeEventListener("pointerdown",this.onPointerDown),(r=this.domElement)==null||r.removeEventListener("pointercancel",this.onPointerCancel),(a=this.domElement)==null||a.removeEventListener("wheel",this.onWheel),(o=this.domElement)==null||o.removeEventListener("contextmenu",this.onContextMenu),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("resize",this.onWindowResize),(l=this.scene)==null||l.remove(this._gizmos),this.disposeGrid()}),M(this,"disposeGrid",()=>{this._grid&&this.scene&&(this.scene.remove(this._grid),this._grid=null)}),M(this,"easeOutCubic",i=>1-Math.pow(1-i,3)),M(this,"activateGizmos",i=>{for(const r of this._gizmos.children)r.material.setValues({opacity:i?1:.6})}),M(this,"getCursorNDC",(i,r,a)=>{const o=a.getBoundingClientRect();return this._v2_1.setX((i-o.left)/o.width*2-1),this._v2_1.setY((o.bottom-r)/o.height*2-1),this._v2_1.clone()}),M(this,"getCursorPosition",(i,r,a)=>(this._v2_1.copy(this.getCursorNDC(i,r,a)),this.camera instanceof st&&(this._v2_1.x*=(this.camera.right-this.camera.left)*.5,this._v2_1.y*=(this.camera.top-this.camera.bottom)*.5),this._v2_1.clone())),M(this,"setCamera",i=>{if(i){i.lookAt(this.target),i.updateMatrix(),i instanceof ke&&(this._fov0=i.fov,this._fovState=i.fov),this._cameraMatrixState0.copy(i.matrix),this._cameraMatrixState.copy(this._cameraMatrixState0),this._cameraProjectionState.copy(i.projectionMatrix),this._zoom0=i.zoom,this._zoomState=this._zoom0,this._initialNear=i.near,this._nearPos0=i.position.distanceTo(this.target)-i.near,this._nearPos=this._initialNear,this._initialFar=i.far,this._farPos0=i.position.distanceTo(this.target)-i.far,this._farPos=this._initialFar,this._up0.copy(i.up),this._upState.copy(i.up),this.camera=i,this.camera.updateProjectionMatrix();const r=this.calculateTbRadius(i);r!==void 0&&(this._tbRadius=r),this.makeGizmos(this.target,this._tbRadius)}}),M(this,"makeGizmos",(i,r)=>{const o=new Vr(0,0,r,r).getPoints(this._curvePts),l=new mt().setFromPoints(o),c=new Ws({color:16744576,fog:!1,transparent:!0,opacity:.6}),h=new Ws({color:8454016,fog:!1,transparent:!0,opacity:.6}),u=new Ws({color:8421631,fog:!1,transparent:!0,opacity:.6}),d=new Ce(l,c),A=new Ce(l,h),f=new Ce(l,u),g=Math.PI*.5;if(d.rotation.x=g,A.rotation.y=g,this._gizmoMatrixState0.identity().setPosition(i),this._gizmoMatrixState.copy(this._gizmoMatrixState0),this.camera&&this.camera.zoom!=1){const p=1/this.camera.zoom;this._scaleMatrix.makeScale(p,p,p),this._translationMatrix.makeTranslation(-i.x,-i.y,-i.z),this._gizmoMatrixState.premultiply(this._translationMatrix).premultiply(this._scaleMatrix),this._translationMatrix.makeTranslation(i.x,i.y,i.z),this._gizmoMatrixState.premultiply(this._translationMatrix)}this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.clear(),this._gizmos.add(d),this._gizmos.add(A),this._gizmos.add(f)}),M(this,"onFocusAnim",(i,r,a,o)=>{if(this._timeStart==-1&&(this._timeStart=i),this._state==ee.ANIMATION_FOCUS){const c=(i-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(o),c>=1)this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,this.scaleFactor),this._timeStart=-1,this.updateTbState(ee.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Me);else{const h=this.easeOutCubic(c),u=1-h+this.scaleFactor*h;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,u,h),this.dispatchEvent(Me);const d=this;this._animationId=window.requestAnimationFrame(function(A){d.onFocusAnim(A,r,a,o.clone())})}}else this._animationId=-1,this._timeStart=-1}),M(this,"onRotationAnim",(i,r,a)=>{if(this._timeStart==-1&&(this._anglePrev=0,this._angleCurrent=0,this._timeStart=i),this._state==ee.ANIMATION_ROTATE){const o=(i-this._timeStart)/1e3;if(a+-this.dampingFactor*o>0){this._angleCurrent=.5*-this.dampingFactor*Math.pow(o,2)+a*o+0,this.applyTransformMatrix(this.rotate(r,this._angleCurrent)),this.dispatchEvent(Me);const c=this;this._animationId=window.requestAnimationFrame(function(h){c.onRotationAnim(h,r,a)})}else this._animationId=-1,this._timeStart=-1,this.updateTbState(ee.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Me)}else this._animationId=-1,this._timeStart=-1,this._state!=ee.ROTATE&&(this.activateGizmos(!1),this.dispatchEvent(Me))}),M(this,"pan",(i,r,a=!1)=>{if(this.camera){const o=i.clone().sub(r);if(this.camera instanceof st&&o.multiplyScalar(1/this.camera.zoom),this.camera instanceof ke&&a){this._v3_1.setFromMatrixPosition(this._cameraMatrixState0),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0);const l=this._v3_1.distanceTo(this._v3_2)/this.camera.position.distanceTo(this._gizmos.position);o.multiplyScalar(1/l)}this._v3_1.set(o.x,o.y,0).applyQuaternion(this.camera.quaternion),this._m4_1.makeTranslation(this._v3_1.x,this._v3_1.y,this._v3_1.z),this.setTransformationMatrices(this._m4_1,this._m4_1)}return nt}),M(this,"reset",()=>{if(this.camera){this.camera.zoom=this._zoom0,this.camera instanceof ke&&(this.camera.fov=this._fov0),this.camera.near=this._nearPos,this.camera.far=this._farPos,this._cameraMatrixState.copy(this._cameraMatrixState0),this._cameraMatrixState.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.up.copy(this._up0),this.camera.updateMatrix(),this.camera.updateProjectionMatrix(),this._gizmoMatrixState.copy(this._gizmoMatrixState0),this._gizmoMatrixState0.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.updateMatrix();const i=this.calculateTbRadius(this.camera);i!==void 0&&(this._tbRadius=i),this.makeGizmos(this._gizmos.position,this._tbRadius),this.camera.lookAt(this._gizmos.position),this.updateTbState(ee.IDLE,!1),this.dispatchEvent(Me)}}),M(this,"rotate",(i,r)=>{const a=this._gizmos.position;return this._translationMatrix.makeTranslation(-a.x,-a.y,-a.z),this._rotationMatrix.makeRotationAxis(i,-r),this._m4_1.makeTranslation(a.x,a.y,a.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1),nt}),M(this,"copyState",()=>{if(this.camera){const i=JSON.stringify(this.camera instanceof st?{arcballState:{cameraFar:this.camera.far,cameraMatrix:this.camera.matrix,cameraNear:this.camera.near,cameraUp:this.camera.up,cameraZoom:this.camera.zoom,gizmoMatrix:this._gizmos.matrix}}:{arcballState:{cameraFar:this.camera.far,cameraFov:this.camera.fov,cameraMatrix:this.camera.matrix,cameraNear:this.camera.near,cameraUp:this.camera.up,cameraZoom:this.camera.zoom,gizmoMatrix:this._gizmos.matrix}});navigator.clipboard.writeText(i)}}),M(this,"pasteState",()=>{const i=this;navigator.clipboard.readText().then(function(a){i.setStateFromJSON(a)})}),M(this,"saveState",()=>{this.camera&&(this._cameraMatrixState0.copy(this.camera.matrix),this._gizmoMatrixState0.copy(this._gizmos.matrix),this._nearPos=this.camera.near,this._farPos=this.camera.far,this._zoom0=this.camera.zoom,this._up0.copy(this.camera.up),this.camera instanceof ke&&(this._fov0=this.camera.fov))}),M(this,"applyScale",(i,r,a=!0)=>{if(!this.camera)return;const o=r.clone();let l=1/i;if(this.camera instanceof st){this.camera.zoom=this._zoomState,this.camera.zoom*=i,this.camera.zoom>this.maxZoom?(this.camera.zoom=this.maxZoom,l=this._zoomState/this.maxZoom):this.camera.zoom<this.minZoom&&(this.camera.zoom=this.minZoom,l=this._zoomState/this.minZoom),this.camera.updateProjectionMatrix(),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState),this._scaleMatrix.makeScale(l,l,l),this._translationMatrix.makeTranslation(-this._v3_1.x,-this._v3_1.y,-this._v3_1.z),this._m4_2.makeTranslation(this._v3_1.x,this._v3_1.y,this._v3_1.z).multiply(this._scaleMatrix),this._m4_2.multiply(this._translationMatrix),o.sub(this._v3_1);const c=o.clone().multiplyScalar(l);return o.sub(c),this._m4_1.makeTranslation(o.x,o.y,o.z),this._m4_2.premultiply(this._m4_1),this.setTransformationMatrices(this._m4_1,this._m4_2),nt}if(this.camera instanceof ke){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let c=this._v3_1.distanceTo(o),h=c-c*l;const u=c-h;u<this.minDistance?(l=this.minDistance/c,h=c-c*l):u>this.maxDistance&&(l=this.maxDistance/c,h=c-c*l);let d=o.clone().sub(this._v3_1).normalize().multiplyScalar(h);if(this._m4_1.makeTranslation(d.x,d.y,d.z),a){const A=this._v3_2;c=A.distanceTo(o),h=c-c*l,d=o.clone().sub(this._v3_2).normalize().multiplyScalar(h),this._translationMatrix.makeTranslation(A.x,A.y,A.z),this._scaleMatrix.makeScale(l,l,l),this._m4_2.makeTranslation(d.x,d.y,d.z).multiply(this._translationMatrix),this._m4_2.multiply(this._scaleMatrix),this._translationMatrix.makeTranslation(-A.x,-A.y,-A.z),this._m4_2.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1,this._m4_2)}else this.setTransformationMatrices(this._m4_1);return nt}}),M(this,"setFov",i=>{this.camera instanceof ke&&(this.camera.fov=le.clamp(i,this.minFov,this.maxFov),this.camera.updateProjectionMatrix())}),M(this,"setTarget",(i,r,a)=>{if(this.camera){this.target.set(i,r,a),this._gizmos.position.set(i,r,a);const o=this.calculateTbRadius(this.camera);o!==void 0&&(this._tbRadius=o),this.makeGizmos(this.target,this._tbRadius),this.camera.lookAt(this.target)}}),M(this,"zRotate",(i,r)=>(this._rotationMatrix.makeRotationAxis(this._rotationAxis,r),this._translationMatrix.makeTranslation(-i.x,-i.y,-i.z),this._m4_1.makeTranslation(i.x,i.y,i.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState).sub(i),this._v3_2.copy(this._v3_1).applyAxisAngle(this._rotationAxis,r),this._v3_2.sub(this._v3_1),this._m4_2.makeTranslation(this._v3_2.x,this._v3_2.y,this._v3_2.z),this.setTransformationMatrices(this._m4_1,this._m4_2),nt)),M(this,"unprojectOnObj",(i,r)=>{if(!this.scene)return null;const a=new Br;a.near=r.near,a.far=r.far,a.setFromCamera(i,r);const o=a.intersectObjects(this.scene.children,!0);for(let l=0;l<o.length;l++)if(o[l].object.uuid!=this._gizmos.uuid&&o[l].face)return o[l].point.clone();return null}),M(this,"unprojectOnTbSurface",(i,r,a,o,l)=>{if(i instanceof st){this._v2_1.copy(this.getCursorPosition(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0);const c=Math.pow(this._v2_1.x,2),h=Math.pow(this._v2_1.y,2),u=Math.pow(this._tbRadius,2);return c+h<=u*.5?this._v3_1.setZ(Math.sqrt(u-(c+h))):this._v3_1.setZ(u*.5/Math.sqrt(c+h)),this._v3_1}if(i instanceof ke){this._v2_1.copy(this.getCursorNDC(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(i.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=i.position.distanceTo(this._gizmos.position),u=Math.pow(l,2),d=this._v3_1.z,A=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));if(A==0)return c.set(this._v3_1.x,this._v3_1.y,l),c;const f=d/A,g=h;let p=Math.pow(f,2)+1,m=2*f*g,C=Math.pow(g,2)-u,E=Math.pow(m,2)-4*p*C;if(E>=0&&(this._v2_1.setX((-m-Math.sqrt(E))/(2*p)),this._v2_1.setY(f*this._v2_1.x+g),le.RAD2DEG*this._v2_1.angle()>=45)){const _=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(h-this._v2_1.y,2));return c.multiplyScalar(_),c.z+=h,c}p=f,m=g,C=-u*.5,E=Math.pow(m,2)-4*p*C,this._v2_1.setX((-m-Math.sqrt(E))/(2*p)),this._v2_1.setY(f*this._v2_1.x+g);const B=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(h-this._v2_1.y,2));return c.multiplyScalar(B),c.z+=h,c}}),M(this,"unprojectOnTbPlane",(i,r,a,o,l=!1)=>{if(i instanceof st)return this._v2_1.copy(this.getCursorPosition(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0),this._v3_1.clone();if(i instanceof ke){this._v2_1.copy(this.getCursorNDC(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(i.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=this._v3_1.z,u=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let d;if(l?d=this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):d=i.position.distanceTo(this._gizmos.position),u==0)return c.set(0,0,0),c;const A=h/u,f=d,g=-f/A,p=Math.sqrt(Math.pow(f,2)+Math.pow(g,2));return c.multiplyScalar(p),c.z=0,c}}),M(this,"updateMatrixState",()=>{this.camera&&(this._cameraMatrixState.copy(this.camera.matrix),this._gizmoMatrixState.copy(this._gizmos.matrix),this.camera instanceof st&&(this._cameraProjectionState.copy(this.camera.projectionMatrix),this.camera.updateProjectionMatrix(),this._zoomState=this.camera.zoom),this.camera instanceof ke&&(this._fovState=this.camera.fov))}),M(this,"updateTbState",(i,r)=>{this._state=i,r&&this.updateMatrixState()}),M(this,"update",()=>{if(!this.target.equals(this._currentTarget)&&this.camera){this._gizmos.position.set(this.target.x,this.target.y,this.target.z);const r=this.calculateTbRadius(this.camera);r!==void 0&&(this._tbRadius=r),this.makeGizmos(this.target,this._tbRadius),this._currentTarget.copy(this.target)}if(this.camera){if(this.camera instanceof st&&(this.camera.zoom>this.maxZoom||this.camera.zoom<this.minZoom)){const r=le.clamp(this.camera.zoom,this.minZoom,this.maxZoom);this.applyTransformMatrix(this.applyScale(r/this.camera.zoom,this._gizmos.position,!0))}if(this.camera instanceof ke){const r=this.camera.position.distanceTo(this._gizmos.position);if(r>this.maxDistance+1e-6||r<this.minDistance-1e-6){const l=le.clamp(r,this.minDistance,this.maxDistance);this.applyTransformMatrix(this.applyScale(l/r,this._gizmos.position)),this.updateMatrixState()}(this.camera.fov<this.minFov||this.camera.fov>this.maxFov)&&(this.camera.fov=le.clamp(this.camera.fov,this.minFov,this.maxFov),this.camera.updateProjectionMatrix());const a=this._tbRadius,o=this.calculateTbRadius(this.camera);if(o!==void 0&&(this._tbRadius=o),a<this._tbRadius-1e-6||a>this._tbRadius+1e-6){const l=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,c=this._tbRadius/l,u=new Vr(0,0,c,c).getPoints(this._curvePts),d=new mt().setFromPoints(u);for(const A in this._gizmos.children){const f=this._gizmos.children[A];f.geometry=d}}}this.camera.lookAt(this._gizmos.position)}}),M(this,"setStateFromJSON",i=>{const r=JSON.parse(i);if(r.arcballState&&this.camera){this._cameraMatrixState.fromArray(r.arcballState.cameraMatrix.elements),this._cameraMatrixState.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.up.copy(r.arcballState.cameraUp),this.camera.near=r.arcballState.cameraNear,this.camera.far=r.arcballState.cameraFar,this.camera.zoom=r.arcballState.cameraZoom,this.camera instanceof ke&&(this.camera.fov=r.arcballState.cameraFov),this._gizmoMatrixState.fromArray(r.arcballState.gizmoMatrix.elements),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.camera.updateMatrix(),this.camera.updateProjectionMatrix(),this._gizmos.updateMatrix();const a=this.calculateTbRadius(this.camera);a!==void 0&&(this._tbRadius=a);const o=new he().copy(this._gizmoMatrixState0);this.makeGizmos(this._gizmos.position,this._tbRadius),this._gizmoMatrixState0.copy(o),this.camera.lookAt(this._gizmos.position),this.updateTbState(ee.IDLE,!1),this.dispatchEvent(Me)}}),this.camera=null,this.domElement=t,this.scene=s,this.mouseActions=[],this._mouseOp=null,this._v2_1=new Qe,this._v3_1=new P,this._v3_2=new P,this._m4_1=new he,this._m4_2=new he,this._quat=new Ie,this._translationMatrix=new he,this._rotationMatrix=new he,this._scaleMatrix=new he,this._rotationAxis=new P,this._cameraMatrixState=new he,this._cameraProjectionState=new he,this._fovState=1,this._upState=new P,this._zoomState=1,this._nearPos=0,this._farPos=0,this._gizmoMatrixState=new he,this._up0=new P,this._zoom0=1,this._fov0=0,this._initialNear=0,this._nearPos0=0,this._initialFar=0,this._farPos0=0,this._cameraMatrixState0=new he,this._gizmoMatrixState0=new he,this._button=-1,this._touchStart=[],this._touchCurrent=[],this._input=xe.NONE,this._switchSensibility=32,this._startFingerDistance=0,this._currentFingerDistance=0,this._startFingerRotation=0,this._currentFingerRotation=0,this._devPxRatio=0,this._downValid=!0,this._nclicks=0,this._downEvents=[],this._clickStart=0,this._maxDownTime=250,this._maxInterval=300,this._posThreshold=24,this._movementThreshold=24,this._currentCursorPosition=new P,this._startCursorPosition=new P,this._grid=null,this._gridPosition=new P,this._gizmos=new Zs,this._curvePts=128,this._timeStart=-1,this._animationId=-1,this.focusAnimationTime=500,this._timePrev=0,this._timeCurrent=0,this._anglePrev=0,this._angleCurrent=0,this._cursorPosPrev=new P,this._cursorPosCurr=new P,this._wPrev=0,this._wCurr=0,this.adjustNearFar=!1,this.scaleFactor=1.1,this.dampingFactor=25,this.wMax=20,this.enableAnimations=!0,this.enableGrid=!1,this.cursorZoom=!1,this.minFov=5,this.maxFov=90,this.enabled=!0,this.enablePan=!0,this.enableRotate=!0,this.enableZoom=!0,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.target=new P(0,0,0),this._currentTarget=new P(0,0,0),this._tbRadius=1,this._state=ee.IDLE,this.setCamera(e),this.scene&&this.scene.add(this._gizmos),this._devPxRatio=window.devicePixelRatio,this.initializeMouseActions(),this.domElement&&this.connect(this.domElement),window.addEventListener("resize",this.onWindowResize)}applyTransformMatrix(e){if(e!=null&&e.camera&&this.camera&&(this._m4_1.copy(this._cameraMatrixState).premultiply(e.camera),this._m4_1.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.updateMatrix(),(this._state==ee.ROTATE||this._state==ee.ZROTATE||this._state==ee.ANIMATION_ROTATE)&&this.camera.up.copy(this._upState).applyQuaternion(this.camera.quaternion)),e!=null&&e.gizmos&&(this._m4_1.copy(this._gizmoMatrixState).premultiply(e.gizmos),this._m4_1.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.updateMatrix()),(this._state==ee.SCALE||this._state==ee.FOCUS||this._state==ee.ANIMATION_FOCUS)&&this.camera){const t=this.calculateTbRadius(this.camera);if(t!==void 0&&(this._tbRadius=t),this.adjustNearFar){const s=this.camera.position.distanceTo(this._gizmos.position),i=new Qo;i.setFromObject(this._gizmos);const r=new Tr;i.getBoundingSphere(r);const a=Math.max(this._nearPos0,r.radius+r.center.length()),o=s-this._initialNear,l=Math.min(a,o);this.camera.near=s-l;const c=Math.min(this._farPos0,-r.radius+r.center.length()),h=s-this._initialFar,u=Math.min(c,h);this.camera.far=s-u,this.camera.updateProjectionMatrix()}else{let s=!1;this.camera.near!=this._initialNear&&(this.camera.near=this._initialNear,s=!0),this.camera.far!=this._initialFar&&(this.camera.far=this._initialFar,s=!0),s&&this.camera.updateProjectionMatrix()}}}setGizmosVisible(e){this._gizmos.visible=e,this.dispatchEvent(Me)}setTransformationMatrices(e=null,t=null){e?nt.camera?nt.camera.copy(e):nt.camera=e.clone():nt.camera=null,t?nt.gizmos?nt.gizmos.copy(t):nt.gizmos=t.clone():nt.gizmos=null}};var fB=Object.defineProperty,gB=(n,e,t)=>e in n?fB(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Re=(n,e,t)=>(gB(n,typeof e!="symbol"?e+"":e,t),t);function $c(n){n.preventDefault()}let mB=class extends pi{constructor(e,t){super(),Re(this,"object"),Re(this,"domElement",null),Re(this,"movementSpeed",1),Re(this,"rollSpeed",.005),Re(this,"dragToLook",!1),Re(this,"autoForward",!1),Re(this,"changeEvent",{type:"change"}),Re(this,"EPS",1e-6),Re(this,"tmpQuaternion",new Ie),Re(this,"mouseStatus",0),Re(this,"movementSpeedMultiplier",1),Re(this,"moveState",{up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0}),Re(this,"moveVector",new P(0,0,0)),Re(this,"rotationVector",new P(0,0,0)),Re(this,"keydown",s=>{if(!s.altKey){switch(s.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this.moveState.forward=1;break;case"KeyS":this.moveState.back=1;break;case"KeyA":this.moveState.left=1;break;case"KeyD":this.moveState.right=1;break;case"KeyR":this.moveState.up=1;break;case"KeyF":this.moveState.down=1;break;case"ArrowUp":this.moveState.pitchUp=1;break;case"ArrowDown":this.moveState.pitchDown=1;break;case"ArrowLeft":this.moveState.yawLeft=1;break;case"ArrowRight":this.moveState.yawRight=1;break;case"KeyQ":this.moveState.rollLeft=1;break;case"KeyE":this.moveState.rollRight=1;break}this.updateMovementVector(),this.updateRotationVector()}}),Re(this,"keyup",s=>{switch(s.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this.moveState.forward=0;break;case"KeyS":this.moveState.back=0;break;case"KeyA":this.moveState.left=0;break;case"KeyD":this.moveState.right=0;break;case"KeyR":this.moveState.up=0;break;case"KeyF":this.moveState.down=0;break;case"ArrowUp":this.moveState.pitchUp=0;break;case"ArrowDown":this.moveState.pitchDown=0;break;case"ArrowLeft":this.moveState.yawLeft=0;break;case"ArrowRight":this.moveState.yawRight=0;break;case"KeyQ":this.moveState.rollLeft=0;break;case"KeyE":this.moveState.rollRight=0;break}this.updateMovementVector(),this.updateRotationVector()}),Re(this,"pointerdown",s=>{if(this.dragToLook)this.mouseStatus++;else{switch(s.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}}),Re(this,"pointermove",s=>{if(!this.dragToLook||this.mouseStatus>0){const i=this.getContainerDimensions(),r=i.size[0]/2,a=i.size[1]/2;this.moveState.yawLeft=-(s.pageX-i.offset[0]-r)/r,this.moveState.pitchDown=(s.pageY-i.offset[1]-a)/a,this.updateRotationVector()}}),Re(this,"pointerup",s=>{if(this.dragToLook)this.mouseStatus--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(s.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()}),Re(this,"lastQuaternion",new Ie),Re(this,"lastPosition",new P),Re(this,"update",s=>{const i=s*this.movementSpeed,r=s*this.rollSpeed;this.object.translateX(this.moveVector.x*i),this.object.translateY(this.moveVector.y*i),this.object.translateZ(this.moveVector.z*i),this.tmpQuaternion.set(this.rotationVector.x*r,this.rotationVector.y*r,this.rotationVector.z*r,1).normalize(),this.object.quaternion.multiply(this.tmpQuaternion),(this.lastPosition.distanceToSquared(this.object.position)>this.EPS||8*(1-this.lastQuaternion.dot(this.object.quaternion))>this.EPS)&&(this.dispatchEvent(this.changeEvent),this.lastQuaternion.copy(this.object.quaternion),this.lastPosition.copy(this.object.position))}),Re(this,"updateMovementVector",()=>{const s=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right,this.moveVector.y=-this.moveState.down+this.moveState.up,this.moveVector.z=-s+this.moveState.back}),Re(this,"updateRotationVector",()=>{this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp,this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft,this.rotationVector.z=-this.moveState.rollRight+this.moveState.rollLeft}),Re(this,"getContainerDimensions",()=>this.domElement!=document&&!(this.domElement instanceof Document)?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}),Re(this,"connect",s=>{this.domElement=s,s instanceof Document||s.setAttribute("tabindex",-1),this.domElement.addEventListener("contextmenu",$c),this.domElement.addEventListener("pointermove",this.pointermove),this.domElement.addEventListener("pointerdown",this.pointerdown),this.domElement.addEventListener("pointerup",this.pointerup),window.addEventListener("keydown",this.keydown),window.addEventListener("keyup",this.keyup)}),Re(this,"dispose",()=>{this.domElement.removeEventListener("contextmenu",$c),this.domElement.removeEventListener("pointermove",this.pointermove),this.domElement.removeEventListener("pointerdown",this.pointerdown),this.domElement.removeEventListener("pointerup",this.pointerup),window.removeEventListener("keydown",this.keydown),window.removeEventListener("keyup",this.keyup)}),this.object=e,t!==void 0&&this.connect(t),this.updateMovementVector(),this.updateRotationVector()}};function di(n){if(typeof TextDecoder<"u")return new TextDecoder().decode(n);let e="";for(let t=0,s=n.length;t<s;t++)e+=String.fromCharCode(n[t]);try{return decodeURIComponent(escape(e))}catch{return e}}const vs="srgb",es="srgb-linear",Xc=3001,pB=3e3;class hl extends Sr{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new BB(t)}),this.register(function(t){return new TB(t)}),this.register(function(t){return new bB(t)}),this.register(function(t){return new MB(t)}),this.register(function(t){return new FB(t)}),this.register(function(t){return new _B(t)}),this.register(function(t){return new xB(t)}),this.register(function(t){return new vB(t)}),this.register(function(t){return new RB(t)}),this.register(function(t){return new yB(t)}),this.register(function(t){return new wB(t)}),this.register(function(t){return new SB(t)}),this.register(function(t){return new LB(t)}),this.register(function(t){return new DB(t)}),this.register(function(t){return new CB(t)}),this.register(function(t){return new PB(t)}),this.register(function(t){return new kB(t)})}load(e,t,s,i){const r=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const c=ei.extractUrlBase(e);a=ei.resolveURL(c,this.path)}else a=ei.extractUrlBase(e);this.manager.itemStart(e);const o=function(c){i?i(c):console.error(c),r.manager.itemError(e),r.manager.itemEnd(e)},l=new ds(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{r.parse(c,a,function(h){t(h),r.manager.itemEnd(e)},o)}catch(h){o(h)}},s,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,s,i){let r;const a={},o={};if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(di(new Uint8Array(e.slice(0,4)))===Gd){try{a[Ee.KHR_BINARY_GLTF]=new OB(e)}catch(h){i&&i(h);return}r=JSON.parse(a[Ee.KHR_BINARY_GLTF].content)}else r=JSON.parse(di(new Uint8Array(e)));else r=e;if(r.asset===void 0||r.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new XB(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c<this.pluginCallbacks.length;c++){const h=this.pluginCallbacks[c](l);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[h.name]=h,a[h.name]=!0}if(r.extensionsUsed)for(let c=0;c<r.extensionsUsed.length;++c){const h=r.extensionsUsed[c],u=r.extensionsRequired||[];switch(h){case Ee.KHR_MATERIALS_UNLIT:a[h]=new IB;break;case Ee.KHR_DRACO_MESH_COMPRESSION:a[h]=new QB(r,this.dracoLoader);break;case Ee.KHR_TEXTURE_TRANSFORM:a[h]=new GB;break;case Ee.KHR_MESH_QUANTIZATION:a[h]=new UB;break;default:u.indexOf(h)>=0&&o[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}l.setExtensions(a),l.setPlugins(o),l.parse(s,i)}parseAsync(e,t){const s=this;return new Promise(function(i,r){s.parse(e,t,i,r)})}}function EB(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const Ee={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class CB{constructor(e){this.parser=e,this.name=Ee.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let s=0,i=t.length;s<i;s++){const r=t[s];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,s="light:"+e;let i=t.cache.get(s);if(i)return i;const r=t.json,l=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let c;const h=new we(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],es);const u=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new Du(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new $a(h),c.distance=u;break;case"spot":c=new wu(h),c.distance=u,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),c.decay=2,$t(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(c),t.cache.add(s,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,s=this.parser,r=s.json.nodes[e],o=(r.extensions&&r.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return s._getNodeRef(t.cache,o,l)})}}class IB{constructor(){this.name=Ee.KHR_MATERIALS_UNLIT}getMaterialType(){return ls}extendParams(e,t,s){const i=[];e.color=new we(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const a=r.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],es),e.opacity=a[3]}r.baseColorTexture!==void 0&&i.push(s.assignTexture(e,"map",r.baseColorTexture,vs))}return Promise.all(i)}}class yB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}}class BB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&r.push(s.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&r.push(s.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(r.push(s.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Qe(o,o)}return Promise.all(r)}}class TB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_DISPERSION}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name];return t.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}}class SB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&r.push(s.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&r.push(s.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(r)}}class _B{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_SHEEN}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new we(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=i.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],es)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&r.push(s.assignTexture(t,"sheenColorMap",a.sheenColorTexture,vs)),a.sheenRoughnessTexture!==void 0&&r.push(s.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(r)}}class xB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&r.push(s.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(r)}}class vB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_VOLUME}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&r.push(s.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new we().setRGB(o[0],o[1],o[2],es),Promise.all(r)}}class RB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_IOR}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name];return t.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}}class wB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_SPECULAR}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&r.push(s.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new we().setRGB(o[0],o[1],o[2],es),a.specularColorTexture!==void 0&&r.push(s.assignTexture(t,"specularColorMap",a.specularColorTexture,vs)),Promise.all(r)}}class DB{constructor(e){this.parser=e,this.name=Ee.EXT_MATERIALS_BUMP}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&r.push(s.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(r)}}class LB{constructor(e){this.parser=e,this.name=Ee.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:Kt}extendMaterialParams(e,t){const s=this.parser,i=s.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],a=i.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&r.push(s.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(r)}}class bB{constructor(e){this.parser=e,this.name=Ee.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,s=t.json,i=s.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const r=i.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(s.extensionsRequired&&s.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,a)}}class MB{constructor(e){this.parser=e,this.name=Ee.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,s=this.parser,i=s.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=i.images[a.source];let l=s.textureLoader;if(o.uri){const c=s.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return s.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return s.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class FB{constructor(e){this.parser=e,this.name=Ee.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,s=this.parser,i=s.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=i.images[a.source];let l=s.textureLoader;if(o.uri){const c=s.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return s.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return s.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class PB{constructor(e){this.name=Ee.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,s=t.bufferViews[e];if(s.extensions&&s.extensions[this.name]){const i=s.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(o){const l=i.byteOffset||0,c=i.byteLength||0,h=i.count,u=i.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,i.mode,i.filter).then(function(A){return A.buffer}):a.ready.then(function(){const A=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(A),h,u,d,i.mode,i.filter),A})})}else return null}}class kB{constructor(e){this.name=Ee.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,s=t.nodes[e];if(!s.extensions||!s.extensions[this.name]||s.mesh===void 0)return null;const i=t.meshes[s.mesh];for(const c of i.primitives)if(c.mode!==ut.TRIANGLES&&c.mode!==ut.TRIANGLE_STRIP&&c.mode!==ut.TRIANGLE_FAN&&c.mode!==void 0)return null;const a=s.extensions[this.name].attributes,o=[],l={};for(const c in a)o.push(this.parser.getDependency("accessor",a[c]).then(h=>(l[c]=h,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const h=c.pop(),u=h.isGroup?h.children:[h],d=c[0].count,A=[];for(const f of u){const g=new he,p=new P,m=new Ie,C=new P(1,1,1),E=new tg(f.geometry,f.material,d);for(let B=0;B<d;B++)l.TRANSLATION&&p.fromBufferAttribute(l.TRANSLATION,B),l.ROTATION&&m.fromBufferAttribute(l.ROTATION,B),l.SCALE&&C.fromBufferAttribute(l.SCALE,B),E.setMatrixAt(B,g.compose(p,m,C));for(const B in l)if(B==="_COLOR_0"){const I=l[B];E.instanceColor=new sg(I.array,I.itemSize,I.normalized)}else B!=="TRANSLATION"&&B!=="ROTATION"&&B!=="SCALE"&&f.geometry.setAttribute(B,l[B]);Xe.prototype.copy.call(E,f),this.parser.assignFinalMaterial(E),A.push(E)}return h.isGroup?(h.clear(),h.add(...A),h):A[0]}))}}const Gd="glTF",bi=12,jc={JSON:1313821514,BIN:5130562};class OB{constructor(e){this.name=Ee.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,bi);if(this.header={magic:di(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Gd)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-bi,i=new DataView(e,bi);let r=0;for(;r<s;){const a=i.getUint32(r,!0);r+=4;const o=i.getUint32(r,!0);if(r+=4,o===jc.JSON){const l=new Uint8Array(e,bi+r,a);this.content=di(l)}else if(o===jc.BIN){const l=bi+r;this.body=e.slice(l,l+a)}r+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class QB{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Ee.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const s=this.json,i=this.dracoLoader,r=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const h in a){const u=fo[h]||h.toLowerCase();o[u]=a[h]}for(const h in e.attributes){const u=fo[h]||h.toLowerCase();if(a[h]!==void 0){const d=s.accessors[e.attributes[h]],A=ri[d.componentType];c[u]=A.name,l[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(u,d){i.decodeDracoFile(h,function(A){for(const f in A.attributes){const g=A.attributes[f],p=l[f];p!==void 0&&(g.normalized=p)}u(A)},o,c,es,d)})})}}class GB{constructor(){this.name=Ee.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class UB{constructor(){this.name=Ee.KHR_MESH_QUANTIZATION}}class Ud extends Cg{constructor(e,t,s,i){super(e,t,s,i)}copySampleValue_(e){const t=this.resultBuffer,s=this.sampleValues,i=this.valueSize,r=e*i*3+i;for(let a=0;a!==i;a++)t[a]=s[r+a];return t}interpolate_(e,t,s,i){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,h=i-t,u=(s-t)/h,d=u*u,A=d*u,f=e*c,g=f-c,p=-2*A+3*d,m=A-d,C=1-p,E=m-d+u;for(let B=0;B!==o;B++){const I=a[g+B+o],_=a[g+B+l]*h,S=a[f+B+o],x=a[f+B]*h;r[B]=C*I+E*_+p*S+m*x}return r}}const NB=new Ie;class HB extends Ud{interpolate_(e,t,s,i){const r=super.interpolate_(e,t,s,i);return NB.fromArray(r).normalize().toArray(r),r}}const ut={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},ri={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Wc={9728:ja,9729:oi,9984:hg,9985:ug,9986:dg,9987:Go},Zc={33071:Zi,33648:Ag,10497:li},ta={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},fo={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",...ig>=152?{TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3"}:{TEXCOORD_0:"uv",TEXCOORD_1:"uv2"},COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},ns={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},KB={CUBICSPLINE:void 0,LINEAR:ku,STEP:fg},sa={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function VB(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new bu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:gg})),n.DefaultMaterial}function Is(n,e,t){for(const s in t.extensions)n[s]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[s]=t.extensions[s])}function $t(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function YB(n,e,t){let s=!1,i=!1,r=!1;for(let c=0,h=e.length;c<h;c++){const u=e[c];if(u.POSITION!==void 0&&(s=!0),u.NORMAL!==void 0&&(i=!0),u.COLOR_0!==void 0&&(r=!0),s&&i&&r)break}if(!s&&!i&&!r)return Promise.resolve(n);const a=[],o=[],l=[];for(let c=0,h=e.length;c<h;c++){const u=e[c];if(s){const d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):n.attributes.position;a.push(d)}if(i){const d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):n.attributes.normal;o.push(d)}if(r){const d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):n.attributes.color;l.push(d)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){const h=c[0],u=c[1],d=c[2];return s&&(n.morphAttributes.position=h),i&&(n.morphAttributes.normal=u),r&&(n.morphAttributes.color=d),n.morphTargetsRelative=!0,n})}function JB(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,s=e.weights.length;t<s;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let s=0,i=t.length;s<i;s++)n.morphTargetDictionary[t[s]]=s}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function zB(n){let e;const t=n.extensions&&n.extensions[Ee.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ia(t.attributes):e=n.indices+":"+ia(n.attributes)+":"+n.mode,n.targets!==void 0)for(let s=0,i=n.targets.length;s<i;s++)e+=":"+ia(n.targets[s]);return e}function ia(n){let e="";const t=Object.keys(n).sort();for(let s=0,i=t.length;s<i;s++)e+=t[s]+":"+n[t[s]]+";";return e}function go(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function qB(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const $B=new he;class XB{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new EB,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let s=!1,i=!1,r=-1;typeof navigator<"u"&&typeof navigator.userAgent<"u"&&(s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,i=navigator.userAgent.indexOf("Firefox")>-1,r=i?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||s||i&&r<98?this.textureLoader=new Lu(this.options.manager):this.textureLoader=new ng(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ds(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const s=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([s.getDependencies("scene"),s.getDependencies("animation"),s.getDependencies("camera")])}).then(function(a){const o={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:s,userData:{}};return Is(r,o,i),$t(o,i),Promise.all(s._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],s=this.json.meshes||[];for(let i=0,r=t.length;i<r;i++){const a=t[i].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let i=0,r=e.length;i<r;i++){const a=e[i];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(s[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,s){if(e.refs[t]<=1)return s;const i=s.clone(),r=(a,o)=>{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,h]of a.children.entries())r(h,o.children[c])};return r(s,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let s=0;s<t.length;s++){const i=e(t[s]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const s=[];for(let i=0;i<t.length;i++){const r=e(t[i]);r&&s.push(r)}return s}getDependency(e,t){const s=e+":"+t;let i=this.cache.get(s);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":i=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(s,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const s=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(r,a){return s.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],s=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Ee.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(r,a){s.load(ei.resolveURL(t.uri,i.path),r,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(s){const i=t.byteLength||0,r=t.byteOffset||0;return s.slice(r,r+i)})}loadAccessor(e){const t=this,s=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const a=ta[i.type],o=ri[i.componentType],l=i.normalized===!0,c=new o(i.count*a);return Promise.resolve(new ti(c,a,l))}const r=[];return i.bufferView!==void 0?r.push(this.getDependency("bufferView",i.bufferView)):r.push(null),i.sparse!==void 0&&(r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(r).then(function(a){const o=a[0],l=ta[i.type],c=ri[i.componentType],h=c.BYTES_PER_ELEMENT,u=h*l,d=i.byteOffset||0,A=i.bufferView!==void 0?s.bufferViews[i.bufferView].byteStride:void 0,f=i.normalized===!0;let g,p;if(A&&A!==u){const m=Math.floor(d/A),C="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+m+":"+i.count;let E=t.cache.get(C);E||(g=new c(o,m*A,i.count*A/h),E=new rg(g,A/h),t.cache.add(C,E)),p=new mg(E,l,d%A/h,f)}else o===null?g=new c(i.count*l):g=new c(o,d,i.count*l),p=new ti(g,l,f);if(i.sparse!==void 0){const m=ta.SCALAR,C=ri[i.sparse.indices.componentType],E=i.sparse.indices.byteOffset||0,B=i.sparse.values.byteOffset||0,I=new C(a[1],E,i.sparse.count*m),_=new c(a[2],B,i.sparse.count*l);o!==null&&(p=new ti(p.array.slice(),p.itemSize,p.normalized));for(let S=0,x=I.length;S<x;S++){const b=I[S];if(p.setX(b,_[S*l]),l>=2&&p.setY(b,_[S*l+1]),l>=3&&p.setZ(b,_[S*l+2]),l>=4&&p.setW(b,_[S*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return p})}loadTexture(e){const t=this.json,s=this.options,r=t.textures[e].source,a=t.images[r];let o=this.textureLoader;if(a.uri){const l=s.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,s){const i=this,r=this.json,a=r.textures[e],o=r.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,s).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(r.samplers||{})[a.sampler]||{};return h.magFilter=Wc[d.magFilter]||oi,h.minFilter=Wc[d.minFilter]||Go,h.wrapS=Zc[d.wrapS]||li,h.wrapT=Zc[d.wrapT]||li,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const s=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const a=i.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=s.getDependency("bufferView",a.bufferView).then(function(u){c=!0;const d=new Blob([u],{type:a.mimeType});return l=o.createObjectURL(d),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then(function(u){return new Promise(function(d,A){let f=d;t.isImageBitmapLoader===!0&&(f=function(g){const p=new ci(g);p.needsUpdate=!0,d(p)}),t.load(ei.resolveURL(u,r.path),f,void 0,A)})}).then(function(u){return c===!0&&o.revokeObjectURL(l),$t(u,a),u.userData.mimeType=a.mimeType||qB(a.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),u});return this.sourceCache[e]=h,h}assignTexture(e,t,s,i){const r=this;return this.getDependency("texture",s.index).then(function(a){if(!a)return null;if(s.texCoord!==void 0&&s.texCoord>0&&(a=a.clone(),a.channel=s.texCoord),r.extensions[Ee.KHR_TEXTURE_TRANSFORM]){const o=s.extensions!==void 0?s.extensions[Ee.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=r.associations.get(a);a=r.extensions[Ee.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),r.associations.set(a,l)}}return i!==void 0&&(typeof i=="number"&&(i=i===Xc?vs:es),"colorSpace"in a?a.colorSpace=i:a.encoding=i===vs?Xc:pB),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let s=e.material;const i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+s.uuid;let l=this.cache.get(o);l||(l=new ag,Yr.prototype.copy.call(l,s),l.color.copy(s.color),l.map=s.map,l.sizeAttenuation=!1,this.cache.add(o,l)),s=l}else if(e.isLine){const o="LineBasicMaterial:"+s.uuid;let l=this.cache.get(o);l||(l=new Ws,Yr.prototype.copy.call(l,s),l.color.copy(s.color),l.map=s.map,this.cache.add(o,l)),s=l}if(i||r||a){let o="ClonedMaterial:"+s.uuid+":";i&&(o+="derivative-tangents:"),r&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=s.clone(),r&&(l.vertexColors=!0),a&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(s))),s=l}e.material=s}getMaterialType(){return bu}loadMaterial(e){const t=this,s=this.json,i=this.extensions,r=s.materials[e];let a;const o={},l=r.extensions||{},c=[];if(l[Ee.KHR_MATERIALS_UNLIT]){const u=i[Ee.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),c.push(u.extendParams(o,r,t))}else{const u=r.pbrMetallicRoughness||{};if(o.color=new we(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){const d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],es),o.opacity=d[3]}u.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",u.baseColorTexture,vs)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}r.doubleSided===!0&&(o.side=Ei);const h=r.alphaMode||sa.OPAQUE;if(h===sa.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===sa.MASK&&(o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&a!==ls&&(c.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new Qe(1,1),r.normalTexture.scale!==void 0)){const u=r.normalTexture.scale;o.normalScale.set(u,u)}if(r.occlusionTexture!==void 0&&a!==ls&&(c.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&a!==ls){const u=r.emissiveFactor;o.emissive=new we().setRGB(u[0],u[1],u[2],es)}return r.emissiveTexture!==void 0&&a!==ls&&c.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,vs)),Promise.all(c).then(function(){const u=new a(o);return r.name&&(u.name=r.name),$t(u,r),t.associations.set(u,{materials:e}),r.extensions&&Is(i,u,r),u})}createUniqueName(e){const t=Wi.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,s=this.extensions,i=this.primitiveCache;function r(o){return s[Ee.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return eh(l,o,t)})}const a=[];for(let o=0,l=e.length;o<l;o++){const c=e[o],h=zB(c),u=i[h];if(u)a.push(u.promise);else{let d;c.extensions&&c.extensions[Ee.KHR_DRACO_MESH_COMPRESSION]?d=r(c):d=eh(new mt,c,t),i[h]={primitive:c,promise:d},a.push(d)}}return Promise.all(a)}loadMesh(e){const t=this,s=this.json,i=this.extensions,r=s.meshes[e],a=r.primitives,o=[];for(let l=0,c=a.length;l<c;l++){const h=a[l].material===void 0?VB(this.cache):this.getDependency("material",a[l].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){const c=l.slice(0,l.length-1),h=l[l.length-1],u=[];for(let A=0,f=h.length;A<f;A++){const g=h[A],p=a[A];let m;const C=c[A];if(p.mode===ut.TRIANGLES||p.mode===ut.TRIANGLE_STRIP||p.mode===ut.TRIANGLE_FAN||p.mode===void 0)m=r.isSkinnedMesh===!0?new Mu(g,C):new ie(g,C),m.isSkinnedMesh===!0&&m.normalizeSkinWeights(),p.mode===ut.TRIANGLE_STRIP?m.geometry=Ml(m.geometry,pg):p.mode===ut.TRIANGLE_FAN&&(m.geometry=Ml(m.geometry,Eg));else if(p.mode===ut.LINES)m=new og(g,C);else if(p.mode===ut.LINE_STRIP)m=new Ce(g,C);else if(p.mode===ut.LINE_LOOP)m=new lg(g,C);else if(p.mode===ut.POINTS)m=new cg(g,C);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+p.mode);Object.keys(m.geometry.morphAttributes).length>0&&JB(m,r),m.name=t.createUniqueName(r.name||"mesh_"+e),$t(m,r),p.extensions&&Is(i,m,p),t.assignFinalMaterial(m),u.push(m)}for(let A=0,f=u.length;A<f;A++)t.associations.set(u[A],{meshes:e,primitives:A});if(u.length===1)return r.extensions&&Is(i,u[0],r),u[0];const d=new Zs;r.extensions&&Is(i,d,r),t.associations.set(d,{meshes:e});for(let A=0,f=u.length;A<f;A++)d.add(u[A]);return d})}loadCamera(e){let t;const s=this.json.cameras[e],i=s[s.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return s.type==="perspective"?t=new ke(le.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):s.type==="orthographic"&&(t=new st(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),s.name&&(t.name=this.createUniqueName(s.name)),$t(t,s),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],s=[];for(let i=0,r=t.joints.length;i<r;i++)s.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?s.push(this.getDependency("accessor",t.inverseBindMatrices)):s.push(null),Promise.all(s).then(function(i){const r=i.pop(),a=i,o=[],l=[];for(let c=0,h=a.length;c<h;c++){const u=a[c];if(u){o.push(u);const d=new he;r!==null&&d.fromArray(r.array,c*16),l.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new Fu(o,l)})}loadAnimation(e){const t=this.json,s=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let u=0,d=i.channels.length;u<d;u++){const A=i.channels[u],f=i.samplers[A.sampler],g=A.target,p=g.node,m=i.parameters!==void 0?i.parameters[f.input]:f.input,C=i.parameters!==void 0?i.parameters[f.output]:f.output;g.node!==void 0&&(a.push(this.getDependency("node",p)),o.push(this.getDependency("accessor",m)),l.push(this.getDependency("accessor",C)),c.push(f),h.push(g))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(u){const d=u[0],A=u[1],f=u[2],g=u[3],p=u[4],m=[];for(let C=0,E=d.length;C<E;C++){const B=d[C],I=A[C],_=f[C],S=g[C],x=p[C];if(B===void 0)continue;B.updateMatrix&&B.updateMatrix();const b=s._createAnimationTracks(B,I,_,S,x);if(b)for(let v=0;v<b.length;v++)m.push(b[v])}return new Pu(r,void 0,m)})}createNodeMesh(e){const t=this.json,s=this,i=t.nodes[e];return i.mesh===void 0?null:s.getDependency("mesh",i.mesh).then(function(r){const a=s._getNodeRef(s.meshCache,i.mesh,r);return i.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=i.weights.length;l<c;l++)o.morphTargetInfluences[l]=i.weights[l]}),a})}loadNode(e){const t=this.json,s=this,i=t.nodes[e],r=s._loadNodeShallow(e),a=[],o=i.children||[];for(let c=0,h=o.length;c<h;c++)a.push(s.getDependency("node",o[c]));const l=i.skin===void 0?Promise.resolve(null):s.getDependency("skin",i.skin);return Promise.all([r,Promise.all(a),l]).then(function(c){const h=c[0],u=c[1],d=c[2];d!==null&&h.traverse(function(A){A.isSkinnedMesh&&A.bind(d,$B)});for(let A=0,f=u.length;A<f;A++)h.add(u[A]);return h})}_loadNodeShallow(e){const t=this.json,s=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],a=r.name?i.createUniqueName(r.name):"",o=[],l=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),r.camera!==void 0&&o.push(i.getDependency("camera",r.camera).then(function(c){return i._getNodeRef(i.cameraCache,r.camera,c)})),i._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let h;if(r.isBone===!0?h=new Xa:c.length>1?h=new Zs:c.length===1?h=c[0]:h=new Xe,h!==c[0])for(let u=0,d=c.length;u<d;u++)h.add(c[u]);if(r.name&&(h.userData.name=r.name,h.name=a),$t(h,r),r.extensions&&Is(s,h,r),r.matrix!==void 0){const u=new he;u.fromArray(r.matrix),h.applyMatrix4(u)}else r.translation!==void 0&&h.position.fromArray(r.translation),r.rotation!==void 0&&h.quaternion.fromArray(r.rotation),r.scale!==void 0&&h.scale.fromArray(r.scale);return i.associations.has(h)||i.associations.set(h,{}),i.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,s=this.json.scenes[e],i=this,r=new Zs;s.name&&(r.name=i.createUniqueName(s.name)),$t(r,s),s.extensions&&Is(t,r,s);const a=s.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(i.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let h=0,u=l.length;h<u;h++)r.add(l[h]);const c=h=>{const u=new Map;for(const[d,A]of i.associations)(d instanceof Yr||d instanceof ci)&&u.set(d,A);return h.traverse(d=>{const A=i.associations.get(d);A!=null&&u.set(d,A)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,s,i,r){const a=[],o=e.name?e.name:e.uuid,l=[];ns[r.path]===ns.weights?e.traverse(function(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}):l.push(o);let c;switch(ns[r.path]){case ns.weights:c=Za;break;case ns.rotation:c=eo;break;case ns.position:case ns.scale:c=Wa;break;default:switch(s.itemSize){case 1:c=Za;break;case 2:case 3:default:c=Wa;break}break}const h=i.interpolation!==void 0?KB[i.interpolation]:ku,u=this._getArrayFromAccessor(s);for(let d=0,A=l.length;d<A;d++){const f=new c(l[d]+"."+ns[r.path],t.array,u,h);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),a.push(f)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const s=go(t.constructor),i=new Float32Array(t.length);for(let r=0,a=t.length;r<a;r++)i[r]=t[r]*s;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(s){const i=this instanceof eo?HB:Ud;return new i(this.times,this.values,this.getValueSize()/3,s)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function jB(n,e,t){const s=e.attributes,i=new Qo;if(s.POSITION!==void 0){const o=t.json.accessors[s.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(i.set(new P(l[0],l[1],l[2]),new P(c[0],c[1],c[2])),o.normalized){const h=go(ri[o.componentType]);i.min.multiplyScalar(h),i.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const o=new P,l=new P;for(let c=0,h=r.length;c<h;c++){const u=r[c];if(u.POSITION!==void 0){const d=t.json.accessors[u.POSITION],A=d.min,f=d.max;if(A!==void 0&&f!==void 0){if(l.setX(Math.max(Math.abs(A[0]),Math.abs(f[0]))),l.setY(Math.max(Math.abs(A[1]),Math.abs(f[1]))),l.setZ(Math.max(Math.abs(A[2]),Math.abs(f[2]))),d.normalized){const g=go(ri[d.componentType]);l.multiplyScalar(g)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(o)}n.boundingBox=i;const a=new Tr;i.getCenter(a.center),a.radius=i.min.distanceTo(i.max)/2,n.boundingSphere=a}function eh(n,e,t){const s=e.attributes,i=[];function r(a,o){return t.getDependency("accessor",a).then(function(l){n.setAttribute(o,l)})}for(const a in s){const o=fo[a]||a.toLowerCase();o in n.attributes||i.push(r(s[a],o))}if(e.indices!==void 0&&!n.index){const a=t.getDependency("accessor",e.indices).then(function(o){n.setIndex(o)});i.push(a)}return $t(n,e),jB(n,e,t),Promise.all(i).then(function(){return e.targets!==void 0?YB(n,e.targets,t):n})}function Nd(n,e,t){const s=t.length-n-1;if(e>=t[s])return s-1;if(e<=t[n])return n;let i=n,r=s,a=Math.floor((i+r)/2);for(;e<t[a]||e>=t[a+1];)e<t[a]?r=a:i=a,a=Math.floor((i+r)/2);return a}function WB(n,e,t,s){const i=[],r=[],a=[];i[0]=1;for(let o=1;o<=t;++o){r[o]=e-s[n+1-o],a[o]=s[n+o]-e;let l=0;for(let c=0;c<o;++c){const h=a[c+1],u=r[o-c],d=i[c]/(h+u);i[c]=l+h*d,l=u*d}i[o]=l}return i}function ZB(n,e,t,s){const i=Nd(n,s,e),r=WB(i,s,n,e),a=new vt(0,0,0,0);for(let o=0;o<=n;++o){const l=t[i-n+o],c=r[o],h=l.w*c;a.x+=l.x*h,a.y+=l.y*h,a.z+=l.z*h,a.w+=l.w*c}return a}function eT(n,e,t,s,i){const r=[];for(let u=0;u<=t;++u)r[u]=0;const a=[];for(let u=0;u<=s;++u)a[u]=r.slice(0);const o=[];for(let u=0;u<=t;++u)o[u]=r.slice(0);o[0][0]=1;const l=r.slice(0),c=r.slice(0);for(let u=1;u<=t;++u){l[u]=e-i[n+1-u],c[u]=i[n+u]-e;let d=0;for(let A=0;A<u;++A){const f=c[A+1],g=l[u-A];o[u][A]=f+g;const p=o[A][u-1]/o[u][A];o[A][u]=d+f*p,d=g*p}o[u][u]=d}for(let u=0;u<=t;++u)a[0][u]=o[u][t];for(let u=0;u<=t;++u){let d=0,A=1;const f=[];for(let g=0;g<=t;++g)f[g]=r.slice(0);f[0][0]=1;for(let g=1;g<=s;++g){let p=0;const m=u-g,C=t-g;u>=g&&(f[A][0]=f[d][0]/o[C+1][m],p=f[A][0]*o[m][C]);const E=m>=-1?1:-m,B=u-1<=C?g-1:t-u;for(let _=E;_<=B;++_)f[A][_]=(f[d][_]-f[d][_-1])/o[C+1][m+_],p+=f[A][_]*o[m+_][C];u<=C&&(f[A][g]=-f[d][g-1]/o[C+1][u],p+=f[A][g]*o[u][C]),a[g][u]=p;const I=d;d=A,A=I}}let h=t;for(let u=1;u<=s;++u){for(let d=0;d<=t;++d)a[u][d]*=h;h*=t-u}return a}function tT(n,e,t,s,i){const r=i<n?i:n,a=[],o=Nd(n,s,e),l=eT(o,s,n,r,e),c=[];for(let h=0;h<t.length;++h){const u=t[h].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,c[h]=u}for(let h=0;h<=r;++h){const u=c[o-n].clone().multiplyScalar(l[h][0]);for(let d=1;d<=n;++d)u.add(c[o-n+d].clone().multiplyScalar(l[h][d]));a[h]=u}for(let h=r+1;h<=i+1;++h)a[h]=new vt(0,0,0);return a}function sT(n,e){let t=1;for(let i=2;i<=n;++i)t*=i;let s=1;for(let i=2;i<=e;++i)s*=i;for(let i=2;i<=n-e;++i)s*=i;return t/s}function iT(n){const e=n.length,t=[],s=[];for(let r=0;r<e;++r){const a=n[r];t[r]=new P(a.x,a.y,a.z),s[r]=a.w}const i=[];for(let r=0;r<e;++r){const a=t[r].clone();for(let o=1;o<=r;++o)a.sub(i[r-o].clone().multiplyScalar(sT(r,o)*s[o]));i[r]=a.divideScalar(s[0])}return i}function nT(n,e,t,s,i){const r=tT(n,e,t,s,i);return iT(r)}class th extends Ig{constructor(e,t,s,i,r){super(),this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=i||0,this.endKnot=r||this.knots.length-1;for(let a=0;a<s.length;++a){const o=s[a];this.controlPoints[a]=new vt(o.x,o.y,o.z,o.w)}}getPoint(e,t){const s=t||new P,i=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=ZB(this.degree,this.knots,this.controlPoints,i);return r.w!=1&&r.divideScalar(r.w),s.set(r.x,r.y,r.z)}getTangent(e,t){const s=t||new P,i=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),r=nT(this.degree,this.knots,this.controlPoints,i,1);return s.copy(r[1]).normalize(),s}}let pe,Oe,it;class ul extends Sr{constructor(e){super(e)}load(e,t,s,i){const r=this,a=r.path===""?ei.extractUrlBase(e):r.path,o=new ds(this.manager);o.setPath(r.path),o.setResponseType("arraybuffer"),o.setRequestHeader(r.requestHeader),o.setWithCredentials(r.withCredentials),o.load(e,function(l){try{t(r.parse(l,a))}catch(c){i?i(c):console.error(c),r.manager.itemError(e)}},s,i)}parse(e,t){if(hT(e))pe=new cT().parse(e);else{const i=Yd(e);if(!uT(i))throw new Error("THREE.FBXLoader: Unknown format.");if(ih(i)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+ih(i));pe=new lT().parse(i)}const s=new Lu(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new rT(s,this.manager).parse(pe)}}class rT{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Oe=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),s=this.parseMaterials(t),i=this.parseDeformers(),r=new aT().parse(i);return this.parseScene(i,r,s),it}parseConnections(){const e=new Map;return"Connections"in pe&&pe.Connections.connections.forEach(function(s){const i=s[0],r=s[1],a=s[2];e.has(i)||e.set(i,{parents:[],children:[]});const o={ID:r,relationship:a};e.get(i).parents.push(o),e.has(r)||e.set(r,{parents:[],children:[]});const l={ID:i,relationship:a};e.get(r).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in pe.Objects){const s=pe.Objects.Video;for(const i in s){const r=s[i],a=parseInt(i);if(e[a]=r.RelativeFilename||r.Filename,"Content"in r){const o=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,l=typeof r.Content=="string"&&r.Content!=="";if(o||l){const c=this.parseImage(s[i]);t[r.RelativeFilename||r.Filename]=c}}}}for(const s in e){const i=e[s];t[i]!==void 0?e[s]=t[i]:e[s]=e[s].split("\\").pop()}return e}parseImage(e){const t=e.Content,s=e.RelativeFilename||e.Filename,i=s.slice(s.lastIndexOf(".")+1).toLowerCase();let r;switch(i){case"bmp":r="image/bmp";break;case"jpg":case"jpeg":r="image/jpeg";break;case"png":r="image/png";break;case"tif":r="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",s),r="image/tga";break;default:console.warn('FBXLoader: Image type "'+i+'" is not supported.');return}if(typeof t=="string")return"data:"+r+";base64,"+t;{const a=new Uint8Array(t);return window.URL.createObjectURL(new Blob([a],{type:r}))}}parseTextures(e){const t=new Map;if("Texture"in pe.Objects){const s=pe.Objects.Texture;for(const i in s){const r=this.parseTexture(s[i],e);t.set(parseInt(i),r)}}return t}parseTexture(e,t){const s=this.loadTexture(e,t);s.ID=e.id,s.name=e.attrName;const i=e.WrapModeU,r=e.WrapModeV,a=i!==void 0?i.value:0,o=r!==void 0?r.value:0;if(s.wrapS=a===0?li:Zi,s.wrapT=o===0?li:Zi,"Scaling"in e){const l=e.Scaling.value;s.repeat.x=l[0],s.repeat.y=l[1]}return s}loadTexture(e,t){let s;const i=this.textureLoader.path,r=Oe.get(e.id).children;r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(s=t[r[0].ID],(s.indexOf("blob:")===0||s.indexOf("data:")===0)&&this.textureLoader.setPath(void 0));let a;const o=e.FileName.slice(-3).toLowerCase();if(o==="tga"){const l=this.manager.getHandler(".tga");l===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",e.RelativeFilename),a=new ci):(l.setPath(this.textureLoader.path),a=l.load(s))}else o==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",e.RelativeFilename),a=new ci):a=this.textureLoader.load(s);return this.textureLoader.setPath(i),a}parseMaterials(e){const t=new Map;if("Material"in pe.Objects){const s=pe.Objects.Material;for(const i in s){const r=this.parseMaterial(s[i],e);r!==null&&t.set(parseInt(i),r)}}return t}parseMaterial(e,t){const s=e.id,i=e.attrName;let r=e.ShadingModel;if(typeof r=="object"&&(r=r.value),!Oe.has(s))return null;const a=this.parseParameters(e,t,s);let o;switch(r.toLowerCase()){case"phong":o=new Jr;break;case"lambert":o=new yg;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),o=new Jr;break}return o.setValues(a),o.name=i,o}parseParameters(e,t,s){const i={};e.BumpFactor&&(i.bumpScale=e.BumpFactor.value),e.Diffuse?i.color=new we().fromArray(e.Diffuse.value):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(i.color=new we().fromArray(e.DiffuseColor.value)),e.DisplacementFactor&&(i.displacementScale=e.DisplacementFactor.value),e.Emissive?i.emissive=new we().fromArray(e.Emissive.value):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(i.emissive=new we().fromArray(e.EmissiveColor.value)),e.EmissiveFactor&&(i.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),e.Opacity&&(i.opacity=parseFloat(e.Opacity.value)),i.opacity<1&&(i.transparent=!0),e.ReflectionFactor&&(i.reflectivity=e.ReflectionFactor.value),e.Shininess&&(i.shininess=e.Shininess.value),e.Specular?i.specular=new we().fromArray(e.Specular.value):e.SpecularColor&&e.SpecularColor.type==="Color"&&(i.specular=new we().fromArray(e.SpecularColor.value));const r=this;return Oe.get(s).children.forEach(function(a){const o=a.relationship;switch(o){case"Bump":i.bumpMap=r.getTexture(t,a.ID);break;case"Maya|TEX_ao_map":i.aoMap=r.getTexture(t,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":i.map=r.getTexture(t,a.ID),i.map!==void 0&&("colorSpace"in i.map?i.map.colorSpace="srgb":i.map.encoding=3001);break;case"DisplacementColor":i.displacementMap=r.getTexture(t,a.ID);break;case"EmissiveColor":i.emissiveMap=r.getTexture(t,a.ID),i.emissiveMap!==void 0&&("colorSpace"in i.emissiveMap?i.emissiveMap.colorSpace="srgb":i.emissiveMap.encoding=3001);break;case"NormalMap":case"Maya|TEX_normal_map":i.normalMap=r.getTexture(t,a.ID);break;case"ReflectionColor":i.envMap=r.getTexture(t,a.ID),i.envMap!==void 0&&(i.envMap.mapping=Bg,"colorSpace"in i.envMap?i.envMap.colorSpace="srgb":i.envMap.encoding=3001);break;case"SpecularColor":i.specularMap=r.getTexture(t,a.ID),i.specularMap!==void 0&&("colorSpace"in i.specularMap?i.specularMap.colorSpace="srgb":i.specularMap.encoding=3001);break;case"TransparentColor":case"TransparencyFactor":i.alphaMap=r.getTexture(t,a.ID),i.transparent=!0;break;case"AmbientColor":case"ShininessExponent":case"SpecularFactor":case"VectorDisplacementColor":default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),i}getTexture(e,t){return"LayeredTexture"in pe.Objects&&t in pe.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Oe.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in pe.Objects){const s=pe.Objects.Deformer;for(const i in s){const r=s[i],a=Oe.get(parseInt(i));if(r.attrType==="Skin"){const o=this.parseSkeleton(a,s);o.ID=i,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,e[i]=o}else if(r.attrType==="BlendShape"){const o={id:i};o.rawTargets=this.parseMorphTargets(a,s),o.id=i,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[i]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const s=[];return e.children.forEach(function(i){const r=t[i.ID];if(r.attrType!=="Cluster")return;const a={ID:i.ID,indices:[],weights:[],transformLink:new he().fromArray(r.TransformLink.a)};"Indexes"in r&&(a.indices=r.Indexes.a,a.weights=r.Weights.a),s.push(a)}),{rawBones:s,bones:[]}}parseMorphTargets(e,t){const s=[];for(let i=0;i<e.children.length;i++){const r=e.children[i],a=t[r.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=Oe.get(parseInt(r.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,s.push(o)}return s}parseScene(e,t,s){it=new Zs;const i=this.parseModels(e.skeletons,t,s),r=pe.Objects.Model,a=this;i.forEach(function(l){const c=r[l.ID];a.setLookAtProperties(l,c),Oe.get(l.ID).parents.forEach(function(u){const d=i.get(u.ID);d!==void 0&&d.add(l)}),l.parent===null&&it.add(l)}),this.bindSkeleton(e.skeletons,t,i),this.createAmbientLight(),it.traverse(function(l){if(l.userData.transformData){l.parent&&(l.userData.transformData.parentMatrix=l.parent.matrix,l.userData.transformData.parentMatrixWorld=l.parent.matrixWorld);const c=Kd(l.userData.transformData);l.applyMatrix4(c),l.updateWorldMatrix()}});const o=new oT().parse();it.children.length===1&&it.children[0].isGroup&&(it.children[0].animations=o,it=it.children[0]),it.animations=o}parseModels(e,t,s){const i=new Map,r=pe.Objects.Model;for(const a in r){const o=parseInt(a),l=r[a],c=Oe.get(o);let h=this.buildSkeleton(c,e,o,l.attrName);if(!h){switch(l.attrType){case"Camera":h=this.createCamera(c);break;case"Light":h=this.createLight(c);break;case"Mesh":h=this.createMesh(c,t,s);break;case"NurbsCurve":h=this.createCurve(c,t);break;case"LimbNode":case"Root":h=new Xa;break;case"Null":default:h=new Zs;break}h.name=l.attrName?Wi.sanitizeNodeName(l.attrName):"",h.ID=o}this.getTransformData(h,l),i.set(o,h)}return i}buildSkeleton(e,t,s,i){let r=null;return e.parents.forEach(function(a){for(const o in t){const l=t[o];l.rawBones.forEach(function(c,h){if(c.ID===a.ID){const u=r;r=new Xa,r.matrixWorld.copy(c.transformLink),r.name=i?Wi.sanitizeNodeName(i):"",r.ID=s,l.bones[h]=r,u!==null&&r.add(u)}})}}),r}createCamera(e){let t,s;if(e.children.forEach(function(i){const r=pe.Objects.NodeAttribute[i.ID];r!==void 0&&(s=r)}),s===void 0)t=new Xe;else{let i=0;s.CameraProjectionType!==void 0&&s.CameraProjectionType.value===1&&(i=1);let r=1;s.NearPlane!==void 0&&(r=s.NearPlane.value/1e3);let a=1e3;s.FarPlane!==void 0&&(a=s.FarPlane.value/1e3);let o=window.innerWidth,l=window.innerHeight;s.AspectWidth!==void 0&&s.AspectHeight!==void 0&&(o=s.AspectWidth.value,l=s.AspectHeight.value);const c=o/l;let h=45;s.FieldOfView!==void 0&&(h=s.FieldOfView.value);const u=s.FocalLength?s.FocalLength.value:null;switch(i){case 0:t=new ke(h,c,r,a),u!==null&&t.setFocalLength(u);break;case 1:t=new st(-o/2,o/2,l/2,-l/2,r,a);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+i+"."),t=new Xe;break}}return t}createLight(e){let t,s;if(e.children.forEach(function(i){const r=pe.Objects.NodeAttribute[i.ID];r!==void 0&&(s=r)}),s===void 0)t=new Xe;else{let i;s.LightType===void 0?i=0:i=s.LightType.value;let r=16777215;s.Color!==void 0&&(r=new we().fromArray(s.Color.value));let a=s.Intensity===void 0?1:s.Intensity.value/100;s.CastLightOnObject!==void 0&&s.CastLightOnObject.value===0&&(a=0);let o=0;s.FarAttenuationEnd!==void 0&&(s.EnableFarAttenuation!==void 0&&s.EnableFarAttenuation.value===0?o=0:o=s.FarAttenuationEnd.value);const l=1;switch(i){case 0:t=new $a(r,a,o,l);break;case 1:t=new Du(r,a);break;case 2:let c=Math.PI/3;s.InnerAngle!==void 0&&(c=le.degToRad(s.InnerAngle.value));let h=0;s.OuterAngle!==void 0&&(h=le.degToRad(s.OuterAngle.value),h=Math.max(h,1)),t=new wu(r,a,o,c,h,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+s.LightType.value+", defaulting to a PointLight."),t=new $a(r,a);break}s.CastShadows!==void 0&&s.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,s){let i,r=null,a=null;const o=[];return e.children.forEach(function(l){t.has(l.ID)&&(r=t.get(l.ID)),s.has(l.ID)&&o.push(s.get(l.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new Jr({color:13421772}),o.push(a)),"color"in r.attributes&&o.forEach(function(l){l.vertexColors=!0}),r.FBX_Deformer?(i=new Mu(r,a),i.normalizeSkinWeights()):i=new ie(r,a),i}createCurve(e,t){const s=e.children.reduce(function(r,a){return t.has(a.ID)&&(r=t.get(a.ID)),r},null),i=new Ws({color:3342591,linewidth:1});return new Ce(s,i)}getTransformData(e,t){const s={};"InheritType"in t&&(s.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?s.eulerOrder=Vd(t.RotationOrder.value):s.eulerOrder="ZYX","Lcl_Translation"in t&&(s.translation=t.Lcl_Translation.value),"PreRotation"in t&&(s.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(s.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(s.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(s.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(s.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(s.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(s.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(s.rotationPivot=t.RotationPivot.value),e.userData.transformData=s}setLookAtProperties(e,t){"LookAtProperty"in t&&Oe.get(e.ID).children.forEach(function(i){if(i.relationship==="LookAtProperty"){const r=pe.Objects.Model[i.ID];if("Lcl_Translation"in r){const a=r.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(a),it.add(e.target)):e.lookAt(new P().fromArray(a))}}})}bindSkeleton(e,t,s){const i=this.parsePoseNodes();for(const r in e){const a=e[r];Oe.get(parseInt(a.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Oe.get(c).parents.forEach(function(u){s.has(u.ID)&&s.get(u.ID).bind(new Fu(a.bones),i[u.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in pe.Objects){const t=pe.Objects.Pose;for(const s in t)if(t[s].attrType==="BindPose"&&t[s].NbPoseNodes>0){const i=t[s].PoseNode;Array.isArray(i)?i.forEach(function(r){e[r.Node]=new he().fromArray(r.Matrix.a)}):e[i.Node]=new he().fromArray(i.Matrix.a)}}return e}createAmbientLight(){if("GlobalSettings"in pe&&"AmbientColor"in pe.GlobalSettings){const e=pe.GlobalSettings.AmbientColor.value,t=e[0],s=e[1],i=e[2];if(t!==0||s!==0||i!==0){const r=new we(t,s,i);it.add(new Tg(r,1))}}}}class aT{parse(e){const t=new Map;if("Geometry"in pe.Objects){const s=pe.Objects.Geometry;for(const i in s){const r=Oe.get(parseInt(i)),a=this.parseGeometry(r,s[i],e);t.set(parseInt(i),a)}}return t}parseGeometry(e,t,s){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,s);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,s){const i=s.skeletons,r=[],a=e.parents.map(function(u){return pe.Objects.Model[u.ID]});if(a.length===0)return;const o=e.children.reduce(function(u,d){return i[d.ID]!==void 0&&(u=i[d.ID]),u},null);e.children.forEach(function(u){s.morphTargets[u.ID]!==void 0&&r.push(s.morphTargets[u.ID])});const l=a[0],c={};"RotationOrder"in l&&(c.eulerOrder=Vd(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const h=Kd(c);return this.genGeometry(t,o,r,h)}genGeometry(e,t,s,i){const r=new mt;e.attrName&&(r.name=e.attrName);const a=this.parseGeoNode(e,t),o=this.genBuffers(a),l=new Wt(o.vertex,3);if(l.applyMatrix4(i),r.setAttribute("position",l),o.colors.length>0&&r.setAttribute("color",new Wt(o.colors,3)),t&&(r.setAttribute("skinIndex",new Sg(o.weightsIndices,4)),r.setAttribute("skinWeight",new Wt(o.vertexWeights,4)),r.FBX_Deformer=t),o.normal.length>0){const c=new Vi().getNormalMatrix(i),h=new Wt(o.normal,3);h.applyNormalMatrix(c),r.setAttribute("normal",h)}if(o.uvs.forEach(function(c,h){xg==="uv2"&&h++;const u=h===0?"uv":`uv${h}`;r.setAttribute(u,new Wt(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let c=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,d){u!==c&&(r.addGroup(h,d-h,c),c=u,h=d)}),r.groups.length>0){const u=r.groups[r.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&r.addGroup(d,o.materialIndex.length-d,c)}r.groups.length===0&&r.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(r,e,s,i),r}parseGeoNode(e,t){const s={};if(s.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],s.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&(s.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(s.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(s.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){s.uv=[];let i=0;for(;e.LayerElementUV[i];)e.LayerElementUV[i].UV&&s.uv.push(this.parseUVs(e.LayerElementUV[i])),i++}return s.weightTable={},t!==null&&(s.skeleton=t,t.rawBones.forEach(function(i,r){i.indices.forEach(function(a,o){s.weightTable[a]===void 0&&(s.weightTable[a]=[]),s.weightTable[a].push({id:r,weight:i.weights[o]})})})),s}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let s=0,i=0,r=!1,a=[],o=[],l=[],c=[],h=[],u=[];const d=this;return e.vertexIndices.forEach(function(A,f){let g,p=!1;A<0&&(A=A^-1,p=!0);let m=[],C=[];if(a.push(A*3,A*3+1,A*3+2),e.color){const E=Sn(f,s,A,e.color);l.push(E[0],E[1],E[2])}if(e.skeleton){if(e.weightTable[A]!==void 0&&e.weightTable[A].forEach(function(E){C.push(E.weight),m.push(E.id)}),C.length>4){r||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),r=!0);const E=[0,0,0,0],B=[0,0,0,0];C.forEach(function(I,_){let S=I,x=m[_];B.forEach(function(b,v,D){if(S>b){D[v]=S,S=b;const U=E[v];E[v]=x,x=U}})}),m=E,C=B}for(;C.length<4;)C.push(0),m.push(0);for(let E=0;E<4;++E)h.push(C[E]),u.push(m[E])}if(e.normal){const E=Sn(f,s,A,e.normal);o.push(E[0],E[1],E[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=Sn(f,s,A,e.material)[0]),e.uv&&e.uv.forEach(function(E,B){const I=Sn(f,s,A,E);c[B]===void 0&&(c[B]=[]),c[B].push(I[0]),c[B].push(I[1])}),i++,p&&(d.genFace(t,e,a,g,o,l,c,h,u,i),s++,i=0,a=[],o=[],l=[],c=[],h=[],u=[])}),t}genFace(e,t,s,i,r,a,o,l,c,h){for(let u=2;u<h;u++)e.vertex.push(t.vertexPositions[s[0]]),e.vertex.push(t.vertexPositions[s[1]]),e.vertex.push(t.vertexPositions[s[2]]),e.vertex.push(t.vertexPositions[s[(u-1)*3]]),e.vertex.push(t.vertexPositions[s[(u-1)*3+1]]),e.vertex.push(t.vertexPositions[s[(u-1)*3+2]]),e.vertex.push(t.vertexPositions[s[u*3]]),e.vertex.push(t.vertexPositions[s[u*3+1]]),e.vertex.push(t.vertexPositions[s[u*3+2]]),t.skeleton&&(e.vertexWeights.push(l[0]),e.vertexWeights.push(l[1]),e.vertexWeights.push(l[2]),e.vertexWeights.push(l[3]),e.vertexWeights.push(l[(u-1)*4]),e.vertexWeights.push(l[(u-1)*4+1]),e.vertexWeights.push(l[(u-1)*4+2]),e.vertexWeights.push(l[(u-1)*4+3]),e.vertexWeights.push(l[u*4]),e.vertexWeights.push(l[u*4+1]),e.vertexWeights.push(l[u*4+2]),e.vertexWeights.push(l[u*4+3]),e.weightsIndices.push(c[0]),e.weightsIndices.push(c[1]),e.weightsIndices.push(c[2]),e.weightsIndices.push(c[3]),e.weightsIndices.push(c[(u-1)*4]),e.weightsIndices.push(c[(u-1)*4+1]),e.weightsIndices.push(c[(u-1)*4+2]),e.weightsIndices.push(c[(u-1)*4+3]),e.weightsIndices.push(c[u*4]),e.weightsIndices.push(c[u*4+1]),e.weightsIndices.push(c[u*4+2]),e.weightsIndices.push(c[u*4+3])),t.color&&(e.colors.push(a[0]),e.colors.push(a[1]),e.colors.push(a[2]),e.colors.push(a[(u-1)*3]),e.colors.push(a[(u-1)*3+1]),e.colors.push(a[(u-1)*3+2]),e.colors.push(a[u*3]),e.colors.push(a[u*3+1]),e.colors.push(a[u*3+2])),t.material&&t.material.mappingType!=="AllSame"&&(e.materialIndex.push(i),e.materialIndex.push(i),e.materialIndex.push(i)),t.normal&&(e.normal.push(r[0]),e.normal.push(r[1]),e.normal.push(r[2]),e.normal.push(r[(u-1)*3]),e.normal.push(r[(u-1)*3+1]),e.normal.push(r[(u-1)*3+2]),e.normal.push(r[u*3]),e.normal.push(r[u*3+1]),e.normal.push(r[u*3+2])),t.uv&&t.uv.forEach(function(d,A){e.uvs[A]===void 0&&(e.uvs[A]=[]),e.uvs[A].push(o[A][0]),e.uvs[A].push(o[A][1]),e.uvs[A].push(o[A][(u-1)*2]),e.uvs[A].push(o[A][(u-1)*2+1]),e.uvs[A].push(o[A][u*2]),e.uvs[A].push(o[A][u*2+1])})}addMorphTargets(e,t,s,i){if(s.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const r=this;s.forEach(function(a){a.rawTargets.forEach(function(o){const l=pe.Objects.Geometry[o.geoID];l!==void 0&&r.genMorphGeometry(e,t,l,i,o.name)})})}genMorphGeometry(e,t,s,i,r){const a=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],o=s.Vertices!==void 0?s.Vertices.a:[],l=s.Indexes!==void 0?s.Indexes.a:[],c=e.attributes.position.count*3,h=new Float32Array(c);for(let f=0;f<l.length;f++){const g=l[f]*3;h[g]=o[f*3],h[g+1]=o[f*3+1],h[g+2]=o[f*3+2]}const u={vertexIndices:a,vertexPositions:h},d=this.genBuffers(u),A=new Wt(d.vertex,3);A.name=r||s.attrName,A.applyMatrix4(i),e.morphAttributes.position.push(A)}parseNormals(e){const t=e.MappingInformationType,s=e.ReferenceInformationType,i=e.Normals.a;let r=[];return s==="IndexToDirect"&&("NormalIndex"in e?r=e.NormalIndex.a:"NormalsIndex"in e&&(r=e.NormalsIndex.a)),{dataSize:3,buffer:i,indices:r,mappingType:t,referenceType:s}}parseUVs(e){const t=e.MappingInformationType,s=e.ReferenceInformationType,i=e.UV.a;let r=[];return s==="IndexToDirect"&&(r=e.UVIndex.a),{dataSize:2,buffer:i,indices:r,mappingType:t,referenceType:s}}parseVertexColors(e){const t=e.MappingInformationType,s=e.ReferenceInformationType,i=e.Colors.a;let r=[];return s==="IndexToDirect"&&(r=e.ColorIndex.a),{dataSize:4,buffer:i,indices:r,mappingType:t,referenceType:s}}parseMaterialIndices(e){const t=e.MappingInformationType,s=e.ReferenceInformationType;if(t==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:s};const i=e.Materials.a,r=[];for(let a=0;a<i.length;++a)r.push(a);return{dataSize:1,buffer:i,indices:r,mappingType:t,referenceType:s}}parseNurbsGeometry(e){if(th===void 0)return console.error("THREE.FBXLoader: The loader relies on NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry."),new mt;const t=parseInt(e.Order);if(isNaN(t))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",e.Order,e.id),new mt;const s=t-1,i=e.KnotVector.a,r=[],a=e.Points.a;for(let u=0,d=a.length;u<d;u+=4)r.push(new vt().fromArray(a,u));let o,l;if(e.Form==="Closed")r.push(r[0]);else if(e.Form==="Periodic"){o=s,l=i.length-1-o;for(let u=0;u<s;++u)r.push(r[u])}const h=new th(s,i,r,o,l).getPoints(r.length*12);return new mt().setFromPoints(h)}}class oT{parse(){const e=[],t=this.parseClips();if(t!==void 0)for(const s in t){const i=t[s],r=this.addClip(i);e.push(r)}return e}parseClips(){if(pe.Objects.AnimationCurve===void 0)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=pe.Objects.AnimationCurveNode,t=new Map;for(const s in e){const i=e[s];if(i.attrName.match(/S|R|T|DeformPercent/)!==null){const r={id:i.id,attr:i.attrName,curves:{}};t.set(r.id,r)}}return t}parseAnimationCurves(e){const t=pe.Objects.AnimationCurve;for(const s in t){const i={id:t[s].id,times:t[s].KeyTime.a.map(dT),values:t[s].KeyValueFloat.a},r=Oe.get(i.id);if(r!==void 0){const a=r.parents[0].ID,o=r.parents[0].relationship;o.match(/X/)?e.get(a).curves.x=i:o.match(/Y/)?e.get(a).curves.y=i:o.match(/Z/)?e.get(a).curves.z=i:o.match(/d|DeformPercent/)&&e.has(a)&&(e.get(a).curves.morph=i)}}}parseAnimationLayers(e){const t=pe.Objects.AnimationLayer,s=new Map;for(const i in t){const r=[],a=Oe.get(parseInt(i));a!==void 0&&(a.children.forEach(function(l,c){if(e.has(l.ID)){const h=e.get(l.ID);if(h.curves.x!==void 0||h.curves.y!==void 0||h.curves.z!==void 0){if(r[c]===void 0){const u=Oe.get(l.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=pe.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const A={modelName:d.attrName?Wi.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};it.traverse(function(f){f.ID===d.id&&(A.transform=f.matrix,f.userData.transformData&&(A.eulerOrder=f.userData.transformData.eulerOrder))}),A.transform||(A.transform=new he),"PreRotation"in d&&(A.preRotation=d.PreRotation.value),"PostRotation"in d&&(A.postRotation=d.PostRotation.value),r[c]=A}}r[c]&&(r[c][h.attr]=h)}else if(h.curves.morph!==void 0){if(r[c]===void 0){const u=Oe.get(l.ID).parents.filter(function(m){return m.relationship!==void 0})[0].ID,d=Oe.get(u).parents[0].ID,A=Oe.get(d).parents[0].ID,f=Oe.get(A).parents[0].ID,g=pe.Objects.Model[f],p={modelName:g.attrName?Wi.sanitizeNodeName(g.attrName):"",morphName:pe.Objects.Deformer[u].attrName};r[c]=p}r[c][h.attr]=h}}}),s.set(parseInt(i),r))}return s}parseAnimStacks(e){const t=pe.Objects.AnimationStack,s={};for(const i in t){const r=Oe.get(parseInt(i)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const a=e.get(r[0].ID);s[i]={name:t[i].attrName,layer:a}}return s}addClip(e){let t=[];const s=this;return e.layer.forEach(function(i){t=t.concat(s.generateTracks(i))}),new Pu(e.name,-1,t)}generateTracks(e){const t=[];let s=new P,i=new Ie,r=new P;if(e.transform&&e.transform.decompose(s,i,r),s=s.toArray(),i=new Zt().setFromQuaternion(i,e.eulerOrder).toArray(),r=r.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,s,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,i,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,r,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,s,i){const r=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(r,t,s);return new Wa(e+"."+i,r,a)}generateRotationTrack(e,t,s,i,r,a){t.x!==void 0&&(this.interpolateRotations(t.x),t.x.values=t.x.values.map(le.degToRad)),t.y!==void 0&&(this.interpolateRotations(t.y),t.y.values=t.y.values.map(le.degToRad)),t.z!==void 0&&(this.interpolateRotations(t.z),t.z.values=t.z.values.map(le.degToRad));const o=this.getTimesForAllAxes(t),l=this.getKeyframeTrackValues(o,t,s);i!==void 0&&(i=i.map(le.degToRad),i.push(a),i=new Zt().fromArray(i),i=new Ie().setFromEuler(i)),r!==void 0&&(r=r.map(le.degToRad),r.push(a),r=new Zt().fromArray(r),r=new Ie().setFromEuler(r).invert());const c=new Ie,h=new Zt,u=[];for(let d=0;d<l.length;d+=3)h.set(l[d],l[d+1],l[d+2],a),c.setFromEuler(h),i!==void 0&&c.premultiply(i),r!==void 0&&c.multiply(r),c.toArray(u,d/3*4);return new eo(e+".quaternion",o,u)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,s=t.values.map(function(r){return r/100}),i=it.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new Za(e.modelName+".morphTargetInfluences["+i+"]",t.times,s)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(s,i){return s-i}),t.length>1){let s=1,i=t[0];for(let r=1;r<t.length;r++){const a=t[r];a!==i&&(t[s]=a,i=a,s++)}t=t.slice(0,s)}return t}getKeyframeTrackValues(e,t,s){const i=s,r=[];let a=-1,o=-1,l=-1;return e.forEach(function(c){if(t.x&&(a=t.x.times.indexOf(c)),t.y&&(o=t.y.times.indexOf(c)),t.z&&(l=t.z.times.indexOf(c)),a!==-1){const h=t.x.values[a];r.push(h),i[0]=h}else r.push(i[0]);if(o!==-1){const h=t.y.values[o];r.push(h),i[1]=h}else r.push(i[1]);if(l!==-1){const h=t.z.values[l];r.push(h),i[2]=h}else r.push(i[2])}),r}interpolateRotations(e){for(let t=1;t<e.values.length;t++){const s=e.values[t-1],i=e.values[t]-s,r=Math.abs(i);if(r>=180){const a=r/180,o=i/a;let l=s+o;const c=e.times[t-1],u=(e.times[t]-c)/a;let d=c+u;const A=[],f=[];for(;d<e.times[t];)A.push(d),d+=u,f.push(l),l+=o;e.times=nh(e.times,t,A),e.values=nh(e.values,t,f)}}}}class lT{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new Hd,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,s=e.split(/[\r\n]+/);return s.forEach(function(i,r){const a=i.match(/^[\s\t]*;/),o=i.match(/^[\s\t]*$/);if(a||o)return;const l=i.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=i.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=i.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(i,l):c?t.parseNodeProperty(i,c,s[++r]):h?t.popStack():i.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(i)}),this.allNodes}parseNodeBegin(e,t){const s=t[1].trim().replace(/^"/,"").replace(/"$/,""),i=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:s},a=this.parseNodeAttr(i),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(s,r):s in o?(s==="PoseNode"?o.PoseNode.push(r):o[s].id!==void 0&&(o[s]={},o[s][o[s].id]=o[s]),a.id!==""&&(o[s][a.id]=r)):typeof a.id=="number"?(o[s]={},o[s][a.id]=r):s!=="Properties70"&&(s==="PoseNode"?o[s]=[r]:o[s]=r),typeof a.id=="number"&&(r.id=a.id),a.name!==""&&(r.attrName=a.name),a.type!==""&&(r.attrType=a.type),this.pushStack(r)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let s="",i="";return e.length>1&&(s=e[1].replace(/^(\w+)::/,""),i=e[2]),{id:t,name:s,type:i}}parseNodeProperty(e,t,s){let i=t[1].replace(/^"/,"").replace(/"$/,"").trim(),r=t[2].replace(/^"/,"").replace(/"$/,"").trim();i==="Content"&&r===","&&(r=s.replace(/"/g,"").replace(/,$/,"").trim());const a=this.getCurrentNode();if(a.name==="Properties70"){this.parseNodeSpecialProperty(e,i,r);return}if(i==="C"){const l=r.split(",").slice(1),c=parseInt(l[0]),h=parseInt(l[1]);let u=r.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),i="connections",r=[c,h],fT(r,u),a[i]===void 0&&(a[i]=[])}i==="Node"&&(a.id=r),i in a&&Array.isArray(a[i])?a[i].push(r):i!=="a"?a[i]=r:a.a=r,this.setCurrentProp(a,i),i==="a"&&r.slice(-1)!==","&&(a.a=ra(r))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=ra(t.a))}parseNodeSpecialProperty(e,t,s){const i=s.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=i[0],a=i[1],o=i[2],l=i[3];let c=i[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=ra(c);break}this.getPrevNode()[r]={type:a,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),r)}}class cT{parse(e){const t=new sh(e);t.skip(23);const s=t.getUint32();if(s<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+s);const i=new Hd;for(;!this.endOfContent(t);){const r=this.parseNode(t,s);r!==null&&i.add(r.name,r)}return i}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const s={},i=t>=7500?e.getUint64():e.getUint32(),r=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const a=e.getUint8(),o=e.getString(a);if(i===0)return null;const l=[];for(let d=0;d<r;d++)l.push(this.parseProperty(e));const c=l.length>0?l[0]:"",h=l.length>1?l[1]:"",u=l.length>2?l[2]:"";for(s.singleProperty=r===1&&e.getOffset()===i;i>e.getOffset();){const d=this.parseNode(e,t);d!==null&&this.parseSubNode(o,s,d)}return s.propertyList=l,typeof c=="number"&&(s.id=c),h!==""&&(s.attrName=h),u!==""&&(s.attrType=u),o!==""&&(s.name=o),s}parseSubNode(e,t,s){if(s.singleProperty===!0){const i=s.propertyList[0];Array.isArray(i)?(t[s.name]=s,s.a=i):t[s.name]=i}else if(e==="Connections"&&s.name==="C"){const i=[];s.propertyList.forEach(function(r,a){a!==0&&i.push(r)}),t.connections===void 0&&(t.connections=[]),t.connections.push(i)}else if(s.name==="Properties70")Object.keys(s).forEach(function(r){t[r]=s[r]});else if(e==="Properties70"&&s.name==="P"){let i=s.propertyList[0],r=s.propertyList[1];const a=s.propertyList[2],o=s.propertyList[3];let l;i.indexOf("Lcl ")===0&&(i=i.replace("Lcl ","Lcl_")),r.indexOf("Lcl ")===0&&(r=r.replace("Lcl ","Lcl_")),r==="Color"||r==="ColorRGB"||r==="Vector"||r==="Vector3D"||r.indexOf("Lcl_")===0?l=[s.propertyList[4],s.propertyList[5],s.propertyList[6]]:l=s.propertyList[4],t[i]={type:r,type2:a,flag:o,value:l}}else t[s.name]===void 0?typeof s.id=="number"?(t[s.name]={},t[s.name][s.id]=s):t[s.name]=s:s.name==="PoseNode"?(Array.isArray(t[s.name])||(t[s.name]=[t[s.name]]),t[s.name].push(s)):t[s.name][s.id]===void 0&&(t[s.name][s.id]=s)}parseProperty(e){const t=e.getString(1);let s;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return s=e.getUint32(),e.getArrayBuffer(s);case"S":return s=e.getUint32(),e.getString(s);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const i=e.getUint32(),r=e.getUint32(),a=e.getUint32();if(r===0)switch(t){case"b":case"c":return e.getBooleanArray(i);case"d":return e.getFloat64Array(i);case"f":return e.getFloat32Array(i);case"i":return e.getInt32Array(i);case"l":return e.getInt64Array(i)}const o=_g(new Uint8Array(e.getArrayBuffer(a))),l=new sh(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(i);case"d":return l.getFloat64Array(i);case"f":return l.getFloat32Array(i);case"i":return l.getInt32Array(i);case"l":return l.getInt64Array(i)}default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class sh{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let s=0;s<e;s++)t.push(this.getBoolean());return t}getUint8(){const e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){const e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){const e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){const t=[];for(let s=0;s<e;s++)t.push(this.getInt32());return t}getUint32(){const e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){const t=[];for(let s=0;s<e;s++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){const e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){const t=[];for(let s=0;s<e;s++)t.push(this.getFloat32());return t}getFloat64(){const e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){const t=[];for(let s=0;s<e;s++)t.push(this.getFloat64());return t}getArrayBuffer(e){const t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){let t=[];for(let i=0;i<e;i++)t[i]=this.getUint8();const s=t.indexOf(0);return s>=0&&(t=t.slice(0,s)),di(new Uint8Array(t))}}class Hd{add(e,t){this[e]=t}}function hT(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===Yd(n,0,e.length)}function uT(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function s(i){const r=n[i-1];return n=n.slice(t+i),t++,r}for(let i=0;i<e.length;++i)if(s(1)===e[i])return!1;return!0}function ih(n){const e=/FBXVersion: (\d+)/,t=n.match(e);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function dT(n){return n/46186158e3}const AT=[];function Sn(n,e,t,s){let i;switch(s.mappingType){case"ByPolygonVertex":i=n;break;case"ByPolygon":i=e;break;case"ByVertice":i=t;break;case"AllSame":i=s.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+s.mappingType)}s.referenceType==="IndexToDirect"&&(i=s.indices[i]);const r=i*s.dataSize,a=r+s.dataSize;return gT(AT,s.buffer,r,a)}const na=new Zt,Qs=new P;function Kd(n){const e=new he,t=new he,s=new he,i=new he,r=new he,a=new he,o=new he,l=new he,c=new he,h=new he,u=new he,d=new he,A=n.inheritType?n.inheritType:0;if(n.translation&&e.setPosition(Qs.fromArray(n.translation)),n.preRotation){const v=n.preRotation.map(le.degToRad);v.push(n.eulerOrder),t.makeRotationFromEuler(na.fromArray(v))}if(n.rotation){const v=n.rotation.map(le.degToRad);v.push(n.eulerOrder),s.makeRotationFromEuler(na.fromArray(v))}if(n.postRotation){const v=n.postRotation.map(le.degToRad);v.push(n.eulerOrder),i.makeRotationFromEuler(na.fromArray(v)),i.invert()}n.scale&&r.scale(Qs.fromArray(n.scale)),n.scalingOffset&&o.setPosition(Qs.fromArray(n.scalingOffset)),n.scalingPivot&&a.setPosition(Qs.fromArray(n.scalingPivot)),n.rotationOffset&&l.setPosition(Qs.fromArray(n.rotationOffset)),n.rotationPivot&&c.setPosition(Qs.fromArray(n.rotationPivot)),n.parentMatrixWorld&&(u.copy(n.parentMatrix),h.copy(n.parentMatrixWorld));const f=t.clone().multiply(s).multiply(i),g=new he;g.extractRotation(h);const p=new he;p.copyPosition(h);const m=p.clone().invert().multiply(h),C=g.clone().invert().multiply(m),E=r,B=new he;if(A===0)B.copy(g).multiply(f).multiply(C).multiply(E);else if(A===1)B.copy(g).multiply(C).multiply(f).multiply(E);else{const D=new he().scale(new P().setFromMatrixScale(u)).clone().invert(),U=C.clone().multiply(D);B.copy(g).multiply(f).multiply(U).multiply(E)}const I=c.clone().invert(),_=a.clone().invert();let S=e.clone().multiply(l).multiply(c).multiply(t).multiply(s).multiply(i).multiply(I).multiply(o).multiply(a).multiply(r).multiply(_);const x=new he().copyPosition(S),b=h.clone().multiply(x);return d.copyPosition(b),S=d.clone().multiply(B),S.premultiply(h.invert()),S}function Vd(n){n=n||0;const e=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return n===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),e[0]):e[n]}function ra(n){return n.split(",").map(function(t){return parseFloat(t)})}function Yd(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=n.byteLength),di(new Uint8Array(n,e,t))}function fT(n,e){for(let t=0,s=n.length,i=e.length;t<i;t++,s++)n[s]=e[t]}function gT(n,e,t,s){for(let i=t,r=0;i<s;i++,r++)n[r]=e[i];return n}function nh(n,e,t){return n.slice(0,e).concat(t).concat(n.slice(e))}class mT extends ci{constructor(e=null,t=1,s=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=ja,this.minFilter=ja,this.wrapR=Zi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class pT{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:i,msg:r,transfer:a}=this.queue.shift();this.workersResolve[e]=i,this.workers[e].postMessage(r,a)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(s=>{const i=this._getIdleWorker();i!==-1?(this._initWorker(i),this.workerStatus|=1<<i,this.workersResolve[i]=s,this.workers[i].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const Jd=0,rh=2,ET=0,CT=0,IT=2,yT=0,BT=0,TT=1,mo=2,ST=0,zd=1,_T=10,xT=64,qd=0,$d=9,Xd=15,jd=16,Wd=22,Zd=37,eA=43,tA=76,sA=83,iA=97,nA=100,rA=103,aA=109,oA=165,lA=166;class vT{constructor(){this.vkFormat=qd,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=Jd,this.levels=[],this.dataFormatDescriptor=[{vendorId:CT,descriptorType:ET,descriptorBlockSize:0,versionNumber:IT,colorModel:yT,colorPrimaries:zd,transferFunction:mo,flags:BT,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class Mi{constructor(e,t,s,i){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,s),this._littleEndian=i,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian),t=this._dataView.getUint32(this._offset+4,this._littleEndian),s=e+2**32*t;return this._offset+=8,s}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t){t===void 0&&(t=0);const s=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==t&&i<e;)i++,this._offset++;return i<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+s,i)}}const We=[171,75,84,88,32,50,48,187,13,10,26,10];function ah(n){return typeof TextDecoder<"u"?new TextDecoder().decode(n):Buffer.from(n).toString("utf8")}function RT(n){const e=new Uint8Array(n.buffer,n.byteOffset,We.length);if(e[0]!==We[0]||e[1]!==We[1]||e[2]!==We[2]||e[3]!==We[3]||e[4]!==We[4]||e[5]!==We[5]||e[6]!==We[6]||e[7]!==We[7]||e[8]!==We[8]||e[9]!==We[9]||e[10]!==We[10]||e[11]!==We[11])throw new Error("Missing KTX 2.0 identifier.");const t=new vT,s=17*Uint32Array.BYTES_PER_ELEMENT,i=new Mi(n,We.length,s,!0);t.vkFormat=i._nextUint32(),t.typeSize=i._nextUint32(),t.pixelWidth=i._nextUint32(),t.pixelHeight=i._nextUint32(),t.pixelDepth=i._nextUint32(),t.layerCount=i._nextUint32(),t.faceCount=i._nextUint32();const r=i._nextUint32();t.supercompressionScheme=i._nextUint32();const a=i._nextUint32(),o=i._nextUint32(),l=i._nextUint32(),c=i._nextUint32(),h=i._nextUint64(),u=i._nextUint64(),d=r*3*8,A=new Mi(n,We.length+s,d,!0);for(let G=0;G<r;G++)t.levels.push({levelData:new Uint8Array(n.buffer,n.byteOffset+A._nextUint64(),A._nextUint64()),uncompressedByteLength:A._nextUint64()});const f=new Mi(n,a,o,!0),g={vendorId:f._skip(4)._nextUint16(),descriptorType:f._nextUint16(),versionNumber:f._nextUint16(),descriptorBlockSize:f._nextUint16(),colorModel:f._nextUint8(),colorPrimaries:f._nextUint8(),transferFunction:f._nextUint8(),flags:f._nextUint8(),texelBlockDimension:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],bytesPlane:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],samples:[]},C=(g.descriptorBlockSize/4-6)/4;for(let G=0;G<C;G++){const H={bitOffset:f._nextUint16(),bitLength:f._nextUint8(),channelType:f._nextUint8(),samplePosition:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};H.channelType&xT?(H.sampleLower=f._nextInt32(),H.sampleUpper=f._nextInt32()):(H.sampleLower=f._nextUint32(),H.sampleUpper=f._nextUint32()),g.samples[G]=H}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(g);const E=new Mi(n,l,c,!0);for(;E._offset<c;){const G=E._nextUint32(),H=E._scan(G),J=ah(H);if(t.keyValue[J]=E._nextUint8Array(G-H.byteLength-1),J.match(/^ktx/i)){const R=ah(t.keyValue[J]);t.keyValue[J]=R.substring(0,R.lastIndexOf("\0"))}const K=G%4?4-G%4:0;E._skip(K)}if(u<=0)return t;const B=new Mi(n,h,u,!0),I=B._nextUint16(),_=B._nextUint16(),S=B._nextUint32(),x=B._nextUint32(),b=B._nextUint32(),v=B._nextUint32(),D=[];for(let G=0;G<r;G++)D.push({imageFlags:B._nextUint32(),rgbSliceByteOffset:B._nextUint32(),rgbSliceByteLength:B._nextUint32(),alphaSliceByteOffset:B._nextUint32(),alphaSliceByteLength:B._nextUint32()});const U=h+B._offset,Q=U+S,j=Q+x,V=j+b,X=new Uint8Array(n.buffer,n.byteOffset+U,S),Z=new Uint8Array(n.buffer,n.byteOffset+Q,x),ae=new Uint8Array(n.buffer,n.byteOffset+j,b),Y=new Uint8Array(n.buffer,n.byteOffset+V,v);return t.globalData={endpointCount:I,selectorCount:_,imageDescs:D,endpointsData:X,selectorsData:Z,tablesData:ae,extendedData:Y},t}let Fi,zt,po;const aa={env:{emscripten_notify_memory_growth:function(n){po=new Uint8Array(zt.exports.memory.buffer)}}};class wT{init(){return Fi||(typeof fetch<"u"?Fi=fetch("data:application/wasm;base64,"+oh).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,aa)).then(this._init):Fi=WebAssembly.instantiate(Buffer.from(oh,"base64"),aa).then(this._init),Fi)}_init(e){zt=e.instance,aa.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!zt)throw new Error("ZSTDDecoder: Await .init() before decoding.");const s=e.byteLength,i=zt.exports.malloc(s);po.set(e,i),t=t||Number(zt.exports.ZSTD_findDecompressedSize(i,s));const r=zt.exports.malloc(t),a=zt.exports.ZSTD_decompress(r,t,i,s),o=po.slice(r,r+a);return zt.exports.free(i),zt.exports.free(r),o}}const oh="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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQh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ASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigC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C0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdB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IAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY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wOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEE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";class DT extends _r{constructor(e,t,s){super(void 0,e[0].width,e[0].height,t,s,vg),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class LT extends _r{constructor(e,t,s,i,r,a){super(e,t,s,r,a),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=Zi}}var bT=Object.defineProperty,MT=(n,e,t)=>e in n?bT(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,_n=(n,e,t)=>(MT(n,typeof e!="symbol"?e+"":e,t),t);const cA=3e3,hA=3001,lh="",FT="display-p3",PT="display-p3-linear",kT="srgb-linear",dl="srgb",oa=new WeakMap;let la=0,ca;const Al=(()=>{const n=class extends Sr{constructor(t){super(t),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new pT,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(t){return this.transcoderPath=t,this}setWorkerLimit(t){return this.workerPool.setWorkerLimit(t),this}detectSupport(t){return this.workerConfig={astcSupported:t.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:t.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:t.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:t.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:t.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:t.extensions.has("WEBGL_compressed_texture_pvrtc")||t.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},t.capabilities.isWebGL2&&(this.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){const t=new ds(this.manager);t.setPath(this.transcoderPath),t.setWithCredentials(this.withCredentials);const s=t.loadAsync("basis_transcoder.js"),i=new ds(this.manager);i.setPath(this.transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const r=i.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([s,r]).then(([a,o])=>{const l=n.BasisWorker.toString(),c=["/* constants */","let _EngineFormat = "+JSON.stringify(n.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(n.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(n.BasisFormat),"/* basis_transcoder.js */",a,"/* worker */",l.substring(l.indexOf("{")+1,l.lastIndexOf("}"))].join(`
|
|
4
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([c])),this.transcoderBinary=o,this.workerPool.setWorkerCreator(()=>{const h=new Worker(this.workerSourceURL),u=this.transcoderBinary.slice(0);return h.postMessage({type:"init",config:this.workerConfig,transcoderBinary:u},[u]),h})}),la>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),la++}return this.transcoderPending}load(t,s,i,r){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const a=new ds(this.manager);a.setResponseType("arraybuffer"),a.setWithCredentials(this.withCredentials),a.load(t,o=>{if(oa.has(o))return oa.get(o).promise.then(s).catch(r);this._createTexture(o).then(l=>s?s(l):null).catch(r)},i,r)}_createTextureFrom(t,s){const{faces:i,width:r,height:a,format:o,type:l,error:c,dfdFlags:h}=t;if(l==="error")return Promise.reject(c);let u;if(s.faceCount===6)u=new DT(i,o,St);else{const A=i[0].mipmaps;u=s.layerCount>1?new LT(A,r,a,s.layerCount,o,St):new _r(A,r,a,o,St)}u.minFilter=i[0].mipmaps.length===1?oi:Go,u.magFilter=oi,u.generateMipmaps=!1,u.needsUpdate=!0;const d=uA(s);return"colorSpace"in u?u.colorSpace=d:u.encoding=d===dl?hA:cA,u.premultiplyAlpha=!!(h&TT),u}async _createTexture(t,s={}){const i=RT(new Uint8Array(t));if(i.vkFormat!==qd)return QT(i);const r=s,a=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:t,taskConfig:r},[t])).then(o=>this._createTextureFrom(o.data,i));return oa.set(t,{promise:a}),a}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),la--,this}};let e=n;return _n(e,"BasisFormat",{ETC1S:0,UASTC_4x4:1}),_n(e,"TranscoderFormat",{ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16}),_n(e,"EngineFormat",{RGBAFormat:Xs,RGBA_ASTC_4x4_Format:Rg,RGBA_BPTC_Format:wg,RGBA_ETC2_EAC_Format:Dg,RGBA_PVRTC_4BPPV1_Format:Lg,RGBA_S3TC_DXT5_Format:bg,RGB_ETC1_Format:Mg,RGB_ETC2_Format:Fg,RGB_PVRTC_4BPPV1_Format:Pg,RGB_S3TC_DXT1_Format:kg}),_n(e,"BasisWorker",function(){let t,s,i;const r=_EngineFormat,a=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",function(p){const m=p.data;switch(m.type){case"init":t=m.config,l(m.transcoderBinary);break;case"transcode":s.then(()=>{try{const{faces:C,buffers:E,width:B,height:I,hasAlpha:_,format:S,dfdFlags:x}=c(m.buffer);self.postMessage({type:"transcode",id:m.id,faces:C,width:B,height:I,hasAlpha:_,format:S,dfdFlags:x},E)}catch(C){console.error(C),self.postMessage({type:"error",id:m.id,error:C.message})}});break}});function l(p){s=new Promise(m=>{i={wasmBinary:p,onRuntimeInitialized:m},BASIS(i)}).then(()=>{i.initializeBasis(),i.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function c(p){const m=new i.KTX2File(new Uint8Array(p));function C(){m.close(),m.delete()}if(!m.isValid())throw C(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");const E=m.isUASTC()?o.UASTC_4x4:o.ETC1S,B=m.getWidth(),I=m.getHeight(),_=m.getLayers()||1,S=m.getLevels(),x=m.getFaces(),b=m.getHasAlpha(),v=m.getDFDFlags(),{transcoderFormat:D,engineFormat:U}=A(E,B,I,b);if(!B||!I||!S)throw C(),new Error("THREE.KTX2Loader: Invalid texture");if(!m.startTranscoding())throw C(),new Error("THREE.KTX2Loader: .startTranscoding failed");const Q=[],j=[];for(let V=0;V<x;V++){const X=[];for(let Z=0;Z<S;Z++){const ae=[];let Y,G;for(let J=0;J<_;J++){const K=m.getImageLevelInfo(Z,J,V);V===0&&Z===0&&J===0&&(K.origWidth%4!==0||K.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),S>1?(Y=K.origWidth,G=K.origHeight):(Y=K.width,G=K.height);const R=new Uint8Array(m.getImageTranscodedSizeInBytes(Z,J,0,D));if(!m.transcodeImage(R,Z,J,V,D,0,-1,-1))throw C(),new Error("THREE.KTX2Loader: .transcodeImage failed.");ae.push(R)}const H=g(ae);X.push({data:H,width:Y,height:G}),j.push(H.buffer)}Q.push({mipmaps:X,width:B,height:I,format:U})}return C(),{faces:Q,buffers:j,width:B,height:I,hasAlpha:b,format:U,dfdFlags:v}}const h=[{if:"astcSupported",basisFormat:[o.UASTC_4x4],transcoderFormat:[a.ASTC_4x4,a.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.BC7_M5,a.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.BC1,a.BC3],engineFormat:[r.RGB_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.ETC1,a.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.ETC1],engineFormat:[r.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.PVRTC1_4_RGB,a.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],u=h.sort(function(p,m){return p.priorityETC1S-m.priorityETC1S}),d=h.sort(function(p,m){return p.priorityUASTC-m.priorityUASTC});function A(p,m,C,E){let B,I;const _=p===o.ETC1S?u:d;for(let S=0;S<_.length;S++){const x=_[S];if(t[x.if]&&x.basisFormat.includes(p)&&!(E&&x.transcoderFormat.length<2)&&!(x.needsPowerOfTwo&&!(f(m)&&f(C))))return B=x.transcoderFormat[E?1:0],I=x.engineFormat[E?1:0],{transcoderFormat:B,engineFormat:I}}return console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."),B=a.RGBA32,I=r.RGBAFormat,{transcoderFormat:B,engineFormat:I}}function f(p){return p<=2?!0:(p&p-1)===0&&p!==0}function g(p){if(p.length===1)return p[0];let m=0;for(let B=0;B<p.length;B++){const I=p[B];m+=I.byteLength}const C=new Uint8Array(m);let E=0;for(let B=0;B<p.length;B++){const I=p[B];C.set(I,E),E+=I.byteLength}return C}}),e})(),OT=new Set([Xs,Ni,Hi]),ha={[aA]:Xs,[iA]:Xs,[Zd]:Xs,[eA]:Xs,[rA]:Ni,[sA]:Ni,[jd]:Ni,[Wd]:Ni,[nA]:Hi,[tA]:Hi,[Xd]:Hi,[$d]:Hi,[lA]:Fl,[oA]:Fl},ua={[aA]:Yn,[iA]:Yi,[Zd]:St,[eA]:St,[rA]:Yn,[sA]:Yi,[jd]:St,[Wd]:St,[nA]:Yn,[tA]:Yi,[Xd]:St,[$d]:St,[lA]:St,[oA]:St};async function QT(n){const{vkFormat:e}=n;if(ha[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let t;n.supercompressionScheme===rh&&(ca||(ca=new Promise(async a=>{const o=new wT;await o.init(),a(o)})),t=await ca);const s=[];for(let a=0;a<n.levels.length;a++){const o=Math.max(1,n.pixelWidth>>a),l=Math.max(1,n.pixelHeight>>a),c=n.pixelDepth?Math.max(1,n.pixelDepth>>a):0,h=n.levels[a];let u;if(n.supercompressionScheme===Jd)u=h.levelData;else if(n.supercompressionScheme===rh)u=t.decode(h.levelData,h.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let d;ua[e]===Yn?d=new Float32Array(u.buffer,u.byteOffset,u.byteLength/Float32Array.BYTES_PER_ELEMENT):ua[e]===Yi?d=new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT):d=u,s.push({data:d,width:o,height:l,depth:c})}let i;if(OT.has(ha[e]))i=n.pixelDepth===0?new Og(s[0].data,n.pixelWidth,n.pixelHeight):new mT(s[0].data,n.pixelWidth,n.pixelHeight,n.pixelDepth);else{if(n.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");i=new _r(s,n.pixelWidth,n.pixelHeight)}i.mipmaps=s,i.type=ua[e],i.format=ha[e],i.needsUpdate=!0;const r=uA(n);return"colorSpace"in i?i.colorSpace=r:i.encoding=r===dl?hA:cA,Promise.resolve(i)}function uA(n){const e=n.dataFormatDescriptor[0];return e.colorPrimaries===zd?e.transferFunction===mo?dl:kT:e.colorPrimaries===_T?e.transferFunction===mo?FT:PT:(e.colorPrimaries===ST||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),lh)}const da=new WeakMap;class GT extends Sr{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,s,i){const r=new ds(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,a=>{const o={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(a,o).then(t).catch(i)},s,i)}decodeDracoFile(e,t,s,i){const r={attributeIDs:s||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!s};this.decodeGeometry(e,r).then(t)}decodeGeometry(e,t){for(const l in t.attributeTypes){const c=t.attributeTypes[l];c.BYTES_PER_ELEMENT!==void 0&&(t.attributeTypes[l]=c.name)}const s=JSON.stringify(t);if(da.has(e)){const l=da.get(e);if(l.key===s)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const r=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(r,a).then(l=>(i=l,new Promise((c,h)=>{i._callbacks[r]={resolve:c,reject:h},i.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{i&&r&&this._releaseTask(i,r)}),da.set(e,{key:s,promise:o}),o}_createGeometry(e){const t=new mt;e.index&&t.setIndex(new ti(e.index.array,1));for(let s=0;s<e.attributes.length;s++){const i=e.attributes[s],r=i.name,a=i.array,o=i.itemSize;t.setAttribute(r,new ti(a,o))}return t}_loadLibrary(e,t){const s=new ds(this.manager);return s.setPath(this.decoderPath),s.setResponseType(t),s.setWithCredentials(this.withCredentials),new Promise((i,r)=>{s.load(e,i,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(s=>{const i=s[0];e||(this.decoderConfig.wasmBinary=s[1]);const r=UT.toString(),a=["/* draco decoder */",i,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
|
|
5
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",decoderConfig:this.decoderConfig}),i.onmessage=function(r){const a=r.data;switch(a.type){case"decode":i._callbacks[a.id].resolve(a);break;case"error":i._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,r){return i._taskLoad>r._taskLoad?-1:1});const s=this.workerPool[this.workerPool.length-1];return s._taskCosts[e]=t,s._taskLoad+=t,s})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this}}function UT(){let n,e;onmessage=function(a){const o=a.data;switch(o.type){case"init":n=o.decoderConfig,e=new Promise(function(h){n.onModuleLoaded=function(u){h({draco:u})},DracoDecoderModule(n)});break;case"decode":const l=o.buffer,c=o.taskConfig;e.then(h=>{const u=h.draco,d=new u.Decoder,A=new u.DecoderBuffer;A.Init(new Int8Array(l),l.byteLength);try{const f=t(u,d,A,c),g=f.attributes.map(p=>p.array.buffer);f.index&&g.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},g)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{u.destroy(A),u.destroy(d)}});break}};function t(a,o,l,c){const h=c.attributeIDs,u=c.attributeTypes;let d,A;const f=o.GetEncodedGeometryType(l);if(f===a.TRIANGULAR_MESH)d=new a.Mesh,A=o.DecodeBufferToMesh(l,d);else if(f===a.POINT_CLOUD)d=new a.PointCloud,A=o.DecodeBufferToPointCloud(l,d);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!A.ok()||d.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+A.error_msg());const g={index:null,attributes:[]};for(const p in h){const m=self[u[p]];let C,E;if(c.useUniqueIDs)E=h[p],C=o.GetAttributeByUniqueId(d,E);else{if(E=o.GetAttributeId(d,a[h[p]]),E===-1)continue;C=o.GetAttribute(d,E)}g.attributes.push(i(a,o,d,p,m,C))}return f===a.TRIANGULAR_MESH&&(g.index=s(a,o,d)),a.destroy(d),g}function s(a,o,l){const h=l.num_faces()*3,u=h*4,d=a._malloc(u);o.GetTrianglesUInt32Array(l,u,d);const A=new Uint32Array(a.HEAPF32.buffer,d,h).slice();return a._free(d),{array:A,itemSize:1}}function i(a,o,l,c,h,u){const d=u.num_components(),f=l.num_points()*d,g=f*h.BYTES_PER_ELEMENT,p=r(a,h),m=a._malloc(g);o.GetAttributeDataArrayForAllPoints(l,u,p,g,m);const C=new h(a.HEAPF32.buffer,m,f).slice();return a._free(m),{name:c,array:C,itemSize:d}}function r(a,o){switch(o){case Float32Array:return a.DT_FLOAT32;case Int8Array:return a.DT_INT8;case Int16Array:return a.DT_INT16;case Int32Array:return a.DT_INT32;case Uint8Array:return a.DT_UINT8;case Uint16Array:return a.DT_UINT16;case Uint32Array:return a.DT_UINT32}}}let xn;const Aa=()=>{if(xn)return xn;const n="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",e="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",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),s=new Uint8Array([32,0,65,253,3,1,2,34,4,106,6,5,11,8,7,20,13,33,12,16,128,9,116,64,19,113,127,15,10,21,22,14,255,66,24,54,136,107,18,23,192,26,114,118,132,17,77,101,130,144,27,87,131,44,45,74,156,154,70,167]);if(typeof WebAssembly!="object")return{supported:!1};let i=n;WebAssembly.validate(t)&&(i=e);let r;const a=WebAssembly.instantiate(o(i),{}).then(u=>{r=u.instance,r.exports.__wasm_call_ctors()});function o(u){const d=new Uint8Array(u.length);for(let f=0;f<u.length;++f){const g=u.charCodeAt(f);d[f]=g>96?g-71:g>64?g-65:g>47?g+4:g>46?63:62}let A=0;for(let f=0;f<u.length;++f)d[A++]=d[f]<60?s[d[f]]:(d[f]-60)*64+d[++f];return d.buffer.slice(0,A)}function l(u,d,A,f,g,p){const m=r.exports.sbrk,C=A+3&-4,E=m(C*f),B=m(g.length),I=new Uint8Array(r.exports.memory.buffer);I.set(g,B);const _=u(E,A,f,B,g.length);if(_===0&&p&&p(E,C,f),d.set(I.subarray(E,E+A*f)),m(E-m(0)),_!==0)throw new Error(`Malformed buffer data: ${_}`)}const c={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},h={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return xn={ready:a,supported:!0,decodeVertexBuffer(u,d,A,f,g){l(r.exports.meshopt_decodeVertexBuffer,u,d,A,f,r.exports[c[g]])},decodeIndexBuffer(u,d,A,f){l(r.exports.meshopt_decodeIndexBuffer,u,d,A,f)},decodeIndexSequence(u,d,A,f){l(r.exports.meshopt_decodeIndexSequence,u,d,A,f)},decodeGltfBuffer(u,d,A,f,g,p){l(r.exports[h[g]],u,d,A,f,r.exports[c[p]])}},xn},NT=new P,HT=T.forwardRef(({scale:n=1,...e},t)=>{const s=T.useRef(null);return T.useImperativeHandle(t,()=>s.current,[]),Ue(i=>{const r=s.current;if(!r)return;const a=Ou(r.getWorldPosition(NT),n,i.camera,i.size);r.scale.setScalar(a*n)}),T.createElement("object3D",be({ref:s},e))});let vn=null,dA="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function AA(n=!0,e=!0,t){return s=>{t&&t(s),n&&(vn||(vn=new GT),vn.setDecoderPath(typeof n=="string"?n:dA),s.setDRACOLoader(vn)),e&&s.setMeshoptDecoder(typeof Aa=="function"?Aa():Aa)}}const fn=(n,e,t,s)=>wt(hl,n,AA(e,t,s));fn.preload=(n,e,t,s)=>wt.preload(hl,n,AA(e,t,s));fn.clear=n=>wt.clear(hl,n);fn.setDecoderPath=n=>{dA=n};const KT=T.forwardRef(({src:n,useDraco:e,useMeshOpt:t,extendLoader:s,...i},r)=>{const{scene:a}=fn(n,e,t,s);return T.createElement(Uo,be({ref:r},i,{object:a}))}),VT=T.forwardRef((n,e)=>{const{camera:t,onChange:s,makeDefault:i,...r}=n,a=$(d=>d.camera),o=$(d=>d.invalidate),l=$(d=>d.get),c=$(d=>d.set),h=t||a,u=T.useMemo(()=>new oB(h),[h]);return T.useEffect(()=>{const d=A=>{o(),s&&s(A)};return u==null||u.addEventListener==null||u.addEventListener("change",d),()=>u==null||u.removeEventListener==null?void 0:u.removeEventListener("change",d)},[s,u,o]),Ue(()=>u==null?void 0:u.update(),-1),T.useEffect(()=>{const d=u;return d==null||d.connect(),()=>d==null?void 0:d.dispose()},[u]),T.useEffect(()=>{if(i){const d=l().controls;return c({controls:u}),()=>c({controls:d})}},[i,u]),u?T.createElement("primitive",be({ref:e,object:u},r)):null}),YT=T.forwardRef(({domElement:n,...e},t)=>{const{onChange:s,makeDefault:i,...r}=e,a=$(f=>f.invalidate),o=$(f=>f.camera),l=$(f=>f.gl),c=$(f=>f.events),h=$(f=>f.get),u=$(f=>f.set),d=n||c.connected||l.domElement,A=T.useMemo(()=>new mB(o),[o]);return T.useEffect(()=>(A.connect(d),()=>void A.dispose()),[d,A,a]),T.useEffect(()=>{const f=g=>{a(),s&&s(g)};return A.addEventListener==null||A.addEventListener("change",f),()=>A.removeEventListener==null?void 0:A.removeEventListener("change",f)},[s,a]),T.useEffect(()=>{if(i){const f=h().controls;return u({controls:A}),()=>u({controls:f})}},[i,A]),Ue((f,g)=>A.update(g)),T.createElement("primitive",be({ref:t,object:A,args:[o,d]},r))}),JT=T.forwardRef((n={enableDamping:!0},e)=>{const{domElement:t,camera:s,makeDefault:i,onChange:r,onStart:a,onEnd:o,...l}=n,c=$(C=>C.invalidate),h=$(C=>C.camera),u=$(C=>C.gl),d=$(C=>C.events),A=$(C=>C.set),f=$(C=>C.get),g=t||d.connected||u.domElement,p=s||h,m=T.useMemo(()=>new Qg(p),[p]);return T.useEffect(()=>{m.connect(g);const C=E=>{c(),r&&r(E)};return m.addEventListener("change",C),a&&m.addEventListener("start",a),o&&m.addEventListener("end",o),()=>{m.dispose(),m.removeEventListener("change",C),a&&m.removeEventListener("start",a),o&&m.removeEventListener("end",o)}},[r,a,o,m,c,g]),T.useEffect(()=>{if(i){const C=f().controls;return A({controls:m}),()=>A({controls:C})}},[i,m]),Ue(()=>m.update(),-1),T.createElement("primitive",be({ref:e,object:m,enableDamping:!0},l))}),zT=T.forwardRef(({makeDefault:n,camera:e,domElement:t,regress:s,onChange:i,onStart:r,onEnd:a,...o},l)=>{const{invalidate:c,camera:h,gl:u,events:d,set:A,get:f,performance:g,viewport:p}=$(),m=e||h,C=t||d.connected||u.domElement,E=T.useMemo(()=>new hB(m),[m]);return Ue(()=>{E.enabled&&E.update()},-1),T.useEffect(()=>(E.connect(C),()=>void E.dispose()),[C,s,E,c]),T.useEffect(()=>{const B=I=>{c(),s&&g.regress(),i&&i(I)};return E.addEventListener("change",B),r&&E.addEventListener("start",r),a&&E.addEventListener("end",a),()=>{r&&E.removeEventListener("start",r),a&&E.removeEventListener("end",a),E.removeEventListener("change",B)}},[i,r,a,E,c]),T.useEffect(()=>{E.handleResize()},[p]),T.useEffect(()=>{if(n){const B=f().controls;return A({controls:E}),()=>A({controls:B})}},[n,E]),T.createElement("primitive",be({ref:l,object:E},o))}),qT=T.forwardRef(({camera:n,makeDefault:e,regress:t,domElement:s,onChange:i,onStart:r,onEnd:a,...o},l)=>{const c=$(E=>E.invalidate),h=$(E=>E.camera),u=$(E=>E.gl),d=$(E=>E.events),A=$(E=>E.set),f=$(E=>E.get),g=$(E=>E.performance),p=n||h,m=s||d.connected||u.domElement,C=T.useMemo(()=>new AB(p),[p]);return Ue(()=>{C.enabled&&C.update()},-1),T.useEffect(()=>(C.connect(m),()=>void C.dispose()),[m,t,C,c]),T.useEffect(()=>{const E=B=>{c(),t&&g.regress(),i&&i(B)};return C.addEventListener("change",E),r&&C.addEventListener("start",r),a&&C.addEventListener("end",a),()=>{C.removeEventListener("change",E),r&&C.removeEventListener("start",r),a&&C.removeEventListener("end",a)}},[i,r,a]),T.useEffect(()=>{if(e){const E=f().controls;return A({controls:C}),()=>A({controls:E})}},[e,C]),T.createElement("primitive",be({ref:l,object:C},o))}),$T=T.forwardRef(({children:n,domElement:e,onChange:t,onMouseDown:s,onMouseUp:i,onObjectChange:r,object:a,makeDefault:o,camera:l,enabled:c,axis:h,mode:u,translationSnap:d,rotationSnap:A,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E,...B},I)=>{const _=$(H=>H.controls),S=$(H=>H.gl),x=$(H=>H.events),b=$(H=>H.camera),v=$(H=>H.invalidate),D=$(H=>H.get),U=$(H=>H.set),Q=l||b,j=e||x.connected||S.domElement,V=T.useMemo(()=>new Xy(Q,j),[Q,j]),X=T.useRef(null);T.useLayoutEffect(()=>(a?V.attach(a instanceof Xe?a:a.current):X.current instanceof Xe&&V.attach(X.current),()=>void V.detach()),[a,n,V]),T.useEffect(()=>{if(_){const H=J=>_.enabled=!J.value;return V.addEventListener("dragging-changed",H),()=>V.removeEventListener("dragging-changed",H)}},[V,_]);const Z=T.useRef(),ae=T.useRef(),Y=T.useRef(),G=T.useRef();return T.useLayoutEffect(()=>void(Z.current=t),[t]),T.useLayoutEffect(()=>void(ae.current=s),[s]),T.useLayoutEffect(()=>void(Y.current=i),[i]),T.useLayoutEffect(()=>void(G.current=r),[r]),T.useEffect(()=>{const H=te=>{v(),Z.current==null||Z.current(te)},J=te=>ae.current==null?void 0:ae.current(te),K=te=>Y.current==null?void 0:Y.current(te),R=te=>G.current==null?void 0:G.current(te);return V.addEventListener("change",H),V.addEventListener("mouseDown",J),V.addEventListener("mouseUp",K),V.addEventListener("objectChange",R),()=>{V.removeEventListener("change",H),V.removeEventListener("mouseDown",J),V.removeEventListener("mouseUp",K),V.removeEventListener("objectChange",R)}},[v,V]),T.useEffect(()=>{if(o){const H=D().controls;return U({controls:V}),()=>U({controls:H})}},[o,V]),T.createElement(T.Fragment,null,T.createElement("primitive",{ref:I,object:V,enabled:c,axis:h,mode:u,translationSnap:d,rotationSnap:A,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E}),T.createElement("group",be({ref:X},B),n))}),XT=T.forwardRef(({domElement:n,selector:e,onChange:t,onLock:s,onUnlock:i,enabled:r=!0,makeDefault:a,...o},l)=>{const{camera:c,...h}=o,u=$(I=>I.setEvents),d=$(I=>I.gl),A=$(I=>I.camera),f=$(I=>I.invalidate),g=$(I=>I.events),p=$(I=>I.get),m=$(I=>I.set),C=c||A,E=n||g.connected||d.domElement,B=T.useMemo(()=>new nB(C),[C]);return T.useEffect(()=>{if(r){B.connect(E);const I=p().events.compute;return u({compute(_,S){const x=S.size.width/2,b=S.size.height/2;S.pointer.set(x/S.size.width*2-1,-(b/S.size.height)*2+1),S.raycaster.setFromCamera(S.pointer,S.camera)}}),()=>{B.disconnect(),u({compute:I})}}},[r,B]),T.useEffect(()=>{const I=x=>{f(),t&&t(x)};B.addEventListener("change",I),s&&B.addEventListener("lock",s),i&&B.addEventListener("unlock",i);const _=()=>B.lock(),S=e?Array.from(document.querySelectorAll(e)):[document];return S.forEach(x=>x&&x.addEventListener("click",_)),()=>{B.removeEventListener("change",I),s&&B.removeEventListener("lock",s),i&&B.removeEventListener("unlock",i),S.forEach(x=>x?x.removeEventListener("click",_):void 0)}},[t,s,i,e,B,f]),T.useEffect(()=>{if(a){const I=p().controls;return m({controls:B}),()=>m({controls:I})}},[a,B]),T.createElement("primitive",be({ref:l,object:B},h))}),jT=T.forwardRef(({domElement:n,makeDefault:e,...t},s)=>{const i=$(u=>u.camera),r=$(u=>u.gl),a=$(u=>u.events),o=$(u=>u.get),l=$(u=>u.set),c=n||a.connected||r.domElement,[h]=T.useState(()=>new zy(i,c));return T.useEffect(()=>{if(e){const u=o().controls;return l({controls:h}),()=>l({controls:u})}},[e,h]),Ue((u,d)=>{h.update(d)},-1),h?T.createElement("primitive",be({ref:s,object:h},t)):null});/*!
|
|
6
|
+
* camera-controls
|
|
7
|
+
* https://github.com/yomotsu/camera-controls
|
|
8
|
+
* (c) 2017 @yomotsu
|
|
9
|
+
* Released under the MIT License.
|
|
10
|
+
*/const Pe={LEFT:1,RIGHT:2,MIDDLE:4},O=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,OFFSET:4,DOLLY:8,ZOOM:16,TOUCH_ROTATE:32,TOUCH_TRUCK:64,TOUCH_OFFSET:128,TOUCH_DOLLY:256,TOUCH_ZOOM:512,TOUCH_DOLLY_TRUCK:1024,TOUCH_DOLLY_OFFSET:2048,TOUCH_DOLLY_ROTATE:4096,TOUCH_ZOOM_TRUCK:8192,TOUCH_ZOOM_OFFSET:16384,TOUCH_ZOOM_ROTATE:32768}),Gs={NONE:0,IN:1,OUT:-1};function ys(n){return n.isPerspectiveCamera}function as(n){return n.isOrthographicCamera}const Us=Math.PI*2,ch=Math.PI/2,fA=1e-5,Pi=Math.PI/180;function Bt(n,e,t){return Math.max(e,Math.min(t,n))}function De(n,e=fA){return Math.abs(n)<e}function Se(n,e,t=fA){return De(n-e,t)}function hh(n,e){return Math.round(n/e)*e}function ki(n){return isFinite(n)?n:n<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Oi(n){return Math.abs(n)<Number.MAX_VALUE?n:n*(1/0)}function Rn(n,e,t,s,i=1/0,r){s=Math.max(1e-4,s);const a=2/s,o=a*r,l=1/(1+o+.48*o*o+.235*o*o*o);let c=n-e;const h=e,u=i*s;c=Bt(c,-u,u),e=n-c;const d=(t.value+a*c)*r;t.value=(t.value-a*d)*l;let A=e+(c+d)*l;return h-n>0==A>h&&(A=h,t.value=(A-h)/r),A}function uh(n,e,t,s,i=1/0,r,a){s=Math.max(1e-4,s);const o=2/s,l=o*r,c=1/(1+l+.48*l*l+.235*l*l*l);let h=e.x,u=e.y,d=e.z,A=n.x-h,f=n.y-u,g=n.z-d;const p=h,m=u,C=d,E=i*s,B=E*E,I=A*A+f*f+g*g;if(I>B){const V=Math.sqrt(I);A=A/V*E,f=f/V*E,g=g/V*E}h=n.x-A,u=n.y-f,d=n.z-g;const _=(t.x+o*A)*r,S=(t.y+o*f)*r,x=(t.z+o*g)*r;t.x=(t.x-o*_)*c,t.y=(t.y-o*S)*c,t.z=(t.z-o*x)*c,a.x=h+(A+_)*c,a.y=u+(f+S)*c,a.z=d+(g+x)*c;const b=p-n.x,v=m-n.y,D=C-n.z,U=a.x-p,Q=a.y-m,j=a.z-C;return b*U+v*Q+D*j>0&&(a.x=p,a.y=m,a.z=C,t.x=(a.x-p)/r,t.y=(a.y-m)/r,t.z=(a.z-C)/r),a}function fa(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function ga(n,e){return as(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class WT{constructor(){this._listeners={}}addEventListener(e,t){const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners[e];if(i!==void 0){const r=i.indexOf(t);r!==-1&&i.splice(r,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const s=this._listeners[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let r=0,a=i.length;r<a;r++)i[r].call(this,e)}}}var ma;const ZT="2.9.0",wn=1/8,eS=/Mac/.test((ma=globalThis==null?void 0:globalThis.navigator)===null||ma===void 0?void 0:ma.platform);let ce,dh,Dn,pa,et,me,Be,Ns,Qi,Dt,Lt,Bs,Ah,fh,lt,Gi,Hs,gh,Ea,mh,Ca,Ia,Ln,ya=class Eo extends WT{static install(e){ce=e.THREE,dh=Object.freeze(new ce.Vector3(0,0,0)),Dn=Object.freeze(new ce.Vector3(0,1,0)),pa=Object.freeze(new ce.Vector3(0,0,1)),et=new ce.Vector2,me=new ce.Vector3,Be=new ce.Vector3,Ns=new ce.Vector3,Qi=new ce.Vector3,Dt=new ce.Vector3,Lt=new ce.Vector3,Bs=new ce.Vector3,Ah=new ce.Vector3,fh=new ce.Vector3,lt=new ce.Spherical,Gi=new ce.Spherical,Hs=new ce.Box3,gh=new ce.Box3,Ea=new ce.Sphere,mh=new ce.Quaternion,Ca=new ce.Quaternion,Ia=new ce.Matrix4,Ln=new ce.Raycaster}static get ACTION(){return O}constructor(e,t){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.verticalDragToForward=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=O.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Gs.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new ce.Vector3,this._focalOffsetVelocity=new ce.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,C,E)=>{let B,I;if(ys(this._camera)){const _=me.copy(this._camera.position).sub(this._target),S=this._camera.getEffectiveFOV()*Pi,x=_.length()*Math.tan(S*.5);B=this.truckSpeed*m*x/this._elementRect.height,I=this.truckSpeed*C*x/this._elementRect.height}else if(as(this._camera)){const _=this._camera;B=m*(_.right-_.left)/_.zoom/this._elementRect.width,I=C*(_.top-_.bottom)/_.zoom/this._elementRect.height}else return;this.verticalDragToForward?(E?this.setFocalOffset(this._focalOffsetEnd.x+B,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(B,0,!0),this.forward(-I,!0)):E?this.setFocalOffset(this._focalOffsetEnd.x+B,this._focalOffsetEnd.y+I,this._focalOffsetEnd.z,!0):this.truck(B,I,!0)},this._rotateInternal=(m,C)=>{const E=Us*this.azimuthRotateSpeed*m/this._elementRect.height,B=Us*this.polarRotateSpeed*C/this._elementRect.height;this.rotate(E,B,!0)},this._dollyInternal=(m,C,E)=>{const B=Math.pow(.95,-m*this.dollySpeed),I=this._sphericalEnd.radius,_=this._sphericalEnd.radius*B,S=Bt(_,this.minDistance,this.maxDistance),x=S-_;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(_,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(x,!0),this._dollyToNoClamp(S,!0)):this._dollyToNoClamp(S,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?_:S)-I,this._dollyControlCoord.set(C,E)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,C,E)=>{const B=Math.pow(.95,m*this.dollySpeed),I=this._zoom,_=this._zoom*B;this.zoomTo(_,!0),this.dollyToCursor&&(this._changedZoom+=_-I,this._dollyControlCoord.set(C,E))},typeof ce>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new ce.Quaternion().setFromUnitVectors(this._camera.up,Dn),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=O.NONE,this._target=new ce.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new ce.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new ce.Spherical().setFromVector3(me.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new ce.Vector3,new ce.Vector3,new ce.Vector3,new ce.Vector3],this._updateNearPlaneCorners(),this._boundary=new ce.Box3(new ce.Vector3(-1/0,-1/0,-1/0),new ce.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new ce.Vector2,this.mouseButtons={left:O.ROTATE,middle:O.DOLLY,right:O.TRUCK,wheel:ys(this._camera)?O.DOLLY:as(this._camera)?O.ZOOM:O.NONE},this.touches={one:O.TOUCH_ROTATE,two:ys(this._camera)?O.TOUCH_DOLLY_TRUCK:as(this._camera)?O.TOUCH_ZOOM_TRUCK:O.NONE,three:O.TOUCH_TRUCK};const s=new ce.Vector2,i=new ce.Vector2,r=new ce.Vector2,a=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const B=this._domElement.getBoundingClientRect(),I=m.clientX/B.width,_=m.clientY/B.height;if(I<this._interactiveArea.left||I>this._interactiveArea.right||_<this._interactiveArea.top||_>this._interactiveArea.bottom)return}const C=m.pointerType!=="mouse"?null:(m.buttons&Pe.LEFT)===Pe.LEFT?Pe.LEFT:(m.buttons&Pe.MIDDLE)===Pe.MIDDLE?Pe.MIDDLE:(m.buttons&Pe.RIGHT)===Pe.RIGHT?Pe.RIGHT:null;if(C!==null){const B=this._findPointerByMouseButton(C);B&&this._disposePointer(B)}if((m.buttons&Pe.LEFT)===Pe.LEFT&&this._lockedPointer)return;const E={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:C};this._activePointers.push(E),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,d(m)},o=m=>{m.cancelable&&m.preventDefault();const C=m.pointerId,E=this._lockedPointer||this._findPointerById(C);if(E){if(E.clientX=m.clientX,E.clientY=m.clientY,E.deltaX=m.movementX,E.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Pe.LEFT)===Pe.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Pe.MIDDLE)===Pe.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Pe.RIGHT)===Pe.RIGHT&&(this._state=this._state|this.mouseButtons.right);A()}},l=m=>{const C=this._findPointerById(m.pointerId);if(!(C&&C===this._lockedPointer)){if(C&&this._disposePointer(C),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=O.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=O.NONE;f()}};let c=-1;const h=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===O.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const _=this._domElement.getBoundingClientRect(),S=m.clientX/_.width,x=m.clientY/_.height;if(S<this._interactiveArea.left||S>this._interactiveArea.right||x<this._interactiveArea.top||x>this._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===O.ROTATE||this.mouseButtons.wheel===O.TRUCK){const _=performance.now();c-_<1e3&&this._getClientRect(this._elementRect),c=_}const C=eS?-1:-3,E=m.deltaMode===1?m.deltaY/C:m.deltaY/(C*10),B=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,I=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case O.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case O.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1),this._isUserControllingTruck=!0;break}case O.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0),this._isUserControllingOffset=!0;break}case O.DOLLY:{this._dollyInternal(-E,B,I),this._isUserControllingDolly=!0;break}case O.ZOOM:{this._zoomInternal(-E,B,I),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Eo.ACTION.NONE){const C=m instanceof PointerEvent?m.pointerId:0,E=this._findPointerById(C);E&&this._disposePointer(E),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},d=m=>{if(!this._enabled)return;if(fa(this._activePointers,et),this._getClientRect(this._elementRect),s.copy(et),i.copy(et),this._activePointers.length>=2){const E=et.x-this._activePointers[1].clientX,B=et.y-this._activePointers[1].clientY,I=Math.sqrt(E*E+B*B);r.set(0,I);const _=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,S=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(_,S)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Pe.LEFT)===Pe.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Pe.MIDDLE)===Pe.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Pe.RIGHT)===Pe.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&O.ROTATE)===O.ROTATE||(this._state&O.TOUCH_ROTATE)===O.TOUCH_ROTATE||(this._state&O.TOUCH_DOLLY_ROTATE)===O.TOUCH_DOLLY_ROTATE||(this._state&O.TOUCH_ZOOM_ROTATE)===O.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&O.TRUCK)===O.TRUCK||(this._state&O.TOUCH_TRUCK)===O.TOUCH_TRUCK||(this._state&O.TOUCH_DOLLY_TRUCK)===O.TOUCH_DOLLY_TRUCK||(this._state&O.TOUCH_ZOOM_TRUCK)===O.TOUCH_ZOOM_TRUCK)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&O.DOLLY)===O.DOLLY||(this._state&O.TOUCH_DOLLY)===O.TOUCH_DOLLY||(this._state&O.TOUCH_DOLLY_TRUCK)===O.TOUCH_DOLLY_TRUCK||(this._state&O.TOUCH_DOLLY_OFFSET)===O.TOUCH_DOLLY_OFFSET||(this._state&O.TOUCH_DOLLY_ROTATE)===O.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&O.ZOOM)===O.ZOOM||(this._state&O.TOUCH_ZOOM)===O.TOUCH_ZOOM||(this._state&O.TOUCH_ZOOM_TRUCK)===O.TOUCH_ZOOM_TRUCK||(this._state&O.TOUCH_ZOOM_OFFSET)===O.TOUCH_ZOOM_OFFSET||(this._state&O.TOUCH_ZOOM_ROTATE)===O.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&O.OFFSET)===O.OFFSET||(this._state&O.TOUCH_OFFSET)===O.TOUCH_OFFSET||(this._state&O.TOUCH_DOLLY_OFFSET)===O.TOUCH_DOLLY_OFFSET||(this._state&O.TOUCH_ZOOM_OFFSET)===O.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},A=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,fa(this._activePointers,et);const C=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,E=C?-C.deltaX:i.x-et.x,B=C?-C.deltaY:i.y-et.y;if(i.copy(et),((this._state&O.ROTATE)===O.ROTATE||(this._state&O.TOUCH_ROTATE)===O.TOUCH_ROTATE||(this._state&O.TOUCH_DOLLY_ROTATE)===O.TOUCH_DOLLY_ROTATE||(this._state&O.TOUCH_ZOOM_ROTATE)===O.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(E,B),this._isUserControllingRotate=!0),(this._state&O.DOLLY)===O.DOLLY||(this._state&O.ZOOM)===O.ZOOM){const I=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,_=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,S=this.dollyDragInverted?-1:1;(this._state&O.DOLLY)===O.DOLLY?(this._dollyInternal(S*B*wn,I,_),this._isUserControllingDolly=!0):(this._zoomInternal(S*B*wn,I,_),this._isUserControllingZoom=!0)}if((this._state&O.TOUCH_DOLLY)===O.TOUCH_DOLLY||(this._state&O.TOUCH_ZOOM)===O.TOUCH_ZOOM||(this._state&O.TOUCH_DOLLY_TRUCK)===O.TOUCH_DOLLY_TRUCK||(this._state&O.TOUCH_ZOOM_TRUCK)===O.TOUCH_ZOOM_TRUCK||(this._state&O.TOUCH_DOLLY_OFFSET)===O.TOUCH_DOLLY_OFFSET||(this._state&O.TOUCH_ZOOM_OFFSET)===O.TOUCH_ZOOM_OFFSET||(this._state&O.TOUCH_DOLLY_ROTATE)===O.TOUCH_DOLLY_ROTATE||(this._state&O.TOUCH_ZOOM_ROTATE)===O.TOUCH_ZOOM_ROTATE){const I=et.x-this._activePointers[1].clientX,_=et.y-this._activePointers[1].clientY,S=Math.sqrt(I*I+_*_),x=r.y-S;r.set(0,S);const b=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,v=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&O.TOUCH_DOLLY)===O.TOUCH_DOLLY||(this._state&O.TOUCH_DOLLY_ROTATE)===O.TOUCH_DOLLY_ROTATE||(this._state&O.TOUCH_DOLLY_TRUCK)===O.TOUCH_DOLLY_TRUCK||(this._state&O.TOUCH_DOLLY_OFFSET)===O.TOUCH_DOLLY_OFFSET?(this._dollyInternal(x*wn,b,v),this._isUserControllingDolly=!0):(this._zoomInternal(x*wn,b,v),this._isUserControllingZoom=!0)}((this._state&O.TRUCK)===O.TRUCK||(this._state&O.TOUCH_TRUCK)===O.TOUCH_TRUCK||(this._state&O.TOUCH_DOLLY_TRUCK)===O.TOUCH_DOLLY_TRUCK||(this._state&O.TOUCH_ZOOM_TRUCK)===O.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(E,B,!1),this._isUserControllingTruck=!0),((this._state&O.OFFSET)===O.OFFSET||(this._state&O.TOUCH_OFFSET)===O.TOUCH_OFFSET||(this._state&O.TOUCH_DOLLY_OFFSET)===O.TOUCH_DOLLY_OFFSET||(this._state&O.TOUCH_ZOOM_OFFSET)===O.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(E,B,!0),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{fa(this._activePointers,et),i.copy(et),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",p),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var m,C,E;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(C=this._domElement)===null||C===void 0||C.ownerDocument.removeEventListener("pointerlockchange",g),(E=this._domElement)===null||E===void 0||E.ownerDocument.removeEventListener("pointerlockerror",p),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},p=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",a),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",a),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",p))},this.cancel=()=>{this._state!==O.NONE&&(this._state=O.NONE,this._activePointers.length=0,f())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Bt(e.width,0,1),this._interactiveArea.height=Bt(e.height,0,1),this._interactiveArea.x=Bt(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Bt(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,s)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,s=!1){this._isUserControllingRotate=!1;const i=Bt(e,this.minAzimuthAngle,this.maxAzimuthAngle),r=Bt(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=i,this._sphericalEnd.phi=r,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const a=!s||Se(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Se(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Gs.NONE,this._changedDolly=0,this._dollyToNoClamp(Bt(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const a=this._collisionTest(),o=Se(a,this._spherical.radius);if(!(s>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,a)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const r=!t||Se(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(Qi).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||Se(this._target.x,this._targetEnd.x,this.restThreshold)&&Se(this._target.y,this._targetEnd.y,this.restThreshold)&&Se(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(s)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Bt(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||Se(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(s)}pan(e,t,s=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,s)}truck(e,t,s=!1){this._camera.updateMatrix(),Dt.setFromMatrixColumn(this._camera.matrix,0),Lt.setFromMatrixColumn(this._camera.matrix,1),Dt.multiplyScalar(e),Lt.multiplyScalar(-t);const i=me.copy(Dt).add(Lt),r=Be.copy(this._targetEnd).add(i);return this.moveTo(r.x,r.y,r.z,s)}forward(e,t=!1){me.setFromMatrixColumn(this._camera.matrix,0),me.crossVectors(this._camera.up,me),me.multiplyScalar(e);const s=Be.copy(this._targetEnd).add(me);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return me.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+me.x,this._targetEnd.y+me.y,this._targetEnd.z+me.z,t)}moveTo(e,t,s,i=!1){this._isUserControllingTruck=!1;const r=me.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,r,this.boundaryFriction),this._needsUpdate=!0,i||this._target.copy(this._targetEnd);const a=!i||Se(this._target.x,this._targetEnd.x,this.restThreshold)&&Se(this._target.y,this._targetEnd.y,this.restThreshold)&&Se(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,t,s,i=!1){const o=me.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,i)}fitToBox(e,t,{cover:s=!1,paddingLeft:i=0,paddingRight:r=0,paddingBottom:a=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?Hs.copy(e):Hs.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=hh(this._sphericalEnd.theta,ch),u=hh(this._sphericalEnd.phi,ch);l.push(this.rotateTo(h,u,t));const d=me.setFromSpherical(this._sphericalEnd).normalize(),A=mh.setFromUnitVectors(d,pa),f=Se(Math.abs(d.y),1);f&&A.multiply(Ca.setFromAxisAngle(Dn,h)),A.multiply(this._yAxisUpSpaceInverse);const g=gh.makeEmpty();Be.copy(c.min).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.min).setX(c.max.x).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.min).setY(c.max.y).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.max).setZ(c.min.z).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.min).setZ(c.max.z).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.max).setY(c.min.y).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.max).setX(c.min.x).applyQuaternion(A),g.expandByPoint(Be),Be.copy(c.max).applyQuaternion(A),g.expandByPoint(Be),g.min.x-=i,g.min.y-=a,g.max.x+=r,g.max.y+=o,A.setFromUnitVectors(pa,d),f&&A.premultiply(Ca.invert()),A.premultiply(this._yAxisUpSpace);const p=g.getSize(me),m=g.getCenter(Be).applyQuaternion(A);if(ys(this._camera)){const C=this.getDistanceToFitBox(p.x,p.y,p.z,s);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(C,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(as(this._camera)){const C=this._camera,E=C.right-C.left,B=C.top-C.bottom,I=s?Math.max(E/p.x,B/p.y):Math.min(E/p.x,B/p.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(I,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const s=[],r="isObject3D"in e?Eo.createBoundingSphere(e,Ea):Ea.copy(e);if(s.push(this.moveTo(r.center.x,r.center.y,r.center.z,t)),ys(this._camera)){const a=this.getDistanceToFitSphere(r.radius);s.push(this.dollyTo(a,t))}else if(as(this._camera)){const a=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*r.radius,c=Math.min(a/l,o/l);s.push(this.zoomTo(c,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,i,r,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Gs.NONE,this._changedDolly=0;const l=Be.set(i,r,a),c=me.set(e,t,s);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!o||Se(this._target.x,this._targetEnd.x,this.restThreshold)&&Se(this._target.y,this._targetEnd.y,this.restThreshold)&&Se(this._target.z,this._targetEnd.z,this.restThreshold)&&Se(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Se(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Se(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(e,t,s,i,r,a,o,l,c,h,u,d,A,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Gs.NONE,this._changedDolly=0;const g=me.set(i,r,a),p=Be.set(e,t,s);lt.setFromVector3(p.sub(g).applyQuaternion(this._yAxisUpSpace));const m=Ns.set(h,u,d),C=Be.set(o,l,c);Gi.setFromVector3(C.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,A));const E=Gi.theta-lt.theta,B=Gi.phi-lt.phi,I=Gi.radius-lt.radius;this._sphericalEnd.set(lt.radius+I*A,lt.phi+B*A,lt.theta+E*A),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const _=!f||Se(this._target.x,this._targetEnd.x,this.restThreshold)&&Se(this._target.y,this._targetEnd.y,this.restThreshold)&&Se(this._target.z,this._targetEnd.z,this.restThreshold)&&Se(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Se(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Se(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(_)}setPosition(e,t,s,i=!1){return this.setLookAt(e,t,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,i)}setTarget(e,t,s,i=!1){const r=this.getPosition(me),a=this.setLookAt(r.x,r.y,r.z,e,t,s,i);return this._sphericalEnd.phi=Bt(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}setFocalOffset(e,t,s,i=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,s),this._needsUpdate=!0,i||this._focalOffset.copy(this._focalOffsetEnd);const r=!i||Se(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Se(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Se(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),Dt.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Lt.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Bs.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const i=me.set(e,t,s),r=i.distanceTo(this._camera.position),a=i.sub(this._camera.position);Dt.multiplyScalar(a.x),Lt.multiplyScalar(a.y),Bs.multiplyScalar(a.z),me.copy(Dt).add(Lt).add(Bs),me.z=me.z+r,this.dollyTo(r,!1),this.setFocalOffset(-me.x,me.y,-me.z,!1),this.moveTo(e,t,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,s,i){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new ce.Vector4,typeof e=="number"?this._viewport.set(e,t,s,i):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,i=!1){if(ga(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const r=e/t,a=this._camera.getEffectiveFOV()*Pi,o=this._camera.aspect;return((i?r>o:r<o)?t:e/o)*.5/Math.tan(a*.5)+s*.5}getDistanceToFitSphere(e){if(ga(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*Pi,s=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,i=1<this._camera.aspect?t:s;return e/Math.sin(i*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new ce.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new ce.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new ce.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new ce.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Us,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Us),this._spherical.theta+=Us*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Us)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Se(this._camera.up.x,this._cameraUp0.x)||!Se(this._camera.up.y,this._cameraUp0.y)||!Se(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(me);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}const t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Dn),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=me.subVectors(this._target,this._camera.position).normalize(),t=Be.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(me);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}update(e){const t=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,i=this._sphericalEnd.radius-this._spherical.radius,r=Ah.subVectors(this._targetEnd,this._target),a=fh.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(De(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Rn(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,e),this._needsUpdate=!0}if(De(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Rn(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,e),this._needsUpdate=!0}if(De(i))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Rn(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,e),this._needsUpdate=!0}if(De(r.x)&&De(r.y)&&De(r.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;uh(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(De(a.x)&&De(a.y)&&De(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;uh(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(De(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Rn(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,e)}if(this.dollyToCursor){if(ys(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,d=this._camera,A=this._getCameraDirection(Qi),f=me.copy(A).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const g=Be.crossVectors(f,A),p=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*Pi*.5),C=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,E=Ns.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*p*d.aspect)).add(g.multiplyScalar(this._dollyControlCoord.y*p)),B=me.copy(this._targetEnd).lerp(E,C),I=this._lastDollyDirection===Gs.IN&&this._spherical.radius<=this.minDistance,_=this._lastDollyDirection===Gs.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(I||_)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const x=Be.copy(A).multiplyScalar(-u);B.add(x)}this._boundary.clampPoint(B,B);const S=Be.subVectors(B,this._targetEnd);this._targetEnd.copy(B),this._target.add(S),this._changedDolly-=u,De(this._changedDolly)&&(this._changedDolly=0)}else if(as(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,d=this._camera,A=me.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),f=Be.set(0,0,-1).applyQuaternion(d.quaternion),g=Ns.copy(A).add(f.multiplyScalar(-A.dot(d.up))),m=-(this._zoom-u-this._zoom)/this._zoom,C=this._getCameraDirection(Qi),E=this._targetEnd.dot(C),B=me.copy(this._targetEnd).lerp(g,m),I=B.dot(C),_=C.multiplyScalar(I-E);B.sub(_),this._boundary.clampPoint(B,B);const S=Be.subVectors(B,this._targetEnd);this._targetEnd.copy(B),this._target.add(S),this._changedZoom-=u,De(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const l=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,l),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!De(this._focalOffset.x)||!De(this._focalOffset.y)||!De(this._focalOffset.z))&&(this._camera.updateMatrixWorld(),Dt.setFromMatrixColumn(this._camera.matrix,0),Lt.setFromMatrixColumn(this._camera.matrix,1),Bs.setFromMatrixColumn(this._camera.matrix,2),Dt.multiplyScalar(this._focalOffset.x),Lt.multiplyScalar(-this._focalOffset.y),Bs.multiplyScalar(this._focalOffset.z),me.copy(Dt).add(Lt).add(Bs),this._camera.position.add(me)),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),me.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const h=this._needsUpdate;return h&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):h?(this.dispatchEvent({type:"update"}),De(t,this.restThreshold)&&De(s,this.restThreshold)&&De(i,this.restThreshold)&&De(r.x,this.restThreshold)&&De(r.y,this.restThreshold)&&De(r.z,this.restThreshold)&&De(a.x,this.restThreshold)&&De(a.y,this.restThreshold)&&De(a.z,this.restThreshold)&&De(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!h&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=h,this._needsUpdate=!1,h}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:ki(this.maxDistance),minZoom:this.minZoom,maxZoom:ki(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:ki(this.maxPolarAngle),minAzimuthAngle:ki(this.minAzimuthAngle),maxAzimuthAngle:ki(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,verticalDragToForward:this.verticalDragToForward,target:this._targetEnd.toArray(),position:me.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){const s=JSON.parse(e);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=Oi(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=Oi(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=Oi(s.maxPolarAngle),this.minAzimuthAngle=Oi(s.minAzimuthAngle),this.maxAzimuthAngle=Oi(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this.verticalDragToForward=s.verticalDragToForward,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],t),lt.setFromVector3(me.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(lt.theta,lt.phi,t),this.dollyTo(lt.radius,t),this.zoomTo(s.zoom,t),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}e.setAttribute("data-camera-controls-version",ZT),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,s){const i=t.lengthSq();if(i===0)return e;const r=Be.copy(t).add(e),o=this._boundary.clampPoint(r,Ns).sub(r),l=o.lengthSq();if(l===0)return e.add(t);if(l===i)return e;if(s===0)return e.add(t).add(o);{const c=1+s*l/t.dot(o);return e.add(Be.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(ys(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*Pi,i=Math.tan(s*.5)*t,r=i*e.aspect;this._nearPlaneCorners[0].set(-r,-i,0),this._nearPlaneCorners[1].set(r,-i,0),this._nearPlaneCorners[2].set(r,i,0),this._nearPlaneCorners[3].set(-r,i,0)}else if(as(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,i=e.right*t,r=e.top*t,a=e.bottom*t;this._nearPlaneCorners[0].set(s,r,0),this._nearPlaneCorners[1].set(i,r,0),this._nearPlaneCorners[2].set(i,a,0),this._nearPlaneCorners[3].set(s,a,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||ga(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(Qi);Ia.lookAt(dh,s,this._camera.up);for(let i=0;i<4;i++){const r=Be.copy(this._nearPlaneCorners[i]);r.applyMatrix4(Ia);const a=Ns.addVectors(this._target,r);Ln.set(a,s),Ln.far=this._spherical.radius+1;const o=Ln.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance<e&&(e=o[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const s=()=>{this.removeEventListener("rest",s),t()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new ce.Sphere){const s=t,i=s.center;Hs.makeEmpty(),e.traverseVisible(a=>{a.isMesh&&Hs.expandByObject(a)}),Hs.getCenter(i);let r=0;return e.traverseVisible(a=>{if(!a.isMesh)return;const o=a,l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const h=l.attributes.position;for(let u=0,d=h.count;u<d;u++)me.fromBufferAttribute(h,u),r=Math.max(r,i.distanceToSquared(me))}),s.radius=Math.sqrt(r),s}};const tS=T.forwardRef((n,e)=>{T.useMemo(()=>{const I={Box3:Qo,MathUtils:{clamp:le.clamp},Matrix4:he,Quaternion:Ie,Raycaster:Br,Sphere:Tr,Spherical:Po,Vector2:Qe,Vector3:P,Vector4:vt};ya.install({THREE:I}),No({CameraControlsImpl:ya})},[]);const{camera:t,domElement:s,makeDefault:i,onStart:r,onEnd:a,onChange:o,regress:l,...c}=n,h=$(I=>I.camera),u=$(I=>I.gl),d=$(I=>I.invalidate),A=$(I=>I.events),f=$(I=>I.setEvents),g=$(I=>I.set),p=$(I=>I.get),m=$(I=>I.performance),C=t||h,E=s||A.connected||u.domElement,B=T.useMemo(()=>new ya(C),[C]);return Ue((I,_)=>{B.enabled&&B.update(_)},-1),T.useEffect(()=>(B.connect(E),()=>void B.disconnect()),[E,B]),T.useEffect(()=>{const I=x=>{d(),l&&m.regress(),o&&o(x)},_=x=>{r&&r(x)},S=x=>{a&&a(x)};return B.addEventListener("update",I),B.addEventListener("controlstart",_),B.addEventListener("controlend",S),B.addEventListener("control",I),B.addEventListener("transitionstart",I),B.addEventListener("wake",I),()=>{B.removeEventListener("update",I),B.removeEventListener("controlstart",_),B.removeEventListener("controlend",S),B.removeEventListener("control",I),B.removeEventListener("transitionstart",I),B.removeEventListener("wake",I)}},[B,r,a,d,f,l,o]),T.useEffect(()=>{if(i){const I=p().controls;return g({controls:B}),()=>g({controls:I})}},[i,B]),T.createElement("primitive",be({ref:e,object:B},c))}),sS=n=>(n==null?void 0:n.current)instanceof Xe,gA=T.createContext(null);function mA(){return T.useContext(gA)}function iS({points:n=50}){const{path:e}=mA(),[t,s]=T.useState([]),[i]=T.useState(()=>new ls({color:"black"})),[r]=T.useState(()=>new Ru(.025,16,16)),a=T.useRef([]);return T.useEffect(()=>{e.curves!==a.current&&(s(e.getPoints(n)),a.current=e.curves)}),T.createElement(T.Fragment,null,t.map((o,l)=>T.createElement("mesh",{key:l,material:i,geometry:r,position:[o.x,o.y,o.z]})))}const nS=T.forwardRef(({children:n,curves:e=[],object:t,debug:s=!1,smooth:i=!1,focus:r,offset:a=void 0,eps:o=1e-5,damping:l=.1,focusDamping:c=.1,maxSpeed:h=1/0,...u},d)=>{const{camera:A}=$(),f=T.useRef(),[g]=T.useState(()=>new Gg),p=T.useRef(a??0),m=T.useMemo(()=>({focus:r,object:(t==null?void 0:t.current)instanceof Xe?t:{current:A},path:g,current:p.current,offset:p.current,point:new P,tangent:new P,next:new P}),[r,t]);T.useLayoutEffect(()=>{var B;g.curves=[];const I=e.length>0?e:(B=f.current)==null?void 0:B.__r3f.objects;for(var _=0;_<I.length;_++)g.add(I[_]);if(i){const S=g.getPoints(typeof i=="number"?i:1),x=new Ug(S);g.curves=[x]}g.updateArcLengths()}),T.useImperativeHandle(d,()=>f.current,[]),T.useLayoutEffect(()=>{p.current=qr.repeat(p.current,1)},[a]);let C=0;const[E]=T.useState(()=>new P);return Ue((B,I)=>{if(C=m.offset,hi.damp(p,"current",a!==void 0?a:m.current,l,I,h,void 0,o),m.offset=qr.repeat(p.current,1),g.getCurveLengths().length>0){g.getPointAt(m.offset,m.point),g.getTangentAt(m.offset,m.tangent).normalize(),g.getPointAt(qr.repeat(p.current-(C-m.offset),1),m.next);const _=(t==null?void 0:t.current)instanceof Xe?t.current:A;_.position.copy(m.point),r&&hi.dampLookAt(_,sS(r)?r.current.getWorldPosition(E):r,c,I,h,void 0,o)}}),T.createElement("group",be({ref:f},u),T.createElement(gA.Provider,{value:m},n,s&&T.createElement(iS,null)))});function fl(n,{path:e}){const[t]=wt(Qu,[n],s=>s.setPath(e));return t}fl.preload=(n,{path:e})=>wt.preload(Qu,[n],t=>t.setPath(e));function rS({children:n,files:e,...t}){const s=fl(e,{...t});return T.createElement(T.Fragment,null,n==null?void 0:n(s))}function Fr(n){return wt(ul,n)}Fr.preload=n=>wt.preload(ul,n);Fr.clear=n=>wt.clear(ul,n);function aS({path:n,...e}){const s=Fr(n).children[0];return T.createElement(Uo,be({},e,{object:s}))}const pA="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master";function Pr(n,e=`${pA}/basis/`){const t=$(i=>i.gl),s=wt(Al,to(n)?Object.values(n):n,i=>{i.detectSupport(t),i.setTranscoderPath(e)});if(T.useEffect(()=>{(Array.isArray(s)?s:[s]).forEach(t.initTexture)},[t,s]),to(n)){const i=Object.keys(n),r={};return i.forEach(a=>Object.assign(r,{[a]:s[i.indexOf(a)]})),r}else return s}Pr.preload=(n,e=`${pA}/basis/`)=>wt.preload(Al,n,t=>{t.setTranscoderPath(e)});Pr.clear=n=>wt.clear(Al,n);const oS=({children:n,input:e,basisPath:t})=>{const s=Pr(e,t);return T.createElement(T.Fragment,null,n==null?void 0:n(s))};function lS(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var EA={exports:{}};(function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var A=o.parseURL(l);if(!A)throw new Error("Error trying to parse base URL.");if(!A.netLoc&&A.path&&A.path[0]!=="/"){var f=i.exec(A.path);A.netLoc=f[1],A.path=f[2]}A.netLoc&&!A.path&&(A.path="/");var g={scheme:A.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(g.netLoc=A.netLoc,d.path[0]!=="/"))if(!d.path)g.path=A.path,d.params||(g.params=A.params,d.query||(g.query=A.query));else{var p=A.path,m=p.substring(0,p.lastIndexOf("/")+1)+d.path;g.path=o.normalizePath(m)}return g.path===null&&(g.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(g)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(EA);var gl=EA.exports;function ph(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function $e(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ph(Object(t),!0).forEach(function(s){uS(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):ph(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function cS(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e||"default");if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function hS(n){var e=cS(n,"string");return typeof e=="symbol"?e:String(e)}function uS(n,e,t){return e=hS(e),e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Ge(){return Ge=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},Ge.apply(this,arguments)}const W=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},dS=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=AS},AS=Number.MAX_SAFE_INTEGER||9007199254740991;let y=function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n}({}),re=function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n}({}),F=function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.UNKNOWN="unknown",n}({});const _s=function(){},Co={trace:_s,debug:_s,log:_s,warn:_s,info:_s,error:_s};let Xi=Co;function fS(n){const e=self.console[n];return e?e.bind(self.console,`[${n}] >`):_s}function gS(n,...e){e.forEach(function(t){Xi[t]=n[t]?n[t].bind(n):fS(t)})}function mS(n,e){if(typeof console=="object"&&n===!0||typeof n=="object"){gS(n,"debug","log","info","warn","error");try{Xi.log(`Debug logs enabled for "${e}" in hls.js version 1.5.19`)}catch{Xi=Co}}else Xi=Co}const w=Xi,pS=/^(\d+)x(\d+)$/,Eh=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Fe{constructor(e){typeof e=="string"&&(e=Fe.parseAttrList(e)),Ge(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=pS.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const s={},i='"';for(Eh.lastIndex=0;(t=Eh.exec(e))!==null;){let r=t[2];r.indexOf(i)===0&&r.lastIndexOf(i)===r.length-1&&(r=r.slice(1,-1));const a=t[1].trim();s[a]=r}return s}}function ES(n){return n!=="ID"&&n!=="CLASS"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function CS(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"}class ml{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const s=t.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==s[i]){w.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=Ge(new Fe({}),s,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=new Date(this.attr["END-DATE"]);W(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(W(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&W(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class gn{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ve={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class pl{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ve.AUDIO]:null,[ve.VIDEO]:null,[ve.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0:t.byteRangeEndOffset)||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=gl.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class qn extends pl{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new gn,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!W(this.programDateTime))return null;const e=W(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ve.AUDIO]=null,e[ve.VIDEO]=null,e[ve.AUDIOVIDEO]=null}}class CA extends pl{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new gn,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const IS=10;class IA{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?W(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||IS}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function El(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function yS(n){const e=Io(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function BS(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function TS(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=El(a)):t=yS(a)}}return t}function Io(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}const Ai=typeof self<"u"?self:void 0;var Te={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ze={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ba(n){switch(n){case Ze.FAIRPLAY:return Te.FAIRPLAY;case Ze.PLAYREADY:return Te.PLAYREADY;case Ze.WIDEVINE:return Te.WIDEVINE;case Ze.CLEARKEY:return Te.CLEARKEY}}var bn={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ta(n){if(n===bn.WIDEVINE)return Te.WIDEVINE;if(n===bn.PLAYREADY)return Te.PLAYREADY;if(n===bn.CENC||n===bn.CLEARKEY)return Te.CLEARKEY}function Sa(n){switch(n){case Te.FAIRPLAY:return Ze.FAIRPLAY;case Te.PLAYREADY:return Ze.PLAYREADY;case Te.WIDEVINE:return Ze.WIDEVINE;case Te.CLEARKEY:return Ze.CLEARKEY}}function Mn(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[Te.FAIRPLAY,Te.WIDEVINE,Te.PLAYREADY,Te.CLEARKEY].filter(i=>!!e[i]):[];return!s[Te.WIDEVINE]&&t&&s.push(Te.WIDEVINE),s}const yA=function(n){return Ai!=null&&(n=Ai.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function SS(n,e,t,s){let i;switch(n){case Te.FAIRPLAY:i=["cenc","sinf"];break;case Te.WIDEVINE:case Te.PLAYREADY:i=["cenc"];break;case Te.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return _S(i,e,t,s)}function _S(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function BA(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=El(o).subarray(0,16);return BS(l),l}}return null}function ws(n,e,t){return Uint8Array.prototype.slice?n.slice(e,t):new Uint8Array(Array.prototype.slice.call(n,e,t))}const Cl=(n,e)=>e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,TA=(n,e)=>e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,ln=(n,e)=>{const t=e;let s=0;for(;Cl(n,e);){s+=10;const i=kr(n,e+6);s+=i,TA(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)},kr=(n,e)=>{let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t},xS=(n,e)=>Cl(n,e)&&kr(n,e+6)+10<=n.length-e,Il=n=>{const e=_A(n);for(let t=0;t<e.length;t++){const s=e[t];if(SA(s))return bS(s)}},SA=n=>n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp",vS=n=>{const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=kr(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}},_A=n=>{let e=0;const t=[];for(;Cl(n,e);){const s=kr(n,e+6);e+=10;const i=e+s;for(;e+8<i;){const r=vS(n.subarray(e)),a=RS(r);a&&t.push(a),e+=r.size+10}TA(n,e)&&(e+=10)}return t},RS=n=>n.type==="PRIV"?wS(n):n.type[0]==="W"?LS(n):DS(n),wS=n=>{if(n.size<2)return;const e=Nt(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}},DS=n=>{if(n.size<2)return;if(n.type==="TXXX"){let t=1;const s=Nt(n.data.subarray(t),!0);t+=s.length+1;const i=Nt(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Nt(n.data.subarray(1));return{key:n.type,data:e}},LS=n=>{if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=Nt(n.data.subarray(t),!0);t+=s.length+1;const i=Nt(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Nt(n.data);return{key:n.type,data:e}},bS=n=>{if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}},Nt=(n,e=!1)=>{const t=MS();if(t){const c=t.decode(n);if(e){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const s=n.length;let i,r,a,o="",l=0;for(;l<s;){if(i=n[l++],i===0&&e)return o;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:r=n[l++],o+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=n[l++],a=n[l++],o+=String.fromCharCode((i&15)<<12|(r&63)<<6|(a&63)<<0);break}}return o};let _a;function MS(){if(!navigator.userAgent.includes("PlayStation 4"))return!_a&&typeof self.TextDecoder<"u"&&(_a=new self.TextDecoder("utf-8")),_a}const Pt={hexDump:function(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}},ur=Math.pow(2,32)-1,FS=[].push,xA={video:1,audio:2,id3:3,text:4};function Ke(n){return String.fromCharCode.apply(null,n)}function vA(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function ne(n,e){const t=RA(n,e);return t<0?4294967296+t:t}function Ch(n,e){let t=ne(n,e);return t*=Math.pow(2,32),t+=ne(n,e+4),t}function RA(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function xa(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function PS(n){const e=n.byteLength;for(let t=0;t<e;){const s=ne(n,t);if(s>8&&n[t+4]===109&&n[t+5]===111&&n[t+6]===111&&n[t+7]===102)return!0;t=s>1?t+s:e}return!1}function fe(n,e){const t=[];if(!e.length)return t;const s=n.byteLength;for(let i=0;i<s;){const r=ne(n,i),a=Ke(n.subarray(i+4,i+8)),o=r>1?i+r:s;if(a===e[0])if(e.length===1)t.push(n.subarray(i+8,o));else{const l=fe(n.subarray(i+8,o),e.slice(1));l.length&&FS.apply(t,l)}i=o}return t}function kS(n){const e=[],t=n[0];let s=8;const i=ne(n,s);s+=4;let r=0,a=0;t===0?(r=ne(n,s),a=ne(n,s+4),s+=8):(r=Ch(n,s),a=Ch(n,s+8),s+=16),s+=2;let o=n.length+a;const l=vA(n,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=ne(n,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return w.warn("SIDX has hierarchical references (not supported)"),null;const f=ne(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function wA(n){const e=[],t=fe(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=fe(r,["tkhd"])[0];if(a){let o=a[0];const l=ne(a,o===0?12:20),c=fe(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=ne(c,o===0?12:20),u=fe(r,["mdia","hdlr"])[0];if(u){const d=Ke(u.subarray(8,12)),A={soun:ve.AUDIO,vide:ve.VIDEO}[d];if(A){const f=fe(r,["mdia","minf","stbl","stsd"])[0],g=OS(f);e[l]={timescale:h,type:A},e[A]=$e({timescale:h,id:l},g)}}}}}return fe(n,["moov","mvex","trex"]).forEach(i=>{const r=ne(i,4),a=e[r];a&&(a.default={duration:ne(i,12),flags:ne(i,20)})}),e}function OS(n){const e=n.subarray(8),t=e.subarray(86),s=Ke(e.subarray(4,8));let i=s;const r=s==="enca"||s==="encv";if(r){const o=fe(e,[s])[0].subarray(s==="enca"?28:78);fe(o,["sinf"]).forEach(c=>{const h=fe(c,["schm"])[0];if(h){const u=Ke(h.subarray(4,8));if(u==="cbcs"||u==="cenc"){const d=fe(c,["frma"])[0];d&&(i=Ke(d))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const a=fe(t,["avcC"])[0];i+="."+Fn(a[1])+Fn(a[2])+Fn(a[3]);break}case"mp4a":{const a=fe(e,[s])[0],o=fe(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=va(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=va(o,l);const h=o[l++];if(h===64)i+="."+Fn(h);else break;if(l+=12,o[l++]!==5)break;l=va(o,l);const u=o[l++];let d=(u&248)>>3;d===31&&(d+=1+((u&7)<<3)+((o[l]&224)>>5)),i+="."+d}break}case"hvc1":case"hev1":{const a=fe(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,h=ne(a,2),u=(o&32)>>5?"H":"L",d=a[12],A=a.subarray(6,12);i+="."+l+c,i+="."+h.toString(16).toUpperCase(),i+="."+u+d;let f="";for(let g=A.length;g--;){const p=A[g];(p||f)&&(f="."+p.toString(16).toUpperCase()+f)}i+=f;break}case"dvh1":case"dvhe":{const a=fe(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;i+="."+bt(o)+"."+bt(l);break}case"vp09":{const a=fe(t,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;i+="."+bt(o)+"."+bt(l)+"."+bt(c);break}case"av01":{const a=fe(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",h=(a[2]&64)>>6,u=(a[2]&32)>>5,d=o===2&&h?u?12:10:h?10:8,A=(a[2]&16)>>4,f=(a[2]&8)>>3,g=(a[2]&4)>>2,p=a[2]&3;i+="."+o+"."+bt(l)+c+"."+bt(d)+"."+A+"."+f+g+p+"."+bt(1)+"."+bt(1)+"."+bt(1)+"."+0;break}}return{codec:i,encrypted:r}}function va(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Fn(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function bt(n){return(n<10?"0":"")+n}function QS(n,e){if(!n||!e)return n;const t=e.keyId;return t&&e.isCommonEncryption&&fe(n,["moov","trak"]).forEach(i=>{const a=fe(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=fe(a,["enca"]);const l=o.length>0;l||(o=fe(a,["encv"])),o.forEach(c=>{const h=l?c.subarray(28):c.subarray(78);fe(h,["sinf"]).forEach(d=>{const A=DA(d);if(A){const f=A.subarray(8,24);f.some(g=>g!==0)||(w.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Pt.hexDump(f)} -> ${Pt.hexDump(t)}`),A.set(t,8))}})})}),n}function DA(n){const e=fe(n,["schm"])[0];if(e){const t=Ke(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return fe(n,["schi","tenc"])[0]}return null}function GS(n,e){return fe(e,["moof","traf"]).reduce((t,s)=>{const i=fe(s,["tfdt"])[0],r=i[0],a=fe(s,["tfhd"]).reduce((o,l)=>{const c=ne(l,4),h=n[c];if(h){let u=ne(i,4);if(r===1){if(u===ur)return w.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;u*=ur+1,u+=ne(i,8)}const d=h.timescale||9e4,A=u/d;if(W(A)&&(o===null||A<o))return A}return o},null);return a!==null&&W(a)&&(t===null||a<t)?a:t},null)}function US(n,e){let t=0,s=0,i=0;const r=fe(n,["moof","traf"]);for(let a=0;a<r.length;a++){const o=r[a],l=fe(o,["tfhd"])[0],c=ne(l,4),h=e[c];if(!h)continue;const u=h.default,d=ne(l,0)|(u==null?void 0:u.flags);let A=u==null?void 0:u.duration;d&8&&(d&2?A=ne(l,12):A=ne(l,8));const f=h.timescale||9e4,g=fe(o,["trun"]);for(let p=0;p<g.length;p++){if(t=NS(g[p]),!t&&A){const m=ne(g[p],4);t=A*m}h.type===ve.VIDEO?s+=t/f:h.type===ve.AUDIO&&(i+=t/f)}}if(s===0&&i===0){let a=1/0,o=0,l=0;const c=fe(n,["sidx"]);for(let h=0;h<c.length;h++){const u=kS(c[h]);if(u!=null&&u.references){a=Math.min(a,u.earliestPresentationTime/u.timescale);const d=u.references.reduce((A,f)=>A+f.info.duration||0,0);o=Math.max(o,d+u.earliestPresentationTime/u.timescale),l=o-a}}if(l&&W(l))return l}return s||i}function NS(n){const e=ne(n,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let s=0;const i=ne(n,4);for(let r=0;r<i;r++){if(e&256){const a=ne(n,t);s+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return s}function HS(n,e,t){fe(e,["moof","traf"]).forEach(s=>{fe(s,["tfhd"]).forEach(i=>{const r=ne(i,4),a=n[r];if(!a)return;const o=a.timescale||9e4;fe(s,["tfdt"]).forEach(l=>{const c=l[0],h=t*o;if(h){let u=ne(l,4);if(c===0)u-=h,u=Math.max(u,0),xa(l,4,u);else{u*=Math.pow(2,32),u+=ne(l,8),u-=h,u=Math.max(u,0);const d=Math.floor(u/(ur+1)),A=Math.floor(u%(ur+1));xa(l,4,d),xa(l,8,A)}}})})})}function KS(n){const e={valid:null,remainder:null},t=fe(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=ws(n,0,s.byteOffset-8),e.remainder=ws(n,s.byteOffset-8),e}function Et(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Ih(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return fe(s,["moof"]).map(l=>{const c=l.byteOffset-8;fe(l,["traf"]).map(u=>{const d=fe(u,["tfdt"]).map(A=>{const f=A[0];let g=ne(A,4);return f===1&&(g*=Math.pow(2,32),g+=ne(A,8)),g/i})[0];return d!==void 0&&(n=d),fe(u,["tfhd"]).map(A=>{const f=ne(A,4),g=ne(A,0)&16777215,p=(g&1)!==0,m=(g&2)!==0,C=(g&8)!==0;let E=0;const B=(g&16)!==0;let I=0;const _=(g&32)!==0;let S=8;f===r&&(p&&(S+=8),m&&(S+=4),C&&(E=ne(A,S),S+=4),B&&(I=ne(A,S),S+=4),_&&(S+=4),e.type==="video"&&(a=VS(e.codec)),fe(u,["trun"]).map(x=>{const b=x[0],v=ne(x,0)&16777215,D=(v&1)!==0;let U=0;const Q=(v&4)!==0,j=(v&256)!==0;let V=0;const X=(v&512)!==0;let Z=0;const ae=(v&1024)!==0,Y=(v&2048)!==0;let G=0;const H=ne(x,4);let J=8;D&&(U=ne(x,J),J+=4),Q&&(J+=4);let K=U+c;for(let R=0;R<H;R++){if(j?(V=ne(x,J),J+=4):V=E,X?(Z=ne(x,J),J+=4):Z=I,ae&&(J+=4),Y&&(b===0?G=ne(x,J):G=RA(x,J),J+=4),e.type===ve.VIDEO){let te=0;for(;te<Z;){const oe=ne(s,K);if(K+=4,YS(a,s[K])){const ue=s.subarray(K,K+oe);LA(ue,a?2:1,n+G/i,t)}K+=oe,te+=oe+4}}n+=V/i}}))})})}),t}function VS(n){if(!n)return!1;const e=n.indexOf("."),t=e<0?n:n.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function YS(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function LA(n,e,t,s){const i=bA(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);const c=i.length-r;let h=r;if(o<c)r+=o;else if(o>c){w.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(i[h++]===181){const d=vA(i,h);if(h+=2,d===49){const A=ne(i,h);if(h+=4,A===1195456820){const f=i[h++];if(f===3){const g=i[h++],p=31&g,m=64&g,C=m?2+p*3:0,E=new Uint8Array(C);if(m){E[0]=g;for(let B=1;B<C;B++)E[B]=i[h++]}s.push({type:f,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){const u=[];for(let f=0;f<16;f++){const g=i[h++].toString(16);u.push(g.length==1?"0"+g:g),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,A=new Uint8Array(d);for(let f=0;f<d;f++)A[f]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:Nt(A),userDataBytes:A})}}}function bA(n){const e=n.byteLength,t=[];let s=1;for(;s<e-2;)n[s]===0&&n[s+1]===0&&n[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return n;const i=e-t.length,r=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),r[s]=n[a];return r}function JS(n){const e=n[0];let t="",s="",i=0,r=0,a=0,o=0,l=0,c=0;if(e===0){for(;Ke(n.subarray(c,c+1))!=="\0";)t+=Ke(n.subarray(c,c+1)),c+=1;for(t+=Ke(n.subarray(c,c+1)),c+=1;Ke(n.subarray(c,c+1))!=="\0";)s+=Ke(n.subarray(c,c+1)),c+=1;s+=Ke(n.subarray(c,c+1)),c+=1,i=ne(n,12),r=ne(n,16),o=ne(n,20),l=ne(n,24),c=28}else if(e===1){c+=4,i=ne(n,c),c+=4;const u=ne(n,c);c+=4;const d=ne(n,c);for(c+=4,a=2**32*u+d,dS(a)||(a=Number.MAX_SAFE_INTEGER,w.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ne(n,c),c+=4,l=ne(n,c),c+=4;Ke(n.subarray(c,c+1))!=="\0";)t+=Ke(n.subarray(c,c+1)),c+=1;for(t+=Ke(n.subarray(c,c+1)),c+=1;Ke(n.subarray(c,c+1))!=="\0";)s+=Ke(n.subarray(c,c+1)),c+=1;s+=Ke(n.subarray(c,c+1)),c+=1}const h=n.subarray(c,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function zS(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function qS(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),zS([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t||new Uint8Array)}function $S(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=XS(i);e.push(r),s+=r.size}}return e}function XS(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Pt.hexDump(new Uint8Array(a,t+12,16)),l=n.getUint32(28);let c=null,h=null;if(r===0){if(e-32<l||l<22)return{offset:t,size:e};h=new Uint8Array(a,t+32,l)}else if(r===1){if(!l||s<t+32+l*16+16)return{offset:t,size:e};c=[];for(let u=0;u<l;u++)c.push(new Uint8Array(a,t+32+u*16,16))}return{version:r,systemId:o,kids:c,data:h,offset:t,size:e}}let Pn={};class fi{static clearKeyUriToKeyIdMap(){Pn={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ze.FAIRPLAY:case Ze.WIDEVINE:case Ze.PLAYREADY:case Ze.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&w.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=jS(e);return new fi(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=TS(this.uri);if(t)switch(this.keyFormat){case Ze.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Ze.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=qS(s,null,t),this.keyId=BA(t);break}default:{let s=t.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=Pn[this.uri];if(!s){const i=Object.keys(Pn).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),Pn[this.uri]=s}this.keyId=s}return this}}function jS(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const MA=/\{\$([a-zA-Z0-9-_]+)\}/g;function yh(n){return MA.test(n)}function tt(n,e,t){if(n.variableList!==null||n.hasVariableRefs)for(let s=t.length;s--;){const i=t[s],r=e[i];r&&(e[i]=yo(n,r))}}function yo(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(MA,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function Bh(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function WS(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function gs(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ZS(n){return typeof self<"u"&&n===self.ManagedMediaSource}const dr={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function e_(n,e){const t=dr[e];return!!t&&!!t[n.slice(0,4)]}function Ra(n,e,t=!0){return!n.split(",").some(s=>!FA(s,e,t))}function FA(n,e,t=!0){var s;const i=gs(t);return(s=i==null?void 0:i.isTypeSupported(cn(n,e)))!=null?s:!1}function cn(n,e){return`${e}/mp4;codecs="${n}"`}function Th(n){if(n){const e=n.substring(0,4);return dr.video[e]}return 2}function Ar(n){return n.split(",").reduce((e,t)=>{const s=dr.video[t];return s?(s*2+e)/(e?3:2):(dr.audio[t]+e)/(e?2:1)},0)}const wa={};function t_(n,e=!0){if(wa[n])return wa[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[n];for(let s=0;s<t.length;s++)if(FA(t[s],"audio",e))return wa[n]=t[s],t[s];return n}const s_=/flac|opus/i;function fr(n,e=!0){return n.replace(s_,t=>t_(t.toLowerCase(),e))}function Sh(n,e){return n&&n!=="mp4a"?n:e&&e.split(",")[0]}function i_(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}const _h=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,xh=/#EXT-X-MEDIA:(.*)/g,n_=/^#EXT(?:INF|-X-TARGETDURATION):/m,vh=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),r_=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Qt{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return gl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return n_.test(e)}static parseMasterPlaylist(e,t){const s=yh(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];_h.lastIndex=0;let a;for(;(a=_h.exec(e))!=null;)if(a[1]){var o;const c=new Fe(a[1]);tt(i,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=yo(i,a[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Qt.resolve(h,t)},d=c.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),a_(c.CODECS,u),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(a[3]){const c=a[3],h=a[4];switch(c){case"SESSION-DATA":{const u=new Fe(h);tt(i,u,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=Rh(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):w.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new Fe(h);tt(i,u,["NAME","VALUE","QUERYPARAM"]),Bh(i,u,t)}break}case"CONTENT-STEERING":{const u=new Fe(h);tt(i,u,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:Qt.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=wh(h);break}}}const l=r.length>0&&r.length<i.levels.length;return i.levels=l?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(xh.lastIndex=0;(i=xh.exec(e))!==null;){const c=new Fe(i[1]),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d,tt(s,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const A=c.LANGUAGE,f=c["ASSOC-LANGUAGE"],g=c.CHANNELS,p=c.CHARACTERISTICS,m=c["INSTREAM-ID"],C={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||A||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:A,url:c.URI?Qt.resolve(c.URI,t):""};if(f&&(C.assocLang=f),g&&(C.channels=g),p&&(C.characteristics=p),m&&(C.instreamId=m),u!=null&&u.length){const E=Qt.findGroup(u,C.groupId)||u[0];Dh(C,E,"audioCodec"),Dh(C,E,"textCodec")}d.push(C)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){const o=new IA(t),l=o.fragments;let c=null,h=0,u=0,d=0,A=0,f=null,g=new qn(i,t),p,m,C,E=-1,B=!1,I=null;for(vh.lastIndex=0,o.m3u8=e,o.hasVariableRefs=yh(e);(p=vh.exec(e))!==null;){B&&(B=!1,g=new qn(i,t),g.start=d,g.sn=h,g.cc=A,g.level=s,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,I&&(g.setByteRange(I),I=null)));const b=p[1];if(b){g.duration=parseFloat(b);const v=(" "+p[2]).slice(1);g.title=v||null,g.tagList.push(v?["INF",b,v]:["INF",b])}else if(p[3]){if(W(g.duration)){g.start=d,C&&Mh(g,C,o),g.sn=h,g.level=s,g.cc=A,l.push(g);const v=(" "+p[3]).slice(1);g.relurl=yo(o,v),Lh(g,f),f=g,d+=g.duration,h++,u=0,B=!0}}else if(p[4]){const v=(" "+p[4]).slice(1);f?g.setByteRange(v,f):g.setByteRange(v)}else if(p[5])g.rawProgramDateTime=(" "+p[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),E===-1&&(E=l.length);else{if(p=p[0].match(r_),!p){w.warn("No matches on slow regex match for level playlist!");continue}for(m=1;m<p.length&&!(typeof p[m]<"u");m++);const v=(" "+p[m]).slice(1),D=(" "+p[m+1]).slice(1),U=p[m+2]?(" "+p[m+2]).slice(1):"";switch(v){case"PLAYLIST-TYPE":o.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(D);break;case"SKIP":{const Q=new Fe(D);tt(o,Q,["RECENTLY-REMOVED-DATERANGES"]);const j=Q.decimalInteger("SKIPPED-SEGMENTS");if(W(j)){o.skippedSegments=j;for(let X=j;X--;)l.unshift(null);h+=j}const V=Q.enumeratedString("RECENTLY-REMOVED-DATERANGES");V&&(o.recentlyRemovedDateranges=V.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(D),1);break;case"VERSION":o.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(D||U)&&g.tagList.push(U?[D,U]:[D]);break;case"DISCONTINUITY":A++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([v]);break;case"BITRATE":g.tagList.push([v,D]);break;case"DATERANGE":{const Q=new Fe(D);tt(o,Q,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),tt(o,Q,Q.clientAttrs);const j=new ml(Q,o.dateRanges[Q.ID]);j.isValid||o.skippedSegments?o.dateRanges[j.id]=j:w.warn(`Ignoring invalid DATERANGE tag: "${D}"`),g.tagList.push(["EXT-X-DATERANGE",D]);break}case"DEFINE":{{const Q=new Fe(D);tt(o,Q,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in Q?WS(o,Q,a):Bh(o,Q,t)}break}case"DISCONTINUITY-SEQUENCE":A=parseInt(D);break;case"KEY":{const Q=Rh(D,t,o);if(Q.isSupported()){if(Q.method==="NONE"){C=void 0;break}C||(C={}),C[Q.keyFormat]&&(C=Ge({},C)),C[Q.keyFormat]=Q}else w.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${D}"`);break}case"START":o.startTimeOffset=wh(D);break;case"MAP":{const Q=new Fe(D);if(tt(o,Q,["BYTERANGE","URI"]),g.duration){const j=new qn(i,t);bh(j,Q,s,C),c=j,g.initSegment=c,c.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=c.rawProgramDateTime)}else{const j=g.byteRangeEndOffset;if(j){const V=g.byteRangeStartOffset;I=`${j-V}@${V}`}else I=null;bh(g,Q,s,C),c=g,B=!0}break}case"SERVER-CONTROL":{const Q=new Fe(D);o.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),o.holdBack=Q.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const Q=new Fe(D);o.partTarget=Q.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Q=o.partList;Q||(Q=o.partList=[]);const j=u>0?Q[Q.length-1]:void 0,V=u++,X=new Fe(D);tt(o,X,["BYTERANGE","URI"]);const Z=new CA(X,g,t,V,j);Q.push(Z),g.duration+=Z.duration;break}case"PRELOAD-HINT":{const Q=new Fe(D);tt(o,Q,["URI"]),o.preloadHint=Q;break}case"RENDITION-REPORT":{const Q=new Fe(D);tt(o,Q,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(Q);break}default:w.warn(`line parsed but not handled: ${p}`);break}}}f&&!f.relurl?(l.pop(),d-=f.duration,o.partList&&(o.fragmentHint=f)):o.partList&&(Lh(g,f),g.cc=A,o.fragmentHint=g,C&&Mh(g,C,o));const _=l.length,S=l[0],x=l[_-1];if(d+=o.skippedSegments*o.targetduration,d>0&&_&&x){o.averagetargetduration=d/_;const b=x.sn;o.endSN=b!=="initSegment"?b:0,o.live||(x.endList=!0),S&&(o.startCC=S.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=A,E>0&&o_(l,E),o}}function Rh(n,e,t){var s,i;const r=new Fe(n);tt(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&w.error(`Invalid IV: ${r.IV}`);const u=o?Qt.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new fi(a,u,h,d,l)}function wh(n){const t=new Fe(n).decimalFloatingPoint("TIME-OFFSET");return W(t)?t:null}function a_(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>e_(r,s));i.length&&(e[`${s}Codec`]=i.join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function Dh(n,e,t){const s=e[t];s&&(n[t]=s)}function o_(n,e){let t=n[e];for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Lh(n,e){n.rawProgramDateTime?n.programDateTime=Date.parse(n.rawProgramDateTime):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime),W(n.programDateTime)||(n.programDateTime=null,n.rawProgramDateTime=null)}function bh(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function Mh(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}var ye={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},se={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Fh(n){const{type:e}=n;switch(e){case ye.AUDIO_TRACK:return se.AUDIO;case ye.SUBTITLE_TRACK:return se.SUBTITLE;default:return se.MAIN}}function Da(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class l_{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ye.MANIFEST,url:s,deliveryDirectives:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:ye.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ye.AUDIO_TRACK,url:r,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ye.SUBTITLE_TRACK,url:r,deliveryDirectives:a})}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=i.context;if(c&&c.url===e.url&&c.level===e.level){w.trace("[playlist-loader]: playlist request ongoing");return}w.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===ye.MANIFEST?r=s.manifestLoadPolicy.default:r=Ge({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),W((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===ye.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ye.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ye.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=Ge({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const A=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=c.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,u,new Error("no EXTM3U delimiter"),d||null,h);return}h.parsing.start=performance.now(),Qt.isMediaPlaylist(f)?this.handleTrackOrLevelPlaylist(c,h,u,d||null,A):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};i.load(e,o,l)}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=Da(e,s),l=Qt.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}const{contentSteering:c,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:A,variableList:f}=l;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=Qt.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(E=>!E.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(w.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Fe({}),bitrate:0,url:""})),r.trigger(y.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:A,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:l,type:c}=s,h=Da(e,s),u=0,d=W(l)?l:W(o)?o:0,A=Fh(s),f=Qt.parseLevelPlaylist(e.data,h,d,A,u,this.variableList);if(c===ye.MANIFEST){const g={attrs:new Fe({}),bitrate:0,details:f,name:"",url:h};a.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:F.MANIFEST_PARSING_ERROR,fatal:t.type===ye.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===ye.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ye.AUDIO_TRACK||e.type===ye.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);w.warn(`[playlist-loader]: ${a}`);let l=F.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case ye.MANIFEST:l=s?F.MANIFEST_LOAD_TIMEOUT:F.MANIFEST_LOAD_ERROR,c=!0;break;case ye.LEVEL:l=s?F.LEVEL_LOAD_TIMEOUT:F.LEVEL_LOAD_ERROR,c=!1;break;case ye.AUDIO_TRACK:l=s?F.AUDIO_TRACK_LOAD_TIMEOUT:F.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ye.SUBTITLE_TRACK:l=s?F.SUBTITLE_TRACK_LOAD_TIMEOUT:F.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:re.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=(t==null?void 0:t.url)||e.url;u.response=$e({url:d,data:void 0},i)}this.hls.trigger(y.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:l,level:c,id:h,groupId:u,deliveryDirectives:d}=i,A=Da(t,i),f=Fh(i),g=typeof i.level=="number"&&f===se.MAIN?c:void 0;if(!e.fragments.length){const m=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:F.LEVEL_EMPTY_ERROR,fatal:!1,url:A,error:m,reason:m.message,response:t,context:i,level:g,parent:f,networkDetails:r,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){o.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:F.LEVEL_PARSING_ERROR,fatal:!1,url:A,error:p,reason:p.message,response:t,context:i,level:g,parent:f,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ye.MANIFEST:case ye.LEVEL:o.trigger(y.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:d});break;case ye.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break;case ye.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break}}}function PA(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function kA(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){w.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){w.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function js(n){const e=n.mode;if(e==="disabled"&&(n.mode="hidden"),n.cues)for(let t=n.cues.length;t--;)n.removeCue(n.cues[t]);e==="disabled"&&(n.mode=e)}function Bo(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=h_(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function c_(n,e){if(e<n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t;for(;s<=i;){const r=Math.floor((i+s)/2);if(e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r}return n[s].startTime-e<e-n[i].startTime?s:i}function h_(n,e,t){const s=[],i=c_(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function $n(n){const e=[];for(let t=0;t<n.length;t++){const s=n[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(n[t])}return e}var ft={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const u_=.25;function To(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ph(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,JSON.stringify(i?$e({type:i},s):s))}return r}const kn=(()=>{const n=To();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function La(n,e){return n.getTime()/1e3-e}function d_(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class A_{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(js(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return PA(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=To();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===ft.emsg&&!s||!i)continue;const c=_A(r[o].data);if(c){const h=r[o].pts;let u=h+r[o].duration;u>kn&&(u=kn),u-h<=0&&(u=h+u_);for(let A=0;A<c.length;A++){const f=c[A];if(!SA(f)){this.updateId3CueEnds(h,l);const g=Ph(a,h,u,f,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===kn&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;i==="audio"?c=h=>h.type===ft.audioId3&&l:i==="video"?c=h=>h.type===ft.emsg&&o:c=h=>h.type===ft.audioId3&&l||h.type===ft.emsg&&o,Bo(r,t,s,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=t,a=Object.keys(r);if(i){const h=Object.keys(s).filter(u=>!a.includes(u));for(let u=h.length;u--;){const d=h[u];Object.keys(s[d].cues).forEach(A=>{i.removeCue(s[d].cues[A])}),delete s[d]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!W(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=To();for(let h=0;h<a.length;h++){const u=a[h],d=r[u],A=La(d.startDate,l),f=s[u],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1,m=kn;const C=d.endDate;if(C)m=La(C,l),p=!0;else if(d.endOnNext&&!p){const B=a.reduce((I,_)=>{if(_!==d.id){const S=r[_];if(S.class===d.class&&S.startDate>d.startDate&&(!I||d.startDate<I.startDate))return S}return I},null);B&&(m=La(B.startDate,l),p=!0)}const E=Object.keys(d.attr);for(let B=0;B<E.length;B++){const I=E[B];if(!ES(I))continue;const _=g[I];if(_)p&&!f.durationKnown&&(_.endTime=m);else if(c){let S=d.attr[I];CS(I)&&(S=d_(S));const x=Ph(c,A,m,{key:I,data:S},ft.dateRange);x&&(x.id=u,this.id3Track.addCue(x),g[I]=x)}}s[u]={cues:g,dateRange:d,durationKnown:p}}}}class f_{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&s||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*i);const h=i;return c+Math.min(this.stallCount*1,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,s=this.levelDetails;if(e===null||t===null||s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(y.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var s;t.details===F.BUFFER_STALLED_ERROR&&(this.stallCount++,(s=this.levelDetails)!=null&&s.live&&w.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||r===1||!t.live)return;const a=this.targetLatency;if(a===null)return;const o=s-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(h,Math.max(1,u))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const So=["NONE","TYPE-0","TYPE-1",null];function g_(n){return So.indexOf(n)>-1}const gr=["SDR","PQ","HLG"];function m_(n){return!!n&&gr.indexOf(n)>-1}var ji={No:"",Yes:"YES",v2:"v2"};function kh(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?ji.v2:ji.Yes:ji.No}class _o{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class bs{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Oh(this._audioGroups,e)}hasSubtitleGroup(e){return Oh(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Oh(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function ba(n,e){const t=e.startPTS;if(W(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&(i.duration=s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.start=n.start+(n.minEndPTS-n.start):e.start=n.start+n.duration:e.start=Math.max(n.start-e.duration,0)}function OA(n,e,t,s,i,r){s-t<=0&&(w.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,l=s;const c=e.startPTS,h=e.endPTS;if(W(c)){const p=Math.abs(c-t);W(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,o=Math.max(t,c),t=Math.min(t,c),i=Math.min(i,e.startDTS),l=Math.min(s,h),s=Math.max(s,h),r=Math.max(r,e.endDTS)}const u=t-e.start;e.start!==0&&(e.start=t),e.duration=s-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const d=e.sn;if(!n||d<n.startSN||d>n.endSN)return 0;let A;const f=d-n.startSN,g=n.fragments;for(g[f]=e,A=f;A>0;A--)ba(g[A],g[A-1]);for(A=f;A<g.length-1;A++)ba(g[A],g[A+1]);return n.fragmentHint&&ba(g[g.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,u}function p_(n,e){let t=null;const s=n.fragments;for(let o=s.length-1;o>=0;o--){const l=s[o].initSegment;if(l){t=l;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let i;I_(n,e,(o,l,c,h)=>{if(e.skippedSegments&&l.cc!==o.cc){const u=o.cc-l.cc;for(let d=c;d<h.length;d++)h[d].cc+=u}W(o.startPTS)&&W(o.endPTS)&&(l.start=l.startPTS=o.startPTS,l.startDTS=o.startDTS,l.maxStartPTS=o.maxStartPTS,l.endPTS=o.endPTS,l.endDTS=o.endDTS,l.minEndPTS=o.minEndPTS,l.duration=o.endPTS-o.startPTS,l.duration&&(i=l),e.PTSKnown=e.alignedSliding=!0),l.elementaryStreams=o.elementaryStreams,l.loader=o.loader,l.stats=o.stats,o.initSegment&&(l.initSegment=o.initSegment,t=o.initSegment)});const r=e.fragments;if(t&&(e.fragmentHint?r.concat(e.fragmentHint):r).forEach(l=>{var c;l&&(!l.initSegment||l.initSegment.relurl===((c=t)==null?void 0:c.relurl))&&(l.initSegment=t)}),e.skippedSegments){if(e.deltaUpdateFailed=r.some(o=>!o),e.deltaUpdateFailed){w.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let o=e.skippedSegments;o--;)r.shift();e.startSN=r[0].sn}else e.canSkipDateRanges&&(e.dateRanges=E_(n.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));e.startCC=e.fragments[0].cc,e.endCC=r[r.length-1].cc}C_(n.partList,e.partList,(o,l)=>{l.elementaryStreams=o.elementaryStreams,l.stats=o.stats}),i?OA(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):QA(n,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const o=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=o),e.driftEndTime=a,e.driftEnd=o}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime}function E_(n,e,t){const s=Ge({},n);return t&&t.forEach(i=>{delete s[i]}),Object.keys(e).forEach(i=>{const r=new ml(e[i].attr,s[i]);r.isValid?s[i]=r:w.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),s}function C_(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<=r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function I_(n,e,t){const s=e.skippedSegments,i=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let c=i;c<=r;c++){const h=l[a+c];let u=o[c];s&&!u&&c<s&&(u=e.fragments[c]=h),h&&u&&t(h,u,c,o)}}function QA(n,e){const t=e.startSN+e.skippedSegments-n.startSN,s=n.fragments;t<0||t>=s.length||xo(e,s[t].start)}function xo(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].start+=e;n.fragmentHint&&(n.fragmentHint.start+=e)}}function y_(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function B_(n,e,t){if(!(n!=null&&n.details))return null;const s=n.details;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function Qh(n,e,t){var s;return n!=null&&n.details?GA((s=n.details)==null?void 0:s.partList,e,t):null}function GA(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function UA(n){n.forEach((e,t)=>{const{details:s}=e;s!=null&&s.fragments&&s.fragments.forEach(i=>{i.level=t})})}function mr(n){switch(n.details){case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_TIMEOUT:case F.LEVEL_LOAD_TIMEOUT:case F.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Gh(n,e){const t=mr(e);return n.default[`${t?"timeout":"error"}Retry`]}function yl(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Uh(n){return $e($e({},n),{errorRetry:null,timeoutRetry:null})}function pr(n,e,t,s){if(!n)return!1;const i=s==null?void 0:s.code,r=e<n.maxNumRetry&&(T_(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function T_(n){return n===0&&navigator.onLine===!1||!!n&&(n<400||n>499)}const NA={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function S_(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!W(e))return null;const s=n[0].programDateTime;if(e<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;t=t||0;for(let r=0;r<n.length;++r){const a=n[r];if(x_(e,t,a))return a}return null}function Er(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[n.sn-e[0].sn+1]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&vo(t,s,r)===0||__(r,n,Math.min(i,s))))return r;const a=NA.search(e,vo.bind(null,t,s));return a&&(a!==n||!r)?a:r}function __(n,e,t){if(e&&e.start===0&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function vo(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function x_(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function v_(n,e){return NA.search(n,t=>t.cc<e?1:t.cc>e?-1:0)}var Ve={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ht={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class HA{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=w.log.bind(w,"[info]:"),this.warn=w.warn.bind(w,"[warning]:"),this.error=w.error.bind(w,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===se.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s,i;if(t.fatal)return;const r=this.hls,a=t.context;switch(t.details){case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case F.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction={action:Ve.DoNothing,flags:ht.None};return}case F.FRAG_GAP:case F.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ve.SendAlternateToPenaltyBox;return}case F.LEVEL_EMPTY_ERROR:case F.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===se.MAIN?t.level:r.loadLevel;t.details===F.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.SUBTITLE_LOAD_ERROR:case F.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=r.levels[r.loadLevel];if(c&&(a.type===ye.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===ye.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Ve.SendAlternateToPenaltyBox,t.errorAction.flags=ht.MoveAllAlternatesMatchingHost;return}}return;case F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],h=c==null?void 0:c.attrs["HDCP-LEVEL"];h?t.errorAction={action:Ve.SendAlternateToPenaltyBox,flags:ht.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(t)}return;case F.BUFFER_ADD_CODEC_ERROR:case F.REMUX_ALLOC_ERROR:case F.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(i=t.level)!=null?i:r.loadLevel);return;case F.INTERNAL_EXCEPTION:case F.BUFFER_APPENDING_ERROR:case F.BUFFER_FULL_ERROR:case F.LEVEL_SWITCH_ERROR:case F.BUFFER_STALLED_ERROR:case F.BUFFER_SEEK_OVER_HOLE:case F.BUFFER_NUDGE_ON_STALL:t.errorAction={action:Ve.DoNothing,flags:ht.None};return}t.type===re.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Gh(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(pr(i,r,mr(e),e.response))return{action:Ve.RetryRequest,flags:ht.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Gh(e.details.startsWith("key")?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==F.FRAG_GAP&&i.fragmentError++,pr(o,l,mr(e),e.response)))return{action:Ve.RetryRequest,flags:ht.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const c=e.details;i.loadError++,c===F.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:A,maxAutoLevel:f}=s;s.autoLevelEnabled||(s.loadLevel=-1);const g=(r=e.frag)==null?void 0:r.type,m=(g===se.AUDIO&&c===F.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===F.BUFFER_ADD_CODEC_ERROR||c===F.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:_})=>i.audioCodec!==_),E=e.sourceBufferName==="video"&&(c===F.BUFFER_ADD_CODEC_ERROR||c===F.BUFFER_APPEND_ERROR)&&u.some(({codecSet:_,audioCodec:S})=>i.codecSet!==_&&i.audioCodec===S),{type:B,groupId:I}=(a=e.context)!=null?a:{};for(let _=u.length;_--;){const S=(_+d)%u.length;if(S!==d&&S>=A&&S<=f&&u[S].loadError===0){var o,l;const x=u[S];if(c===F.FRAG_GAP&&g===se.MAIN&&e.frag){const b=u[S].details;if(b){const v=Er(e.frag,b.fragments,e.frag.start);if(v!=null&&v.gap)continue}}else{if(B===ye.AUDIO_TRACK&&x.hasAudioGroup(I)||B===ye.SUBTITLE_TRACK&&x.hasSubtitleGroup(I))continue;if(g===se.AUDIO&&(o=i.audioGroups)!=null&&o.some(b=>x.hasAudioGroup(b))||g===se.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(b=>x.hasSubtitleGroup(b))||m&&i.audioCodec===x.audioCodec||!m&&i.audioCodec!==x.audioCodec||E&&i.codecSet===x.codecSet)continue}h=S;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ve.SendAlternateToPenaltyBox,flags:ht.None,nextAutoLevel:h}}return{action:Ve.SendAlternateToPenaltyBox,flags:ht.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ve.DoNothing:break;case Ve.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==F.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case Ve.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:a}=s;switch(i){case ht.None:this.switchLevel(e,a);break;case ht.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=So[So.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(e,a)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Or{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=w.log.bind(w,`${t}:`),this.warn=w.warn.bind(w,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){w.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(a["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=s&&kh(s);return new _o(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||s!=null&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&p_(s,i),!this.canLoad||!i.live)return;let l,c,h;if(i.canBlockReload&&i.endSN&&i.advanced){const p=this.hls.config.lowLatencyMode,m=i.lastPartSn,C=i.endSN,E=i.lastPartIndex,B=E!==-1,I=m===C,_=p?0:E;B?(c=I?C+1:m,h=I?_:E+1):c=C+1;const S=i.age,x=S+i.ageHeader;let b=Math.min(x-i.partTarget,i.targetduration*1.5);if(b>0){if(s&&b>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${b} with playlist age: ${i.age}`),b=0;else{const v=Math.floor(b/i.targetduration);if(c+=v,h!==void 0){const D=Math.round(b%i.targetduration/i.partTarget);h+=D}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${S.toFixed(2)}s goal: ${b} skip sn ${v} to part ${h}`)}i.tuneInGoal=b}if(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h),p||!I){this.loadPlaylist(l);return}}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h));const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,A=(i.edge-d)*1e3,f=y_(i,A);i.updated&&a>this.requestScheduled+f&&(this.requestScheduled=r.loading.start),c!==void 0&&i.canBlockReload?this.requestScheduled=r.loading.first+f-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+f<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=f);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${e} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(e,t,s,i){let r=kh(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=ji.No),new _o(s,i,r)}checkRetry(e){const t=e.details,s=mr(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===Ve.RetryRequest||!i.resolved&&r===Ve.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=yl(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}class Ks{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class R_{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ks(e),this.fast_=new Ks(t),this.defaultTTFB_=i,this.ttfb_=new Ks(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ks(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ks(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ks(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const KA={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Nh={};function w_(n,e,t,s,i,r){const a=n.audioCodec?n.audioGroups:null,o=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,c=l?parseInt(l):o?1/0:2;let h=null;if(a!=null&&a.length)try{a.length===1&&a[0]?h=e.groups[a[0]].channels:h=a.reduce((u,d)=>{if(d){const A=e.groups[d];if(!A)throw new Error(`Audio track group ${d} not found`);Object.keys(A.channels).forEach(f=>{u[f]=(u[f]||0)+A.channels[f]})}return u},{2:0})}catch{return!0}return n.videoCodec!==void 0&&(n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!h&&W(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function D_(n,e,t){const s=n.videoCodec,i=n.audioCodec;if(!s||!i||!t)return Promise.resolve(KA);const r={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)),framerate:n.frameRate||30},a=n.videoRange;a!=="SDR"&&(r.transferFunction=a.toLowerCase());const o=s.split(",").map(l=>({type:"media-source",video:$e($e({},r),{},{contentType:cn(l,"video")})}));return i&&n.audioGroups&&n.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(h=>{if(h.groupId===l){const u=h.channels||"",d=parseFloat(u);W(d)&&d>2&&o.push.apply(o,i.split(",").map(A=>({type:"media-source",audio:{contentType:cn(A,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=L_(l);return Nh[c]||(Nh[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function L_(n){const{audio:e,video:t}=n,s=t||e;if(s){const i=s.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${i}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}function b_(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function M_(n,e){let t=!1,s=[];return n&&(t=n!=="SDR",s=[n]),e&&(s=e.allowedVideoRanges||gr.slice(0),t=e.preferHDR!==void 0?e.preferHDR:b_(),t?s=s.filter(i=>i!=="SDR"):s=["SDR"]),{preferHDR:t,allowedVideoRanges:s}}function F_(n,e,t,s,i){const r=Object.keys(n),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,l=a&&parseInt(a)===2;let c=!0,h=!1,u=1/0,d=1/0,A=1/0,f=0,g=[];const{preferHDR:p,allowedVideoRanges:m}=M_(e,i);for(let I=r.length;I--;){const _=n[r[I]];c=_.channels[2]>0,u=Math.min(u,_.minHeight),d=Math.min(d,_.minFramerate),A=Math.min(A,_.minBitrate);const S=m.filter(x=>_.videoRanges[x]>0);S.length>0&&(h=!0,g=S)}u=W(u)?u:0,d=W(d)?d:0;const C=Math.max(1080,u),E=Math.max(30,d);return A=W(A)?A:t,t=Math.max(A,t),h||(e=void 0,g=[]),{codecSet:r.reduce((I,_)=>{const S=n[_];if(_===I)return I;if(S.minBitrate>t)return Yt(_,`min bitrate of ${S.minBitrate} > current estimate of ${t}`),I;if(!S.hasDefaultAudio)return Yt(_,"no renditions with default or auto-select sound found"),I;if(o&&_.indexOf(o.substring(0,4))%5!==0)return Yt(_,`audio codec preference "${o}" not found`),I;if(a&&!l){if(!S.channels[a])return Yt(_,`no renditions with ${a} channel sound found (channels options: ${Object.keys(S.channels)})`),I}else if((!o||l)&&c&&S.channels[2]===0)return Yt(_,"no renditions with stereo sound found"),I;return S.minHeight>C?(Yt(_,`min resolution of ${S.minHeight} > maximum of ${C}`),I):S.minFramerate>E?(Yt(_,`min framerate of ${S.minFramerate} > maximum of ${E}`),I):g.some(x=>S.videoRanges[x]>0)?S.maxScore<f?(Yt(_,`max score of ${S.maxScore} < selected max of ${f}`),I):I&&(Ar(_)>=Ar(I)||S.fragmentError>n[I].fragmentError)?I:(f=S.maxScore,_):(Yt(_,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),I)},void 0),videoRanges:g,preferHDR:p,minFramerate:d,minBitrate:A}}function Yt(n,e){w.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function P_(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function k_(n,e,t,s){return n.slice(t,s+1).reduce((i,r)=>{if(!r.codecSet)return i;const a=r.audioGroups;let o=i[r.codecSet];o||(i[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,r.frameRate),o.maxScore=Math.max(o.maxScore,r.score),o.fragmentError+=r.fragmentError,o.videoRanges[r.videoRange]=(o.videoRanges[r.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const h=e.groups[c];h&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{o.channels[u]=(o.channels[u]||0)+h.channels[u]}))}),i},{})}function Gt(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(ai(n,i,t))return s}return-1}function ai(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,characteristics:o,default:l}=n,c=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||e.lang===r)&&(r===void 0||e.assocLang===a)&&(l===void 0||e.default===l)&&(c===void 0||e.forced===c)&&(o===void 0||O_(o,e.characteristics))&&(t===void 0||t(n,e))}function O_(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Vs(n,e){const{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Q_(n,e,t,s,i){const r=e[s],o=e.reduce((d,A,f)=>{const g=A.uri;return(d[g]||(d[g]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=Hh(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const A=d.audioGroups,f=t.filter(g=>!A||A.indexOf(g.groupId)!==-1);return Gt(n,f,i)>-1});return u>-1?u:Hh(e,s,d=>{const A=d.audioGroups,f=t.filter(g=>!A||A.indexOf(g.groupId)!==-1);return Gt(n,f,i)>-1})}function Hh(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}class VA{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:s,hls:i}=this,{autoLevelEnabled:r,media:a}=i;if(!t||!a)return;const o=performance.now(),l=s?s.stats:t.stats,c=s?s.duration:t.duration,h=o-l.loading.start,u=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||a.paused||!a.playbackRate||!a.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const A=this.bwEstimator.getEstimateTTFB(),f=Math.abs(a.playbackRate);if(h<=Math.max(A,1e3*(c/(f*2))))return;const g=d.len/f,p=l.loading.first?l.loading.first-l.loading.start:-1,m=l.loaded&&p>-1,C=this.getBwEstimate(),E=i.levels,B=E[t.level],I=l.total||Math.max(l.loaded,Math.round(c*B.averageBitrate/8));let _=m?h-p:h;_<1&&m&&(_=Math.min(h,l.loaded*8/C));const S=m?l.loaded*1e3/_:0,x=S?(I-l.loaded)/S:I*8/C+A/1e3;if(x<=g)return;const b=S?S*8:C;let v=Number.POSITIVE_INFINITY,D;for(D=t.level-1;D>u;D--){const Q=E[D].maxBitrate;if(v=this.getTimeToLoadFrag(A/1e3,b,c*Q,!E[D].details),v<g)break}if(v>=x||v>c*10)return;i.nextLoadLevel=i.nextAutoLevel=D,m?this.bwEstimator.sample(h-Math.min(A,p),l.loaded):this.bwEstimator.sampleTTFB(h);const U=E[D].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>U&&this.resetEstimator(U),this.clearTimer(),w.warn(`[abr] Fragment ${t.sn}${s?" part "+s.index:""} of level ${t.level} is loading too slowly;
|
|
11
|
+
Time to underbuffer: ${g.toFixed(3)} s
|
|
12
|
+
Estimated load time for current fragment: ${x.toFixed(3)} s
|
|
13
|
+
Estimated load time for down switch fragment: ${v.toFixed(3)} s
|
|
14
|
+
TTFB estimate: ${p|0} ms
|
|
15
|
+
Current BW estimate: ${W(C)?C|0:"Unknown"} bps
|
|
16
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
17
|
+
Switching to level ${D} @ ${U|0} bps`),i.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(w.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new R_(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case F.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,a=i?this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.start;W(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===se.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==se.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return w.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const p=this.findBestLevel(l,a,i,c,0,h,u);if(p>=0)return p}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const p=this.bitrateTestDelay;p&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-p,w.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const A=this.findBestLevel(l,a,i,c,d,h,u);if(w.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${A}`),A>-1)return A;const f=s.levels[a],g=s.levels[s.loadLevel];return(f==null?void 0:f.bitrate)<(g==null?void 0:g.bitrate)?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,a,o){var l;const c=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:A}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(f.length===1)return 0;const C=f[u],E=!!(C!=null&&(l=C.details)!=null&&l.live),B=p===-1||h===-1;let I,_="SDR",S=(C==null?void 0:C.frameRate)||0;const{audioPreference:x,videoPreference:b}=m,v=this.audioTracksByGroup||(this.audioTracksByGroup=P_(g));if(B){if(this.firstSelection!==-1)return this.firstSelection;const V=this.codecTiers||(this.codecTiers=k_(f,v,t,s)),X=F_(V,_,e,x,b),{codecSet:Z,videoRanges:ae,minFramerate:Y,minBitrate:G,preferHDR:H}=X;I=Z,_=H?ae[ae.length-1]:ae[0],S=Y,e=Math.max(e,G),w.log(`[abr] picked start tier ${JSON.stringify(X)}`)}else I=C==null?void 0:C.codecSet,_=C==null?void 0:C.videoRange;const D=A?A.duration:d?d.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,Q=[];for(let V=s;V>=t;V--){var j;const X=f[V],Z=V>u;if(!X)continue;if(m.useMediaCapabilities&&!X.supportedResult&&!X.supportedPromise){const R=navigator.mediaCapabilities;typeof(R==null?void 0:R.decodingInfo)=="function"&&w_(X,v,_,S,e,x)?(X.supportedPromise=D_(X,v,R),X.supportedPromise.then(te=>{if(!this.hls)return;X.supportedResult=te;const oe=this.hls.levels,ue=oe.indexOf(X);te.error?w.warn(`[abr] MediaCapabilities decodingInfo error: "${te.error}" for level ${ue} ${JSON.stringify(te)}`):te.supported||(w.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${ue} ${JSON.stringify(te)}`),ue>-1&&oe.length>1&&(w.log(`[abr] Removing unsupported level ${ue}`),this.hls.removeLevel(ue)))})):X.supportedResult=KA}if(I&&X.codecSet!==I||_&&X.videoRange!==_||Z&&S>X.frameRate||!Z&&S>0&&S<X.frameRate||X.supportedResult&&!((j=X.supportedResult.decodingInfoResults)!=null&&j[0].smooth)){Q.push(V);continue}const ae=X.details,Y=(A?ae==null?void 0:ae.partTarget:ae==null?void 0:ae.averagetargetduration)||D;let G;Z?G=o*e:G=a*e;const H=D&&i>=D*2&&r===0?f[V].averageBitrate:f[V].maxBitrate,J=this.getTimeToLoadFrag(U,G,H*Y,ae===void 0);if(G>=H&&(V===h||X.loadError===0&&X.fragmentError===0)&&(J<=U||!W(J)||E&&!this.bitrateTestDelay||J<c)){const R=this.forcedAutoLevel;return V!==p&&(R===-1||R!==p)&&(Q.length&&w.trace(`[abr] Skipped level(s) ${Q.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[Q[0]].codecs}" ${f[Q[0]].videoRange}; not compatible with "${C.codecs}" ${_}`),w.info(`[abr] switch candidate:${u}->${V} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-H)} ttfb:${U.toFixed(1)} avgDuration:${Y.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${J.toFixed(1)} firstSelection:${B} codecSet:${I} videoRange:${_} hls.loadLevel:${p}`)),B&&(this.firstSelection=V),V}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls,i=Math.min(Math.max(e,s),t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}}class G_{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var qe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class U_{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;const a=r.end;if(r.start<=e&&a!==null&&e<=a)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const a=s[i[r]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,s,i){this.timeRanges&&(this.timeRanges[e]=t);const r=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===s&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return h&&this.removeFragment(o.body),h})})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i}=e;if(!t||s.sn==="initSegment")return;const r=Ys(s),a=this.fragments[r];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(l=>{const c=s.elementaryStreams[l];if(!c)return;const h=t[l],u=o||c.partial===!0;a.range[l]=this.getBufferedTimes(s,i,u,h)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=s.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),On(a)||this.removeParts(s.sn-1,s.type)):this.removeFragment(a.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=s.filter(i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ys(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){const A=Math.max(a,i.start(h)),f=Math.min(o,i.end(h));f>A&&(r.partial=!0,r.time.push({startPTS:A,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&On(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||On(t))}getState(e){const t=Ys(e),s=this.fragments[t];return s?s.buffered?On(s)?qe.PARTIAL:qe.OK:qe.APPENDING:qe.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onFragLoaded(e,t){const{frag:s,part:i}=t;if(s.sn==="initSegment"||s.bitrateTest)return;const r=i?null:t,a=Ys(s);this.fragments[a]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(s.sn==="initSegment")return;const a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,a,i)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ys(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Ys(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=s.filter(r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function On(n){var e,t,s;return n.buffered&&(n.body.gap||((e=n.range.video)==null?void 0:e.partial)||((t=n.range.audio)==null?void 0:t.partial)||((s=n.range.audiovideo)==null?void 0:s.partial))}function Ys(n){return`${n.type}_${n.level}_${n.sn}`}const N_={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){try{if(e){const s=Le.getBuffered(e);for(let i=0;i<s.length;i++)if(t>=s.start(i)&&t<=s.end(i))return!0}}catch{}return!1}static bufferInfo(e,t,s){try{if(e){const i=Le.getBuffered(e),r=[];let a;for(a=0;a<i.length;a++)r.push({start:i.start(a),end:i.end(a)});return this.bufferedInfo(r,t,s)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.sort(function(c,h){const u=c.start-h.start;return u||h.end-c.end});let i=[];if(s)for(let c=0;c<e.length;c++){const h=i.length;if(h){const u=i[h-1].end;e[c].start-u<s?e[c].end>u&&(i[h-1].end=e[c].end):i.push(e[c])}else i.push(e[c])}else i=e;let r=0,a,o=t,l=t;for(let c=0;c<i.length;c++){const h=i[c].start,u=i[c].end;if(t+s>=h&&t<u)o=h,l=u,r=l-t;else if(t+s<h){a=h;break}}return{len:r,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return w.log("failed to get media.buffered",t),N_}}}class Qr{constructor(e,t,s,i=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Qn(),this.buffering={audio:Qn(),video:Qn(),audiovideo:Qn()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}}function Qn(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Xn(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function H_(n,e,t){return!!(e&&(t.endCC>t.startCC||n&&n.cc<t.startCC))}function K_(n,e){const t=n.fragments,s=e.fragments;if(!s.length||!t.length){w.log("No fragments to align");return}const i=Xn(t,s[0].cc);if(!i||i&&!i.startPTS){w.log("No frag in previous level to align on");return}return i}function Kh(n,e){if(n){const t=n.start+e;n.start=n.startPTS=t,n.endPTS=t+n.duration}}function YA(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Kh(t[s],n);e.fragmentHint&&Kh(e.fragmentHint,n),e.alignedSliding=!0}function V_(n,e,t){e&&(Y_(n,t,e),!t.alignedSliding&&e&&Cr(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&QA(e,t))}function Y_(n,e,t){if(H_(n,t,e)){const s=K_(t,e);s&&W(s.start)&&(w.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),YA(s.start,e))}}function Cr(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const t=n.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(i=Xn(s,a),r=Xn(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Xn(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-i.start);YA(c,n)}const Vh=Math.pow(2,17);class J_{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Xt({type:re.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(A=>A[0]==="GAP")){l(Jh(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(i):new a(i),h=Yh(e),u=Uh(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Vh};e.stats=c.stats,c.load(h,d,{onSuccess:(A,f,g,p)=>{this.resetLoader(e,c);let m=A.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(m.slice(0,16)),m=m.slice(16)),o({frag:e,part:null,payload:m,networkDetails:p})},onError:(A,f,g,p)=>{this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:$e({url:s,data:void 0},A),error:new Error(`HTTP Error ${A.code} ${A.text}`),networkDetails:g,stats:p}))},onAbort:(A,f,g)=>{this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:A}))},onTimeout:(A,f,g)=>{this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:A}))},onProgress:(A,f,g,p)=>{t&&t({frag:e,part:null,payload:g,networkDetails:p})}})})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Jh(e,t));return}const c=this.loader=e.loader=r?new r(i):new a(i),h=Yh(e,t),u=Uh(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Vh};t.stats=c.stats,c.load(h,d,{onSuccess:(A,f,g,p)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const m={frag:e,part:t,payload:A.data,networkDetails:p};s(m),o(m)},onError:(A,f,g,p)=>{this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:$e({url:h.url,data:void 0},A),error:new Error(`HTTP Error ${A.code} ${A.text}`),networkDetails:g,stats:p}))},onAbort:(A,f,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:A}))},onTimeout:(A,f,g)=>{this.resetLoader(e,c),l(new Xt({type:re.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:A}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Yh(n,e=null){const t=e||n,s={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(W(i)&&W(r)){var a;let o=i,l=r;if(n.sn==="initSegment"&&((a=n.decryptdata)==null?void 0:a.method)==="AES-128"){const c=r-i;c%16&&(l=r+(16-c%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=l}return s}function Jh(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:re.MEDIA_ERROR,details:F.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new Xt(s)}class Xt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class z_{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class q_{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function $_(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?ws(n,0,e-t):n}class X_{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],A=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?A[p]=p<<1:A[p]=p<<1^283;for(p=0;p<256;p++){let m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^m&255^99,e[f]=m,t[m]=f;const C=A[f],E=A[C],B=A[E];let I=A[m]*257^m*16843008;i[f]=I<<24|I>>>8,r[f]=I<<16|I>>>16,a[f]=I<<8|I>>>24,o[f]=I,I=B*16843009^E*65537^C*257^f*16843008,c[m]=I<<24|I>>>8,h[m]=I<<16|I>>>16,u[m]=I<<8|I>>>24,d[m]=I,f?(f=C^A[A[A[B^C]]],g^=A[A[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,A=this.invSubMix,f=A[0],g=A[1],p=A[2],m=A[3];let C,E;for(o=0;o<a;o++){if(o<r){C=c[o]=t[o];continue}E=C,o%r===0?(E=E<<8|E>>>24,E=u[E>>>24]<<24|u[E>>>16&255]<<16|u[E>>>8&255]<<8|u[E&255],E^=d[o/r|0]<<24):r>6&&o%r===4&&(E=u[E>>>24]<<24|u[E>>>16&255]<<16|u[E>>>8&255]<<8|u[E&255]),c[o]=C=(c[o-r]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=c[o]:E=c[o-4],l<4||o<=4?h[l]=E:h[l]=f[u[E>>>24]]^g[u[E>>>16&255]]^p[u[E>>>8&255]]^m[u[E&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let A=d[0],f=d[1],g=d[2],p=d[3];const m=new Int32Array(e),C=new Int32Array(m.length);let E,B,I,_,S,x,b,v,D,U,Q,j,V,X;const Z=this.networkToHostOrderSwap;for(;t<m.length;){for(D=Z(m[t]),U=Z(m[t+1]),Q=Z(m[t+2]),j=Z(m[t+3]),S=D^r[0],x=j^r[1],b=Q^r[2],v=U^r[3],V=4,X=1;X<i;X++)E=l[S>>>24]^c[x>>16&255]^h[b>>8&255]^u[v&255]^r[V],B=l[x>>>24]^c[b>>16&255]^h[v>>8&255]^u[S&255]^r[V+1],I=l[b>>>24]^c[v>>16&255]^h[S>>8&255]^u[x&255]^r[V+2],_=l[v>>>24]^c[S>>16&255]^h[x>>8&255]^u[b&255]^r[V+3],S=E,x=B,b=I,v=_,V=V+4;E=a[S>>>24]<<24^a[x>>16&255]<<16^a[b>>8&255]<<8^a[v&255]^r[V],B=a[x>>>24]<<24^a[b>>16&255]<<16^a[v>>8&255]<<8^a[S&255]^r[V+1],I=a[b>>>24]<<24^a[v>>16&255]<<16^a[S>>8&255]<<8^a[x&255]^r[V+2],_=a[v>>>24]<<24^a[S>>16&255]<<16^a[x>>8&255]<<8^a[b&255]^r[V+3],C[t]=Z(E^A),C[t+1]=Z(_^f),C[t+2]=Z(I^g),C[t+3]=Z(B^p),A=D,f=U,g=Q,p=j,t=t+4}return C.buffer}}const j_=16;class Bl{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?$_(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s){return this.useSoftware?new Promise((i,r)=>{this.softwareDecrypt(new Uint8Array(e),t,s);const a=this.flush();a?i(a.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s)}softwareDecrypt(e,t,s){const{currentIV:i,currentResult:r,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=Et(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new X_),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=ws(o,-16).buffer,c||null}webCryptoDecrypt(e,t,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s));this.key=t,this.fastAesKey=new q_(this.subtle,t)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new z_(this.subtle,new Uint8Array(s)).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(w.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s)))}onWebCryptoError(e,t,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%j_;return s!==e.length&&(t=ws(e,0,s),this.remainderData=ws(e,s)),t}logOnce(e){this.logEnabled&&(w.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const W_={toString:function(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}},N={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Gr extends G_{constructor(e,t,s,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=N.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=w.log.bind(w,`${i}:`),this.warn=w.warn.bind(w,`${i}:`),this.hls=e,this.fragmentLoader=new J_(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Bl(e.config),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=N.STOPPED}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const s=t.partList;if(s!=null&&s.length){const r=s[s.length-1];return Le.isBuffered(this.media,r.start+r.duration/2)}const i=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===N.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,a=s?s.currentTime:0,o=Le.bufferInfo(i||s,a,e.maxBufferHole);if(this.log(`media seeking to ${W(a)?a.toFixed(3):a}, state: ${r}`),this.state===N.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,h=t.start+t.duration+l;if(!o.len||h<o.start||c>o.end){const u=a>h;(a<c||u)&&(u&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=N.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const a=this.state;if(this.fragContextChanged(e)){(a===N.FRAG_LOADING||!this.fragCurrent&&a===N.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=N.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(y.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===N.STOPPED||this.state===N.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===qe.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===qe.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(y.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{if(!s||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{payload:r}=s,a=e.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer).catch(l=>{throw i.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return i.trigger(y.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===N.STOPPED||this.state===N.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state=N.IDLE,e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var s,i,r,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===se.MAIN?"level":"track"} ${e.level} (frag:[${((s=e.startPTS)!=null?s:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${o?W_.toString(Le.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==se.SUBTITLE){const h=e.elementaryStreams;if(!Object.keys(h).some(u=>!!h[u])){this.state=N.IDLE;return}}const c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=N.IDLE,o&&(!this.loadedmetadata&&e.type==se.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(l=>!l),o=new Qr(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;const a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=N.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(y.KEY_LOADED,h),this.state===N.KEY_LOADING&&(this.state=N.IDLE),h}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),s=Math.max(e.start,s||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const h=a.partList;if(h&&i){s>e.end&&a.fragmentHint&&(e=a.fragmentHint);const u=this.getNextPart(h,e,s);if(u>-1){const d=h[u];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${u}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=N.FRAG_LOADING;let A;return o?A=o.then(f=>!f||this.fragContextChanged(f.frag)?null:this.doFragPartsLoad(e,d,t,i)).catch(f=>this.handleFragLoadError(f)):A=this.doFragPartsLoad(e,d,t,i).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:d,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):A}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),W(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=N.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(h=>!h||this.fragContextChanged(h==null?void 0:h.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([h])=>(!l&&h&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const l=[],c=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;const A=d.part;this.hls.trigger(y.FRAG_LOADED,d);const f=Qh(s,e.sn,u.index+1)||GA(c,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:A,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===F.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==N.PARSING){!this.fragCurrent&&this.state!==N.STOPPED&&this.state!==N.ERROR&&(this.state=N.IDLE);return}const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(s,i,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const o=t[i],l=a>-1?Qh(o,r,a):null,c=l?l.fragment:B_(o,r,s);return c?(s&&s!==c&&(c.stats=s.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var a;if(!e||this.state!==N.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=Et(o,l)),!((a=c)!=null&&a.length))return;const h={type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:c};if(this.hls.trigger(y.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=Le.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const s=this.getLoadPosition();return W(s)?this.getFwdBufferInfoAtPos(e,s,t):null}getFwdBufferInfoAtPos(e,t,s){const{config:{maxBufferHole:i}}=this,r=Le.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&r.nextStart<a.end)return Le.bufferInfo(e,t,Math.max(r.nextStart,i))}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=se.MAIN){const s=this.fragmentTracker.getAppendedFrag(e,se.MAIN);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=s[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a)&&(o=this.getInitialLiveFragment(t,s),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=s[0]);if(!o){const l=r.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===qe.OK||s===qe.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&s.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(l!==null&&s.len+l.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,i>-1&&s<c.start)break;const h=c.loaded;h?i=-1:(r||c.independent||a)&&c.fragment===t&&(i=o),r=h}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=S_(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=v_(t,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(i.lowLatencyMode&&h!=null&&h.length&&l);u&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let d;if(e<t){const A=e>t-c?0:c;d=Er(r,a,e,A)}else d=a[a.length-1];if(d){const A=d.sn-s.startSN,f=this.fragmentTracker.getState(d);if((f===qe.OK||f===qe.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn)&&r&&d.level===r.level){const p=a[A+1];d.sn<o&&this.fragmentTracker.getState(p)!==qe.OK?d=p:d=null}}return d}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=s.currentTime,a=e.fragments[0].start,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&s.readyState<4||r<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,a=!t,o=e.alignedSliding&&W(r);if(a||!o&&!r){const{fragPrevious:l}=this;V_(l,s,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;if(s<t&&(s=-1),s===-1||this.lastCurrentTime===-1){const i=this.startTimeOffset!==null,r=i?this.startTimeOffset:e.startTimeOffset;r!==null&&W(r)?(s=t+r,r<0&&(s+=e.totalduration),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):e.live?s=this.hls.liveSyncPosition||t:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==N.FRAG_LOADING_WAITING_RETRY)&&(this.state=N.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const h=this.getCurrentContext(t.chunkMeta);h&&(t.frag=h.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const r=t.details===F.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===Ve.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=yl(c,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),a.resolved=!0,this.retryDate=self.performance.now()+h,this.state=N.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(e),l<c.maxNumRetry)!r&&o!==Ve.RemoveAlternatePermanently&&(a.resolved=!0);else{w.warn(`${t.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.action)===Ve.SendAlternateToPenaltyBox?this.state=N.WAITING_LEVEL:this.state=N.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===N.PARSING||this.state===N.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===se.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==N.STOPPED&&(this.state=N.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===N.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=N.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){var r;const a=s.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const h=e.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const d=i?0:OA(a,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:a,level:s,drift:d,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)&&((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(s.fragmentError===0&&(s.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=N.PARSED,this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class JA{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Z_(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Z_(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}function ex(){return typeof __HLS_WORKER_BUNDLE__=="function"}function tx(){const n=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(n);return{worker:new self.Worker(e),objectURL:e}}function sx(n){const e=new self.URL(n,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ot(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Tl{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Et(this.cachedData,e),this.cachedData=null);let s=ln(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,l=s?Il(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&W(l))&&(this.basePTS=ix(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ft.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else xS(e,i)?(s=ln(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ft.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const h=ws(e,r);this.cachedData?this.cachedData=Et(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:Ot(),id3Track:o,textTrack:Ot()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ot(),id3Track:this._id3Track,textTrack:Ot()}}destroy(){}}const ix=(n,e,t)=>{if(W(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};function nx(n,e,t,s){let i,r,a,o;const l=navigator.userAgent.toLowerCase(),c=s,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[t+2]&192)>>>6)+1;const u=(e[t+2]&60)>>>2;if(u>h.length-1){const d=new Error(`invalid ADTS sampling index:${u}`);n.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,w.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,o=new Array(4),r=u-3):(i=2,o=new Array(2),r=u):l.indexOf("android")!==-1?(i=2,o=new Array(2),r=u):(i=5,o=new Array(4),s&&(s.indexOf("mp4a.40.29")!==-1||s.indexOf("mp4a.40.5")!==-1)||!s&&u>=6?r=u-3:((s&&s.indexOf("mp4a.40.2")!==-1&&(u>=6&&a===1||/vivaldi/i.test(l))||!s&&a===1)&&(i=2,o=new Array(2)),r=u)),o[0]=i<<3,o[0]|=(u&14)>>1,o[1]|=(u&1)<<7,o[1]|=a<<3,i===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:a,codec:"mp4a.40."+i,manifestCodec:c}}function zA(n,e){return n[e]===255&&(n[e+1]&246)===240}function qA(n,e){return n[e+1]&1?7:9}function Sl(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function rx(n,e){return e+5<n.length}function Ir(n,e){return e+1<n.length&&zA(n,e)}function ax(n,e){return rx(n,e)&&zA(n,e)&&Sl(n,e)<=n.length-e}function ox(n,e){if(Ir(n,e)){const t=qA(n,e);if(e+t>=n.length)return!1;const s=Sl(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Ir(n,i)}return!1}function $A(n,e,t,s,i){if(!n.samplerate){const r=nx(e,t,s,i);if(!r)return;n.config=r.config,n.samplerate=r.samplerate,n.channelCount=r.channelCount,n.codec=r.codec,n.manifestCodec=r.manifestCodec,w.log(`parsed codec:${n.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function XA(n){return 1024*9e4/n}function lx(n,e){const t=qA(n,e);if(e+t<=n.length){const s=Sl(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function jA(n,e,t,s,i){const r=XA(n.samplerate),a=s+i*r,o=lx(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,A=d+u,f=Math.max(0,t+A-e.length);f?(l=new Uint8Array(A-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+A);const g={unit:l,pts:a};return f||n.samples.push(g),{sample:g,length:A,missing:f}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Gn=null;const cx=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],hx=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ux=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],dx=[0,1,1,4];function WA(n,e,t,s,i){if(t+24>e.length)return;const r=ZA(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function ZA(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-s:s===3?3:4,c=cx[l*14+i-1]*1e3,u=hx[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,A=ux[t][s],f=dx[s],g=A*8*f,p=Math.floor(A*c/u+a)*f;if(Gn===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gn=E?parseInt(E[1]):0}return!!Gn&&Gn<=87&&s===2&&c>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:p,samplesPerFrame:g}}}function _l(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function ef(n,e){return e+1<n.length&&_l(n,e)}function Ax(n,e){return _l(n,e)&&4<=n.length-e}function tf(n,e){if(e+1<n.length&&_l(n,e)){const s=ZA(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||ef(n,r)}return!1}class fx extends Tl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ln(e,0);let s=(t==null?void 0:t.length)||0;if(tf(e,s))return!1;for(let i=e.length;s<i;s++)if(ox(e,s))return w.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ax(e,t)}appendFrame(e,t,s){$A(e,this.observer,t,s,e.manifestCodec);const i=jA(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const gx=/\/emsg[-/]ID3/i;class mx{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ot("video",1),a=this.audioTrack=Ot("audio",1),o=this.txtTrack=Ot("text",1);if(this.id3Track=Ot("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=wA(e);if(l.video){const{id:c,timescale:h,codec:u}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=xA.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return PS(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Et(this.remainderData,e));const o=KS(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return r.samples=Ih(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ih(e,t),{videoTrack:t,audioTrack:Ot(),id3Track:i,textTrack:Ot()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=fe(e.samples,["emsg"]);i&&i.forEach(r=>{const a=JS(r);if(gx.test(a.schemeIdUri)){const o=W(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:ft.emsg,duration:l})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const sf=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class px extends Tl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=nf(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=ln(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Il(t)!==void 0&&sf(e,s)<16}}function nf(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const A=(e[t+6]<<8|e[t+7])>>12-d&1,g=[2,1,2,3,3,4,4,5][u]+A,p=e[t+5]>>3,m=e[t+5]&7,C=new Uint8Array([r<<6|p<<1|m>>2,(m&3)<<6|u<<3|A<<2|l>>4,l<<4&224]),E=1536/o*9e4,B=s+i*E,I=e.subarray(t,t+h);return n.config=C,n.channelCount=g,n.samplerate=o,n.samples.push({unit:I,pts:B}),h}class Ex{constructor(){this.VideoSample=null}createVideoSample(e,t,s,i){return{key:e,frame:!1,pts:t,dts:s,units:[],debug:i,length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&w.log(e.pts+"/"+e.dts+":"+e.debug)}}class zh{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&w.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,s=8,i;for(let r=0;r<e;r++)s!==0&&(i=this.readEG(),s=(t+i+256)%256),t=s===0?t:s}readSPS(){let e=0,t=0,s=0,i=0,r,a,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),A=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const p=l();if(c(5),d(3),l(),f(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const _=h();if(_===3&&d(1),f(),f(),d(1),u())for(a=_!==3?8:12,o=0;o<a;o++)u()&&(o<6?g(16):g(64))}f();const m=h();if(m===0)h();else if(m===1)for(d(1),A(),A(),r=h(),o=0;o<r;o++)A();f(),d(1);const C=h(),E=h(),B=c(1);B===0&&d(1),d(1),u()&&(e=h(),t=h(),s=h(),i=h());let I=[1,1];if(u()&&u())switch(l()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((C+1)*16-e*2-t*2),height:(2-B)*(E+1)*16-(B?2:4)*(s+i),pixelRatio:I}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Cx extends Ex{parseAVCPES(e,t,s,i,r){const a=this.parseAVCNALu(e,s.data);let o=this.VideoSample,l,c=!1;s.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),a.forEach(h=>{var u;switch(h.type){case 1:{let g=!1;l=!0;const p=h.data;if(c&&p.length>4){const m=new zh(p).readSliceType();(m===2||m===4||m===7||m===9)&&(g=!0)}if(g){var d;(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,LA(h.data,1,s.pts,t.samples);break}case 7:{var A,f;l=!0,c=!0;const g=h.data,m=new zh(g).readSPS();if(!e.sps||e.width!==m.width||e.height!==m.height||((A=e.pixelRatio)==null?void 0:A[0])!==m.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[g],e.duration=r;const C=g.subarray(1,4);let E="avc1.";for(let B=0;B<3;B++){let I=C[B].toString(16);I.length<2&&(I="0"+I),E+=I}e.codec=E}break}case 8:l=!0,e.pps=[h.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+h.type+" ");break}o&&l&&o.units.push(h)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const s=t.byteLength;let i=e.naluState||0;const r=i,a=[];let o=0,l,c,h,u=-1,d=0;for(i===-1&&(u=0,d=t[0]&31,i=0,o=1);o<s;){if(l=t[o++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(c=o-i-1,u>=0){const A={data:t.subarray(u,c),type:d};a.push(A)}else{const A=this.getLastNalUnit(e.samples);A&&(r&&o<=4-r&&A.state&&(A.data=A.data.subarray(0,A.data.byteLength-r)),c>0&&(A.data=Et(A.data,t.subarray(0,c)),A.state=0))}o<s?(h=t[o]&31,u=o,d=h,i=0):i=-1}else i=0}if(u>=0&&i>=0){const A={data:t.subarray(u,s),type:d,state:i};a.push(A)}if(a.length===0){const A=this.getLastNalUnit(e.samples);A&&(A.data=Et(A.data,t))}return e.naluState=i,a}}class Ix{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Bl(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=bA(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}const ze=188;class os{constructor(e,t,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.videoParser=new Cx}static probe(e){const t=os.syncOffset(e);return t>0&&w.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let s=Math.min(ze*5,t-ze)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<t;l+=ze)if(e[l]===71&&(t-l===ze||e[l+ze]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+ze*99,e.length-ze)+1)),r||(r=Ro(e,l)===0),r&&o>1&&(a===0&&o>2||l+ze>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:xA[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=os.createTrack("video"),this._audioTrack=os.createTrack("audio",i),this._id3Track=os.createTrack("id3"),this._txtTrack=os.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,A=l.pid,f=o.pesData,g=l.pesData,p=null,m=this.pmtParsed,C=this._pmtId,E=e.length;if(this.remainderData&&(e=Et(this.remainderData,e),E=e.length,this.remainderData=null),E<ze&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const B=Math.max(0,os.syncOffset(e));E-=(E-B)%ze,E<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let I=0;for(let S=B;S<E;S+=ze)if(e[S]===71){const x=!!(e[S+1]&64),b=Ro(e,S),v=(e[S+3]&48)>>4;let D;if(v>1){if(D=S+5+e[S+4],D===S+ze)continue}else D=S+4;switch(b){case h:x&&(u&&(r=Js(u))&&this.videoParser.parseAVCPES(a,c,r,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(e.subarray(D,S+ze)),u.size+=S+ze-D);break;case d:if(x){if(f&&(r=Js(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(D,S+ze)),f.size+=S+ze-D);break;case A:x&&(g&&(r=Js(g))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(D,S+ze)),g.size+=S+ze-D);break;case 0:x&&(D+=e[D]+1),C=this._pmtId=yx(e,D);break;case C:{x&&(D+=e[D]+1);const U=Bx(e,D,this.typeSupported,s,this.observer);h=U.videoPid,h>0&&(a.pid=h,a.segmentCodec=U.segmentVideoCodec),d=U.audioPid,d>0&&(o.pid=d,o.segmentCodec=U.segmentAudioCodec),A=U.id3Pid,A>0&&(l.pid=A),p!==null&&!m&&(w.warn(`MPEG-TS PMT found at ${S} after unknown PID '${p}'. Backtracking to sync byte @${B} to parse all TS packets.`),p=null,S=B-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=b;break}}else I++;I>0&&yr(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`)),a.pesData=u,o.pesData=f,l.pesData=g;const _={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(_),_}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,a=s.pesData,o=t.pesData,l=i.pesData;let c;if(a&&(c=Js(a))?(this.videoParser.parseAVCPES(s,r,c,!0,this._duration),s.pesData=null):s.pesData=a,o&&(c=Js(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&w.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=Js(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new Ix(this.observer,this.config,t);return this.decrypt(i,r)}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=Et(i.sample.unit,r);else{const A=d-u;i.sample.unit.set(r.subarray(0,u),A),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=r.length;a<o-1&&!Ir(r,a);a++);if(a!==s){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",yr(this.observer,new Error(u),d),!d)return}$A(e,this.observer,r,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(i){const u=XA(e.samplerate);l=i.sample.pts+u}else{w.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;a<o;)if(h=jA(e,r,a,l,c),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;a<o-1&&!Ir(r,a);a++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(o===void 0){w.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(ef(s,a)){const l=WA(e,s,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){w.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,l;for(;o<r&&(l=nf(e,s,o,i,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){w.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=Ge({},t,{type:this._videoTrack?ft.emsg:ft.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Ro(n,e){return((n[e+1]&31)<<8)+n[e+2]}function yx(n,e){return(n[e+10]&31)<<8|n[e+11]}function Bx(n,e,t,s,i){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(n[e+1]&15)<<8|n[e+2],o=e+3+a-4,l=(n[e+10]&15)<<8|n[e+11];for(e+=12+l;e<o;){const c=Ro(n,e),h=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){Ma("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=c);break;case 21:r.id3Pid===-1&&(r.id3Pid=c);break;case 219:if(!s){Ma("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=c,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?w.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="mp3");break;case 193:if(!s){Ma("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="ac3"):w.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&h>0){let u=e+5,d=h;for(;d>2;){switch(n[u]){case 106:t.ac3!==!0?w.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3");break}const f=n[u+1]+2;u+=f,d-=f}}break;case 194:case 135:return yr(i,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return yr(i,new Error("Unsupported HEVC in M2TS found")),r}e+=h+5}return r}function yr(n,e,t){w.warn(`parsing error: ${e.message}`),n.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Ma(n){w.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Js(n){let e=0,t,s,i,r,a;const o=n.data;if(!n||n.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Et(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(s=(t[4]<<8)+t[5],s&&s>n.size-6)return null;const c=t[7];c&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-a>60*9e4&&(w.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),i=t[8];let h=i+9;if(n.size<=h)return null;n.size-=h;const u=new Uint8Array(n.size);for(let d=0,A=o.length;d<A;d++){t=o[d];let f=t.byteLength;if(h)if(h>f){h-=f;continue}else t=t.subarray(h),f-=h,h=0;u.set(t,e),e+=f}return s&&(s-=i+3),{data:u,pts:r,dts:a,len:s}}return null}class Tx extends Tl{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ln(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Il(t)!==void 0&&sf(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(tf(e,s))return w.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Ax(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return WA(e,t,s,this.basePTS,this.frameIndex)}}class qh{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const rs=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,l,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(rs+1)),i=Math.floor(t%(rs+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale,e.duration),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale,e[0].duration)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(rs+1)),i=Math.floor(t%(rs+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,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,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?L.box(L.types.stsd,L.STSD,L.mp3(e)):e.segmentCodec==="ac3"?L.box(L.types.stsd,L.STSD,L.ac3(e)):L.box(L.types.stsd,L.STSD,L.mp4a(e)):L.box(L.types.stsd,L.STSD,L.avc1(e))}static tkhd(e){const t=e.id,s=e.duration*e.timescale,i=e.width,r=e.height,a=Math.floor(s/(rs+1)),o=Math.floor(s%(rs+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(rs+1)),a=Math.floor(t%(rs+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)l=s[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,a)}static initSegment(e){L.types||L.init();const t=L.moov(e);return Et(L.FTYP,t)}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const rf=9e4;function xl(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function Sx(n,e,t=1,s=!1){return xl(n,e,1/t,s)}function Ui(n,e=!1){return xl(n,1e3,1/rf,e)}function _x(n,e=1){return xl(n,rf,1/e)}const xx=10*1e3,$h=1024,vx=1152,Rx=1536;let zs=null,Fa=null;class jn{constructor(e,t,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,zs===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);zs=a?parseInt(a[1]):0}if(Fa===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Fa=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){w.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){w.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){w.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=dt(o,s),l=o-r),l>0?r:o},s);return t&&w.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,l){let c,h,u,d,A,f,g=r,p=r;const m=e.pid>-1,C=t.pid>-1,E=t.samples.length,B=e.samples.length>0,I=o&&E>0||E>1;if((!m||B)&&(!C||I)||this.ISGenerated||o){if(this.ISGenerated){var S,x,b,v;const j=this.videoTrackConfig;j&&(t.width!==j.width||t.height!==j.height||((S=t.pixelRatio)==null?void 0:S[0])!==((x=j.pixelRatio)==null?void 0:x[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((v=j.pixelRatio)==null?void 0:v[1]))&&this.resetInitSegment()}else u=this.generateIS(e,t,r,a);const D=this.isVideoContiguous;let U=-1,Q;if(I&&(U=wx(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,U>0){w.warn(`[mp4-remuxer]: Dropped ${U} out of ${E} video samples due to a missing keyframe`);const j=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(U),t.dropped+=U,p+=(t.samples[0].pts-j)/t.inputTimeScale,Q=p}else U===-1&&(w.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(B&&I){const j=this.getVideoStartPts(t.samples),X=(dt(e.samples[0].pts,j)-j)/t.inputTimeScale;g+=Math.max(0,X),p+=Math.max(0,-X)}if(B){if(e.samplerate||(w.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,g,this.isAudioContiguous,a,C||I||l===se.AUDIO?p:void 0),I){const j=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(w.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,p,D,j)}}else I&&(c=this.remuxVideo(t,p,D,0));c&&(c.firstKeyFrame=U,c.independent=U!==-1,c.firstKeyFramePTS=Q)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(A=af(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=of(i,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:f,text:d,id3:A}}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let h=!c||i,u="audio/mp4",d,A,f;if(h&&(d=A=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(f=e.inputTimeScale,!c||f!==c.timescale?d=A=r[0].pts-Math.round(f*s):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(f=t.inputTimeScale,!c||f!==c.timescale){const g=this.getVideoStartPts(a),p=Math.round(f*s);A=Math.min(A,dt(a[0].dts,g)-p),d=Math.min(d,g-p)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:d,timescale:f},this._initDTS={baseTime:A,timescale:f}):d=f=void 0,{tracks:l,initPTS:d,timescale:f}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let h=this.nextAvcDts,u=8,d=this.videoSampleDuration,A,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!s||h===null){const Y=t*r,G=a[0].pts-dt(a[0].dts,a[0].pts);zs&&h!==null&&Math.abs(Y-G-h)<15e3?s=!0:h=Y-G}const C=c.baseTime*r/c.timescale;for(let Y=0;Y<l;Y++){const G=a[Y];G.pts=dt(G.pts-C,h),G.dts=dt(G.dts-C,h),G.dts<a[Y>0?Y-1:Y].dts&&(m=!0)}m&&a.sort(function(Y,G){const H=Y.dts-G.dts,J=Y.pts-G.pts;return H||J}),A=a[0].dts,f=a[a.length-1].dts;const E=f-A,B=E?Math.round(E/(l-1)):d||e.inputTimeScale/30;if(s){const Y=A-h,G=Y>B,H=Y<-1;if((G||H)&&(G?w.warn(`AVC: ${Ui(Y,!0)} ms (${Y}dts) hole between fragments detected at ${t.toFixed(3)}`):w.warn(`AVC: ${Ui(-Y,!0)} ms (${Y}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!H||h>=a[0].pts||zs)){A=h;const J=a[0].pts-Y;if(G)a[0].dts=A,a[0].pts=J;else for(let K=0;K<a.length&&!(a[K].dts>J);K++)a[K].dts-=Y,a[K].pts-=Y;w.log(`Video: Initial PTS/DTS adjusted: ${Ui(J,!0)}/${Ui(A,!0)}, delta: ${Ui(Y,!0)} ms`)}}A=Math.max(0,A);let I=0,_=0,S=A;for(let Y=0;Y<l;Y++){const G=a[Y],H=G.units,J=H.length;let K=0;for(let R=0;R<J;R++)K+=H[R].data.length;_+=K,I+=J,G.length=K,G.dts<S?(G.dts=S,S+=B/4|0||1):S=G.dts,g=Math.min(G.pts,g),p=Math.max(G.pts,p)}f=a[l-1].dts;const x=_+4*I+8;let b;try{b=new Uint8Array(x)}catch(Y){this.observer.emit(y.ERROR,y.ERROR,{type:re.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:x,reason:`fail allocating video mdat ${x}`});return}const v=new DataView(b.buffer);v.setUint32(0,x),b.set(L.types.mdat,4);let D=!1,U=Number.POSITIVE_INFINITY,Q=Number.POSITIVE_INFINITY,j=Number.NEGATIVE_INFINITY,V=Number.NEGATIVE_INFINITY;for(let Y=0;Y<l;Y++){const G=a[Y],H=G.units;let J=0;for(let te=0,oe=H.length;te<oe;te++){const ue=H[te],Je=ue.data,rt=ue.data.byteLength;v.setUint32(u,rt),u+=4,b.set(Je,u),u+=rt,J+=4+rt}let K;if(Y<l-1)d=a[Y+1].dts-G.dts,K=a[Y+1].pts-G.pts;else{const te=this.config,oe=Y>0?G.dts-a[Y-1].dts:B;if(K=Y>0?G.pts-a[Y-1].pts:B,te.stretchShortVideoTrack&&this.nextAudioPts!==null){const ue=Math.floor(te.maxBufferHole*r),Je=(i?g+i*r:this.nextAudioPts)-G.pts;Je>ue?(d=Je-oe,d<0?d=oe:D=!0,w.log(`[mp4-remuxer]: It is approximately ${Je/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=oe}else d=oe}const R=Math.round(G.pts-G.dts);U=Math.min(U,d),j=Math.max(j,d),Q=Math.min(Q,K),V=Math.max(V,K),o.push(new Xh(G.key,d,J,R))}if(o.length){if(zs){if(zs<70){const Y=o[0].flags;Y.dependsOn=2,Y.isNonSync=0}}else if(Fa&&V-Q<j-U&&B/j<.025&&o[0].cts===0){w.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let Y=A;for(let G=0,H=o.length;G<H;G++){const J=Y+o[G].duration,K=Y+o[G].cts;if(G<H-1){const R=J+o[G+1].cts;o[G].duration=R-K}else o[G].duration=G?o[G-1].duration:B;o[G].cts=0,Y=J}}}d=D||!d?B:d,this.nextAvcDts=h=f+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const ae={data1:L.moof(e.sequenceNumber++,A,Ge({},e,{samples:o})),data2:b,startPTS:g/r,endPTS:(p+d)/r,startDTS:A/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,ae}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return vx;case"ac3":return Rx;default:return $h}}remuxAudio(e,t,s,i,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),h=c*l,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,A=[],f=r!==void 0;let g=e.samples,p=d?0:8,m=this.nextAudioPts||-1;const C=t*a,E=u.baseTime*a/u.timescale;if(this.isAudioContiguous=s=s||g.length&&m>0&&(i&&Math.abs(C-m)<9e3||Math.abs(dt(g[0].pts-E,C)-m)<20*h),g.forEach(function(X){X.pts=dt(X.pts-E,C)}),!s||m<0){if(g=g.filter(X=>X.pts>=0),!g.length)return;r===0?m=0:i&&!f?m=Math.max(0,C):m=g[0].pts}if(e.segmentCodec==="aac"){const X=this.config.maxAudioFramesDrift;for(let Z=0,ae=m;Z<g.length;Z++){const Y=g[Z],G=Y.pts,H=G-ae,J=Math.abs(1e3*H/a);if(H<=-X*h&&f)Z===0&&(w.warn(`Audio frame @ ${(G/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*H/a)} ms.`),this.nextAudioPts=m=ae=G);else if(H>=X*h&&J<xx&&f){let K=Math.round(H/h);ae=G-K*h,ae<0&&(K--,ae+=h),Z===0&&(this.nextAudioPts=m=ae),w.warn(`[mp4-remuxer]: Injecting ${K} audio frame @ ${(ae/a).toFixed(3)}s due to ${Math.round(1e3*H/a)} ms gap.`);for(let R=0;R<K;R++){const te=Math.max(ae,0);let oe=qh.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);oe||(w.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),oe=Y.unit.subarray()),g.splice(Z,0,{unit:oe,pts:te}),ae+=h,Z++}}Y.pts=ae,ae+=h}}let B=null,I=null,_,S=0,x=g.length;for(;x--;)S+=g[x].unit.byteLength;for(let X=0,Z=g.length;X<Z;X++){const ae=g[X],Y=ae.unit;let G=ae.pts;if(I!==null){const J=A[X-1];J.duration=Math.round((G-I)/l)}else if(s&&e.segmentCodec==="aac"&&(G=m),B=G,S>0){S+=p;try{_=new Uint8Array(S)}catch(J){this.observer.emit(y.ERROR,y.ERROR,{type:re.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:J,bytes:S,reason:`fail allocating audio mdat ${S}`});return}d||(new DataView(_.buffer).setUint32(0,S),_.set(L.types.mdat,4))}else return;_.set(Y,p);const H=Y.byteLength;p+=H,A.push(new Xh(!0,c,H,0)),I=G}const b=A.length;if(!b)return;const v=A[A.length-1];this.nextAudioPts=m=I+l*v.duration;const D=d?new Uint8Array(0):L.moof(e.sequenceNumber++,B/l,Ge({},e,{samples:A}));e.samples=[];const U=B/a,Q=m/a,V={data1:D,data2:_,startPTS:U,endPTS:Q,startDTS:U,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,V}remuxEmptyAudio(e,t,s,i){const r=e.inputTimeScale,a=e.samplerate?e.samplerate:r,o=r/a,l=this.nextAudioPts,c=this._initDTS,h=c.baseTime*9e4/c.timescale,u=(l!==null?l:i.startDTS*r)+h,d=i.endDTS*r+h,A=o*$h,f=Math.ceil((d-u)/A),g=qh.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(w.warn("[mp4-remuxer]: remux empty Audio"),!g){w.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const p=[];for(let m=0;m<f;m++){const C=u+m*A;p.push({unit:g,pts:C,dts:C})}return e.samples=p,this.remuxAudio(e,t,s,!1)}}function dt(n,e){let t;if(e===null)return n;for(e<n?t=-8589934592:t=8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function wx(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function af(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const l=n.samples[o];l.pts=dt(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=dt(l.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function of(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=dt(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class Xh{constructor(e,t,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Dx{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(QS(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=wA(e);i.audio&&(t=jh(i.audio,ve.AUDIO)),i.video&&(s=jh(i.video,ve.VIDEO));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:e,id:"main"}:w.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,a){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};W(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!(d!=null&&d.length))return u;const A={initPTS:void 0,timescale:1};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((l=f)!=null&&l.length))return w.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(A.tracks=this.initTracks,this.emitInitSegment=!1);const g=US(d,f),p=GS(f,d),m=p===null?r:p;(Lx(c,m,r,g)||A.timescale!==c.timescale&&a)&&(A.initPTS=m-r,c&&c.timescale===1&&w.warn(`Adjusting initPTS by ${A.initPTS-c.baseTime}`),this.initPTS=c={baseTime:A.initPTS,timescale:1});const C=e?m-c.baseTime/c.timescale:h,E=C+g;HS(f,d,c.baseTime/c.timescale),g>0?this.lastEndTime=E:(w.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const B=!!f.audio,I=!!f.video;let _="";B&&(_+="audio"),I&&(_+="video");const S={data1:d,startPTS:C,startDTS:C,endPTS:E,endDTS:E,type:_,hasAudio:B,hasVideo:I,nb:1,dropped:0};return u.audio=S.type==="audio"?S:void 0,u.video=S.type!=="audio"?S:void 0,u.initSegment=A,u.id3=af(s,r,c,c),i.samples.length&&(u.text=of(i,r,c)),u}}function Lx(n,e,t,s){if(n===null)return!0;const i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>i}function jh(n,e){const t=n==null?void 0:n.codec;if(t&&t.length>4)return t;if(e===ve.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return fr(t,!1);const s="mp4a.40.5";return w.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${s}"`),s}return w.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let jt;try{jt=self.performance.now.bind(self.performance)}catch{w.debug("Unable to use Performance API on this environment"),jt=Ai==null?void 0:Ai.Date.now}const Wn=[{demux:mx,remux:Dx},{demux:os,remux:jn},{demux:fx,remux:jn},{demux:Tx,remux:jn}];Wn.splice(2,0,{demux:px,remux:jn});class Wh{constructor(e,t,s,i,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.vendor=i,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=jt();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:A,initSegmentChange:f}=i||o,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:C,initSegmentData:E}=l,B=bx(a,t);if(B&&B.method==="AES-128"){const x=this.getDecrypter();if(x.isSync()){let b=x.softwareDecrypt(a,B.key.buffer,B.iv.buffer);if(s.part>-1&&(b=x.flush()),!b)return r.executeEnd=jt(),Pa(s);a=new Uint8Array(b)}else return this.decryptionPromise=x.webCryptoDecrypt(a,B.key.buffer,B.iv.buffer).then(b=>{const v=this.push(b,null,s);return this.decryptionPromise=null,v}),this.decryptionPromise}const I=this.needsProbing(h,u);if(I){const x=this.configureTransmuxer(a);if(x)return w.warn(`[transmuxer] ${x.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),r.executeEnd=jt(),Pa(s)}(h||u||f||I)&&this.resetInitSegment(E,g,p,C,t),(h||f||I)&&this.resetInitialTimestamp(m),c||this.resetContiguity();const _=this.transmux(a,B,A,d,s),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,r.executeEnd=jt(),_}flush(e){const t=e.transmuxing;t.executeStart=jt();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=jt(),[Pa(e)];const h=l.flush(o);return Zn(h)?h.then(u=>(this.flushRemux(a,u,e),a)):(this.flushRemux(a,h,e),a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;w.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,a,o,c,l,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=jt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i,vendor:r}=this;let a;for(let d=0,A=Wn.length;d<A;d++){var o;if((o=Wn[d].demux)!=null&&o.probe(e)){a=Wn[d];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=a.remux,u=a.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(s,t,i,r)),(!l||!(l instanceof u))&&(this.demuxer=new u(s,t,i),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Bl(this.config)),e}}function bx(n,e){let t=null;return n.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Pa=n=>({remuxResult:{},chunkMeta:n});function Zn(n){return"then"in n&&n.then instanceof Function}class Mx{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Fx{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}var lf={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var A=new i(h,u||l,d),f=t?t+c:c;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],A]:l._events[f].push(A):(l._events[f]=A,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,A=u.length,f=new Array(A);d<A;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,A,f){var g=t?t+c:c;if(!this._events[g])return!1;var p=this._events[g],m=arguments.length,C,E;if(p.fn){switch(p.once&&this.removeListener(c,p.fn,void 0,!0),m){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,u),!0;case 4:return p.fn.call(p.context,h,u,d),!0;case 5:return p.fn.call(p.context,h,u,d,A),!0;case 6:return p.fn.call(p.context,h,u,d,A,f),!0}for(E=1,C=new Array(m-1);E<m;E++)C[E-1]=arguments[E];p.fn.apply(p.context,C)}else{var B=p.length,I;for(E=0;E<B;E++)switch(p[E].once&&this.removeListener(c,p[E].fn,void 0,!0),m){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,h);break;case 3:p[E].fn.call(p[E].context,h,u);break;case 4:p[E].fn.call(p[E].context,h,u,d);break;default:if(!C)for(I=1,C=new Array(m-1);I<m;I++)C[I-1]=arguments[I];p[E].fn.apply(p[E].context,C)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var A=t?t+c:c;if(!this._events[A])return this;if(!h)return a(this,A),this;var f=this._events[A];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&a(this,A);else{for(var g=0,p=[],m=f.length;g<m;g++)(f[g].fn!==h||d&&!f[g].once||u&&f[g].context!==u)&&p.push(f[g]);p.length?this._events[A]=p.length===1?p[0]:p:a(this,A)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(lf);var Px=lf.exports,vl=lS(Px);class cf{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(c,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,c===y.ERROR&&(this.error=h.error),this.hls.trigger(c,h)};this.observer=new vl,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);const o=gs(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||ex())){try{r.workerPath?(w.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=sx(r.workerPath)):(w.log(`injecting Web Worker for "${t}"`),this.workerContext=tx()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=u=>{const d=new Error(`${u.message} (${u.filename}:${u.lineno})`);r.enableWorker=!1,w.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:t,config:JSON.stringify(r)})}catch(h){w.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new Wh(this.observer,l,r,"",t)}return}this.transmuxer=new Wh(this.observer,l,r,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{transmuxer:A}=this,f=a?a.start:r.start,g=r.decryptdata,p=this.frag,m=!(p&&r.cc===p.cc),C=!(p&&c.level===p.level),E=p?c.sn-p.sn:-1,B=this.part?c.part-this.part.index:-1,I=E===0&&c.id>1&&c.id===(p==null?void 0:p.stats.chunkCount),_=!C&&(E===1||E===0&&(B===1||I&&B<=0)),S=self.performance.now();(C||E||r.stats.parsing.start===0)&&(r.stats.parsing.start=S),a&&(B||!_)&&(a.stats.parsing.start=S);const x=!(p&&((u=r.initSegment)==null?void 0:u.url)===((d=p.initSegment)==null?void 0:d.url)),b=new Fx(m,_,l,C,f,x);if(!_||m||x){w.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
|
|
18
|
+
discontinuity: ${m}
|
|
19
|
+
trackSwitch: ${C}
|
|
20
|
+
contiguous: ${_}
|
|
21
|
+
accurateTimeOffset: ${l}
|
|
22
|
+
timeOffset: ${f}
|
|
23
|
+
initSegmentChange: ${x}`);const v=new Mx(s,i,t,o,h);this.configureTransmuxer(v)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:b},e instanceof ArrayBuffer?[e]:[]);else if(A){const v=A.push(e,g,c,b);Zn(v)?(A.async=!0,v.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,c,"transmuxer-interface push error")})):(A.async=!1,this.handleTransmuxComplete(v))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let s=t.flush(e);Zn(s)||t.async?(Zn(s)||(s=Promise.resolve(s)),s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(!(t!=null&&t.event)){w.warn(`worker message received with no ${t?"event name":"data"}`);return}const s=this.hls;if(this.hls)switch(t.event){case"init":{var i;const r=(i=this.workerContext)==null?void 0:i.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":w[t.data.logType]&&w[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,s.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function hf(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!gi(n[t].attrs,e[t].attrs))return!1;return!0}function gi(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}function wo(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}const Zh=100;class uf extends Gr{constructor(e,t,s){super(e,t,s,"[audio-stream-controller]",se.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){if(s==="main"){const a=t.cc;this.initPTS[t.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${a} found from main: ${i}`),this.videoTrackCC=a,this.state===N.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=N.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Zh),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=N.IDLE):(this.loadedmetadata=!1,this.state=N.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case N.IDLE:this.doTickIdle();break;case N.WAITING_TRACK:{var e;const{levels:s,trackId:i}=this,r=s==null||(e=s[i])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=N.WAITING_INIT_PTS}break}case N.FRAG_LOADING_WAITING_RETRY:{var t;const s=performance.now(),i=this.retryDate;if(!i||s>=i||(t=this.media)!=null&&t.seeking){const{levels:r,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((r==null?void 0:r[a])||null),this.state=N.IDLE}break}case N.WAITING_INIT_PTS:{const s=this.waitingData;if(s){const{frag:i,part:r,cache:a,complete:o}=s;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=N.FRAG_LOADING;const l=a.flush(),c={frag:i,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=Le.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);vo(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=N.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=N.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:s,trackId:i}=this,r=e.config;if(!this.buffering||!s&&(this.startFragRequested||!r.startFragPrefetch)||!(t!=null&&t[i]))return;const a=t[i],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=N.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ve.AUDIO,se.AUDIO));const c=this.getFwdBufferInfo(l,se.AUDIO);if(c===null)return;const{bufferedTrack:h,switchingTrack:u}=this;if(!u&&this._streamEnded(c,o)){e.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=N.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,se.MAIN),A=c.len,f=this.getMaxBufferLength(d==null?void 0:d.len),g=o.fragments,p=g[0].start;let m=this.flushing?this.getLoadPosition():c.end;if(u&&s){const I=this.getLoadPosition();h&&!gi(u.attrs,h.attrs)&&(m=I),o.PTSKnown&&I<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}if(A>=f&&!u&&m<g[g.length-1].start)return;let C=this.getNextFragment(m,o),E=!1;if(C&&this.isLoopLoading(C,m)&&(E=!!C.gap,C=this.getNextFragmentLoopLoading(C,o,c,se.MAIN,f)),!C){this.bufferFlushed=!0;return}const B=d&&C.start>d.end+o.targetduration;if(B||!(d!=null&&d.len)&&c.len){const I=this.getAppendedFrag(C.start,se.MAIN);if(I===null||(E||(E=!!I.gap||!!B&&d.len===0),B&&!E||E&&c.nextStart&&c.nextStart<I.end))return}this.loadFragment(C,a,m)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new bs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(Zh):this.resetTransmuxer(),s?(this.switchingTrack=t,this.state=N.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=N.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(y.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var s;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:i}=this,{details:r,id:a}=t;if(!i){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=i[a];let l=0;if(r.live||(s=o.details)!=null&&s.live){this.checkLiveUpdate(r);const h=this.mainDetails;if(r.deltaUpdateFailed||!h)return;if(!o.details&&r.hasProgramDateTime&&h.hasProgramDateTime)Cr(r,h),l=r.fragments[0].start;else{var c;l=this.alignPlaylists(r,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,l),this.state===N.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=N.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new cf(this.hls,se.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const A=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(A!==void 0){const p=i?i.index:-1,m=p!==-1,C=new Qr(s.level,s.sn,s.stats.chunkCount,r.byteLength,p,m);d.push(r,f,u,"",s,i,h.totalduration,!1,C,A)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new JA,complete:!1};g.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=N.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==se.AUDIO){if(!this.loadedmetadata&&s.type===se.MAIN){const r=this.videoBuffer||this.media;r&&Le.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(s.sn!=="initSegment"){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,$e({},r)))}this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=N.ERROR;return}switch(t.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(se.AUDIO,t);break;case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===N.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===ye.AUDIO_TRACK&&(this.state=N.IDLE);break;case F.BUFFER_APPEND_ERROR:case F.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===F.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ve.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ve.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===N.ENDED&&(this.state=N.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,se.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:A,id3:f,initSegment:g}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=N.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(h,g.tracks,p,a),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:s,tracks:g.tracks})}if(d){const{startPTS:p,endPTS:m,startDTS:C,endDTS:E}=d;c&&(c.elementaryStreams[ve.AUDIO]={startPTS:p,endPTS:m,startDTS:C,endDTS:E}),l.setElementaryStreamInfo(ve.AUDIO,p,m,C,E),this.bufferFragmentData(d,l,c,a)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=Ge({id:s,frag:l,details:u},f);i.trigger(y.FRAG_PARSING_METADATA,p)}if(A){const p=Ge({id:s,frag:l,details:u},A);i.trigger(y.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,s,i){if(this.state!==N.PARSING)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.id="audio";const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===qe.NOT_LOADED||i===qe.PARTIAL){var r;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=N.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&Cr(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:s}=this,i=s==null?void 0:s.attrs,r=e.attrs;t&&i&&(i.CHANNELS!==r.CHANNELS||s.name!==e.name||s.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,$e({},e))}}class df extends Or{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,A)=>{d.id=A});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Gt(l,o,Vs);if(d>-1)r=o[d];else{const A=Gt(l,this.tracks);r=this.tracks[A]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===ye.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&ai(e,i,Vs))return i;const r=Gt(e,this.tracksInGroup,Vs);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Q_(e,t.levels,s,a,Vs);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Gt(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,$e({},i)),r))return;const a=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||ai(e,i,Vs)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(ai({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,Vs))return c}for(let c=0;c<t.length;c++){const h=t[c];if(gi(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(gi(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${s} "${t.name}" lang:${t.lang} group:${i}`),this.clearTimer(),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}}const eu=500;class Af extends Gr{constructor(e,t,s){super(e,t,s,"[subtitle-stream-controller]",se.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.ERROR,this.onError,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.ERROR,this.onError,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=N.IDLE,this.setInterval(eu),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragPrevious=s,this.state=N.IDLE,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=s.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,se.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===se.MAIN){var s;(s=this.media)!=null&&s.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===se.SUBTITLE&&(t.details===F.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==N.STOPPED&&(this.state=N.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&hf(this.levels,t)){this.levels=t.map(s=>new bs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new bs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,se.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(eu)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(s=l.details)!=null&&s.live){const u=this.mainDetails;if(a.deltaUpdateFailed||!u)return;const d=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Cr(a,u),c=a.fragments[0].start):d&&(c=d.start,xo(a,c));else{var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&d&&(c=d.start,xo(a,c))}}l.details=a,this.levelLastLoaded=l,o===i&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===N.IDLE&&(Er(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&i.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch(o=>{throw r.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=N.IDLE})}}doTick(){if(!this.media){this.state=N.IDLE;return}if(this.state===N.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),a=Le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,se.MAIN),h=s.details,u=this.getMaxBufferLength(c==null?void 0:c.len)+h.levelTargetDuration;if(l>u)return;const d=h.fragments,A=d.length,f=h.edge;let g=null;const p=this.fragPrevious;if(o<f){const m=i.maxFragLookUpTolerance,C=o>f-m?0:m;g=Er(p,d,Math.max(d[0].start,o),C),!g&&p&&p.start<d[0].start&&(g=d[0])}else g=d[A-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const m=g.sn-h.startSN,C=d[m-1];C&&C.cc===g.cc&&this.fragmentTracker.getState(C)===qe.NOT_LOADED&&(g=C)}this.fragmentTracker.getState(g)===qe.NOT_LOADED&&this.loadFragment(g,s,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,s){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,s))}get mediaBufferTimeRanges(){return new kx(this.tracksBuffered[this.currentTrackId]||[])}}class kx{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}class ff extends Or{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=$n(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),$n(this.media.textTracks).forEach(t=>{js(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Gt(o,a);if(h>-1)r=a[h];else{const u=Gt(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||ai(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(gi(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(gi(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(wo(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ye.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&ai(e,s))return s;const i=Gt(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Gt(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=$n(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>wo(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!W(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:h}=i;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:h});const u=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(u)}}class Ox{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,s){const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const s=new Promise(r=>{t=r}),i={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),s}executeNext(e){const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(i){w.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${i}`),s.onError(i);const r=this.buffers[e];r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const tu=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class gf{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=s=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:s,mediaSource:i}=this;this.log("Media source opened"),s&&(s.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:s,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&w.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=ZS(gs(e.config.preferManagedMediaSource)),this.log=w.log.bind(w,t),this.warn=w.warn.bind(w,t),this.error=w.error.bind(w,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Ox(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const s=this.media=t.media,i=gs(this.appendSource);if(s&&i){var r;const a=this.mediaSource=new i;this.log(`created media source: ${(r=a.constructor)==null?void 0:r.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,su(s),Qx(s,o),s.load()}catch{s.src=o}else s.src=o;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:s}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(e.removeAttribute("src"),this.appendSource&&su(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(y.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var s;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(i){this.warn(`onBufferReset ${e}`,i)}}onBufferCodecs(e,t){const s=this.getSourceBufferTypes().length,i=Object.keys(t);if(i.forEach(a=>{if(s){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:h,levelCodec:u,container:d,metadata:A}=t[a],f=Sh(l.codec,l.levelCodec),g=f==null?void 0:f.replace(tu,"$1");let p=Sh(h,u);const m=(o=p)==null?void 0:o.replace(tu,"$1");if(p&&g!==m){a.slice(0,5)==="audio"&&(p=fr(p,this.appendSource));const C=`${d};codecs=${p}`;this.appendChangeType(a,C),this.log(`switching codec ${f} to ${p}`),this.tracks[a]={buffer:l.buffer,codec:h,container:d,levelCodec:u,metadata:A,id:c}}}}else this.pendingTracks[a]=t[a]}),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:s}=this,i={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),s.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};s.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:s,operationQueue:i,tracks:r}=this,{data:a,type:o,frag:l,part:c,chunkMeta:h}=t,u=h.buffering[o],d=self.performance.now();u.start=d;const A=l.stats.buffering,f=c?c.stats.buffering:null;A.start===0&&(A.start=d),f&&f.start===0&&(f.start=d);const g=r.audio;let p=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const m=l.start,C={execute:()=>{if(u.executeStart=self.performance.now(),p){const E=this.sourceBuffer[o];if(E){const B=m-E.timestampOffset;Math.abs(B)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${m} (delta: ${B}) sn: ${l.sn})`),E.timestampOffset=m)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const E=self.performance.now();u.executeEnd=u.end=E,A.first===0&&(A.first=E),f&&f.first===0&&(f.first=E);const{sourceBuffer:B}=this,I={};for(const _ in B)I[_]=Le.getBuffered(B[_]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:I})},onError:E=>{const B={type:re.MEDIA_ERROR,parent:l.type,details:F.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:h,error:E,err:E,fatal:!1};if(E.code===DOMException.QUOTA_EXCEEDED_ERR)B.details=F.BUFFER_FULL_ERROR;else{const I=++this.appendErrors[o];B.details=F.BUFFER_APPEND_ERROR,this.warn(`Failed ${I}/${s.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),I>=s.config.appendErrorMaxRetry&&(B.fatal=!0)}s.trigger(y.ERROR,B)}};i.append(C,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:s}=this,i=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:r})},onError:a=>{this.warn(`Failed to remove from ${r} SourceBuffer`,a)}});t.type?s.append(i(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{s.append(i(r),r)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ve.AUDIOVIDEO]?r.push("audiovideo"):(a[ve.AUDIO]&&r.push("audio"),a[ve.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();s.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:s.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:s,part:i,stats:c,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((i,r)=>{const a=this.sourceBuffer[r];return a&&(!t.type||t.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} sourceBuffer now EOS`))),i&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const a=this.sourceBuffer[r];a&&(a.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.getSourceBufferTypes().length)return;const r=e.config,a=s.currentTime,o=t.levelTargetDuration,l=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(W(l)&&l>0){const c=Math.max(l,o),h=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,h)}if(W(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(c,o),u=Math.floor(a/o)*o+h;this.flushFrontBuffer(a,o,u)}}flushBackBuffer(e,t,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];if(l){const c=Le.getBuffered(l);if(c.length>0&&s>c.start(0)){if(this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s}),i!=null&&i.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l.ended&&c.end(c.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:o})}}})}flushFrontBuffer(e,t,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(a=>{const o=i[a];if(o){const l=Le.getBuffered(o),c=l.length;if(c<2)return;const h=l.start(c-1),u=l.end(c-1);if(s>h||e>=h&&e<=u)return;if(o.ended&&e-u<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:s,mediaSource:i}=this,r=e.fragments[0].start+e.totalduration,a=s.duration,o=W(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>a||!W(a))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(e){const t=this.mediaSource,s=e.fragments;if(s.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,s[0].start),a=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${a}.`),t.setLiveSeekableRange(r,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!e||i===2||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(y.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var i;const a=e[r];if(!a)throw Error(`source buffer exists for track ${r}, however track does not`);let o=((i=a.levelCodec)==null?void 0:i.indexOf(","))===-1?a.levelCodec:a.codec;o&&r.slice(0,5)==="audio"&&(o=fr(o,this.appendSource));const l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const c=t[r]=s.addSourceBuffer(l),h=r;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(h,"bufferedchange",(u,d)=>{const A=d.removedRanges;A!=null&&A.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:s}=this;s.current(e).onComplete(),s.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(i)}removeExecutor(e,t,s){const{media:i,mediaSource:r,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!i||!r||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const c=W(i.duration)?i.duration:1/0,h=W(r.duration)?r.duration:1/0,u=Math.max(0,t),d=Math.min(s,c,h);d>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),l.remove(u,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.sourceBuffer[t];if(!s){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:s}=this,i=t.map(r=>s.appendBlocker(r));Promise.all(i).then(()=>{e(),t.forEach(r=>{const a=this.sourceBuffer[r];a!=null&&a.updating||s.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,s){const i=this.sourceBuffer[e];if(!i)return;const r=s.bind(this,e);this.listeners[e].push({event:t,listener:r}),i.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(s=>{t.removeEventListener(s.event,s.listener)})}}function su(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function Qx(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}const Gx={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},mf=n=>String.fromCharCode(Gx[n]||n),Tt=15,Jt=100,Ux={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Nx={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Hx={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Kx={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Vx=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yx{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;w.log(`${this.time} [${e}] ${s}`)}}}const Ts=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class pf{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Jx{constructor(){this.uchar=" ",this.penState=new pf}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class zx{constructor(e){this.chars=[],this.pos=0,this.currPenState=new pf,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Jt;t++)this.chars.push(new Jx);this.logger=e}equals(e){for(let t=0;t<Jt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Jt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Jt;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Jt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Jt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=mf(e);if(this.pos>=Jt){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Jt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Jt;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class ka{constructor(e){this.rows=[],this.currRow=Tt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Tt;t++)this.rows.push(new zx(e));this.logger=e}reset(){for(let e=0;e<Tt;e++)this.rows[e].clear();this.currRow=Tt-1}equals(e){let t=!0;for(let s=0;s<Tt;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Tt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Tt;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Tt;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Tt;r++){const a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
24
|
+
`)),s}getTextAndFormat(){return this.rows}}class iu{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ka(s),this.nonDisplayedMemory=new ka(s),this.lastOutputScreen=new ka(s),this.currRollUpRow=this.displayedMemory.rows[Tt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Tt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class nu{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=$x(),this.logger=void 0;const i=this.logger=new Yx;this.channels=[null,new iu(e,t,i),new iu(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Ts([t[s],t[s+1]])+"] -> ("+Ts([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(qx(i,r,l)){Un(null,null,l),this.logger.log(3,()=>"Repeated command ("+Ts([i,r])+") is dropped");continue}Un(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else Un(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ts([i,r])+" orig: "+Ts([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ts([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const a=e<=23?1:2;t>=64&&t<=95?s=a===1?Ux[e]:Hx[e]:s=a===1?Nx[e]:Kx[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+mf(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Ts(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Vx[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Un(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Un(n,e,t){t.a=n,t.b=e}function qx(n,e,t){return t.a===n&&t.b===e}function $x(){return{a:null,b:null}}class Nn{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Rl=function(){if(Ai!=null&&Ai.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",A=!1,f=o,g=l,p=c,m=null,C="",E=!0,B="auto",I="start",_=50,S="middle",x=50,b="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(v){d=""+v}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return A},set:function(v){A=!!v}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(v){if(typeof v!="number")throw new TypeError("Start time must be set to a number.");f=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return g},set:function(v){if(typeof v!="number")throw new TypeError("End time must be set to a number.");g=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return p},set:function(v){p=""+v,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return m},set:function(v){m=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return C},set:function(v){const D=s(v);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");C=D,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return E},set:function(v){E=!!v,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return B},set:function(v){if(typeof v!="number"&&v!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");B=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return I},set:function(v){const D=i(v);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");I=D,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return _},set:function(v){if(v<0||v>100)throw new Error("Position must be between 0 and 100.");_=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return S},set:function(v){const D=i(v);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return x},set:function(v){if(v<0||v>100)throw new Error("Size must be between 0 and 100.");x=v,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return b},set:function(v){const D=i(v);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");b=D,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Xx{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ef(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class jx{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Cf(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Do=new Rl(0,0,""),Hn=Do.align==="middle"?"middle":"center";function Wx(n,e,t){const s=n;function i(){const o=Ef(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new jx;Cf(o,function(d,A){let f;switch(d){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===A){c.set(d,t[g].region);break}break;case"vertical":c.alt(d,A,["rl","lr"]);break;case"line":f=A.split(","),c.integer(d,f[0]),c.percent(d,f[0])&&c.set("snapToLines",!1),c.alt(d,f[0],["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start",Hn,"end"]);break;case"position":f=A.split(","),c.percent(d,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start",Hn,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,A);break;case"align":c.alt(d,A,["start",Hn,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&Do.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Hn);let u=c.get("position","auto");u==="auto"&&Do.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function If(n){return n.replace(/<br(?: \/)?>/gi,`
|
|
25
|
+
`)}class Zx{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Xx,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=If(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
26
|
+
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
27
|
+
`&&++a,t.buffer=r.slice(a),o}function i(r){Cf(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Rl(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Wx(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
28
|
+
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
29
|
+
|
|
30
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const ev=/\r\n|\n\r|\n|\r/g,Oa=function(e,t,s=0){return e.slice(s,s+t.length)===t},tv=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!W(t)||!W(s)||!W(i)||!W(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t},Qa=function(e){let t=5381,s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return(t>>>0).toString()};function wl(n,e,t){return Qa(n.toString())+Qa(e.toString())+Qa(t)}const sv=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function iv(n,e,t,s,i,r,a){const o=new Zx,l=Nt(new Uint8Array(n)).trim().replace(ev,`
|
|
31
|
+
`).split(`
|
|
32
|
+
`),c=[],h=e?_x(e.baseTime,e.timescale):0;let u="00:00.000",d=0,A=0,f,g=!0;o.oncue=function(p){const m=t[s];let C=t.ccOffset;const E=(d-h)/9e4;if(m!=null&&m.new&&(A!==void 0?C=t.ccOffset=m.start:sv(t,s,E)),E){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}C=E-t.presentationOffset}const B=p.endTime-p.startTime,I=dt((p.startTime+C-A)*9e4,i*9e4)/9e4;p.startTime=Math.max(I,0),p.endTime=Math.max(I+B,0);const _=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(_)),p.id||(p.id=wl(p.startTime,p.endTime,_)),p.endTime>0&&c.push(p)},o.onparsingerror=function(p){f=p},o.onflush=function(){if(f){a(f);return}r(c)},l.forEach(p=>{if(g)if(Oa(p,"X-TIMESTAMP-MAP=")){g=!1,p.slice(16).split(",").forEach(m=>{Oa(m,"LOCAL:")?u=m.slice(6):Oa(m,"MPEGTS:")&&(d=parseInt(m.slice(7)))});try{A=tv(u)/1e3}catch(m){f=m}return}else p===""&&(g=!1);o.parse(p+`
|
|
33
|
+
`)}),o.flush()}const Ga="stpp.ttml.im1t",yf=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Bf=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,nv={left:"start",center:"center",right:"end",start:"start",end:"end"};function ru(n,e,t,s){const i=fe(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Nt(o)),a=Sx(e.baseTime,1,e.timescale);try{r.forEach(o=>t(rv(o,a)))}catch(o){s(o)}}function rv(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",l=au(Ua(i,"styling","style")),c=au(Ua(i,"layout","region")),h=Ua(i,"body","[begin]");return[].map.call(h,u=>{const d=Tf(u,o);if(!d||!u.hasAttribute("begin"))return null;const A=Ha(u.getAttribute("begin"),a),f=Ha(u.getAttribute("dur"),a);let g=Ha(u.getAttribute("end"),a);if(A===null)throw ou(u);if(g===null){if(f===null)throw ou(u);g=A+f}const p=new Rl(A-e,g-e,d);p.id=wl(p.startTime,p.endTime,p.text);const m=c[u.getAttribute("region")],C=l[u.getAttribute("style")],E=av(m,C,l),{textAlign:B}=E;if(B){const I=nv[B];I&&(p.lineAlign=I),p.align=B}return Ge(p,E),p}).filter(u=>u!==null)}function Ua(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function au(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Tf(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
|
|
34
|
+
`:(r=s.childNodes)!=null&&r.length?Tf(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function av(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,l)=>{const c=Na(e,s,l)||Na(n,s,l)||Na(i,s,l);return c&&(o[l]=c),o},{})}function Na(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function ou(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Ha(n,e){if(!n)return null;let t=Ef(n);return t===null&&(yf.test(n)?t=ov(n,e):Bf.test(n)&&(t=lv(n,e))),t}function ov(n,e){const t=yf.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function lv(n,e){const t=Bf.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class Sf{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cu(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Nn(this,"textTrack1"),t=new Nn(this,"textTrack2"),s=new Nn(this,"textTrack3"),i=new Nn(this,"textTrack4");this.cea608Parser1=new nu(1,e,t),this.cea608Parser2=new nu(3,s,i)}}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=cv(l[0],l[1],t,s);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,c/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:a}=this;s==="main"&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(y.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(lu(r,{name:e,lang:t,attrs:{}}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)s[e]=o,js(s[e]),PA(s[e],i);else{const l=this.createTextTrack("captions",r,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{js(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cu(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)js(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ga);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(hf(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?$n(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&lu(o[d],l)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)js(h);else{const u=_f(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&w.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===se.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===se.SUBTITLE)if(i.byteLength){const r=s.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ga?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;ru(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{w.log(`Failed to parse IMSC1: ${i}`),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=s.initSegment)!=null&&t.data?Et(s.initSegment.data,new Uint8Array(i)):i;iv(c,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(s,i),w.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||ru(t,this.initPTS[e.cc],()=>{s.textCodec=Ga,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>kA(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===se.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:a}=t;if(!(r.type===se.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);s.addData(a[o].pts,c[0]),i.addData(a[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Bo(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Bo(o[l],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function _f(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function lu(n,e){return!!n&&n.kind===_f(e)&&wo(e,n)}function cv(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function cu(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Ur{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&W(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&w.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Ur.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}}class xf{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;w.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Kn="[eme]";class Ds{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Ds.CDMCleanupPromise?[Ds.CDMCleanupPromise]:[],this.debug=w.debug.bind(w,Kn),this.log=w.log.bind(w,Kn),this.warn=w.warn.bind(w,Kn),this.error=w.error.bind(w,Kn),this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Mn(this.config));const o=a.map(Sa).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Ba(a);let l,c;if(s==="sinf"){if(o!==Te.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}const f=Ke(new Uint8Array(i));try{const g=El(JSON.parse(f).sinf),p=DA(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=p.subarray(8,24),c=Te.FAIRPLAY}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}}else{if(o!==Te.WIDEVINE&&o!==Te.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}const f=$S(i),g=f.filter(m=>!!m.systemId&&Ta(m.systemId)===o);g.length>1&&this.warn(`${r} Using first of ${g.length} pssh found for selected key-system ${o}`);const p=g[0];if(!p){f.length===0||f.some(m=>!m.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${f.map(m=>Ta(m.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(c=Ta(p.systemId),p.version===0&&p.data)if(c===Te.WIDEVINE){const m=p.data.length-22;l=p.data.subarray(m,m+16)}else c===Te.PLAYREADY&&(l=BA(p.data))}if(!c||!l){this.log(`Unable to handle ${r} with key-system ${o}`);return}const h=Pt.hexDump(l),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let A=u[h];for(let f=0;f<d.length;f++){const g=d[f],p=g.decryptdata;if(!p.keyId)continue;const m=Pt.hexDump(p.keyId);if(h===m||p.uri.replace(/-/g,"").indexOf(h)!==-1){if(A=u[m],p.pssh)break;delete u[m],p.pssh=new Uint8Array(i),p.keyId=l,A=u[h]=A.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),A.catch(C=>this.handleError(C));break}}if(!A){if(c!==o){this.log(`Ignoring "${r}" with ${c} init data for selected key-system ${o}`);return}A=u[h]=this.getKeySystemSelectionPromise([c]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const m=new fi("ISO-23001-7",h,(p=Sa(f))!=null?p:"");return m.pssh=new Uint8Array(i),m.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const C=this.createMediaKeySessionContext({decryptdata:m,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(C,s,i,"encrypted-event-no-match")})}),A.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===Te.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof ct?o(u):o(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return yA===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){const i=SS(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),a=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),c.then(u=>u?this.setMediaKeysServerCertificate(h,e,u):h))),o.mediaKeys.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),o.mediaKeys})}return a.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Pt.hexDump(e.keyId||[])}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Pt.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Pt.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])}
|
|
35
|
+
} (data length: ${t&&t.byteLength})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,s)=>{const i=Mn(this.config),r=e.map(Ba).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Sa(a);o?t(o):s(new Error(`Unable to find format for key-system "${a}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ct?this.hls.trigger(y.ERROR,e.data):this.hls.trigger(y.ERROR,{type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ba(e.keyFormat),r=i?[i]:Mn(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Mn(this.config)),e.length===0)throw new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const f=o.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=e.decryptdata.pssh=f.initData?new Uint8Array(f.initData):null}catch(f){var l;if(this.warn(f.message),(l=this.hls)!=null&&l.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${t} length: ${s?s.byteLength:null})`);const h=new vl,u=e._onmessage=f=>{const g=e.mediaKeysSession;if(!g){h.emit("error",new Error("invalid state"));return}const{messageType:p,message:m}=f;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${m.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,m).catch(C=>{this.handleError(C),h.emit("error",C)}):p==="license-release"?e.keySystem===Te.FAIRPLAY&&(this.updateKeySession(e,Io("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;h.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",u),e.mediaKeysSession.addEventListener("keystatuseschange",d);const A=new Promise((f,g)=>{h.on("error",g),h.on("keyStatus",p=>{p.startsWith("usable")?f():p==="output-restricted"?g(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c}`)}).catch(f=>{throw new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>A).catch(f=>{throw h.removeAllListeners(),this.removeSession(e),f}).then(()=>(h.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Pt.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Pt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,A,f,g)=>{a(d.data)},onError:(d,A,f,g)=>{o(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:$e({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,A,f)=>{o(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,A,f)=>{o(new Error("aborted"))}};i.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s==null?void 0:s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const A=(a=h.querySelector("name"))==null?void 0:a.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;A&&f&&e.setRequestHeader(A,f)}}const l=i.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Io(atob(c))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(h){this.error(h)}i(l)}else{const l=s.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new ct({type:re.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==Te.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},fi.clearKeyUriToKeyIdMap();const s=t.length;Ds.CDMCleanupPromise=Promise.all(t.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Ds.CDMCleanupPromise=void 0;class ct extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var je;(function(n){n.MANIFEST="m",n.AUDIO="a",n.VIDEO="v",n.MUXED="av",n.INIT="i",n.CAPTION="c",n.TIMED_TEXT="tt",n.KEY="k",n.OTHER="o"})(je||(je={}));var Lo;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(Lo||(Lo={}));var Rs;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(Rs||(Rs={}));const hv={[Rs.OBJECT]:["br","d","ot","tb"],[Rs.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Rs.SESSION]:["cid","pr","sf","sid","st","v"],[Rs.STATUS]:["bs","rtp"]};class mi{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(s=>s instanceof mi?s:new mi(s))),this.value=e,this.params=t}}class vf{constructor(e){this.description=void 0,this.description=e}}const uv="Dict";function dv(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Av(n,e,t,s){return new Error(`failed to ${n} "${dv(e)}" as ${t}`,{cause:s})}const hu="Bare Item",fv="Boolean",gv="Byte Sequence",mv="Decimal",pv="Integer";function Ev(n){return n<-999999999999999||999999999999999<n}const Cv=/[\x00-\x1f\x7f]+/,Iv="Token",yv="Key";function Ht(n,e,t){return Av("serialize",n,e,t)}function Bv(n){if(typeof n!="boolean")throw Ht(n,fv);return n?"?1":"?0"}function Tv(n){return btoa(String.fromCharCode(...n))}function Sv(n){if(ArrayBuffer.isView(n)===!1)throw Ht(n,gv);return`:${Tv(n)}:`}function Rf(n){if(Ev(n))throw Ht(n,pv);return n.toString()}function _v(n){return`@${Rf(n.getTime()/1e3)}`}function wf(n,e){if(n<0)return-wf(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const i=Math.floor(n*t);return(i%2===0?i:i+1)/t}else return Math.round(n*t)/t}function xv(n){const e=wf(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ht(n,mv);const t=e.toString();return t.includes(".")?t:`${t}.0`}const vv="String";function Rv(n){if(Cv.test(n))throw Ht(n,vv);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function wv(n){return n.description||n.toString().slice(7,-1)}function uu(n){const e=wv(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ht(e,Iv);return e}function bo(n){switch(typeof n){case"number":if(!W(n))throw Ht(n,hu);return Number.isInteger(n)?Rf(n):xv(n);case"string":return Rv(n);case"symbol":return uu(n);case"boolean":return Bv(n);case"object":if(n instanceof Date)return _v(n);if(n instanceof Uint8Array)return Sv(n);if(n instanceof vf)return uu(n);default:throw Ht(n,hu)}}function Mo(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Ht(n,yv);return n}function Dl(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${Mo(e)}`:`;${Mo(e)}=${bo(t)}`).join("")}function Df(n){return n instanceof mi?`${bo(n.value)}${Dl(n.params)}`:bo(n)}function Dv(n){return`(${n.value.map(Df).join(" ")})${Dl(n.params)}`}function Lv(n,e={whitespace:!0}){if(typeof n!="object")throw Ht(n,uv);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof mi||(r=new mi(r));let a=Mo(i);return r.value===!0?a+=Dl(r.params):(a+="=",Array.isArray(r.value)?a+=Dv(r):a+=Df(r)),a}).join(`,${s}`)}function bv(n,e){return Lv(n,e)}const Mv=n=>n==="ot"||n==="sf"||n==="st",Fv=n=>typeof n=="number"?W(n):n!=null&&n!==""&&n!==!1;function Pv(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")}function kv(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}const er=n=>Math.round(n),Ov=(n,e)=>(e!=null&&e.baseUrl&&(n=Pv(n,e.baseUrl)),encodeURIComponent(n)),Vn=n=>er(n/100)*100,Qv={br:er,d:er,bl:Vn,dl:Vn,mtp:Vn,nor:Ov,rtp:Vn,tb:er};function Gv(n,e){const t={};if(n==null||typeof n!="object")return t;const s=Object.keys(n).sort(),i=Ge({},Qv,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return s.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const l=i[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Fv(o)&&(Mv(a)&&typeof o=="string"&&(o=new vf(o)),t[a]=o))}),t}function Lf(n,e={}){return n?bv(Gv(n,e),Ge({whitespace:!1},e)):""}function Uv(n,e={}){if(!n)return{};const t=Object.entries(n),s=Object.entries(hv).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),i=t.reduce((r,a)=>{var o,l;const[c,h]=a,u=((o=s.find(d=>d[1].includes(c)))==null?void 0:o[0])||Rs.REQUEST;return(l=r[u])!=null||(r[u]={}),r[u][c]=h,r},{});return Object.entries(i).reduce((r,[a,o])=>(r[a]=Lf(o,e),r),{})}function Nv(n,e,t){return Ge(n,Uv(e,t))}const Hv="CMCD";function Kv(n,e={}){if(!n)return"";const t=Lf(n,e);return`${Hv}=${encodeURIComponent(t)}`}const du=/CMCD=[^&#]+/;function Vv(n,e,t){const s=Kv(e,t);if(!s)return n;if(du.test(n))return n.replace(du,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class bf{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:je.MANIFEST,su:!this.initialized})}catch(r){w.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===je.VIDEO||o===je.AUDIO||o==je.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){w.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||kv(),this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Lo.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ge(t,this.createData());const s=t.ot===je.INIT||t.ot===je.VIDEO||t.ot===je.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((r,a)=>(i.includes(a)&&(r[a]=t[a]),r),{})),this.useHeaders?(e.headers||(e.headers={}),Nv(e.headers,t)):e.url=Vv(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return je.TIMED_TEXT;if(e.sn==="initSegment")return je.INIT;if(t==="audio")return je.AUDIO;if(t==="main")return this.hls.audioTracks.length?je.VIDEO:je.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===je.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,s=e===je.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Le.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const Yv=3e5;class Mf{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=w.log.bind(w,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===Ve.SendAlternateToPenaltyBox&&s.flags===ht.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=i.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),s.resolved||w.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Yv&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,UA(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===ye.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===ye.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new Fe(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,A=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),A&&(i[u.SUBTITLES]=A,u.SUBTITLES=A);const f=Ff(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new bs({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)g.addGroupId("audio",`${h.audioGroups[p]}_clone_${a}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)g.addGroupId("text",`${h.subtitleGroups[p]}_clone_${a}`);return g});t.push(...c),Au(this.audioTracks,s,l,a),Au(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,A)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":m}=f;if(g)try{this.uri=new self.URL(g,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const C={steeringManifest:f,url:i.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,C),m&&this.updatePathwayPriority(m)},onError:(h,u,d,A)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Au(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=Ge({},a);return o.details=void 0,o.attrs=new Fe(o.attrs),o.url=o.attrs.URI=Ff(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Ff(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const l=new self.URL(n);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const Jv=/^age:\s*[\d.]+\s*$/im;class Pf{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new gn,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{this.callbacks.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&W(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType==="text"?t.responseText:null;if(a>=200&&a<300){const u=o??t.response;if(u!=null){s.loading.end=Math.max(self.performance.now(),s.loading.first);const d=t.responseType==="arraybuffer"?u.byteLength:u.length;if(s.loaded=s.total=d,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first),!this.callbacks)return;const A=this.callbacks.onProgress;if(A&&A(s,e,u,t),!this.callbacks)return;const f={url:t.responseURL,data:u,code:a};this.callbacks.onSuccess(f,s,e,t);return}}const l=r.loadPolicy.errorRetry,c=s.retry,h={url:e.url,data:void 0,code:a};pr(l,c,!1,h)?this.retry(l):(w.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,s))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(pr(e,t,!0))this.retry(e);else{var s;w.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=yl(e,s.retry),s.retry++,w.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Jv.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function zv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const qv=/(\d+)-(\d+)\/(\d+)/;class fu{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Wv,this.controller=new self.AbortController,this.stats=new gn}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=$v(e,this.controller.signal),a=s.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&W(c)?c:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},t.timeout),self.fetch(this.request).then(u=>{this.response=this.loader=u;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},h-(d-i.loading.start)),!u.ok){const{status:A,statusText:f}=u;throw new Zv(f||"fetch, bad network response",A,u)}return i.loading.first=d,i.total=jv(u.headers)||i.total,a&&W(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,a):o?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const A=u[l];A&&(i.loaded=i.total=A);const f={url:d.url,data:u,code:d.status};a&&!W(t.highWaterMark)&&a(i,e,u,d),s.onSuccess(f,i,e,d)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const d=u&&u.code||0,A=u?u.message:null;s.onError({code:d,text:A},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new JA,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush(),e)):r(t,s,h,e),l()}).catch(()=>Promise.reject());return l()}}function $v(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ge({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function Xv(n){const e=qv.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function jv(n){const e=n.get("Content-Range");if(e){const s=Xv(e);if(W(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function Wv(n,e){return new self.Request(n.url,e)}class Zv extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const eR=/\s/,tR={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let g=0;g<r.chars.length;g++)eR.test(r.chars[g].uchar)&&o?l++:(c+=r.chars[g].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const A=If(c.trim()),f=wl(e,t,A);n!=null&&(u=n.cues)!=null&&u.getCueById(f)||(a=new h(e,t,A),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,A)=>d.line==="auto"||A.line==="auto"?0:d.line>8&&A.line>8?A.line-d.line:d.line-A.line),i.forEach(d=>kA(n,d))),i}},sR={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},kf=$e($e({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Pf,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:VA,bufferController:gf,capLevelController:Ur,errorController:HA,fpsController:xf,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:yA,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:sR},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},iR()),{},{subtitleStreamController:Af,subtitleTrackController:ff,timelineController:Sf,audioStreamController:uf,audioTrackController:df,emeController:Ds,cmcdController:bf,contentSteeringController:Mf});function iR(){return{cueHandler:tR,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function nR(n,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=Fo(n),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=e[a]===void 0,l=[];i.forEach(c=>{const h=`${r}Loading${c}`,u=e[h];if(u!==void 0&&o){l.push(h);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=u,d.maxTimeToFirstByteMs=u;break;case"MaxRetry":d.errorRetry.maxNumRetry=u,d.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":d.errorRetry.retryDelayMs=u,d.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=u,d.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&w.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),$e($e({},t),e)}function Fo(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Fo):Object.keys(n).reduce((e,t)=>(e[t]=Fo(n[t]),e),{}):n}function rR(n){const e=n.loader;e!==fu&&e!==Pf?(w.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):zv()&&(n.loader=fu,n.progressive=!0,n.enableSoftwareAES=!0,w.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Ka;class aR extends Or{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{var u,d;const A=h.attrs;let{audioCodec:f,videoCodec:g}=h;((u=f)==null?void 0:u.indexOf("mp4a.40.34"))!==-1&&(Ka||(Ka=/chrome|firefox/i.test(navigator.userAgent)),Ka&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=fr(f,s)),((d=g)==null?void 0:d.indexOf("avc1"))===0&&(g=h.videoCodec=i_(g));const{width:p,height:m,unknownCodecs:C}=h;if(o||(o=!!(p&&m)),l||(l=!!g),c||(c=!!f),C!=null&&C.length||f&&!Ra(f,"audio",s)||g&&!Ra(g,"video",s))return;const{CODECS:E,"FRAME-RATE":B,"HDCP-LEVEL":I,"PATHWAY-ID":_,RESOLUTION:S,"VIDEO-RANGE":x}=A,v=`${`${_||"."}-`}${h.bitrate}-${S}-${B}-${E}-${x}-${I}`;if(r[v])if(r[v].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const D=a[v]+=1;h.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const U=new bs(h);r[v]=U,i.push(U)}else r[v].addGroupId("audio",A.AUDIO),r[v].addGroupId("text",A.SUBTITLES);else{const D=new bs(h);r[v]=D,a[v]=1,i.push(D)}}),this.filterAndSortMediaOptions(i,t,o,l,c)}filterAndSortMediaOptions(e,t,s,i,r){let a=[],o=[],l=e;if((s||i)&&r&&(l=l.filter(({videoCodec:f,videoRange:g,width:p,height:m})=>(!!f||!!(p&&m))&&m_(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:f}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Ra(g.audioCodec,"audio",f)),gu(a)}t.subtitles&&(o=t.subtitles,gu(o));const c=l.slice(0);l.sort((f,g)=>{if(f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&f.height!==g.height)return f.height-g.height;if(f.frameRate!==g.frameRate)return f.frameRate-g.frameRate;if(f.videoRange!==g.videoRange)return gr.indexOf(f.videoRange)-gr.indexOf(g.videoRange);if(f.videoCodec!==g.videoCodec){const p=Th(f.videoCodec),m=Th(g.videoCodec);if(p!==m)return m-p}if(f.uri===g.uri&&f.codecSet!==g.codecSet){const p=Ar(f.codecSet),m=Ar(g.codecSet);if(p!==m)return m-p}return f.averageBitrate!==g.averageBitrate?f.averageBitrate-g.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){h=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===h){var u;this._firstLevel=f;const g=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const m=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);m>p&&p===kf.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}const d=r&&!i,A={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:!d&&a.some(f=>!!f.url)};this.hls.trigger(y.MANIFEST_PARSED,A),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:F.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&a.details&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i==null?void 0:i.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ye.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===se.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=this._levels[i];if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(i,t,a.details)):(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:t,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const s=this._levels.filter((i,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));UA(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(y.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function gu(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class oR{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=F.KEY_LOAD_ERROR,s,i,r){return new Xt({type:re.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const a=t[r];if(i<=a.cc&&(s==="initSegment"||a.sn==="initSegment"||s<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,F.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,F.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,F.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=s.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,A,f,g)=>{const{frag:p,keyInfo:m,url:C}=f;if(!p.decryptdata||m!==this.keyUriToKeyInfo[C])return o(this.createKeyLoadError(p,F.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));m.decryptdata.key=p.decryptdata.key=new Uint8Array(d.data),p.keyLoader=null,m.loader=null,a({frag:p,keyInfo:m})},onError:(d,A,f,g)=>{this.resetLoader(A),o(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,$e({url:l.url,data:void 0},d)))},onTimeout:(d,A,f)=>{this.resetLoader(A),o(this.createKeyLoadError(t,F.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,A,f)=>{this.resetLoader(A),o(this.createKeyLoadError(t,F.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function Of(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ll(){if(!gs())return!1;const e=Of();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Qf(){if(!Ll())return!1;const n=gs();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(cn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(cn(e,"audio"))))}function lR(){var n;const e=Of();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const cR=250,tr=2,hR=.1,uR=.05;class dR{constructor(e,t,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:s,media:i,stalled:r}=this;if(i===null)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const p=self.performance.now()-r;w.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!Le.getBuffered(i).length){this.nudgeRetry=0;return}const h=Le.bufferInfo(i,a,0),u=h.nextStart||0;if(o){const p=h.len>tr,m=!u||t&&t.start<=a||u-a>tr&&!this.fragmentTracker.getPartialFragment(a);if(p||m)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(h.len>0)&&!u)return;const m=Math.max(u,h.start||0)-a,C=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,B=(C==null||(d=C.details)==null?void 0:d.live)?C.details.targetduration*2:tr,I=this.fragmentTracker.getPartialFragment(a);if(m>0&&(m<=B||I)){i.paused||this._trySkipBufferHole(I);return}}const A=self.performance.now();if(r===null){this.stalled=A;return}const f=A-r;if(!o&&f>=cR&&(this._reportStall(h),!this.media))return;const g=Le.bufferInfo(i,a,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(r===null)return;const a=r.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-a<s.maxBufferHole)&&t>s.highBufferWatchdogPeriod*1e3&&(w.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);w.warn(r.message),t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:i}=this;if(i===null)return 0;const r=i.currentTime,a=Le.bufferInfo(i,r,0),o=r<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&i.readyState<3,h=o-r;if(h>0&&(l||c)){if(h>t.maxBufferHole){const{fragmentTracker:d}=this;let A=!1;if(r===0){const f=d.getAppendedFrag(0,se.MAIN);f&&o<f.end&&(A=!0)}if(!A){const f=e||d.getAppendedFrag(r,se.MAIN);if(f){let g=!1,p=f.end;for(;p<o;){const m=d.getPartialFragment(p);if(m)p+=m.duration;else{g=!0;break}}if(g)return 0}}}const u=Math.max(o+uR,r+hR);if(w.warn(`skipping hole, adjusting currentTime from ${r} to ${u}`),this.moved=!0,this.stalled=null,i.currentTime=u,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${u}`);s.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return u}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:s,nudgeRetry:i}=this;if(s===null)return;const r=s.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const a=r+(i+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${a}`);w.warn(o.message),s.currentTime=a,t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);w.error(a.message),t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const AR=100;class fR extends Gr{constructor(e,t,s){super(e,t,s,"[stream-controller]",se.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.ERROR,this.onError,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.ERROR,this.onError,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:s}=this;if(this.stopLoad(),this.setInterval(AR),this.level=-1,!this.startFragRequested){let i=s.startLevel;i===-1&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),s.nextLoadLevel=i,this.level=s.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=N.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=N.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case N.WAITING_LEVEL:{const{levels:t,level:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=N.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=N.IDLE;break}break}case N.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,level:r}=this,a=i==null?void 0:i[r];this.resetStartWhenNotLoaded(a||null),this.state=N.IDLE}}break}this.state===N.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(y.BUFFER_EOS,g),this.state=N.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===N.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=r,this.state=N.WAITING_LEVEL;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let A=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&A&&A.sn!=="initSegment"&&this.fragmentTracker.getState(A)!==qe.OK){var f;const p=((f=this.backtrackFragment)!=null?f:A).sn-c.startSN,m=c.fragments[p-1];m&&A.cc===m.cc&&(A=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(A&&this.isLoopLoading(A,d)){if(!A.gap){const p=this.audioOnly&&!this.altAudio?ve.AUDIO:ve.VIDEO,m=(p===ve.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,p,se.MAIN)}A=this.getNextFragmentLoopLoading(A,c,o,se.MAIN,u)}A&&(A.initSegment&&!A.initSegment.data&&!this.bitrateTest&&(A=A.initSegment),this.loadFragment(A,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===qe.NOT_LOADED||i===qe.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,s)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,se.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:s=0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,h=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case N.KEY_LOADING:case N.FRAG_LOADING:case N.FRAG_LOADING_WAITING_RETRY:case N.PARSING:case N.PARSED:this.state=N.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new dR(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;W(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const s=this.getMainFwdBufferInfo();if(s===null||s.len===0){this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let s=!1,i=!1;t.levels.forEach(r=>{const a=r.audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!lR(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==N.IDLE)return;const i=s[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=N.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i}=this,r=t.level,a=t.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[r],c=this.fragCurrent;c&&(this.state===N.FRAG_LOADING||this.state===N.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(a.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(y.LEVEL_UPDATED,{details:a,level:r}),this.state===N.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=N.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level],l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),A=this.transmuxer=this.transmuxer||new cf(this.hls,se.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=f!==-1,p=new Qr(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[s.cc];A.push(r,u,d,c,s,i,l.totalduration,h,p,m)}onAudioTrackSwitching(e,t){const s=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;s&&(r.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=t.id,i=!!this.hls.audioTracks[s].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s&&s.type!==se.MAIN)return;if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===N.PARSED&&(this.state=N.IDLE);return}const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),s.sn!=="initSegment"&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=N.ERROR;return}switch(t.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(se.MAIN,t);break;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===N.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===ye.LEVEL&&(this.state=N.IDLE);break;case F.BUFFER_APPEND_ERROR:case F.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===F.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!Le.getBuffered(e).length){const s=this.state!==N.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,s)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=N.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ve.AUDIO||this.audioOnly&&!this.altAudio){const s=(t===ve.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(s,t,se.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=Le.getBuffered(e),a=(i.length?i.start(0):0)-s;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),s+=a,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${t}`),e.currentTime=s}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state=N.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(y.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{video:u,text:d,id3:A,initSegment:f}=r,{details:g}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=N.PARSING,f){if(f!=null&&f.tracks){const E=l.initSegment||l;this._bufferInitSegment(h,f.tracks,E,a),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:s,tracks:f.tracks})}const m=f.initPTS,C=f.timescale;W(m)&&(this.initPTS[l.cc]={baseTime:m,timescale:C},i.trigger(y.INIT_PTS_FOUND,{frag:l,id:s,initPTS:m,timescale:C}))}if(u&&g&&l.sn!=="initSegment"){const m=g.fragments[l.sn-1-g.startSN],C=l.sn===g.startSN,E=!m||l.cc>m.cc;if(r.independent!==!1){const{startPTS:B,endPTS:I,startDTS:_,endDTS:S}=u;if(c)c.elementaryStreams[u.type]={startPTS:B,endPTS:I,startDTS:_,endDTS:S};else if(u.firstKeyFrame&&u.independent&&a.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const x=this.getMainFwdBufferInfo(),b=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,v=u.firstKeyFramePTS?u.firstKeyFramePTS:B;if(!C&&b<v-this.config.maxBufferHole&&!E){this.backtrack(l);return}else E&&(l.gap=!0);l.setElementaryStreamInfo(u.type,l.start,I,l.start,S,!0)}else C&&B>tr&&(l.gap=!0);l.setElementaryStreamInfo(u.type,B,I,_,S),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,a,C||E)}else if(C||E)l.gap=!0;else{this.backtrack(l);return}}if(p){const{startPTS:m,endPTS:C,startDTS:E,endDTS:B}=p;c&&(c.elementaryStreams[ve.AUDIO]={startPTS:m,endPTS:C,startDTS:E,endDTS:B}),l.setElementaryStreamInfo(ve.AUDIO,m,C,E,B),this.bufferFragmentData(p,l,c,a)}if(g&&A!=null&&(t=A.samples)!=null&&t.length){const m={id:s,frag:l,details:g,samples:A.samples};i.trigger(y.FRAG_PARSING_METADATA,m)}if(g&&d){const m={id:s,frag:l,details:g,samples:d.samples};i.trigger(y.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,s,i){if(this.state!==N.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(y.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,se.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=N.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(Le.isBuffered(e,s)?t=this.getAppendedFrag(s):Le.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,s=this.currentFrag;if(s&&W(t)&&W(s.programDateTime)){const i=s.programDateTime+(t-s.start)*1e3;return new Date(i)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class us{static get version(){return"1.5.19"}static isMSESupported(){return Ll()}static isSupported(){return Qf()}static getMediaSource(){return gs()}static get Events(){return y}static get ErrorTypes(){return re}static get ErrorDetails(){return F}static get DefaultConfig(){return us.defaultConfig?us.defaultConfig:kf}static set DefaultConfig(e){us.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new vl,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,mS(e.debug||!1,"Hls instance");const t=this.config=nR(us.DefaultConfig,e);this.userConfig=e,t.progressive&&rR(t);const{abrController:s,bufferController:i,capLevelController:r,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new s(this),h=this.bufferController=new i(this),u=this.capLevelController=new r(this),d=new o(this),A=new l_(this),f=new A_(this),g=t.contentSteeringController,p=g?new g(this):null,m=this.levelController=new aR(this,p),C=new U_(this),E=new oR(this.config),B=this.streamController=new fR(this,C,E);u.setStreamController(B),d.setStreamController(B);const I=[A,m,B];p&&I.splice(1,0,p),this.networkControllers=I;const _=[c,h,u,d,f,C];this.audioTrackController=this.createController(t.audioTrackController,I);const S=t.audioStreamController;S&&I.push(new S(this,C,E)),this.subtitleTrackController=this.createController(t.subtitleTrackController,I);const x=t.subtitleStreamController;x&&I.push(new x(this,C,E)),this.createController(t.timelineController,_),E.emeController=this.emeController=this.createController(t.emeController,_),this.cmcdController=this.createController(t.cmcdController,_),this.latencyController=this.createController(f_,_),this.coreComponents=_,I.push(l);const b=l.onErrorOut;typeof b=="function"&&this.on(y.ERROR,b,l)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(w.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===y.ERROR;this.trigger(y.ERROR,{type:re.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){w.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){w.log("attachMedia"),this._media=e,this.trigger(y.MEDIA_ATTACHING,{media:e})}detachMedia(){w.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,s=this.url,i=this.url=gl.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,w.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.MANIFEST_LOADING,{url:e})}startLoad(e=-1){w.log(`startLoad(${e})`),this.started=!0,this.resumeBuffering();for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].startLoad(e),!(!this.started||!this.networkControllers));t++);}stopLoad(){w.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}resumeBuffering(){w.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()})}pauseBuffering(){w.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()})}swapAudioCodec(){w.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){w.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){w.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){w.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){w.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){w.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){w.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(w.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){g_(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}us.defaultConfig=void 0;const gR=Object.freeze(Object.defineProperty({__proto__:null,AbrController:VA,AttrList:Fe,AudioStreamController:uf,AudioTrackController:df,BasePlaylistController:Or,BaseSegment:pl,BaseStreamController:Gr,BufferController:gf,CMCDController:bf,CapLevelController:Ur,ChunkMetadata:Qr,ContentSteeringController:Mf,DateRange:ml,EMEController:Ds,ErrorActionFlags:ht,ErrorController:HA,ErrorDetails:F,ErrorTypes:re,Events:y,FPSController:xf,Fragment:qn,Hls:us,HlsSkip:ji,HlsUrlParameters:_o,KeySystemFormats:Ze,KeySystems:Te,Level:bs,LevelDetails:IA,LevelKey:fi,LoadStats:gn,MetadataSchema:ft,NetworkErrorAction:Ve,Part:CA,PlaylistLevelType:se,SubtitleStreamController:Af,SubtitleTrackController:ff,TimelineController:Sf,default:us,getMediaSource:gs,isMSESupported:Ll,isSupported:Qf},Symbol.toStringTag,{value:"Module"}));var mu,pu;const mR=typeof window<"u"&&typeof((mu=window.document)==null?void 0:mu.createElement)=="function"&&typeof((pu=window.navigator)==null?void 0:pu.userAgent)=="string";let Va=null;async function pR(...n){var e;(e=Va)!==null&&e!==void 0||(Va=await fC(()=>Promise.resolve().then(()=>gR),void 0));const t=Va.default;return t.isSupported()?new t(...n):null}function Gf(n,{unsuspend:e="loadedmetadata",start:t=!0,hls:s={},crossOrigin:i="anonymous",muted:r=!0,loop:a=!0,playsInline:o=!0,onVideoFrame:l,...c}={}){const h=$(f=>f.gl),u=T.useRef(null),d=Ci(()=>new Promise(async f=>{let g,p;typeof n=="string"?g=n:p=n;const m=Object.assign(document.createElement("video"),{src:g,srcObject:p,crossOrigin:i,loop:a,muted:r,playsInline:o,...c});if(g&&mR&&g.endsWith(".m3u8")){const E=u.current=await pR(s);E&&(E.on(y.MEDIA_ATTACHED,()=>void E.loadSource(g)),E.attachMedia(m))}const C=new Ng(m);"colorSpace"in C?C.colorSpace=h.outputColorSpace:C.encoding=h.outputEncoding,m.addEventListener(e,()=>f(C))}),[n]),A=d.source.data;return ER(A,l),T.useEffect(()=>(t&&d.image.play(),()=>{u.current&&(u.current.destroy(),u.current=null)}),[d,t]),d}const Nr=T.forwardRef(({children:n,src:e,...t},s)=>{const i=Gf(e,t);return T.useEffect(()=>()=>void i.dispose(),[i]),T.useImperativeHandle(s,()=>i,[i]),T.createElement(T.Fragment,null,n==null?void 0:n(i))}),ER=(n,e)=>{T.useEffect(()=>{if(!e||!n.requestVideoFrameCallback)return;let t;const s=(...i)=>{e(...i),t=n.requestVideoFrameCallback(s)};return n.requestVideoFrameCallback(s),()=>n.cancelVideoFrameCallback(t)},[n,e])};var Uf={exports:{}};(function(n,e){(function(t,s){n.exports=s()})(dC,function(){var t=function(){function s(A){return a.appendChild(A.dom),A}function i(A){for(var f=0;f<a.children.length;f++)a.children[f].style.display=f===A?"block":"none";r=A}var r=0,a=document.createElement("div");a.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",a.addEventListener("click",function(A){A.preventDefault(),i(++r%a.children.length)},!1);var o=(performance||Date).now(),l=o,c=0,h=s(new t.Panel("FPS","#0ff","#002")),u=s(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=s(new t.Panel("MB","#f08","#201"));return i(0),{REVISION:16,dom:a,addPanel:s,showPanel:i,begin:function(){o=(performance||Date).now()},end:function(){c++;var A=(performance||Date).now();if(u.update(A-o,200),A>l+1e3&&(h.update(1e3*c/(A-l),100),l=A,c=0,d)){var f=performance.memory;d.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return A},update:function(){o=this.end()},domElement:a,setMode:i}};return t.Panel=function(s,i,r){var a=1/0,o=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,u=48*c,d=3*c,A=2*c,f=3*c,g=15*c,p=74*c,m=30*c,C=document.createElement("canvas");C.width=h,C.height=u,C.style.cssText="width:80px;height:48px";var E=C.getContext("2d");return E.font="bold "+9*c+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=r,E.fillRect(0,0,h,u),E.fillStyle=i,E.fillText(s,d,A),E.fillRect(f,g,p,m),E.fillStyle=r,E.globalAlpha=.9,E.fillRect(f,g,p,m),{dom:C,update:function(B,I){a=Math.min(a,B),o=Math.max(o,B),E.fillStyle=r,E.globalAlpha=1,E.fillRect(0,0,h,g),E.fillStyle=i,E.fillText(l(B)+" "+s+" ("+l(a)+"-"+l(o)+")",d,A),E.drawImage(C,f+c,g,p-c,m,f,g,p-c,m),E.fillRect(f+p-c,g,c,m),E.fillStyle=r,E.globalAlpha=.9,E.fillRect(f+p-c,g,c,l((1-B/I)*m))}}},t})})(Uf);var CR=Uf.exports;const IR=AC(CR);function yR(n,e=[],t){const[s,i]=T.useState();return T.useLayoutEffect(()=>{const r=n();return i(r),()=>void 0},e),s}function BR({showPanel:n=0,className:e,parent:t}){const s=yR(()=>new IR,[]);return T.useEffect(()=>{if(s){const i=t&&t.current||document.body;s.showPanel(n),i==null||i.appendChild(s.dom);const r=(e??"").split(" ").filter(l=>l);r.length&&s.dom.classList.add(...r);const a=ko(()=>s.begin()),o=Gu(()=>s.end());return()=>{r.length&&s.dom.classList.remove(...r),i==null||i.removeChild(s.dom),a(),o()}}},[t,s,e,n]),null}class TR{constructor(e,t,s){this.name=e,this.fg=t,this.bg=s,this.gradient=null,this.PR=Math.round(window.devicePixelRatio||1),this.WIDTH=90*this.PR,this.HEIGHT=48*this.PR,this.TEXT_X=3*this.PR,this.TEXT_Y=2*this.PR,this.GRAPH_X=3*this.PR,this.GRAPH_Y=15*this.PR,this.GRAPH_WIDTH=84*this.PR,this.GRAPH_HEIGHT=30*this.PR,this.canvas=document.createElement("canvas"),this.canvas.width=this.WIDTH,this.canvas.height=this.HEIGHT,this.canvas.style.width="90px",this.canvas.style.height="48px",this.canvas.style.position="absolute",this.canvas.style.cssText="width:90px;height:48px",this.context=this.canvas.getContext("2d"),this.initializeCanvas()}createGradient(){if(!this.context)throw new Error("No context");const e=this.context.createLinearGradient(0,this.GRAPH_Y,0,this.GRAPH_Y+this.GRAPH_HEIGHT);let t;const s=this.fg;switch(this.fg.toLowerCase()){case"#0ff":t="#006666";break;case"#0f0":t="#006600";break;case"#ff0":t="#666600";break;case"#e1e1e1":t="#666666";break;default:t=this.bg;break}return e.addColorStop(0,t),e.addColorStop(1,s),e}initializeCanvas(){this.context&&(this.context.font="bold "+9*this.PR+"px Helvetica,Arial,sans-serif",this.context.textBaseline="top",this.gradient=this.createGradient(),this.context.fillStyle=this.bg,this.context.fillRect(0,0,this.WIDTH,this.HEIGHT),this.context.fillStyle=this.fg,this.context.fillText(this.name,this.TEXT_X,this.TEXT_Y),this.context.fillStyle=this.fg,this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT))}update(e,t,s,i,r=0){if(!this.context||!this.gradient)return;const a=Math.min(1/0,e),o=Math.max(s,e);i=Math.max(i,t),this.context.globalAlpha=1,this.context.fillStyle=this.bg,this.context.fillRect(0,0,this.WIDTH,this.GRAPH_Y),this.context.fillStyle=this.fg,this.context.fillText(`${e.toFixed(r)} ${this.name} (${a.toFixed(r)}-${parseFloat(o.toFixed(r))})`,this.TEXT_X,this.TEXT_Y),this.context.drawImage(this.canvas,this.GRAPH_X+this.PR,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT,this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT);const l=this.GRAPH_HEIGHT-(1-t/i)*this.GRAPH_HEIGHT;l>0&&(this.context.globalAlpha=1,this.context.fillStyle=this.gradient,this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y+this.GRAPH_HEIGHT-l,this.PR,l))}}const Nf=class $s{constructor({trackGPU:e=!1,logsPerSecond:t=30,samplesLog:s=60,samplesGraph:i=10,precision:r=2,minimal:a=!1,horizontal:o=!0,mode:l=0}={}){this.gl=null,this.ext=null,this.activeQuery=null,this.gpuQueries=[],this.threeRendererPatched=!1,this.frames=0,this.renderCount=0,this.isRunningCPUProfiling=!1,this.totalCpuDuration=0,this.totalGpuDuration=0,this.totalGpuDurationCompute=0,this.totalFps=0,this.gpuPanel=null,this.gpuPanelCompute=null,this.averageFps={logs:[],graph:[]},this.averageCpu={logs:[],graph:[]},this.averageGpu={logs:[],graph:[]},this.averageGpuCompute={logs:[],graph:[]},this.handleClick=c=>{c.preventDefault(),this.showPanel(++this.mode%this.dom.children.length)},this.handleResize=()=>{this.resizePanel(this.fpsPanel,0),this.resizePanel(this.msPanel,1),this.gpuPanel&&this.resizePanel(this.gpuPanel,2),this.gpuPanelCompute&&this.resizePanel(this.gpuPanelCompute,3)},this.mode=l,this.horizontal=o,this.minimal=a,this.trackGPU=e,this.samplesLog=s,this.samplesGraph=i,this.precision=r,this.logsPerSecond=t,this.dom=document.createElement("div"),this.initializeDOM(),this.beginTime=performance.now(),this.prevTime=this.beginTime,this.prevCpuTime=this.beginTime,this.fpsPanel=this.addPanel(new $s.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new $s.Panel("CPU","#0f0","#020"),1),this.setupEventListeners()}initializeDOM(){this.dom.style.cssText=`
|
|
36
|
+
position: fixed;
|
|
37
|
+
top: 0;
|
|
38
|
+
left: 0;
|
|
39
|
+
opacity: 0.9;
|
|
40
|
+
z-index: 10000;
|
|
41
|
+
${this.minimal?"cursor: pointer;":""}
|
|
42
|
+
`}setupEventListeners(){this.minimal?(this.dom.addEventListener("click",this.handleClick),this.showPanel(this.mode)):window.addEventListener("resize",this.handleResize)}async init(e){if(!e){console.error('Stats: The "canvas" parameter is undefined.');return}this.handleThreeRenderer(e)||await this.handleWebGPURenderer(e)||this.initializeWebGL(e)}handleThreeRenderer(e){return e.isWebGLRenderer&&!this.threeRendererPatched?(this.patchThreeRenderer(e),this.gl=e.getContext(),this.trackGPU&&this.initializeGPUTracking(),!0):!1}async handleWebGPURenderer(e){return e.isWebGPURenderer?(this.trackGPU&&(e.backend.trackTimestamp=!0,await e.hasFeatureAsync("timestamp-query")&&this.initializeWebGPUPanels()),this.info=e.info,!0):!1}initializeWebGPUPanels(){this.gpuPanel=this.addPanel(new $s.Panel("GPU","#ff0","#220"),2),this.gpuPanelCompute=this.addPanel(new $s.Panel("CPT","#e1e1e1","#212121"),3)}initializeWebGL(e){if(e instanceof WebGL2RenderingContext)this.gl=e;else if(e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas){if(this.gl=e.getContext("webgl2"),!this.gl)return console.error("Stats: Unable to obtain WebGL2 context."),!1}else return console.error("Stats: Invalid input type. Expected WebGL2RenderingContext, HTMLCanvasElement, or OffscreenCanvas."),!1;return!0}initializeGPUTracking(){this.gl&&(this.ext=this.gl.getExtension("EXT_disjoint_timer_query_webgl2"),this.ext&&(this.gpuPanel=this.addPanel(new $s.Panel("GPU","#ff0","#220"),2)))}begin(){this.isRunningCPUProfiling||this.beginProfiling("cpu-started"),!(!this.gl||!this.ext)&&(this.activeQuery&&this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.activeQuery=this.gl.createQuery(),this.activeQuery&&this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,this.activeQuery))}end(){this.renderCount++,this.gl&&this.ext&&this.activeQuery&&(this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.gpuQueries.push({query:this.activeQuery}),this.activeQuery=null)}update(){this.info?this.processWebGPUTimestamps():this.processGpuQueries(),this.endProfiling("cpu-started","cpu-finished","cpu-duration"),this.updateAverages(),this.resetCounters()}processWebGPUTimestamps(){this.totalGpuDuration=this.info.render.timestamp,this.totalGpuDurationCompute=this.info.compute.timestamp,this.addToAverage(this.totalGpuDurationCompute,this.averageGpuCompute)}updateAverages(){this.addToAverage(this.totalCpuDuration,this.averageCpu),this.addToAverage(this.totalGpuDuration,this.averageGpu)}resetCounters(){this.renderCount=0,this.totalCpuDuration===0&&this.beginProfiling("cpu-started"),this.totalCpuDuration=0,this.totalFps=0,this.beginTime=this.endInternal()}resizePanel(e,t){e.canvas.style.position="absolute",this.minimal?e.canvas.style.display="none":(e.canvas.style.display="block",this.horizontal?(e.canvas.style.top="0px",e.canvas.style.left=t*e.WIDTH/e.PR+"px"):(e.canvas.style.left="0px",e.canvas.style.top=t*e.HEIGHT/e.PR+"px"))}addPanel(e,t){return e.canvas&&(this.dom.appendChild(e.canvas),this.resizePanel(e,t)),e}showPanel(e){for(let t=0;t<this.dom.children.length;t++){const s=this.dom.children[t];s.style.display=t===e?"block":"none"}this.mode=e}processGpuQueries(){!this.gl||!this.ext||(this.totalGpuDuration=0,this.gpuQueries.forEach((e,t)=>{if(this.gl){const s=this.gl.getQueryParameter(e.query,this.gl.QUERY_RESULT_AVAILABLE),i=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT);if(s&&!i){const a=this.gl.getQueryParameter(e.query,this.gl.QUERY_RESULT)*1e-6;this.totalGpuDuration+=a,this.gl.deleteQuery(e.query),this.gpuQueries.splice(t,1)}}}))}endInternal(){this.frames++;const e=(performance||Date).now(),t=e-this.prevTime;if(e>=this.prevCpuTime+1e3/this.logsPerSecond){const s=Math.round(this.frames*1e3/t);this.addToAverage(s,this.averageFps),this.updatePanel(this.fpsPanel,this.averageFps,0),this.updatePanel(this.msPanel,this.averageCpu,this.precision),this.updatePanel(this.gpuPanel,this.averageGpu,this.precision),this.gpuPanelCompute&&this.updatePanel(this.gpuPanelCompute,this.averageGpuCompute),this.frames=0,this.prevCpuTime=e,this.prevTime=e}return e}addToAverage(e,t){t.logs.push(e),t.logs.length>this.samplesLog&&t.logs.shift(),t.graph.push(e),t.graph.length>this.samplesGraph&&t.graph.shift()}beginProfiling(e){window.performance&&(window.performance.mark(e),this.isRunningCPUProfiling=!0)}endProfiling(e,t,s){if(window.performance&&t&&this.isRunningCPUProfiling){window.performance.mark(t);const i=performance.measure(s,e,t);this.totalCpuDuration+=i.duration,this.isRunningCPUProfiling=!1}}updatePanel(e,t,s=2){if(t.logs.length>0){let i=0,r=.01;for(let l=0;l<t.logs.length;l++)i+=t.logs[l],t.logs[l]>r&&(r=t.logs[l]);let a=0,o=.01;for(let l=0;l<t.graph.length;l++)a+=t.graph[l],t.graph[l]>o&&(o=t.graph[l]);e&&e.update(i/Math.min(t.logs.length,this.samplesLog),a/Math.min(t.graph.length,this.samplesGraph),r,o,s)}}get domElement(){return this.dom}patchThreeRenderer(e){const t=e.render,s=this;e.render=function(i,r){s.begin(),t.call(this,i,r),s.end()},this.threeRendererPatched=!0}};Nf.Panel=TR;let SR=Nf;const Hf=T.forwardRef(({className:n,parent:e,id:t,clearStatsGlStyle:s,...i},r)=>{const a=$(l=>l.gl),o=T.useMemo(()=>{const l=new SR({...i});return l.init(a),l},[a]);return T.useImperativeHandle(r,()=>o.domElement,[o]),T.useEffect(()=>{if(o){const l=e&&e.current||document.body;l==null||l.appendChild(o.domElement),o.domElement.querySelectorAll("canvas").forEach(u=>{u.style.removeProperty("position")}),t&&(o.domElement.id=t),s&&o.domElement.removeAttribute("style"),o.domElement.removeAttribute("style");const c=(n??"").split(" ").filter(u=>u);c.length&&o.domElement.classList.add(...c);const h=Gu(()=>o.update());return()=>{c.length&&o.domElement.classList.remove(...c),l==null||l.removeChild(o.domElement),h()}}},[e,o,n,t,s]),null});Hf.displayName="StatsGl";function _R({size:n=256,frames:e=1/0}={}){const t=$(h=>h.viewport.dpr),{width:s,height:i}=$(h=>h.size),r=n||s*t,a=n||i*t,o=T.useMemo(()=>{const h=new Uu(r,a);return h.format=Nu,h.type=Hu,{depthTexture:h}},[r,a]);let l=0;const c=Ku(r,a,o);return Ue(h=>{(e===1/0||l<e)&&(h.gl.setRenderTarget(c),h.gl.render(h.scene,h.camera),h.gl.setRenderTarget(null),l++)}),c.depthTexture}function xR(n,e,t=1){const s=$(a=>a.viewport),i=e*(s.aspect>n/e?s.width/n:s.height/e);return[n*(s.aspect>n/e?s.width/n:s.height/e)*t,i*t,1]}function vR(n,e){const t=$(i=>i.pointer),[s]=T.useState(()=>{const i=new Br;return e&&Oo(i,e,{}),function(r,a){i.setFromCamera(t,n instanceof Hg?n:n.current);const o=this.constructor.prototype.raycast.bind(this);o&&o(i,a)}});return s}function Ya(n,e,t,s){return new(t||(t=Promise))(function(i,r){function a(c){try{l(s.next(c))}catch(h){r(h)}}function o(c){try{l(s.throw(c))}catch(h){r(h)}}function l(c){var h;c.done?i(c.value):(h=c.value,h instanceof t?h:new t(function(u){u(h)})).then(a,o)}l((s=s.apply(n,[])).next())})}const RR=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function Eu(n){return n=n.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const Kf=typeof window>"u",Mt=(()=>{if(Kf)return;const{userAgent:n,platform:e,maxTouchPoints:t}=window.navigator,s=/(iphone|ipod|ipad)/i.test(n),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(n)||s||i,isSafari12:/Version\/12.+Safari/.test(n),isFirefox:/Firefox/.test(n)}})();function wR(n,e,t){if(!t)return[e];const s=function(c){const h=`
|
|
43
|
+
precision highp float;
|
|
44
|
+
attribute vec3 aPosition;
|
|
45
|
+
varying float vvv;
|
|
46
|
+
void main() {
|
|
47
|
+
vvv = 0.31622776601683794;
|
|
48
|
+
gl_Position = vec4(aPosition, 1.0);
|
|
49
|
+
}
|
|
50
|
+
`,u=`
|
|
51
|
+
precision highp float;
|
|
52
|
+
varying float vvv;
|
|
53
|
+
void main() {
|
|
54
|
+
vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv;
|
|
55
|
+
enc = fract(enc);
|
|
56
|
+
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
|
|
57
|
+
gl_FragColor = enc;
|
|
58
|
+
}
|
|
59
|
+
`,d=c.createShader(35633),A=c.createShader(35632),f=c.createProgram();if(!(A&&d&&f))return;c.shaderSource(d,h),c.shaderSource(A,u),c.compileShader(d),c.compileShader(A),c.attachShader(f,d),c.attachShader(f,A),c.linkProgram(f),c.detachShader(f,d),c.detachShader(f,A),c.deleteShader(d),c.deleteShader(A),c.useProgram(f);const g=c.createBuffer();c.bindBuffer(34962,g),c.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const p=c.getAttribLocation(f,"aPosition");c.vertexAttribPointer(p,3,5126,!1,0,0),c.enableVertexAttribArray(p),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const m=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,m),c.deleteProgram(f),c.deleteBuffer(g),m.join("")}(n),i="801621810",r="8016218135",a="80162181161",o=Mt!=null&&Mt.isIpad?[["a7",a,12],["a8",r,15],["a8x",r,15],["a9",r,15],["a9x",r,15],["a10",r,15],["a10x",r,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",a,12],["a8",r,12],["a9",r,15],["a10",r,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let l;return s==="80162181255"?l=o.filter(([,,c])=>c>=14):(l=o.filter(([,c])=>c===s),l.length||(l=o)),l.map(([c])=>`apple ${c} gpu`)}class Cu extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const Ja=[],Iu=[];function DR(n,e){if(n===e)return 0;const t=n;n.length>e.length&&(n=e,e=t);let s=n.length,i=e.length;for(;s>0&&n.charCodeAt(~-s)===e.charCodeAt(~-i);)s--,i--;let r,a=0;for(;a<s&&n.charCodeAt(a)===e.charCodeAt(a);)a++;if(s-=a,i-=a,s===0)return i;let o,l,c=0,h=0,u=0;for(;h<s;)Iu[h]=n.charCodeAt(a+h),Ja[h]=++h;for(;u<i;)for(r=e.charCodeAt(a+u),o=u++,c=u,h=0;h<s;h++)l=r===Iu[h]?o:o+1,o=Ja[h],c=Ja[h]=o>c?l>c?c+1:l:l>o?o+1:l;return c}function LR(n){return n!=null}const bR=({mobileTiers:n=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:r="https://unpkg.com/detect-gpu@5.0.64/dist/benchmarks"}={})=>Ya(void 0,void 0,void 0,function*(){const a={};if(Kf)return{tier:0,type:"SSR"};const{isIpad:o=!!(Mt!=null&&Mt.isIpad),isMobile:l=!!(Mt!=null&&Mt.isMobile),screenSize:c=window.screen,loadBenchmarks:h=I=>Ya(void 0,void 0,void 0,function*(){const _=yield fetch(`${r}/${I}`).then(S=>S.json());if(parseInt(_.shift().split(".")[0],10)<4)throw new Cu("Detect GPU benchmark data is out of date. Please update to version 4x");return _})}=t;let{renderer:u}=t;const d=(I,_,S,x,b)=>({device:b,fps:x,gpu:S,isMobile:l,tier:I,type:_});let A,f="";if(u)u=Eu(u),A=[u];else{const I=s||function(S,x=!1){const b={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:x,powerPreference:"high-performance",stencil:!1};S&&delete b.powerPreference;const v=window.document.createElement("canvas"),D=v.getContext("webgl",b)||v.getContext("experimental-webgl",b);return D??void 0}(Mt==null?void 0:Mt.isSafari12,i);if(!I)return d(0,"WEBGL_UNSUPPORTED");const _=Mt!=null&&Mt.isFirefox?null:I.getExtension("WEBGL_debug_renderer_info");if(u=_?I.getParameter(_.UNMASKED_RENDERER_WEBGL):I.getParameter(I.RENDERER),!u)return d(1,"FALLBACK");f=u,u=Eu(u),A=function(S,x,b){return x==="apple gpu"?wR(S,x,b):[x]}(I,u,l)}const g=(yield Promise.all(A.map(function(I){var _;return Ya(this,void 0,void 0,function*(){const S=(K=>{const R=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const te of R)if(K.includes(te))return te})(I);if(!S)return;const x=`${l?"m":"d"}-${S}${o?"-ipad":""}.json`,b=a[x]=(_=a[x])!==null&&_!==void 0?_:h(x);let v;try{v=yield b}catch(K){if(K instanceof Cu)throw K;return}const D=function(K){var R;const te=(K=K.replace(/\([^)]+\)/,"")).match(/\d+/)||K.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(R=te==null?void 0:te.join("").replace(/\W|amd/g,""))!==null&&R!==void 0?R:""}(I);let U=v.filter(([,K])=>K===D);U.length||(U=v.filter(([K])=>K.includes(I)));const Q=U.length;if(Q===0)return;const j=I.split(/[.,()\[\]/\s]/g).sort().filter((K,R,te)=>R===0||K!==te[R-1]).join(" ");let V,[X,,,,Z]=Q>1?U.map(K=>[K,DR(j,K[2])]).sort(([,K],[,R])=>K-R)[0][0]:U[0],ae=Number.MAX_VALUE;const{devicePixelRatio:Y}=window,G=c.width*Y*c.height*Y;for(const K of Z){const[R,te]=K,oe=R*te,ue=Math.abs(G-oe);ue<ae&&(ae=ue,V=K)}if(!V)return;const[,,H,J]=V;return[ae,H,X,J]})}))).filter(LR).sort(([I=Number.MAX_VALUE,_],[S=Number.MAX_VALUE,x])=>I===S?_-x:I-S);if(!g.length){const I=RR.find(_=>u.includes(_));return I?d(0,"BLOCKLISTED",I):d(1,"FALLBACK",`${u} (${f})`)}const[,p,m,C]=g[0];if(p===-1)return d(0,"BLOCKLISTED",m,p,C);const E=l?n:e;let B=0;for(let I=0;I<E.length;I++)p>=E[I]&&(B=I);return d(B,"BENCHMARK",m,p,C)}),Vf=n=>Ci(()=>bR(n),["useDetectGPU"]);function MR({children:n,...e}){const t=Vf(e);return T.createElement(T.Fragment,null,n==null?void 0:n(t))}function FR(...n){const e=T.useRef([]);return e.current=n.map(t=>T.useContext(t)),T.useMemo(()=>({children:t})=>n.reduceRight((s,i,r)=>T.createElement(i.Provider,{value:e.current[r],children:s}),t),[])}function PR(n,e){const t=T.useRef(),[s]=T.useState(()=>e?e instanceof Xe?{current:e}:e:t),[i]=T.useState(()=>new Kg(void 0));T.useLayoutEffect(()=>{e&&(s.current=e instanceof Xe?e:e.current),i._root=s.current});const r=T.useRef({}),a=T.useMemo(()=>{const o={};return n.forEach(l=>Object.defineProperty(o,l.name,{enumerable:!0,get(){if(s.current)return r.current[l.name]||(r.current[l.name]=i.clipAction(l,s.current))},configurable:!0})),{ref:s,clips:n,actions:o,names:n.map(l=>l.name),mixer:i}},[n]);return Ue((o,l)=>i.update(l)),T.useEffect(()=>{const o=s.current;return()=>{r.current={},i.stopAllAction(),Object.values(a.actions).forEach(l=>{o&&i.uncacheAction(l,o)})}},[n]),a}const kR=`
|
|
60
|
+
#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )
|
|
61
|
+
vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );
|
|
62
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
63
|
+
vWorldPosition = worldPosition.xyz;
|
|
64
|
+
#endif
|
|
65
|
+
#endif
|
|
66
|
+
`,OR=`
|
|
67
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
68
|
+
uniform vec3 envMapSize;
|
|
69
|
+
uniform vec3 envMapPosition;
|
|
70
|
+
varying vec3 vWorldPosition;
|
|
71
|
+
|
|
72
|
+
vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) {
|
|
73
|
+
vec3 nDir = normalize( v );
|
|
74
|
+
vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir;
|
|
75
|
+
vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir;
|
|
76
|
+
vec3 rbminmax;
|
|
77
|
+
rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x;
|
|
78
|
+
rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y;
|
|
79
|
+
rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z;
|
|
80
|
+
float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z );
|
|
81
|
+
vec3 boxIntersection = vWorldPosition + nDir * correction;
|
|
82
|
+
return boxIntersection - cubePos;
|
|
83
|
+
}
|
|
84
|
+
#endif
|
|
85
|
+
`,QR=`
|
|
86
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
87
|
+
worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition );
|
|
88
|
+
#endif
|
|
89
|
+
`,GR=`
|
|
90
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
91
|
+
reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition );
|
|
92
|
+
#endif
|
|
93
|
+
`;function UR(n,e,t){n.defines.BOX_PROJECTED_ENV_MAP=!0,n.uniforms.envMapPosition={value:e},n.uniforms.envMapSize={value:t},n.vertexShader=`
|
|
94
|
+
varying vec3 vWorldPosition;
|
|
95
|
+
${n.vertexShader.replace("#include <worldpos_vertex>",kR)}`,n.fragmentShader=`
|
|
96
|
+
${OR}
|
|
97
|
+
${n.fragmentShader.replace("#include <envmap_physical_pars_fragment>",Vg.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );",`vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
|
|
98
|
+
${QR}
|
|
99
|
+
`).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );",`reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
|
|
100
|
+
${GR}
|
|
101
|
+
`)}`}function NR(n=new P,e=new P){const[t]=T.useState(()=>({position:new P,size:new P}));Oo(t,{position:n,size:e});const s=T.useRef(null),i=T.useMemo(()=>({ref:s,onBeforeCompile:r=>UR(r,t.position,t.size),customProgramCacheKey:()=>JSON.stringify(t.position.toArray())+JSON.stringify(t.size.toArray())}),[...t.position.toArray(),...t.size.toArray()]);return T.useLayoutEffect(()=>void(s.current.needsUpdate=!0),[t]),i}function HR(n,e,t=.9){return e*t+n*(1-t)}const KR=n=>Math.sqrt(1-Math.pow(n-1,2));class VR{constructor({size:e=256,maxAge:t=750,radius:s=.3,intensity:i=.2,interpolate:r=0,smoothing:a=0,minForce:o=.3,blend:l="screen",ease:c=KR}={}){this.size=e,this.maxAge=t,this.radius=s,this.intensity=i,this.ease=c,this.interpolate=r,this.smoothing=a,this.minForce=o,this.blend=l,this.trail=[],this.force=0,this.initTexture()}initTexture(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=this.size;const e=this.canvas.getContext("2d");if(e===null)throw new Error("2D not available");this.ctx=e,this.ctx.fillStyle="black",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.texture=new ci(this.canvas),this.canvas.id="touchTexture",this.canvas.style.width=this.canvas.style.height=`${this.canvas.width}px`}update(e){this.clear(),this.trail.forEach((t,s)=>{t.age+=e*1e3,t.age>this.maxAge&&this.trail.splice(s,1)}),this.trail.length||(this.force=0),this.trail.forEach(t=>{this.drawTouch(t)}),this.texture.needsUpdate=!0}clear(){this.ctx.globalCompositeOperation="source-over",this.ctx.fillStyle="black",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)}addTouch(e){const t=this.trail[this.trail.length-1];if(t){const s=t.x-e.x,i=t.y-e.y,r=s*s+i*i,a=Math.max(this.minForce,Math.min(r*1e4,1));if(this.force=HR(a,this.force,this.smoothing),this.interpolate){const o=Math.ceil(r/Math.pow(this.radius*.5/this.interpolate,2));if(o>1)for(let l=1;l<o;l++)this.trail.push({x:t.x-s/o*l,y:t.y-i/o*l,age:0,force:a})}}this.trail.push({x:e.x,y:e.y,age:0,force:this.force})}drawTouch(e){const t={x:e.x*this.size,y:(1-e.y)*this.size};let s=1;e.age<this.maxAge*.3?s=this.ease(e.age/(this.maxAge*.3)):s=this.ease(1-(e.age-this.maxAge*.3)/(this.maxAge*.7)),s*=e.force,this.ctx.globalCompositeOperation=this.blend;const i=this.size*this.radius*s,r=this.ctx.createRadialGradient(t.x,t.y,Math.max(0,i*.25),t.x,t.y,Math.max(0,i));r.addColorStop(0,`rgba(255, 255, 255, ${this.intensity})`),r.addColorStop(1,"rgba(0, 0, 0, 0.0)"),this.ctx.beginPath(),this.ctx.fillStyle=r,this.ctx.arc(t.x,t.y,Math.max(0,i),0,Math.PI*2),this.ctx.fill()}}function Yf(n={}){const{size:e,maxAge:t,radius:s,intensity:i,interpolate:r,smoothing:a,minForce:o,blend:l,ease:c}=n,h=T.useMemo(()=>new VR(n),[e,t,s,i,r,a,o,l,c]);Ue((d,A)=>void h.update(A));const u=T.useCallback(d=>h.addTouch(d.uv),[h]);return[h.texture,u]}const YR=({children:n,...e})=>{const t=Yf(e);return T.createElement(T.Fragment,null,n==null?void 0:n(t))},JR=T.forwardRef(({font:n,color:e="#cbcbcb",bevelSize:t=.04,debug:s=!1,children:i,...r},a)=>{const[o,l]=T.useState(0),c=T.useCallback((d=1)=>l(o+d),[o]),h=T.useCallback((d=1)=>l(o-d),[o]),u=T.useMemo(()=>({incr:c,decr:h}),[c,h]);return T.useImperativeHandle(a,()=>u,[u]),T.createElement("group",r,T.createElement(T.Suspense,{fallback:null},T.createElement(Vu,{top:!0,cacheKey:JSON.stringify({counter:o,font:n})},T.createElement(Yu,{bevelEnabled:!0,bevelSize:t,font:n},s?T.createElement("meshNormalMaterial",{wireframe:!0}):T.createElement("meshStandardMaterial",{color:e}),o))),i)});function zR(n){const e=T.useRef(null);return T.useLayoutEffect(()=>{var t;const s=(t=e.current)==null?void 0:t.parent,i=s==null?void 0:s.geometry;if(i){const r=s.material;s.material=e.current.__r3f.objects;const a=[...i.groups];return i.clearGroups(),s.material.forEach((o,l)=>{l<s.material.length-1&&(o.depthWrite=!1),i.addGroup(0,1/0,l)}),()=>{s.material=r,i.groups=a}}}),T.createElement("group",be({ref:e},n))}const qR=T.forwardRef(({mixBlur:n=0,mixStrength:e=.5,resolution:t=256,blur:s=[0,0],args:i=[1,1],minDepthThreshold:r=.9,maxDepthThreshold:a=1,depthScale:o=0,depthToBlurRatioBias:l=.25,mirror:c=0,children:h,debug:u=0,distortion:d=1,mixContrast:A=1,distortionMap:f,...g},p)=>{No({MeshReflectorMaterial:Yg}),T.useEffect(()=>{console.warn("Reflector has been deprecated and will be removed next major. Replace it with <MeshReflectorMaterial />!")},[]);const m=$(({gl:K})=>K),C=$(({camera:K})=>K),E=$(({scene:K})=>K);s=Array.isArray(s)?s:[s,s];const B=s[0]+s[1]>0,I=T.useRef(null);T.useImperativeHandle(p,()=>I.current,[]);const[_]=T.useState(()=>new xu),[S]=T.useState(()=>new P),[x]=T.useState(()=>new P),[b]=T.useState(()=>new P),[v]=T.useState(()=>new he),[D]=T.useState(()=>new P(0,0,-1)),[U]=T.useState(()=>new vt),[Q]=T.useState(()=>new P),[j]=T.useState(()=>new P),[V]=T.useState(()=>new vt),[X]=T.useState(()=>new he),[Z]=T.useState(()=>new ke),ae=T.useCallback(()=>{if(x.setFromMatrixPosition(I.current.matrixWorld),b.setFromMatrixPosition(C.matrixWorld),v.extractRotation(I.current.matrixWorld),S.set(0,0,1),S.applyMatrix4(v),Q.subVectors(x,b),Q.dot(S)>0)return;Q.reflect(S).negate(),Q.add(x),v.extractRotation(C.matrixWorld),D.set(0,0,-1),D.applyMatrix4(v),D.add(b),j.subVectors(x,D),j.reflect(S).negate(),j.add(x),Z.position.copy(Q),Z.up.set(0,1,0),Z.up.applyMatrix4(v),Z.up.reflect(S),Z.lookAt(j),Z.far=C.far,Z.updateMatrixWorld(),Z.projectionMatrix.copy(C.projectionMatrix),X.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),X.multiply(Z.projectionMatrix),X.multiply(Z.matrixWorldInverse),X.multiply(I.current.matrixWorld),_.setFromNormalAndCoplanarPoint(S,x),_.applyMatrix4(Z.matrixWorldInverse),U.set(_.normal.x,_.normal.y,_.normal.z,_.constant);const K=Z.projectionMatrix;V.x=(Math.sign(U.x)+K.elements[8])/K.elements[0],V.y=(Math.sign(U.y)+K.elements[9])/K.elements[5],V.z=-1,V.w=(1+K.elements[10])/K.elements[14],U.multiplyScalar(2/U.dot(V)),K.elements[2]=U.x,K.elements[6]=U.y,K.elements[10]=U.z+1,K.elements[14]=U.w},[]),[Y,G,H,J]=T.useMemo(()=>{const K={type:Yi,minFilter:oi,magFilter:oi},R=new Pl(t,t,K);R.depthBuffer=!0,R.depthTexture=new Uu(t,t),R.depthTexture.format=Nu,R.depthTexture.type=Hu;const te=new Pl(t,t,K),oe=new Jg({gl:m,resolution:t,width:s[0],height:s[1],minDepthThreshold:r,maxDepthThreshold:a,depthScale:o,depthToBlurRatioBias:l}),ue={mirror:c,textureMatrix:X,mixBlur:n,tDiffuse:R.texture,tDepth:R.depthTexture,tDiffuseBlur:te.texture,hasBlur:B,mixStrength:e,minDepthThreshold:r,maxDepthThreshold:a,depthScale:o,depthToBlurRatioBias:l,transparent:!0,debug:u,distortion:d,distortionMap:f,mixContrast:A,"defines-USE_BLUR":B?"":void 0,"defines-USE_DEPTH":o>0?"":void 0,"defines-USE_DISTORTION":f?"":void 0};return[R,te,oe,ue]},[m,s,X,t,c,B,n,e,r,a,o,l,u,d,f,A]);return Ue(()=>{if(!(I!=null&&I.current))return;I.current.visible=!1;const K=m.xr.enabled,R=m.shadowMap.autoUpdate;ae(),m.xr.enabled=!1,m.shadowMap.autoUpdate=!1,m.setRenderTarget(Y),m.state.buffers.depth.setMask(!0),m.autoClear||m.clear(),m.render(E,Z),B&&H.render(m,Y,G),m.xr.enabled=K,m.shadowMap.autoUpdate=R,I.current.visible=!0,m.setRenderTarget(null)}),T.createElement("mesh",be({ref:I},g),T.createElement("planeGeometry",{args:i}),h?h("meshReflectorMaterial",J):T.createElement("meshReflectorMaterial",J))});function $R(n){switch(n){case 64:return"-64px";case 128:return"-128px";case 256:return"-256px";case 512:return"-512px";default:return""}}const XR="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json",jR="https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d";function Jf(n=0,e=1024,t){const s=Ci(()=>fetch(XR).then(h=>h.json()),["matcapList"]),i=s[0],r=T.useMemo(()=>Object.keys(s).length,[]),o=`${T.useMemo(()=>typeof n=="string"?n:typeof n=="number"?s[n]:null,[n])||i}${$R(e)}.png`,l=`${jR}/${e}/${o}`;return[Ho(l,t),l,r]}const WR=({children:n,id:e,format:t,onLoad:s})=>{const i=Jf(e,t,s);return T.createElement(T.Fragment,null,n==null?void 0:n(i))},ZR="https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb",ew="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json";function zf(n=0,e={},t){const{repeat:s=[1,1],anisotropy:i=1,offset:r=[0,0]}=e,a=Ci(()=>fetch(ew).then(d=>d.json()),["normalsList"]),o=T.useMemo(()=>Object.keys(a).length,[]),l=a[0],c=a[n]||l,h=`${ZR}/normals/${c}`,u=Ho(h,t);return T.useLayoutEffect(()=>{u&&(u.wrapS=u.wrapT=li,u.repeat=new Qe(s[0],s[1]),u.offset=new Qe(r[0],r[1]),u.anisotropy=i)},[u,i,s,r]),[u,h,o]}const tw=({children:n,id:e,onLoad:t,...s})=>{const i=zf(e,s,t);return T.createElement(T.Fragment,null,n==null?void 0:n(i))},fs={uniforms:{strokeOpacity:1,fillOpacity:.25,fillMix:0,thickness:.05,colorBackfaces:!1,dashInvert:!0,dash:!1,dashRepeats:4,dashLength:.5,squeeze:!1,squeezeMin:.2,squeezeMax:1,stroke:new we("#ff0000"),backfaceStroke:new we("#0000ff"),fill:new we("#00ff00")},vertex:`
|
|
102
|
+
attribute vec3 barycentric;
|
|
103
|
+
|
|
104
|
+
varying vec3 v_edges_Barycentric;
|
|
105
|
+
varying vec3 v_edges_Position;
|
|
106
|
+
|
|
107
|
+
void initWireframe() {
|
|
108
|
+
v_edges_Barycentric = barycentric;
|
|
109
|
+
v_edges_Position = position.xyz;
|
|
110
|
+
}
|
|
111
|
+
`,fragment:`
|
|
112
|
+
#ifndef PI
|
|
113
|
+
#define PI 3.1415926535897932384626433832795
|
|
114
|
+
#endif
|
|
115
|
+
|
|
116
|
+
varying vec3 v_edges_Barycentric;
|
|
117
|
+
varying vec3 v_edges_Position;
|
|
118
|
+
|
|
119
|
+
uniform float strokeOpacity;
|
|
120
|
+
uniform float fillOpacity;
|
|
121
|
+
uniform float fillMix;
|
|
122
|
+
uniform float thickness;
|
|
123
|
+
uniform bool colorBackfaces;
|
|
124
|
+
|
|
125
|
+
// Dash
|
|
126
|
+
uniform bool dashInvert;
|
|
127
|
+
uniform bool dash;
|
|
128
|
+
uniform bool dashOnly;
|
|
129
|
+
uniform float dashRepeats;
|
|
130
|
+
uniform float dashLength;
|
|
131
|
+
|
|
132
|
+
// Squeeze
|
|
133
|
+
uniform bool squeeze;
|
|
134
|
+
uniform float squeezeMin;
|
|
135
|
+
uniform float squeezeMax;
|
|
136
|
+
|
|
137
|
+
// Colors
|
|
138
|
+
uniform vec3 stroke;
|
|
139
|
+
uniform vec3 backfaceStroke;
|
|
140
|
+
uniform vec3 fill;
|
|
141
|
+
|
|
142
|
+
// This is like
|
|
143
|
+
float wireframe_aastep(float threshold, float dist) {
|
|
144
|
+
float afwidth = fwidth(dist) * 0.5;
|
|
145
|
+
return smoothstep(threshold - afwidth, threshold + afwidth, dist);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
float wireframe_map(float value, float min1, float max1, float min2, float max2) {
|
|
149
|
+
return min2 + (value - min1) * (max2 - min2) / (max1 - min1);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
float getWireframe() {
|
|
153
|
+
vec3 barycentric = v_edges_Barycentric;
|
|
154
|
+
|
|
155
|
+
// Distance from center of each triangle to its edges.
|
|
156
|
+
float d = min(min(barycentric.x, barycentric.y), barycentric.z);
|
|
157
|
+
|
|
158
|
+
// for dashed rendering, we can use this to get the 0 .. 1 value of the line length
|
|
159
|
+
float positionAlong = max(barycentric.x, barycentric.y);
|
|
160
|
+
if (barycentric.y < barycentric.x && barycentric.y < barycentric.z) {
|
|
161
|
+
positionAlong = 1.0 - positionAlong;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// the thickness of the stroke
|
|
165
|
+
float computedThickness = wireframe_map(thickness, 0.0, 1.0, 0.0, 0.34);
|
|
166
|
+
|
|
167
|
+
// if we want to shrink the thickness toward the center of the line segment
|
|
168
|
+
if (squeeze) {
|
|
169
|
+
computedThickness *= mix(squeezeMin, squeezeMax, (1.0 - sin(positionAlong * PI)));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Create dash pattern
|
|
173
|
+
if (dash) {
|
|
174
|
+
// here we offset the stroke position depending on whether it
|
|
175
|
+
// should overlap or not
|
|
176
|
+
float offset = 1.0 / dashRepeats * dashLength / 2.0;
|
|
177
|
+
if (!dashInvert) {
|
|
178
|
+
offset += 1.0 / dashRepeats / 2.0;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// if we should animate the dash or not
|
|
182
|
+
// if (dashAnimate) {
|
|
183
|
+
// offset += time * 0.22;
|
|
184
|
+
// }
|
|
185
|
+
|
|
186
|
+
// create the repeating dash pattern
|
|
187
|
+
float pattern = fract((positionAlong + offset) * dashRepeats);
|
|
188
|
+
computedThickness *= 1.0 - wireframe_aastep(dashLength, pattern);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// compute the anti-aliased stroke edge
|
|
192
|
+
float edge = 1.0 - wireframe_aastep(computedThickness, d);
|
|
193
|
+
|
|
194
|
+
return edge;
|
|
195
|
+
}
|
|
196
|
+
`},sw=Ju(fs.uniforms,fs.vertex+`
|
|
197
|
+
void main() {
|
|
198
|
+
initWireframe();
|
|
199
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
200
|
+
}
|
|
201
|
+
`,fs.fragment+`
|
|
202
|
+
void main () {
|
|
203
|
+
// Compute color
|
|
204
|
+
|
|
205
|
+
float edge = getWireframe();
|
|
206
|
+
vec4 colorStroke = vec4(stroke, edge);
|
|
207
|
+
|
|
208
|
+
#ifdef FLIP_SIDED
|
|
209
|
+
colorStroke.rgb = backfaceStroke;
|
|
210
|
+
#endif
|
|
211
|
+
|
|
212
|
+
vec4 colorFill = vec4(fill, fillOpacity);
|
|
213
|
+
vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
|
|
214
|
+
|
|
215
|
+
gl_FragColor = outColor;
|
|
216
|
+
}
|
|
217
|
+
`);function iw(n,e){n.onBeforeCompile=t=>{t.uniforms={...t.uniforms,...e},t.vertexShader=t.vertexShader.replace("void main() {",`
|
|
218
|
+
${fs.vertex}
|
|
219
|
+
void main() {
|
|
220
|
+
initWireframe();
|
|
221
|
+
`),t.fragmentShader=t.fragmentShader.replace("void main() {",`
|
|
222
|
+
${fs.fragment}
|
|
223
|
+
void main() {
|
|
224
|
+
`),t.fragmentShader=t.fragmentShader.replace("#include <color_fragment>",`
|
|
225
|
+
#include <color_fragment>
|
|
226
|
+
float edge = getWireframe();
|
|
227
|
+
vec4 colorStroke = vec4(stroke, edge);
|
|
228
|
+
#ifdef FLIP_SIDED
|
|
229
|
+
colorStroke.rgb = backfaceStroke;
|
|
230
|
+
#endif
|
|
231
|
+
vec4 colorFill = vec4(mix(diffuseColor.rgb, fill, fillMix), mix(diffuseColor.a, fillOpacity, fillMix));
|
|
232
|
+
vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
|
|
233
|
+
|
|
234
|
+
diffuseColor.rgb = outColor.rgb;
|
|
235
|
+
diffuseColor.a *= outColor.a;
|
|
236
|
+
`)},n.side=Ei,n.transparent=!0}function nw(n,e){T.useEffect(()=>{var t;return void(n.fillOpacity.value=(t=e.fillOpacity)!==null&&t!==void 0?t:n.fillOpacity.value)},[e.fillOpacity]),T.useEffect(()=>{var t;return void(n.fillMix.value=(t=e.fillMix)!==null&&t!==void 0?t:n.fillMix.value)},[e.fillMix]),T.useEffect(()=>{var t;return void(n.strokeOpacity.value=(t=e.strokeOpacity)!==null&&t!==void 0?t:n.strokeOpacity.value)},[e.strokeOpacity]),T.useEffect(()=>{var t;return void(n.thickness.value=(t=e.thickness)!==null&&t!==void 0?t:n.thickness.value)},[e.thickness]),T.useEffect(()=>void(n.colorBackfaces.value=!!e.colorBackfaces),[e.colorBackfaces]),T.useEffect(()=>void(n.dash.value=!!e.dash),[e.dash]),T.useEffect(()=>void(n.dashInvert.value=!!e.dashInvert),[e.dashInvert]),T.useEffect(()=>{var t;return void(n.dashRepeats.value=(t=e.dashRepeats)!==null&&t!==void 0?t:n.dashRepeats.value)},[e.dashRepeats]),T.useEffect(()=>{var t;return void(n.dashLength.value=(t=e.dashLength)!==null&&t!==void 0?t:n.dashLength.value)},[e.dashLength]),T.useEffect(()=>void(n.squeeze.value=!!e.squeeze),[e.squeeze]),T.useEffect(()=>{var t;return void(n.squeezeMin.value=(t=e.squeezeMin)!==null&&t!==void 0?t:n.squeezeMin.value)},[e.squeezeMin]),T.useEffect(()=>{var t;return void(n.squeezeMax.value=(t=e.squeezeMax)!==null&&t!==void 0?t:n.squeezeMax.value)},[e.squeezeMax]),T.useEffect(()=>void(n.stroke.value=e.stroke?new we(e.stroke):n.stroke.value),[e.stroke]),T.useEffect(()=>void(n.fill.value=e.fill?new we(e.fill):n.fill.value),[e.fill]),T.useEffect(()=>void(n.backfaceStroke.value=e.backfaceStroke?new we(e.backfaceStroke):n.backfaceStroke.value),[e.backfaceStroke])}function rw(n){return!!(n!=null&&n.geometry)}function aw(n){return!!(n!=null&&n.isBufferGeometry)}function ow(n){return!!(n!=null&&n.current)}function yu(n){return(n==null?void 0:n.current)!==void 0}function Bu(n){return n.type==="WireframeGeometry"}function lw(){const n={};for(const e in fs.uniforms)n[e]={value:fs.uniforms[e]};return n}function cw(n,e){const s=n.getAttribute("position").count,i=[];for(let r=0;r<s;r++){const a=r%2===0,o=e?1:0;a?i.push(0,0,1,0,1,0,1,0,o):i.push(0,1,0,0,0,1,1,0,o)}return new ti(Float32Array.from(i),3)}function qf(n){const e=ow(n)?n.current:n;if(aw(e))return e;{if(Bu(e))throw new Error("Wireframe: WireframeGeometry is not supported.");const t=e.parent;if(rw(t)){if(Bu(t.geometry))throw new Error("Wireframe: WireframeGeometry is not supported.");return t.geometry}}}function $f(n,e){if(n.index){console.warn("Wireframe: Requires non-indexed geometry, converting to non-indexed geometry.");const s=n.toNonIndexed();n.copy(s),n.setIndex(null)}const t=cw(n,e);n.setAttribute("barycentric",t)}function hw({geometry:n,simplify:e=!1,...t}){No({MeshWireframeMaterial:sw});const[s,i]=T.useState(null);T.useLayoutEffect(()=>{const a=qf(n);if(!a)throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry.");$f(a,e),yu(n)&&i(a)},[e,n]);const r=yu(n)?s:n;return T.createElement(T.Fragment,null,r&&T.createElement("mesh",{geometry:r},T.createElement("meshWireframeMaterial",be({attach:"material",transparent:!0,side:Ei,polygonOffset:!0,polygonOffsetFactor:-4},t,{extensions:{derivatives:!0,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1}}))))}function uw({simplify:n=!1,...e}){const t=T.useRef(null),s=T.useMemo(()=>lw(),[fs.uniforms]);return nw(s,e),T.useLayoutEffect(()=>{const i=qf(t);if(!i)throw new Error("Wireframe: Must be a child of a Mesh, Line or Points object or specify a geometry prop.");const r=i.clone();return $f(i,n),()=>{i.copy(r),r.dispose()}},[n]),T.useLayoutEffect(()=>{const i=t.current.parent,r=i.material.clone();return iw(i.material,s),()=>{i.material.dispose(),i.material=r}},[]),T.createElement("object3D",{ref:t})}function dw({geometry:n,...e}){return n?T.createElement(hw,be({geometry:n},e)):T.createElement(uw,e)}function Aw({opacity:n,alphaMap:e}){const t=T.useRef(null),s=T.useRef(null),i=T.useRef({value:1}),r=T.useRef({value:null}),a=T.useRef({value:!1});return T.useLayoutEffect(()=>{t.current.onBeforeCompile=s.current.onBeforeCompile=o=>{const l=o.fragmentShader.indexOf("void main");let c="",h,u=l;for(;h!==`
|
|
237
|
+
`&&u<l+100;)h=o.fragmentShader.charAt(u),c+=h,u++;c=c.trim(),o.vertexShader=o.vertexShader.replace("void main() {",`
|
|
238
|
+
varying vec2 custom_vUv;
|
|
239
|
+
|
|
240
|
+
void main() {
|
|
241
|
+
custom_vUv = uv;
|
|
242
|
+
|
|
243
|
+
`),o.fragmentShader=o.fragmentShader.replace(c,`
|
|
244
|
+
uniform float uShadowOpacity;
|
|
245
|
+
uniform sampler2D uAlphaMap;
|
|
246
|
+
uniform bool uHasAlphaMap;
|
|
247
|
+
|
|
248
|
+
varying vec2 custom_vUv;
|
|
249
|
+
|
|
250
|
+
float bayerDither2x2( vec2 v ) {
|
|
251
|
+
return mod( 3.0 * v.y + 2.0 * v.x, 4.0 );
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
float bayerDither4x4( vec2 v ) {
|
|
255
|
+
vec2 P1 = mod( v, 2.0 );
|
|
256
|
+
vec2 P2 = mod( floor( 0.5 * v ), 2.0 );
|
|
257
|
+
return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
void main() {
|
|
261
|
+
float alpha =
|
|
262
|
+
uHasAlphaMap ?
|
|
263
|
+
uShadowOpacity * texture2D(uAlphaMap, custom_vUv).x
|
|
264
|
+
: uShadowOpacity;
|
|
265
|
+
|
|
266
|
+
if( ( bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ) ) / 16.0 >= alpha ) discard;
|
|
267
|
+
|
|
268
|
+
`),o.uniforms.uShadowOpacity=i.current,o.uniforms.uAlphaMap=r.current,o.uniforms.uHasAlphaMap=a.current}},[]),Ue(()=>{var o;const l=(o=t.current.__r3f)==null?void 0:o.parent;if(l){const c=l.material;c&&(i.current.value=n??c.opacity,e===!1?(r.current.value=null,a.current.value=!1):(r.current.value=e||c.alphaMap,a.current.value=!!r.current.value))}}),T.createElement(T.Fragment,null,T.createElement("meshDepthMaterial",{ref:t,attach:"customDepthMaterial",depthPacking:zg}),T.createElement("meshDistanceMaterial",{ref:s,attach:"customDistanceMaterial"}))}const Tu=new he,Su=new qg,za=new Tr,qa=new P;function fw(n,e){const t=this.geometry,s=this.material,i=this.matrixWorld;s!==void 0&&(t.boundingSphere===null&&t.computeBoundingSphere(),za.copy(t.boundingSphere),za.applyMatrix4(i),n.ray.intersectsSphere(za)!==!1&&(Tu.copy(i).invert(),Su.copy(n.ray).applyMatrix4(Tu),!(t.boundingBox!==null&&Su.intersectBox(t.boundingBox,qa)===null)&&e.push({distance:qa.distanceTo(n.ray.origin),point:qa.clone(),object:this})))}const gw=T.forwardRef(({options:n={video:!0},...e},t)=>{const s=Ci(()=>navigator.mediaDevices.getDisplayMedia(n),[]);return T.useEffect(()=>()=>{s==null||s.getTracks().forEach(i=>i.stop()),zu([])},[s]),T.createElement(Nr,be({ref:t},e,{src:s}))}),Xf=T.forwardRef(({constraints:n={audio:!1,video:{facingMode:"user"}},...e},t)=>{const s=Ci(()=>navigator.mediaDevices.getUserMedia(n),[]);return T.useEffect(()=>()=>{s==null||s.getTracks().forEach(i=>i.stop()),zu([])},[s]),T.createElement(Nr,be({ref:t},e,{src:s}))});function _u(n,e){return n.clone().add(e).multiplyScalar(.5)}function qs(n,e,t){const s=n.localToWorld(e);return t.worldToLocal(s)}const jf=T.createContext({}),mw=T.forwardRef(({camera:n,videoTexture:e={start:!0},manualDetect:t=!1,faceLandmarkerResult:s,manualUpdate:i=!1,makeDefault:r,smoothTime:a=.25,offset:o=!0,offsetScalar:l=80,eyes:c=!1,eyesAsOrigin:h=!0,depth:u=.15,debug:d=!1,facemesh:A},f)=>{var g,p;const m=$(oe=>oe.scene),C=$(oe=>oe.camera),E=$(oe=>oe.set),B=$(oe=>oe.get),I=n||C,_=T.useRef(null),[S]=T.useState(()=>new Xe),[x]=T.useState(()=>new P),[b]=T.useState(()=>new P),[v]=T.useState(()=>new P),[D]=T.useState(()=>new P),U=T.useCallback(()=>{S.parent=I.parent;const oe=_.current;if(oe){const{outerRef:ue,eyeRightRef:Je,eyeLeftRef:rt}=oe;if(Je.current&&rt.current){const{irisDirRef:Ii}=Je.current,{irisDirRef:Hr}=rt.current;Ii.current&&Hr.current&&ue.current&&(x.copy(qs(Ii.current,new P(0,0,0),ue.current)),b.copy(qs(Hr.current,new P(0,0,0),ue.current)),S.position.copy(qs(ue.current,_u(x,b),I.parent||m)),v.copy(qs(Ii.current,new P(0,0,1),ue.current)),D.copy(qs(Hr.current,new P(0,0,1),ue.current)),S.lookAt(ue.current.localToWorld(_u(v,D))))}else ue.current&&(S.position.copy(qs(ue.current,new P(0,0,0),I.parent||m)),S.lookAt(ue.current.localToWorld(new P(0,0,1))))}return S},[I,b,D,x,v,m,S]),[Q]=T.useState(()=>new Xe),j=T.useCallback(function(oe,ue){if(I){var Je;(Je=ue)!==null&&Je!==void 0||(ue=U()),a>0?(hi.damp3(Q.position,ue.position,a,oe,void 0,void 0,1e-9),hi.dampE(Q.rotation,ue.rotation,a,oe,void 0,void 0,1e-9)):(Q.position.copy(ue.position),Q.rotation.copy(ue.rotation)),I.position.copy(Q.position),I.rotation.copy(Q.rotation)}},[I,U,a,Q.position,Q.rotation]);Ue((oe,ue)=>{i||j(ue)});const V=T.useRef(null),[X,Z]=T.useState(),ae=qu(),Y=T.useCallback((oe,ue)=>{const Je=V.current;if(!Je)return;const rt=Je.source.data,Ii=ae==null?void 0:ae.detectForVideo(rt,oe);Z(Ii)},[ae]),G=T.useMemo(()=>Object.assign(Object.create($g.prototype),{computeTarget:U,update:j,facemeshApiRef:_}),[U,j]);T.useImperativeHandle(f,()=>G,[G]),T.useEffect(()=>{if(r){const oe=B().controls;return E({controls:G}),()=>E({controls:oe})}},[r,G,B,E]);const H=s??X,J=H==null?void 0:H.faceLandmarks[0],K=H==null||(g=H.facialTransformationMatrixes)==null?void 0:g[0],R=H==null||(p=H.faceBlendshapes)==null?void 0:p[0],te={onVideoFrame:Y,...e};return T.createElement(jf.Provider,{value:G},!t&&T.createElement(T.Suspense,{fallback:null},"src"in te?T.createElement(Nr,be({ref:V},te)):T.createElement(Xf,be({ref:V},te))),T.createElement($u,be({ref:_,children:T.createElement("meshNormalMaterial",{side:Ei})},A,{points:J,depth:u,facialTransformationMatrix:K,faceBlendshapes:R,eyes:c,eyesAsOrigin:h,offset:o,offsetScalar:l,debug:d,"rotation-z":Math.PI,visible:d})))}),pw=()=>T.useContext(jf),Nw=Object.freeze(Object.defineProperty({__proto__:null,AccumulativeShadows:Xg,AdaptiveDpr:jg,AdaptiveEvents:Wg,ArcballControls:qT,AsciiRenderer:Zg,BBAnchor:em,Backdrop:tm,BakeShadows:sm,Billboard:im,Bounds:nm,Box:rm,Bvh:am,CameraControls:tS,CameraShake:om,Capsule:lm,CatmullRomLine:cm,Caustics:hm,Center:Vu,Circle:um,Clone:Uo,Cloud:dm,CloudInstance:Am,Clouds:fm,ComputedAttribute:gm,Cone:mm,ContactShadows:pm,CubeCamera:Em,CubeTexture:rS,CubicBezierLine:Cm,CurveModifier:Im,CycleRaycast:ym,Cylinder:Bm,Decal:Tm,Detailed:Sm,DetectGPU:MR,DeviceOrientationControls:VT,Dodecahedron:_m,DragControls:BC,Edges:xm,Effects:vm,Environment:Rm,EnvironmentCube:wm,EnvironmentMap:Dm,EnvironmentPortal:Lm,Example:JR,Extrude:bm,FaceControls:mw,FaceLandmarker:Mm,FaceLandmarkerDefaults:Fm,Facemesh:$u,FacemeshDatas:Pm,FacemeshEye:km,FacemeshEyeDefaults:Om,Fbo:Qm,Fbx:aS,FirstPersonControls:jT,Fisheye:Gm,Float:Um,FlyControls:YT,GizmoHelper:Nm,GizmoViewcube:Hm,GizmoViewport:Km,Gltf:KT,GradientTexture:Vm,GradientType:Ym,Grid:Jm,Helper:zm,Html:qm,Hud:$m,Icosahedron:Xm,Image:jm,Instance:Wm,InstancedAttribute:Zm,Instances:ep,IsObject:to,KeyboardControls:Ky,Ktx2:oS,Lathe:tp,Lightformer:sp,Line:ip,Loader:yC,MapControls:JT,MarchingCube:np,MarchingCubes:rp,MarchingPlane:ap,Mask:op,MatcapTexture:WR,Merged:lp,MeshDiscardMaterial:cp,MeshDistortMaterial:hp,MeshPortalMaterial:up,MeshReflectorMaterial:dp,MeshRefractionMaterial:Ap,MeshTransmissionMaterial:fp,MeshWobbleMaterial:gp,MotionPathControls:nS,MultiMaterial:zR,NormalTexture:tw,Octahedron:mp,OrbitControls:pp,OrthographicCamera:Ep,Outlines:Cp,PerformanceMonitor:Ip,PerspectiveCamera:yp,PivotControls:Bp,Plane:Tp,Point:Sp,PointMaterial:_p,PointMaterialImpl:xp,PointerLockControls:XT,Points:vp,PointsBuffer:Rp,Polyhedron:wp,PositionMesh:Dp,PositionPoint:Lp,PositionalAudio:bp,Preload:Mp,PresentationControls:Uy,Progress:CC,QuadraticBezierLine:Fp,RandomizedLight:Pp,Reflector:qR,RenderCubeTexture:kp,RenderTexture:Op,Resize:Qp,Ring:Gp,RoundedBox:Up,Sampler:Np,ScreenQuad:Hp,ScreenSizer:HT,ScreenSpace:Kp,ScreenVideoTexture:gw,Scroll:TI,ScrollControls:II,Segment:Vp,SegmentObject:Yp,Segments:Jp,Select:zp,Shadow:qp,ShadowAlpha:Aw,Shape:$p,Sky:Xp,SoftShadows:jp,Sparkles:Wp,Sphere:Zp,Splat:eE,SpotLight:tE,SpotLightShadow:sE,SpriteAnimator:iE,Stage:nE,Stars:rE,Stats:BR,StatsGl:Hf,Svg:aE,Tetrahedron:oE,Text:lE,Text3D:Yu,Texture:cE,Torus:hE,TorusKnot:uE,TrackballControls:zT,Trail:dE,TrailTexture:YR,TransformControls:$T,Tube:AE,VideoTexture:Nr,View:fE,WebcamVideoTexture:Xf,Wireframe:dw,accumulativeContext:gE,calcPosFromAngles:mE,calculateScaleFactor:Ou,checkIfFrameIsEmpty:pE,createInstances:EE,getFirstFrame:CE,isWebGL2Available:IE,meshBounds:fw,shaderMaterial:Ju,useAnimations:PR,useAspect:xR,useBVH:yE,useBounds:BE,useBoxProjectedEnv:NR,useCamera:vR,useContextBridge:FR,useCubeCamera:TE,useCubeTexture:fl,useCursor:gC,useDepthBuffer:_R,useDetectGPU:Vf,useEnvironment:SE,useFBO:Ku,useFBX:Fr,useFaceControls:pw,useFaceLandmarker:qu,useFont:_E,useGLTF:fn,useGizmoContext:xE,useHelper:vE,useIntersect:RE,useKTX2:Pr,useKeyboardControls:Vy,useMask:wE,useMatcapTexture:Jf,useMotion:mA,useNormalTexture:zf,usePerformanceMonitor:DE,useProgress:Jo,useScroll:qo,useSelect:LE,useSpriteAnimator:bE,useSpriteLoader:ME,useSurfaceSampler:FE,useTexture:Ho,useTrail:PE,useTrailTexture:Yf,useVideoTexture:Gf},Symbol.toStringTag,{value:"Module"}));function Wf(n,e,t,s){const i=$(r=>r.camera);Ue(()=>{n.current!=null&&e(kE(i,n.current,t,s))})}function Ew({children:n,direction:e,angle:t=Math.PI/2}){const s=T.useRef(null);return Wf(s,i=>{s.current!=null&&(s.current.visible=i)},e,t),ts.jsx("group",{ref:s,children:n})}function Cw({children:n,direction:e,angle:t=Math.PI/2}){const s=T.useRef(null),[i,r]=T.useState(!1);return Wf(s,r,e,t),i?ts.jsx(ts.Fragment,{children:n}):null}function Iw({children:n,mode:e}){const t=Ko(e);return ts.jsx("group",{visible:t,children:n})}function yw({children:n,mode:e}){return Ko(e)?ts.jsx(ts.Fragment,{children:n}):null}function Bw({children:n}){const e=Vo();return ts.jsx("group",{visible:e==null||e==="visible",children:n})}function Tw({children:n}){const e=Vo();return e!="visible"&&e!=null?null:ts.jsx(ts.Fragment,{children:n})}function Sw(){const n=xr();return T.useMemo(()=>Yo.bind(null,n),[n])}function _w(){const[n,e]=T.useState(void 0),t=T.useRef(()=>{}),s=xr(),i=T.useCallback(async r=>{var l;(l=t.current)==null||l.call(t),t.current=void 0;let a=!1;t.current=()=>a=!0;const o=await Yo(s,r);if(a){o==null||o.delete();return}return t.current=()=>o==null?void 0:o.delete(),e(o),o},[s]);return T.useEffect(()=>()=>{var r;return void((r=t.current)==null?void 0:r.call(t))},[]),[n,i]}function xw(n,e={},t={},s="left"){const i=xr(),r=T.useMemo(()=>OE(),[]);Ue((a,o,l)=>r(typeof n=="function"?n:n.current,i,a.camera,o,e,t,s,o,a,l))}function vw({batchEvents:n,clickThesholdMs:e,contextMenuButton:t,customSort:s,dblClickThresholdMs:i,filter:r,forwardPointerCapture:a,intersectEveryFrame:o,pointerTypePrefix:l}){const c=$(A=>A.gl.domElement),h=$(A=>A.frameloop==="always"),u=$(A=>A.camera),d=$(A=>A.scene);return T.useEffect(()=>{const{destroy:A,update:f}=QE(c,()=>u,d,{batchEvents:n??h,clickThesholdMs:e,contextMenuButton:t,customSort:s,dblClickThresholdMs:i,filter:r,forwardPointerCapture:a,intersectEveryFrame:o,pointerTypePrefix:l}),g=ko(f);return()=>{g(),A()}},[c,u,d,h,n,e,t,s,i,r,a,o,l]),null}const Rw=()=>({enabled:!1,priority:0}),Hw=Object.freeze(Object.defineProperty({__proto__:null,ARButton:GE,CombinedPointer:UE,DefaultXRController:NE,DefaultXRControllerGrabPointer:HE,DefaultXRGaze:KE,DefaultXRHand:VE,DefaultXRHandGrabPointer:YE,DefaultXRHandTouchPointer:JE,DefaultXRInputSourceRayPointer:zE,DefaultXRInputSourceTeleportPointer:qE,DefaultXRScreenInput:$E,DefaultXRTransientPointer:XE,FallbackXRLayerImplementation:jE,IfFacingCamera:Cw,IfInSessionMode:WE,IfSessionModeSupported:yw,IfSessionVisible:Tw,Interactive:ZE,PointerCursorModel:e0,PointerEvents:vw,PointerRayModel:t0,RayGrab:s0,RootCombinedPointer:i0,ShowIfFacingCamera:Ew,ShowIfInSessionMode:n0,ShowIfSessionModeSupported:Iw,ShowIfSessionVisible:Bw,TeleportPointerRayModel:r0,TeleportTarget:a0,VRButton:o0,XR:l0,XRButton:c0,XRControllerComponent:h0,XRControllerModel:u0,XRDomOverlay:d0,XRHandJoint:A0,XRHandModel:f0,XRHitTest:g0,XRLayer:m0,XRLayerImplementation:p0,XRMeshModel:E0,XROrigin:C0,XRPlaneModel:I0,XRSpace:y0,createXRHitTestSource:B0,createXRStore:T0,defaultGrabPointerOpacity:S0,defaultRayPointerOpacity:_0,defaultTouchPointerOpacity:x0,isXRInputSourceState:v0,noEvents:Rw,privateKeys:R0,requestXRAnchor:Yo,requestXRHitTest:w0,useApplyXRSpaceMatrix:D0,useGetXRSpaceMatrix:L0,useGrabPointer:b0,useHover:M0,useInitRoomCapture:F0,useInteraction:P0,useLayerStore:k0,useLinesPointer:O0,useLoadXRControllerLayout:Q0,useLoadXRControllerModel:G0,usePointerXRInputSourceEvents:U0,useRayPointer:N0,useRequestXRAnchor:Sw,useSessionFeatureEnabled:H0,useSessionModeSupported:Ko,useTouchPointer:K0,useXR:V0,useXRAnchor:_w,useXRControllerButtonEvent:Y0,useXRControllerLocomotion:xw,useXRControllerState:J0,useXREvent:z0,useXRGazeState:q0,useXRHandState:$0,useXRHitTest:X0,useXRHitTestSource:j0,useXRInputSourceEvent:W0,useXRInputSourceState:Z0,useXRInputSourceStateContext:eC,useXRInputSourceStates:tC,useXRMeshGeometry:sC,useXRMeshes:iC,useXRPlaneGeometry:nC,useXRPlanes:rC,useXRReferenceSpace:aC,useXRRequestHitTest:oC,useXRScreenInputState:lC,useXRSessionVisibilityState:Vo,useXRSpace:cC,useXRStore:xr,useXRTransientPointerState:hC},Symbol.toStringTag,{value:"Module"}));export{Nw as D,Hw as X};
|
|
269
|
+
//# sourceMappingURL=chunk-B0wKlVcO.js.map
|