vuer 0.0.37__py3-none-any.whl → 0.0.38__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.

Files changed (28) hide show
  1. vuer/client_build/404.html +1 -1
  2. vuer/client_build/assets/chunks/chunk-4LUg6Nka.js +4660 -0
  3. vuer/client_build/assets/chunks/chunk-4LUg6Nka.js.map +1 -0
  4. vuer/client_build/assets/chunks/chunk-BNUl1M03.js +3 -0
  5. vuer/client_build/assets/chunks/chunk-BNUl1M03.js.map +1 -0
  6. vuer/client_build/assets/chunks/chunk-CWeX3-Jb.js +7681 -0
  7. vuer/client_build/assets/chunks/chunk-CWeX3-Jb.js.map +1 -0
  8. vuer/client_build/assets/chunks/chunk-DTi-TijR.js +269 -0
  9. vuer/client_build/assets/chunks/chunk-DTi-TijR.js.map +1 -0
  10. vuer/client_build/assets/chunks/chunk-diNchMM3.js +102 -0
  11. vuer/client_build/assets/chunks/chunk-diNchMM3.js.map +1 -0
  12. vuer/client_build/assets/entries/entry-client-routing.CJn7-aYM.js +5 -0
  13. vuer/client_build/assets/entries/entry-client-routing.CJn7-aYM.js.map +1 -0
  14. vuer/client_build/assets/entries/pages_editor.Bw5JyCoD.js +2 -0
  15. vuer/client_build/assets/entries/pages_editor.Bw5JyCoD.js.map +1 -0
  16. vuer/client_build/assets/entries/pages_index.DNSn4EPa.js +2 -0
  17. vuer/client_build/assets/entries/pages_index.DNSn4EPa.js.map +1 -0
  18. vuer/client_build/assets/entries/pages_simple.BDfGtgso.js +2 -0
  19. vuer/client_build/assets/entries/pages_simple.BDfGtgso.js.map +1 -0
  20. vuer/client_build/editor/index.html +4 -4
  21. vuer/client_build/index.html +4 -4
  22. vuer/client_build/simple/index.html +3 -3
  23. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/METADATA +1 -1
  24. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/RECORD +28 -10
  25. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/LICENSE +0 -0
  26. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/WHEEL +0 -0
  27. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/entry_points.txt +0 -0
  28. {vuer-0.0.37.dist-info → vuer-0.0.38.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,269 @@
1
+ import{g as js,h as k,i as Kt,j as tA,u as $,k as eA,Q as It,l as dt,m as wt,o as xs,C as kt,r as Te,E as qe,s as ca,t as Ot,v as ol,T as mf,w as ha,x as Aa,y as ct,A as ts,B as jt,G as or,J as ua,U as Vs,W as Ds,X as me,Y as li,$ as ve,a0 as $e,a1 as nt,a2 as Et,a3 as ci,a4 as gi,a5 as Zs,a6 as iA,a7 as _r,a8 as xo,a9 as sA,aa as da,ab as xr,ac as Pt,ad as se,ae as pf,af as Ef,ag as fa,ah as Cf,ai as Ki,aj as If,ak as Do,al as kn,am as Qn,an as Dr,ao as yf,ap as Bf,aq as al,ar as On,as as ll,at as vf,au as Sf,av as Tf,aw as _f,ax as xf,ay as Df,az as Rf,aA as wf,aB as Lf,aC as bf,aD as Ff,aE as nA,aF as Mf,aG as cl,aH as ar,aI as Pf,aJ as ye,aK as Gn,aL as kf,aM as Ni,aN as Qf,aO as Of,aP as Gf,aQ as Uf,aR as Nf,aS as Hf,aT as Kf,aU as Yf,aV as Vf,aW as Tn,aX as Rs,aY as Jf,aZ as Bs,a_ as vs,a$ as hl,b0 as Ro,b1 as rA,b2 as xe,b3 as ga,b4 as ma,b5 as zf,b6 as pa,b7 as $f,b8 as qf,b9 as oA,ba as wo,bb as es,bc as Xf,bd as aA,be as lA,bf as cA,bg as hA,bh as AA,bi as Wf,bj as jf,bk as Zf,bl as uA,bm as dA,bn as tg,bo as Al,bp as eg,bq as Ea,br as fA,bs as ig,bt as sg,bu as gA,bv as mA,bw as ng,bx as pA,by as rg,bz as og,bA as ag,bB as lg,bC as cg,bD as hg,bE as Ag,bF as ug,bG as dg,bH as fg,bI as gg,bJ as mg,bK as pg,bL as Eg,bM as Cg,bN as Ig,bO as yg,bP as Bg,bQ as vg,bR as Sg,bS as Tg,bT as _g,bU as xg,bV as Dg,bW as Rg,bX as wg,bY as Lg,bZ as bg,b_ as Fg,b$ as Mg,c0 as Pg,c1 as kg,c2 as Qg,c3 as Og,c4 as Gg,c5 as Ug,c6 as Ng,c7 as Hg,c8 as Kg,c9 as Yg,ca as Vg,cb as Jg,cc as zg,cd as $g,ce as qg,cf as Xg,cg as Wg,ch as jg,ci as Zg,cj as tm,ck as em,cl as im,cm as sm,cn as nm,co as rm,cp as om,cq as am,cr as lm,cs as cm,ct as hm,cu as Am,cv as um,cw as dm,cx as fm,cy as gm,cz as mm,cA as pm,cB as Em,cC as Cm,cD as Im,cE as ym,cF as Bm,cG as vm,cH as Sm,cI as Tm,cJ as _m,cK as xm,cL as Dm,cM as Rm,cN as wm,cO as Lm,cP as bm,cQ as Fm,cR as Mm,cS as Pm,cT as km,cU as Qm,cV as Om,cW as Gm,cX as Um,cY as Nm,cZ as Hm,c_ as Km,c$ as Ym,d0 as Vm,d1 as Jm,d2 as zm,d3 as $m,d4 as qm,d5 as Xm,d6 as Wm,d7 as jm,d8 as Zm,d9 as tp,da as ep,db as ip,dc as sp,dd as np,de as rp,df as op,dg as ap,dh as lp,di as cp,dj as hp,dk as Ap,dl as up,dm as dp,dn as fp,dp as gp,dq as mp,dr as pp,ds as Ep,dt as Cp,du as Ip,dv as yp,dw as Bp,dx as vp,dy as Sp,dz as Tp,dA as _p,dB as xp,dC as Dp,dD as Rp,dE as wp,dF as Lp,dG as bp,dH as Fp,dI as Mp,dJ as Pp,dK as kp,dL as Qp,dM as Op,dN as Gp,dO as Up,dP as Np,dQ as Hp,dR as Kp,dS as Yp,dT as Vp,dU as Ca,dV as Ia,dW as lr,dX as ya,dY as Jp,dZ as zp,d_ as $p,d$ as qp,e0 as Xp,e1 as Wp,e2 as jp,e3 as Zp,e4 as t0,e5 as e0,e6 as i0,e7 as s0,e8 as n0,e9 as r0,ea as o0,eb as a0,ec as l0,ed as c0,ee as h0,ef as A0,eg as u0,eh as d0,ei as f0,ej as g0,ek as m0,el as p0,em as E0,en as C0,eo as I0,ep as y0,eq as B0,er as v0,es as S0,et as T0,eu as _0,ev as x0,ew as D0,ex as R0,ey as w0,ez as L0,eA as b0,eB as F0,eC as M0,eD as P0,eE as k0,eF as Q0,eG as O0,eH as G0,eI as U0,eJ as N0,eK as H0,eL as K0,eM as Y0,eN as V0,eO as J0,eP as z0,eQ as $0,eR as q0,eS as X0,eT as W0,eU as j0,eV as Z0,eW as tE,eX as eE,eY as iE,eZ as sE,e_ as nE,e$ as rE,f0 as oE,f1 as aE,f2 as lE,f3 as cE,f4 as hE,f5 as AE,f6 as uE,f7 as dE,f8 as fE,f9 as gE,fa as mE,fb as pE,fc as EE,fd as CE}from"./chunk-CWeX3-Jb.js";import{r as B,o as ul,d as IE,e as yE,g as BE,j as Xe}from"./chunk-T_klmvss.js";import{_ as vE}from"./chunk-D7HrI6pR.js";function SE(n,t="pointer",e="auto",i=document.body){B.useEffect(()=>{if(n)return i.style.cursor=t,()=>void(i.style.cursor=e)},[n])}const dl=n=>{let t;const e=new Set,i=(c,h)=>{const A=typeof c=="function"?c(t):c;if(!Object.is(A,t)){const u=t;t=h??(typeof A!="object"||A===null)?A:Object.assign({},t,A),e.forEach(d=>d(t,u))}},s=()=>t,a={setState:i,getState:s,getInitialState:()=>l,subscribe:c=>(e.add(c),()=>e.delete(c))},l=t=n(i,s,a);return a},TE=n=>n?dl(n):dl,_E=n=>n;function xE(n,t=_E){const e=ul.useSyncExternalStore(n.subscribe,()=>t(n.getState()),()=>t(n.getInitialState()));return ul.useDebugValue(e),e}const fl=n=>{const t=TE(n),e=i=>xE(t,i);return Object.assign(e,t),e},EA=n=>n?fl(n):fl;let ss=0;const Ba=EA(n=>(js.onStart=(t,e,i)=>{n({active:!0,item:t,loaded:e,total:i,progress:(e-ss)/(i-ss)*100})},js.onLoad=()=>{n({active:!1})},js.onError=t=>n(e=>({errors:[...e.errors,t]})),js.onProgress=(t,e,i)=>{e===i&&(ss=i),n({active:!0,item:t,loaded:e,total:i,progress:(e-ss)/(i-ss)*100||100})},{errors:[],active:!1,progress:0,item:"",loaded:0,total:0}));function DE({children:n}){const t=Ba();return B.createElement(B.Fragment,null,n==null?void 0:n(t))}const RE=n=>`Loading ${n.toFixed(2)}%`;function wE({containerStyles:n,innerStyles:t,barStyles:e,dataStyles:i,dataInterpolation:s=RE,initialState:r=o=>o}){const{active:o,progress:a}=Ba(),l=B.useRef(0),c=B.useRef(0),h=B.useRef(null),[A,u]=B.useState(r(o));B.useEffect(()=>{let f;return o!==A&&(f=setTimeout(()=>u(o),300)),()=>clearTimeout(f)},[A,o]);const d=B.useCallback(()=>{h.current&&(l.current+=(a-l.current)/2,(l.current>.95*a||a===100)&&(l.current=a),h.current.innerText=s(l.current),l.current<a&&(c.current=requestAnimationFrame(d)))},[s,a]);return B.useEffect(()=>(d(),()=>cancelAnimationFrame(c.current)),[d]),A?B.createElement("div",{style:{...tn.container,opacity:o?1:0,...n}},B.createElement("div",null,B.createElement("div",{style:{...tn.inner,...t}},B.createElement("div",{style:{...tn.bar,transform:`scaleX(${a/100})`,...e}}),B.createElement("span",{ref:h,style:{...tn.data,...i}})))):null}const tn={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"}},Rr=new k,gl=new Kt,hi=new k,en=new k,ns=new k,ml=new tA,LE=B.forwardRef(({autoTransform:n=!0,matrix:t,axisLock:e,dragLimits:i,onHover:s,onDragStart:r,onDrag:o,onDragEnd:a,children:l,dragConfig:c,...h},A)=>{const u=$(E=>E.controls),{camera:d,size:f,raycaster:g,invalidate:p}=$(),m=B.useRef(null),C=eA({onHover:({hovering:E})=>s&&s(E??!1),onDragStart:({event:E})=>{u&&(u.enabled=!1);const{point:v}=E;m.current.matrix.decompose(Rr,new It,new k),hi.copy(v),en.copy(hi).sub(Rr),r&&r(Rr),p()},onDrag:({xy:[E,v],intentional:y})=>{if(!y)return;const S=(E-f.left)/f.width*2-1,T=-((v-f.top)/f.height)*2+1;if(gl.set(S,T),g.setFromCamera(gl,d),!e)d.getWorldDirection(ns).negate();else switch(e){case"x":ns.set(1,0,0);break;case"y":ns.set(0,1,0);break;case"z":ns.set(0,0,1);break}ml.setFromNormalAndCoplanarPoint(ns,hi),g.ray.intersectPlane(ml,hi);const x=m.current.matrix.clone(),F=m.current.matrixWorld.clone(),_=new k(hi.x-en.x,hi.y-en.y,hi.z-en.z);if(i&&(_.x=i[0]?Math.max(Math.min(_.x,i[0][1]),i[0][0]):_.x,_.y=i[1]?Math.max(Math.min(_.y,i[1][1]),i[1][0]):_.y,_.z=i[2]?Math.max(Math.min(_.z,i[2][1]),i[2][0]):_.z),n){m.current.matrix.setPosition(_);const w=m.current.matrix.clone().multiply(x.invert()),U=m.current.matrix.clone().multiply(F.invert());o&&o(m.current.matrix,w,m.current.matrixWorld,U)}else{const w=new dt().copy(m.current.matrix);w.setPosition(_);const U=w.clone().multiply(x.invert()),O=w.clone().multiply(F.invert());o&&o(w,U,m.current.matrixWorld,O)}p()},onDragEnd:()=>{u&&(u.enabled=!0),a&&a(),p()}},{drag:{filterTaps:!0,threshold:1,...typeof c=="object"?c:{}}});return B.useImperativeHandle(A,()=>m.current,[]),B.useLayoutEffect(()=>{t&&(m.current.matrix=t)},[t]),B.createElement("group",wt({ref:m},C(),{matrix:t,matrixAutoUpdate:!1},h),l)});function ws(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function Lo(n,t){return Lo=Object.setPrototypeOf||function(i,s){return i.__proto__=s,i},Lo(n,t)}function bE(){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 FE(){for(var n=arguments.length,t=new Array(n),e=0;e<n;e++)t[e]=arguments[e];var i=t[0],s=t[1],r=t[2],o=t[3],a=t[4],l=t[5],c=t[6],h=t[7],A=t[8];return i*a*A+s*l*c+r*o*h-r*a*c-s*o*A-i*l*h}function pl(n,t){for(var e=[],i=n.toArray(),s=t.toArray(),r=0;r<i.length;r++)e[r]=i[r]+s[r];return new xs().fromArray(e)}function ME(n){if(Array.isArray(n))return n}function PE(n,t){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var i=[],s=!0,r=!1,o,a;try{for(e=e.call(n);!(s=(o=e.next()).done)&&(i.push(o.value),!(t&&i.length===t));s=!0);}catch(l){r=!0,a=l}finally{try{!s&&e.return!=null&&e.return()}finally{if(r)throw a}}return i}}function bo(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=new Array(t);e<t;e++)i[e]=n[e];return i}function CA(n,t){if(n){if(typeof n=="string")return bo(n,t);var e=Object.prototype.toString.call(n).slice(8,-1);if(e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set")return Array.from(n);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return bo(n,t)}}function kE(){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 Oe(n,t){return ME(n)||PE(n,t)||CA(n,t)||kE()}function QE(n){if(Array.isArray(n))return bo(n)}function OE(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function GE(){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 Un(n){return QE(n)||OE(n)||CA(n)||GE()}function _n(n,t,e){return bE()?_n=Reflect.construct:_n=function(s,r,o){var a=[null];a.push.apply(a,r);var l=Function.bind.apply(s,a),c=new l;return o&&Lo(c,o.prototype),c},_n.apply(null,arguments)}function UE(n){var t=Oe(n[0],2),e=t[0],i=t[1],s=Oe(n[1],2),r=s[0],o=s[1],a=Oe(n[2],2),l=a[0],c=a[1];return FE(e,i,1,r,o,1,l,c,1)}function NE(n){return UE(n)===0}var HE=new Kt,KE=new Kt;function El(n){var t=n.map(function(c){return Array.isArray(c)?_n(Kt,Un(c)):c}),e=Oe(t,3),i=e[0],s=e[1],r=e[2];if(NE(n))return!1;var o=HE.subVectors(s,i),a=KE.subVectors(r,i),l=a.cross(o);return l>0}function IA(n,t,e){return Math.max(t,Math.min(e,n))}function yA(n,t){return IA(n-Math.floor(n/t)*t,0,t)}function BA(n,t){var e=yA(t-n,Math.PI*2);return e>Math.PI&&(e-=Math.PI*2),e}function YE(n){return n/180*Math.PI}function VE(n){return n*180/Math.PI}function JE(n,t){for(var e=t.radius,i=e===void 0?1:e,s=n.length/3,r=2/s,o=Math.PI*(3-2.2360679775),a=0;a<n.length;a+=3){var l=a*r-1+r/2,c=Math.sqrt(1-Math.pow(l,2)),h=a%s*o,A=Math.cos(h)*c,u=Math.sin(h)*c;n[a]=A*i,n[a+1]=l*i,n[a+2]=u*i}}function zE(n,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Number.EPSILON;return Math.abs(n.x-t.x)<e&&Math.abs(n.y-t.y)<e&&Math.abs(n.z-t.z)<e}function vA(n,t){return n.x===t.x?typeof n.z<"u"&&n.y===t.y?n.z-t.z:n.y-t.y:n.x-t.x}function $E(n){for(var t=n.sort(vA),e=[t[0],t[1]],i=2;i<t.length;i++)for(e.push(t[i]);e.length>2&&El(Un(e.slice(-3)));)e.splice(e.length-2,1);for(var s=[t[t.length-1],t[t.length-2]],r=t.length-3;r>=0;r--)for(s.push(t[r]);s.length>2&&El(Un(s.slice(-3)));)s.splice(s.length-2,1);s.splice(0,1),s.splice(s.length-1,1);var o=[].concat(e,s);return o}function qE(n,t,e){var i=Oe(t,2),s=i[0],r=i[1],o=Oe(e,2),a=o[0],l=o[1];return a+(n-s)*(l-a)/(r-s)}function XE(n){return n*n*n*(n*(n*6-15)+10)}function WE(n,t,e){return n*(1-e)+t*e}function SA(n,t,e){return(e-n)/(t-n)}function jE(n,t,e){var i=Math.sqrt(n*n+t*t+e*e);return[n/i,t/i,e/i]}function ZE(n,t,e){var i=n*n,s=t*t,r=e*e,o=n*Math.sqrt(1-(s+r)/2+s*r/3),a=t*Math.sqrt(1-(r+i)/2+r*i/3),l=e*Math.sqrt(1-(i+s)/2+i*s/3);return[o,a,l]}function TA(n,t){var e=new k().crossVectors(n,t),i=n.dot(t),s=new xs().identity(),r=new xs().set(0,-e.z,e.y,e.z,0,-e.x,-e.y,e.x,0),o=new xs().multiplyMatrices(r,r).multiplyScalar(1/(1+i)),a=pl(pl(s,r),o);return a}function tC(n,t,e){var i=Math.asin(t),s=Math.atan2(n,-e);return[i,s]}function eC(n,t){var e=Math.sin(n),i=Math.cos(n),s=Math.sin(t)*i,r=-Math.cos(t)*i;return[s,e,r]}function iC(n,t){var e=Oe(t,2),i=e[0],s=e[1],r=TA(n.normal,new k(0,1,0)),o=SA(i.clone().applyMatrix3(r).y,s.clone().applyMatrix3(r).y,0);return new k().lerpVectors(i,s,o)}function sC(n,t){var e=t.normal.dot(n);return e}function nC(n,t){var e=Oe(n,3),i=e[0],s=e[1],r=e[2],o=Oe(t,2),a=o[0],l=o[1];return r*a*l+s*a+i}function rC(n,t){var e=Oe(t,2),i=e[0],s=e[1],r=i*s,o=n/r,a=n-r*o,l=a/i,c=a%i;return[c,l,o]}function oC(n,t){return n[0]+t[0]*n[1]}function aC(n,t){var e=n%t,i=Math.floor(n/t);return[e,i]}var wr=Object.freeze({__proto__:null,clamp:IA,repeat:yA,deltaAngle:BA,degToRad:YE,radToDeg:VE,fibonacciOnSphere:JE,vectorEquals:zE,lexicographic:vA,convexHull:$E,remap:qE,fade:XE,lerp:WE,inverseLerp:SA,normalize:jE,pointOnCubeToPointOnSphere:ZE,rotateVectorOnVector:TA,pointToCoordinate:tC,coordinateToPoint:eC,planeSegmentIntersection:iC,pointToPlaneDistance:sC,getIndexFrom3D:nC,get3DFromIndex:rC,getIndexFrom2D:oC,get2DFromIndex:aC});function _A(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}var re=function n(t,e,i){var s=this;_A(this,n),ws(this,"dot2",function(r,o){return s.x*r+s.y*o}),ws(this,"dot3",function(r,o,a){return s.x*r+s.y*o+s.z*a}),this.x=t,this.y=e,this.z=i},lC=[new re(1,1,0),new re(-1,1,0),new re(1,-1,0),new re(-1,-1,0),new re(1,0,1),new re(-1,0,1),new re(1,0,-1),new re(-1,0,-1),new re(0,1,1),new re(0,-1,1),new re(0,1,-1),new re(0,-1,-1)],Cl=[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],Il=new Array(512),yl=new Array(512),cC=function(t){t>0&&t<1&&(t*=65536),t=Math.floor(t),t<256&&(t|=t<<8);for(var e=0;e<256;e++){var i;e&1?i=Cl[e]^t&255:i=Cl[e]^t>>8&255,Il[e]=Il[e+256]=i,yl[e]=yl[e+256]=lC[i%12]}};cC(0);function hC(n){if(typeof n=="number")n=Math.abs(n);else if(typeof n=="string"){var t=n;n=0;for(var e=0;e<t.length;e++)n=(n+(e+1)*(t.charCodeAt(e)%96))%2147483647}return n===0&&(n=311),n}function Bl(n){var t=hC(n);return function(){var e=t*48271%2147483647;return t=e,e/2147483647}}var AC=function n(t){var e=this;_A(this,n),ws(this,"seed",0),ws(this,"init",function(i){e.seed=i,e.value=Bl(i)}),ws(this,"value",Bl(this.seed)),this.init(t)};new AC(Math.random());var uC=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return i/Math.atan(1/e)*Math.atan(Math.sin(2*Math.PI*t*s)/e)},xA=function(t){return 1/(1+t+.48*t*t+.235*t*t*t)},dC=function(t){return t},fC={in:function(t){return 1-Math.cos(t*Math.PI/2)},out:function(t){return Math.sin(t*Math.PI/2)},inOut:function(t){return-(Math.cos(Math.PI*t)-1)/2}},gC={in:function(t){return t*t*t},out:function(t){return 1-Math.pow(1-t,3)},inOut:function(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}},mC={in:function(t){return t*t*t*t*t},out:function(t){return 1-Math.pow(1-t,5)},inOut:function(t){return t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2}},pC={in:function(t){return 1-Math.sqrt(1-Math.pow(t,2))},out:function(t){return Math.sqrt(1-Math.pow(t-1,2))},inOut:function(t){return t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2}},EC={in:function(t){return t*t*t*t},out:function(t){return 1- --t*t*t*t},inOut:function(t){return t<.5?8*t*t*t*t:1-8*--t*t*t*t}},CC={in:function(t){return t===0?0:Math.pow(2,10*t-10)},out:function(t){return t===1?1:1-Math.pow(2,-10*t)},inOut:function(t){return t===0?0:t===1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2}};function Yt(n,t,e){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,r=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:xA,a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,l="velocity_"+t;if(n.__damp===void 0&&(n.__damp={}),n.__damp[l]===void 0&&(n.__damp[l]=0),Math.abs(n[t]-e)<=a)return n[t]=e,!1;i=Math.max(1e-4,i);var c=2/i,h=o(c*s),A=n[t]-e,u=e,d=r*i;A=Math.min(Math.max(A,-d),d),e=n[t]-A;var f=(n.__damp[l]+c*A)*s;n.__damp[l]=(n.__damp[l]-c*f)*h;var g=e+(A+f)*h;return u-n[t]>0==g>u&&(g=u,n.__damp[l]=(g-u)/s),n[t]=g,!0}var IC=function(t){return t&&t.isCamera},yC=function(t){return t&&t.isLight},rs=new k,vl=new It,Sl=new It,os=new dt,Lr=new k;function BC(n,t,e,i,s,r,o){typeof t=="number"?rs.setScalar(t):Array.isArray(t)?rs.set(t[0],t[1],t[2]):rs.copy(t);var a=n.parent;n.updateWorldMatrix(!0,!1),Lr.setFromMatrixPosition(n.matrixWorld),IC(n)||yC(n)?os.lookAt(Lr,rs,n.up):os.lookAt(rs,Lr,n.up),Nn(n.quaternion,Sl.setFromRotationMatrix(os),e,i,s,r,o),a&&(os.extractRotation(a.matrixWorld),vl.setFromRotationMatrix(os),Nn(n.quaternion,Sl.copy(n.quaternion).premultiply(vl.invert()),e,i,s,r,o))}function Yi(n,t,e,i,s,r,o,a){return Yt(n,t,n[t]+BA(n[t],e),i,s,r,o,a)}var as=new Kt,Tl,_l;function vC(n,t,e,i,s,r,o){return typeof t=="number"?as.setScalar(t):Array.isArray(t)?as.set(t[0],t[1]):as.copy(t),Tl=Yt(n,"x",as.x,e,i,s,r,o),_l=Yt(n,"y",as.y,e,i,s,r,o),Tl||_l}var Si=new k,xl,Dl,Rl;function Fo(n,t,e,i,s,r,o){return typeof t=="number"?Si.setScalar(t):Array.isArray(t)?Si.set(t[0],t[1],t[2]):Si.copy(t),xl=Yt(n,"x",Si.x,e,i,s,r,o),Dl=Yt(n,"y",Si.y,e,i,s,r,o),Rl=Yt(n,"z",Si.z,e,i,s,r,o),xl||Dl||Rl}var Ai=new Te,wl,Ll,bl,Fl;function SC(n,t,e,i,s,r,o){return typeof t=="number"?Ai.setScalar(t):Array.isArray(t)?Ai.set(t[0],t[1],t[2],t[3]):Ai.copy(t),wl=Yt(n,"x",Ai.x,e,i,s,r,o),Ll=Yt(n,"y",Ai.y,e,i,s,r,o),bl=Yt(n,"z",Ai.z,e,i,s,r,o),Fl=Yt(n,"w",Ai.w,e,i,s,r,o),wl||Ll||bl||Fl}var ls=new qe,Ml,Pl,kl;function TC(n,t,e,i,s,r,o){return Array.isArray(t)?ls.set(t[0],t[1],t[2],t[3]):ls.copy(t),Ml=Yi(n,"x",ls.x,e,i,s,r,o),Pl=Yi(n,"y",ls.y,e,i,s,r,o),kl=Yi(n,"z",ls.z,e,i,s,r,o),Ml||Pl||kl}var Ti=new kt,Ql,Ol,Gl;function _C(n,t,e,i,s,r,o){return t instanceof kt?Ti.copy(t):Array.isArray(t)?Ti.setRGB(t[0],t[1],t[2]):Ti.set(t),Ql=Yt(n,"r",Ti.r,e,i,s,r,o),Ol=Yt(n,"g",Ti.g,e,i,s,r,o),Gl=Yt(n,"b",Ti.b,e,i,s,r,o),Ql||Ol||Gl}var pe=new It,Ne=new Te,Ul=new Te,cs=new Te,Nl,Hl,Kl,Yl;function Nn(n,t,e,i,s,r,o){var a=n;Array.isArray(t)?pe.set(t[0],t[1],t[2],t[3]):pe.copy(t);var l=n.dot(pe)>0?1:-1;return pe.x*=l,pe.y*=l,pe.z*=l,pe.w*=l,Nl=Yt(n,"x",pe.x,e,i,s,r,o),Hl=Yt(n,"y",pe.y,e,i,s,r,o),Kl=Yt(n,"z",pe.z,e,i,s,r,o),Yl=Yt(n,"w",pe.w,e,i,s,r,o),Ne.set(n.x,n.y,n.z,n.w).normalize(),Ul.set(a.__damp.velocity_x,a.__damp.velocity_y,a.__damp.velocity_z,a.__damp.velocity_w),cs.copy(Ne).multiplyScalar(Ul.dot(Ne)/Ne.dot(Ne)),a.__damp.velocity_x-=cs.x,a.__damp.velocity_y-=cs.y,a.__damp.velocity_z-=cs.z,a.__damp.velocity_w-=cs.w,n.set(Ne.x,Ne.y,Ne.z,Ne.w),Nl||Hl||Kl||Yl}var hs=new ca,Vl,Jl,zl;function xC(n,t,e,i,s,r,o){return Array.isArray(t)?hs.set(t[0],t[1],t[2]):hs.copy(t),Vl=Yt(n,"radius",hs.radius,e,i,s,r,o),Jl=Yi(n,"phi",hs.phi,e,i,s,r,o),zl=Yi(n,"theta",hs.theta,e,i,s,r,o),Vl||Jl||zl}var sn=new dt,$l=new k,ql=new It,Xl=new k,Wl,jl,Zl;function DC(n,t,e,i,s,r,o){var a=n;return a.__damp===void 0&&(a.__damp={position:new k,rotation:new It,scale:new k},n.decompose(a.__damp.position,a.__damp.rotation,a.__damp.scale)),Array.isArray(t)?sn.set.apply(sn,Un(t)):sn.copy(t),sn.decompose($l,ql,Xl),Wl=Fo(a.__damp.position,$l,e,i,s,r,o),jl=Nn(a.__damp.rotation,ql,e,i,s,r,o),Zl=Fo(a.__damp.scale,Xl,e,i,s,r,o),n.compose(a.__damp.position,a.__damp.rotation,a.__damp.scale),Wl||jl||Zl}var $i=Object.freeze({__proto__:null,rsqw:uC,exp:xA,linear:dC,sine:fC,cubic:gC,quint:mC,circ:pC,quart:EC,expo:CC,damp:Yt,dampLookAt:BC,dampAngle:Yi,damp2:vC,damp3:Fo,damp4:SC,dampE:TC,dampC:_C,dampQ:Nn,dampS:xC,dampM:DC});const va=B.createContext(null);function Sa(){return B.useContext(va)}function RC({eps:n=1e-5,enabled:t=!0,infinite:e,horizontal:i,pages:s=1,distance:r=1,damping:o=.25,maxSpeed:a=1/0,prepend:l=!1,style:c={},children:h}){const{get:A,setEvents:u,gl:d,size:f,invalidate:g,events:p}=$(),[m]=B.useState(()=>document.createElement("div")),[C]=B.useState(()=>document.createElement("div")),[E]=B.useState(()=>document.createElement("div")),v=d.domElement.parentNode,y=B.useRef(0),S=B.useMemo(()=>({el:m,eps:n,fill:C,fixed:E,horizontal:i,damping:o,offset:0,delta:0,scroll:y,pages:s,range(F,_,w=0){const U=F-w,O=U+_+w*2;return this.offset<U?0:this.offset>O?1:(this.offset-U)/(O-U)},curve(F,_,w=0){return Math.sin(this.range(F,_,w)*Math.PI)},visible(F,_,w=0){const U=F-w,O=U+_+w*2;return this.offset>=U&&this.offset<=O}}),[n,o,i,s]);B.useEffect(()=>{m.style.position="absolute",m.style.width="100%",m.style.height="100%",m.style[i?"overflowX":"overflowY"]="auto",m.style[i?"overflowY":"overflowX"]="hidden",m.style.top="0px",m.style.left="0px";for(const _ in c)m.style[_]=c[_];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=i?"100%":`${s*r*100}%`,C.style.width=i?`${s*r*100}%`:"100%",C.style.pointerEvents="none",m.appendChild(C),l?v.prepend(m):v.appendChild(m),m[i?"scrollLeft":"scrollTop"]=1;const x=p.connected||d.domElement;requestAnimationFrame(()=>p.connect==null?void 0:p.connect(m));const F=A().events.compute;return u({compute(_,w){const{left:U,top:O}=v.getBoundingClientRect(),W=_.clientX-U,K=_.clientY-O;w.pointer.set(W/w.size.width*2-1,-(K/w.size.height)*2+1),w.raycaster.setFromCamera(w.pointer,w.camera)}}),()=>{v.removeChild(m),u({compute:F}),p.connect==null||p.connect(x)}},[s,r,i,m,C,E,v]),B.useEffect(()=>{if(p.connected===m){const x=f[i?"width":"height"],F=m[i?"scrollWidth":"scrollHeight"],_=F-x;let w=0,U=!0,O=!0;const W=()=>{if(!(!t||O)&&(g(),w=m[i?"scrollLeft":"scrollTop"],y.current=w/_,e)){if(!U){if(w>=_){const q=1-S.offset;m[i?"scrollLeft":"scrollTop"]=1,y.current=S.offset=-q,U=!0}else if(w<=0){const q=1+S.offset;m[i?"scrollLeft":"scrollTop"]=F,y.current=S.offset=q,U=!0}}U&&setTimeout(()=>U=!1,40)}};m.addEventListener("scroll",W,{passive:!0}),requestAnimationFrame(()=>O=!1);const K=q=>m.scrollLeft+=q.deltaY/2;return i&&m.addEventListener("wheel",K,{passive:!0}),()=>{m.removeEventListener("scroll",W),i&&m.removeEventListener("wheel",K)}}},[m,p,f,e,S,g,i,t]);let T=0;return Ot((x,F)=>{T=S.offset,$i.damp(S,"offset",y.current,o,F,a,void 0,n),$i.damp(S,"delta",Math.abs(T-S.offset),o,F,a,void 0,n),S.delta>n&&g()}),B.createElement(va.Provider,{value:S},h)}const wC=B.forwardRef(({children:n},t)=>{const e=B.useRef(null);B.useImperativeHandle(t,()=>e.current,[]);const i=Sa(),{width:s,height:r}=$(o=>o.viewport);return Ot(()=>{e.current.position.x=i.horizontal?-s*(i.pages-1)*i.offset:0,e.current.position.y=i.horizontal?0:r*(i.pages-1)*i.offset}),B.createElement("group",{ref:e},n)}),LC=B.forwardRef(({children:n,style:t,...e},i)=>{const s=Sa(),r=B.useRef(null);B.useImperativeHandle(i,()=>r.current,[]);const{width:o,height:a}=$(h=>h.size),l=B.useContext(ol),c=B.useMemo(()=>IE(s.fixed),[s.fixed]);return Ot(()=>{s.delta>s.eps&&(r.current.style.transform=`translate3d(${s.horizontal?-o*(s.pages-1)*s.offset:0}px,${s.horizontal?0:a*(s.pages-1)*-s.offset}px,0)`)}),c.render(B.createElement("div",wt({ref:r,style:{...t,position:"absolute",top:0,left:0,willChange:"transform"}},e),B.createElement(va.Provider,{value:s},B.createElement(ol.Provider,{value:l},n)))),null}),bC=B.forwardRef(({html:n,...t},e)=>{const i=n?LC:wC;return B.createElement(i,wt({ref:e},t))});var Ta=zs(),ut=n=>Js(n,Ta),_a=zs();ut.write=n=>Js(n,_a);var cr=zs();ut.onStart=n=>Js(n,cr);var xa=zs();ut.onFrame=n=>Js(n,xa);var Da=zs();ut.onFinish=n=>Js(n,Da);var Vi=[];ut.setTimeout=(n,t)=>{const e=ut.now()+t,i=()=>{const r=Vi.findIndex(o=>o.cancel==i);~r&&Vi.splice(r,1),si-=~r?1:0},s={time:e,handler:n,cancel:i};return Vi.splice(DA(e),0,s),si+=1,RA(),s};var DA=n=>~(~Vi.findIndex(t=>t.time>n)||~Vi.length);ut.cancel=n=>{cr.delete(n),xa.delete(n),Da.delete(n),Ta.delete(n),_a.delete(n)};ut.sync=n=>{Mo=!0,ut.batchedUpdates(n),Mo=!1};ut.throttle=n=>{let t;function e(){try{n(...t)}finally{t=null}}function i(...s){t=s,ut.onStart(e)}return i.handler=n,i.cancel=()=>{cr.delete(e),t=null},i};var Ra=typeof window<"u"?window.requestAnimationFrame:()=>{};ut.use=n=>Ra=n;ut.now=typeof performance<"u"?()=>performance.now():Date.now;ut.batchedUpdates=n=>n();ut.catch=console.error;ut.frameLoop="always";ut.advance=()=>{ut.frameLoop!=="demand"?console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"):LA()};var ii=-1,si=0,Mo=!1;function Js(n,t){Mo?(t.delete(n),n(0)):(t.add(n),RA())}function RA(){ii<0&&(ii=0,ut.frameLoop!=="demand"&&Ra(wA))}function FC(){ii=-1}function wA(){~ii&&(Ra(wA),ut.batchedUpdates(LA))}function LA(){const n=ii;ii=ut.now();const t=DA(ii);if(t&&(bA(Vi.splice(0,t),e=>e.handler()),si-=t),!si){FC();return}cr.flush(),Ta.flush(n?Math.min(64,ii-n):16.667),xa.flush(),_a.flush(),Da.flush()}function zs(){let n=new Set,t=n;return{add(e){si+=t==n&&!n.has(e)?1:0,n.add(e)},delete(e){return si-=t==n&&n.has(e)?1:0,n.delete(e)},flush(e){t.size&&(n=new Set,si-=t.size,bA(t,i=>i(e)&&n.add(i)),si+=n.size,t=n)}}}function bA(n,t){n.forEach(e=>{try{t(e)}catch(i){ut.catch(i)}})}var MC=Object.defineProperty,PC=(n,t)=>{for(var e in t)MC(n,e,{get:t[e],enumerable:!0})},_e={};PC(_e,{assign:()=>QC,colors:()=>ri,createStringInterpolator:()=>La,skipAnimation:()=>MA,to:()=>FA,willAdvance:()=>ba});function Po(){}var kC=(n,t,e)=>Object.defineProperty(n,t,{value:e,writable:!0,configurable:!0}),z={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 Ve(n,t){if(z.arr(n)){if(!z.arr(t)||n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}return n===t}var vt=(n,t)=>n.forEach(t);function We(n,t,e){if(z.arr(n)){for(let i=0;i<n.length;i++)t.call(e,n[i],`${i}`);return}for(const i in n)n.hasOwnProperty(i)&&t.call(e,n[i],i)}var fe=n=>z.und(n)?[]:z.arr(n)?n:[n];function Ls(n,t){if(n.size){const e=Array.from(n);n.clear(),vt(e,t)}}var Ss=(n,...t)=>Ls(n,e=>e(...t)),wa=()=>typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),La,FA,ri=null,MA=!1,ba=Po,QC=n=>{n.to&&(FA=n.to),n.now&&(ut.now=n.now),n.colors!==void 0&&(ri=n.colors),n.skipAnimation!=null&&(MA=n.skipAnimation),n.createStringInterpolator&&(La=n.createStringInterpolator),n.requestAnimationFrame&&ut.use(n.requestAnimationFrame),n.batchedUpdates&&(ut.batchedUpdates=n.batchedUpdates),n.willAdvance&&(ba=n.willAdvance),n.frameLoop&&(ut.frameLoop=n.frameLoop)},bs=new Set,de=[],br=[],Hn=0,hr={get idle(){return!bs.size&&!de.length},start(n){Hn>n.priority?(bs.add(n),ut.onStart(OC)):(PA(n),ut(ko))},advance:ko,sort(n){if(Hn)ut.onFrame(()=>hr.sort(n));else{const t=de.indexOf(n);~t&&(de.splice(t,1),kA(n))}},clear(){de=[],bs.clear()}};function OC(){bs.forEach(PA),bs.clear(),ut(ko)}function PA(n){de.includes(n)||kA(n)}function kA(n){de.splice(GC(de,t=>t.priority>n.priority),0,n)}function ko(n){const t=br;for(let e=0;e<de.length;e++){const i=de[e];Hn=i.priority,i.idle||(ba(i),i.advance(n),i.idle||t.push(i))}return Hn=0,br=de,br.length=0,de=t,de.length>0}function GC(n,t){const e=n.findIndex(t);return e<0?n.length:e}var UC=(n,t,e)=>Math.min(Math.max(e,n),t),NC={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},Se="[-+]?\\d*\\.?\\d+",Kn=Se+"%";function Ar(...n){return"\\(\\s*("+n.join(")\\s*,\\s*(")+")\\s*\\)"}var HC=new RegExp("rgb"+Ar(Se,Se,Se)),KC=new RegExp("rgba"+Ar(Se,Se,Se,Se)),YC=new RegExp("hsl"+Ar(Se,Kn,Kn)),VC=new RegExp("hsla"+Ar(Se,Kn,Kn,Se)),JC=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,zC=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,$C=/^#([0-9a-fA-F]{6})$/,qC=/^#([0-9a-fA-F]{8})$/;function XC(n){let t;return typeof n=="number"?n>>>0===n&&n>=0&&n<=4294967295?n:null:(t=$C.exec(n))?parseInt(t[1]+"ff",16)>>>0:ri&&ri[n]!==void 0?ri[n]:(t=HC.exec(n))?(_i(t[1])<<24|_i(t[2])<<16|_i(t[3])<<8|255)>>>0:(t=KC.exec(n))?(_i(t[1])<<24|_i(t[2])<<16|_i(t[3])<<8|ic(t[4]))>>>0:(t=JC.exec(n))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+"ff",16)>>>0:(t=qC.exec(n))?parseInt(t[1],16)>>>0:(t=zC.exec(n))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+t[4]+t[4],16)>>>0:(t=YC.exec(n))?(tc(ec(t[1]),nn(t[2]),nn(t[3]))|255)>>>0:(t=VC.exec(n))?(tc(ec(t[1]),nn(t[2]),nn(t[3]))|ic(t[4]))>>>0:null}function Fr(n,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?n+(t-n)*6*e:e<1/2?t:e<2/3?n+(t-n)*(2/3-e)*6:n}function tc(n,t,e){const i=e<.5?e*(1+t):e+t-e*t,s=2*e-i,r=Fr(s,i,n+1/3),o=Fr(s,i,n),a=Fr(s,i,n-1/3);return Math.round(r*255)<<24|Math.round(o*255)<<16|Math.round(a*255)<<8}function _i(n){const t=parseInt(n,10);return t<0?0:t>255?255:t}function ec(n){return(parseFloat(n)%360+360)%360/360}function ic(n){const t=parseFloat(n);return t<0?0:t>1?255:Math.round(t*255)}function nn(n){const t=parseFloat(n);return t<0?0:t>100?1:t/100}function sc(n){let t=XC(n);if(t===null)return n;t=t||0;const e=(t&4278190080)>>>24,i=(t&16711680)>>>16,s=(t&65280)>>>8,r=(t&255)/255;return`rgba(${e}, ${i}, ${s}, ${r})`}var ks=(n,t,e)=>{if(z.fun(n))return n;if(z.arr(n))return ks({range:n,output:t,extrapolate:e});if(z.str(n.output[0]))return La(n);const i=n,s=i.output,r=i.range||[0,1],o=i.extrapolateLeft||i.extrapolate||"extend",a=i.extrapolateRight||i.extrapolate||"extend",l=i.easing||(c=>c);return c=>{const h=jC(c,r);return WC(c,r[h],r[h+1],s[h],s[h+1],l,o,a,i.map)}};function WC(n,t,e,i,s,r,o,a,l){let c=l?l(n):n;if(c<t){if(o==="identity")return c;o==="clamp"&&(c=t)}if(c>e){if(a==="identity")return c;a==="clamp"&&(c=e)}return i===s?i:t===e?n<=t?i:s:(t===-1/0?c=-c:e===1/0?c=c-t:c=(c-t)/(e-t),c=r(c),i===-1/0?c=-c:s===1/0?c=c+i:c=c*(s-i)+i,c)}function jC(n,t){for(var e=1;e<t.length-1&&!(t[e]>=n);++e);return e-1}var ZC=(n,t="end")=>e=>{e=t==="end"?Math.min(e,.999):Math.max(e,.001);const i=e*n,s=t==="end"?Math.floor(i):Math.ceil(i);return UC(0,1,s/n)},Yn=1.70158,rn=Yn*1.525,nc=Yn+1,rc=2*Math.PI/3,oc=2*Math.PI/4.5,on=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,tI={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=>nc*n*n*n-Yn*n*n,easeOutBack:n=>1+nc*Math.pow(n-1,3)+Yn*Math.pow(n-1,2),easeInOutBack:n=>n<.5?Math.pow(2*n,2)*((rn+1)*2*n-rn)/2:(Math.pow(2*n-2,2)*((rn+1)*(n*2-2)+rn)+2)/2,easeInElastic:n=>n===0?0:n===1?1:-Math.pow(2,10*n-10)*Math.sin((n*10-10.75)*rc),easeOutElastic:n=>n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n*10-.75)*rc)+1,easeInOutElastic:n=>n===0?0:n===1?1:n<.5?-(Math.pow(2,20*n-10)*Math.sin((20*n-11.125)*oc))/2:Math.pow(2,-20*n+10)*Math.sin((20*n-11.125)*oc)/2+1,easeInBounce:n=>1-on(1-n),easeOutBounce:on,easeInOutBounce:n=>n<.5?(1-on(1-2*n))/2:(1+on(2*n-1))/2,steps:ZC},Qs=Symbol.for("FluidValue.get"),qi=Symbol.for("FluidValue.observers"),Me=n=>!!(n&&n[Qs]),Ae=n=>n&&n[Qs]?n[Qs]():n,ac=n=>n[qi]||null;function eI(n,t){n.eventObserved?n.eventObserved(t):n(t)}function Vn(n,t){const e=n[qi];e&&e.forEach(i=>{eI(i,t)})}var iI=class{constructor(n){if(!n&&!(n=this.get))throw Error("Unknown getter");sI(this,n)}},sI=(n,t)=>QA(n,Qs,t);function $s(n,t){if(n[Qs]){let e=n[qi];e||QA(n,qi,e=new Set),e.has(t)||(e.add(t),n.observerAdded&&n.observerAdded(e.size,t))}return t}function Jn(n,t){const e=n[qi];if(e&&e.has(t)){const i=e.size-1;i?e.delete(t):n[qi]=null,n.observerRemoved&&n.observerRemoved(i,t)}}var QA=(n,t,e)=>Object.defineProperty(n,t,{value:e,writable:!0,configurable:!0}),xn=/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,nI=/(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi,lc=new RegExp(`(${xn.source})(%|[a-z]+)`,"i"),rI=/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi,ur=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/,OA=n=>{const[t,e]=oI(n);if(!t||wa())return n;const i=window.getComputedStyle(document.documentElement).getPropertyValue(t);if(i)return i.trim();if(e&&e.startsWith("--")){const s=window.getComputedStyle(document.documentElement).getPropertyValue(e);return s||n}else{if(e&&ur.test(e))return OA(e);if(e)return e}return n},oI=n=>{const t=ur.exec(n);if(!t)return[,];const[,e,i]=t;return[e,i]},Mr,aI=(n,t,e,i,s)=>`rgba(${Math.round(t)}, ${Math.round(e)}, ${Math.round(i)}, ${s})`,GA=n=>{Mr||(Mr=ri?new RegExp(`(${Object.keys(ri).join("|")})(?!\\w)`,"g"):/^\b$/);const t=n.output.map(r=>Ae(r).replace(ur,OA).replace(nI,sc).replace(Mr,sc)),e=t.map(r=>r.match(xn).map(Number)),s=e[0].map((r,o)=>e.map(a=>{if(!(o in a))throw Error('The arity of each "output" value must be equal');return a[o]})).map(r=>ks({...n,output:r}));return r=>{var l;const o=!lc.test(t[0])&&((l=t.find(c=>lc.test(c)))==null?void 0:l.replace(xn,""));let a=0;return t[0].replace(xn,()=>`${s[a++](r)}${o||""}`).replace(rI,aI)}},Fa="react-spring: ",UA=n=>{const t=n;let e=!1;if(typeof t!="function")throw new TypeError(`${Fa}once requires a function parameter`);return(...i)=>{e||(t(...i),e=!0)}},lI=UA(console.warn);function cI(){lI(`${Fa}The "interpolate" function is deprecated in v9 (use "to" instead)`)}var hI=UA(console.warn);function AI(){hI(`${Fa}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 dr(n){return z.str(n)&&(n[0]=="#"||/\d/.test(n)||!wa()&&ur.test(n)||n in(ri||{}))}var Ma=wa()?B.useEffect:B.useLayoutEffect,uI=()=>{const n=B.useRef(!1);return Ma(()=>(n.current=!0,()=>{n.current=!1}),[]),n};function NA(){const n=B.useState()[1],t=uI();return()=>{t.current&&n(Math.random())}}function dI(n,t){const[e]=B.useState(()=>({inputs:t,result:n()})),i=B.useRef(),s=i.current;let r=s;return r?r.inputs&&fI(t,r.inputs)||(r={inputs:t,result:n()}):r=e,B.useEffect(()=>{i.current=r,s==e&&(e.inputs=e.result=void 0)},[r]),r.result}function fI(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var HA=n=>B.useEffect(n,gI),gI=[];function cc(n){const t=B.useRef();return B.useEffect(()=>{t.current=n}),t.current}var Os=Symbol.for("Animated:node"),mI=n=>!!n&&n[Os]===n,be=n=>n&&n[Os],Pa=(n,t)=>kC(n,Os,t),fr=n=>n&&n[Os]&&n[Os].getPayload(),KA=class{constructor(){Pa(this,this)}getPayload(){return this.payload||[]}},qs=class extends KA{constructor(n){super(),this._value=n,this.done=!0,this.durationProgress=0,z.num(this._value)&&(this.lastPosition=this._value)}static create(n){return new qs(n)}getPayload(){return[this]}getValue(){return this._value}setValue(n,t){return z.num(n)&&(this.lastPosition=n,t&&(n=Math.round(n/t)*t,this.done&&(this.lastPosition=n))),this._value===n?!1:(this._value=n,!0)}reset(){const{done:n}=this;this.done=!1,z.num(this._value)&&(this.elapsedTime=0,this.durationProgress=0,this.lastPosition=this._value,n&&(this.lastVelocity=null),this.v0=null)}},Gs=class extends qs{constructor(n){super(0),this._string=null,this._toString=ks({output:[n,n]})}static create(n){return new Gs(n)}getValue(){const n=this._string;return n??(this._string=this._toString(this._value))}setValue(n){if(z.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=ks({output:[this.getValue(),n]})),this._value=0,super.reset()}},zn={dependencies:null},ka=class extends KA{constructor(n){super(),this.source=n,this.setValue(n)}getValue(n){const t={};return We(this.source,(e,i)=>{mI(e)?t[i]=e.getValue(n):Me(e)?t[i]=Ae(e):n||(t[i]=e)}),t}setValue(n){this.source=n,this.payload=this._makePayload(n)}reset(){this.payload&&vt(this.payload,n=>n.reset())}_makePayload(n){if(n){const t=new Set;return We(n,this._addToPayload,t),Array.from(t)}}_addToPayload(n){zn.dependencies&&Me(n)&&zn.dependencies.add(n);const t=fr(n);t&&vt(t,e=>this.add(e))}},YA=class extends ka{constructor(n){super(n)}static create(n){return new YA(n)}getValue(){return this.source.map(n=>n.getValue())}setValue(n){const t=this.getPayload();return n.length==t.length?t.map((e,i)=>e.setValue(n[i])).some(Boolean):(super.setValue(n.map(pI)),!0)}};function pI(n){return(dr(n)?Gs:qs).create(n)}function Qo(n){const t=be(n);return t?t.constructor:z.arr(n)?YA:dr(n)?Gs:qs}var hc=(n,t)=>{const e=!z.fun(n)||n.prototype&&n.prototype.isReactComponent;return B.forwardRef((i,s)=>{const r=B.useRef(null),o=e&&B.useCallback(f=>{r.current=II(s,f)},[s]),[a,l]=CI(i,t),c=NA(),h=()=>{const f=r.current;if(e&&!f)return;(f?t.applyAnimatedValues(f,a.getValue(!0)):!1)===!1&&c()},A=new EI(h,l),u=B.useRef();Ma(()=>(u.current=A,vt(l,f=>$s(f,A)),()=>{u.current&&(vt(u.current.deps,f=>Jn(f,u.current)),ut.cancel(u.current.update))})),B.useEffect(h,[]),HA(()=>()=>{const f=u.current;vt(f.deps,g=>Jn(g,f))});const d=t.getComponentProps(a.getValue());return B.createElement(n,{...d,ref:o})})},EI=class{constructor(n,t){this.update=n,this.deps=t}eventObserved(n){n.type=="change"&&ut.write(this.update)}};function CI(n,t){const e=new Set;return zn.dependencies=e,n.style&&(n={...n,style:t.createAnimatedStyle(n.style)}),n=new ka(n),zn.dependencies=null,[n,e]}function II(n,t){return n&&(z.fun(n)?n(t):n.current=t),t}var Ac=Symbol.for("AnimatedComponent"),yI=(n,{applyAnimatedValues:t=()=>!1,createAnimatedStyle:e=s=>new ka(s),getComponentProps:i=s=>s}={})=>{const s={applyAnimatedValues:t,createAnimatedStyle:e,getComponentProps:i},r=o=>{const a=uc(o)||"Anonymous";return z.str(o)?o=r[o]||(r[o]=hc(o,s)):o=o[Ac]||(o[Ac]=hc(o,s)),o.displayName=`Animated(${a})`,o};return We(n,(o,a)=>{z.arr(n)&&(a=uc(o)),r[a]=r(o)}),{animated:r}},uc=n=>z.str(n)?n:n&&z.str(n.displayName)?n.displayName:z.fun(n)&&n.name||null;function pi(n,...t){return z.fun(n)?n(...t):n}var Fs=(n,t)=>n===!0||!!(t&&n&&(z.fun(n)?n(t):fe(n).includes(t))),VA=(n,t)=>z.obj(n)?t&&n[t]:n,JA=(n,t)=>n.default===!0?n[t]:n.default?n.default[t]:void 0,BI=n=>n,Qa=(n,t=BI)=>{let e=vI;n.default&&n.default!==!0&&(n=n.default,e=Object.keys(n));const i={};for(const s of e){const r=t(n[s],s);z.und(r)||(i[s]=r)}return i},vI=["config","onProps","onStart","onChange","onPause","onResume","onRest"],SI={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 TI(n){const t={};let e=0;if(We(n,(i,s)=>{SI[s]||(t[s]=i,e++)}),e)return t}function zA(n){const t=TI(n);if(t){const e={to:t};return We(n,(i,s)=>s in t||(e[s]=i)),e}return{...n}}function Us(n){return n=Ae(n),z.arr(n)?n.map(Us):dr(n)?_e.createStringInterpolator({range:[0,1],output:[n,n]})(1):n}function _I(n){for(const t in n)return!0;return!1}function Oo(n){return z.fun(n)||z.arr(n)&&z.obj(n[0])}function xI(n,t){var e;(e=n.ref)==null||e.delete(n),t==null||t.delete(n)}function DI(n,t){var e;t&&n.ref!==t&&((e=n.ref)==null||e.delete(n),t.add(n),n.ref=t)}var RI={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}},Go={...RI.default,mass:1,damping:1,easing:tI.linear,clamp:!1},wI=class{constructor(){this.velocity=0,Object.assign(this,Go)}};function LI(n,t,e){e&&(e={...e},dc(e,t),t={...e,...t}),dc(n,t),Object.assign(n,t);for(const o in Go)n[o]==null&&(n[o]=Go[o]);let{frequency:i,damping:s}=n;const{mass:r}=n;return z.und(i)||(i<.01&&(i=.01),s<0&&(s=0),n.tension=Math.pow(2*Math.PI/i,2)*r,n.friction=4*Math.PI*s*r/i),n}function dc(n,t){if(!z.und(t.decay))n.duration=void 0;else{const e=!z.und(t.tension)||!z.und(t.friction);(e||!z.und(t.frequency)||!z.und(t.damping)||!z.und(t.mass))&&(n.duration=void 0,n.decay=void 0),e&&(n.frequency=void 0)}}var fc=[],bI=class{constructor(){this.changed=!1,this.values=fc,this.toValues=null,this.fromValues=fc,this.config=new wI,this.immediate=!1}};function $A(n,{key:t,props:e,defaultProps:i,state:s,actions:r}){return new Promise((o,a)=>{let l,c,h=Fs(e.cancel??(i==null?void 0:i.cancel),t);if(h)d();else{z.und(e.pause)||(s.paused=Fs(e.pause,t));let f=i==null?void 0:i.pause;f!==!0&&(f=s.paused||Fs(f,t)),l=pi(e.delay||0,t),f?(s.resumeQueue.add(u),r.pause()):(r.resume(),u())}function A(){s.resumeQueue.add(u),s.timeouts.delete(c),c.cancel(),l=c.time-ut.now()}function u(){l>0&&!_e.skipAnimation?(s.delayed=!0,c=ut.setTimeout(d,l),s.pauseQueue.add(A),s.timeouts.add(c)):d()}function d(){s.delayed&&(s.delayed=!1),s.pauseQueue.delete(A),s.timeouts.delete(c),n<=(s.cancelId||0)&&(h=!0);try{r.start({...e,callId:n,cancel:h},o)}catch(f){a(f)}}})}var Oa=(n,t)=>t.length==1?t[0]:t.some(e=>e.cancelled)?Ji(n.get()):t.every(e=>e.noop)?qA(n.get()):Be(n.get(),t.every(e=>e.finished)),qA=n=>({value:n,noop:!0,finished:!0,cancelled:!1}),Be=(n,t,e=!1)=>({value:n,finished:t,cancelled:e}),Ji=n=>({value:n,cancelled:!0,finished:!1});function XA(n,t,e,i){const{callId:s,parentId:r,onRest:o}=t,{asyncTo:a,promise:l}=e;return!r&&n===a&&!t.reset?l:e.promise=(async()=>{e.asyncId=s,e.asyncTo=n;const c=Qa(t,(p,m)=>m==="onRest"?void 0:p);let h,A;const u=new Promise((p,m)=>(h=p,A=m)),d=p=>{const m=s<=(e.cancelId||0)&&Ji(i)||s!==e.asyncId&&Be(i,!1);if(m)throw p.result=m,A(p),p},f=(p,m)=>{const C=new gc,E=new mc;return(async()=>{if(_e.skipAnimation)throw Ns(e),E.result=Be(i,!1),A(E),E;d(C);const v=z.obj(p)?{...p}:{...m,to:p};v.parentId=s,We(c,(S,T)=>{z.und(v[T])&&(v[T]=S)});const y=await i.start(v);return d(C),e.paused&&await new Promise(S=>{e.resumeQueue.add(S)}),y})()};let g;if(_e.skipAnimation)return Ns(e),Be(i,!1);try{let p;z.arr(n)?p=(async m=>{for(const C of m)await f(C)})(n):p=Promise.resolve(n(f,i.stop.bind(i))),await Promise.all([p.then(h),u]),g=Be(i.get(),!0,!1)}catch(p){if(p instanceof gc)g=p.result;else if(p instanceof mc)g=p.result;else throw p}finally{s==e.asyncId&&(e.asyncId=r,e.asyncTo=r?a:void 0,e.promise=r?l:void 0)}return z.fun(o)&&ut.batchedUpdates(()=>{o(g,i,i.item)}),g})()}function Ns(n,t){Ls(n.timeouts,e=>e.cancel()),n.pauseQueue.clear(),n.resumeQueue.clear(),n.asyncId=n.asyncTo=n.promise=void 0,t&&(n.cancelId=t)}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.")}},mc=class extends Error{constructor(){super("SkipAnimationSignal")}},Uo=n=>n instanceof Ga,FI=1,Ga=class extends iI{constructor(){super(...arguments),this.id=FI++,this._priority=0}get priority(){return this._priority}set priority(n){this._priority!=n&&(this._priority=n,this._onPriorityChange(n))}get(){const n=be(this);return n&&n.getValue()}to(...n){return _e.to(this,n)}interpolate(...n){return cI(),_e.to(this,n)}toJSON(){return this.get()}observerAdded(n){n==1&&this._attach()}observerRemoved(n){n==0&&this._detach()}_attach(){}_detach(){}_onChange(n,t=!1){Vn(this,{type:"change",parent:this,value:n,idle:t})}_onPriorityChange(n){this.idle||hr.sort(this),Vn(this,{type:"priority",parent:this,priority:n})}},yi=Symbol.for("SpringPhase"),WA=1,No=2,Ho=4,Pr=n=>(n[yi]&WA)>0,je=n=>(n[yi]&No)>0,As=n=>(n[yi]&Ho)>0,pc=(n,t)=>t?n[yi]|=No|WA:n[yi]&=~No,Ec=(n,t)=>t?n[yi]|=Ho:n[yi]&=~Ho,MI=class extends Ga{constructor(n,t){if(super(),this.animation=new bI,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,!z.und(n)||!z.und(t)){const e=z.obj(n)?{...n}:{...t,from:n};z.und(e.default)&&(e.default=!0),this.start(e)}}get idle(){return!(je(this)||this._state.asyncTo)||As(this)}get goal(){return Ae(this.animation.to)}get velocity(){const n=be(this);return n instanceof qs?n.lastVelocity||0:n.getPayload().map(t=>t.lastVelocity||0)}get hasAnimated(){return Pr(this)}get isAnimating(){return je(this)}get isPaused(){return As(this)}get isDelayed(){return this._state.delayed}advance(n){let t=!0,e=!1;const i=this.animation;let{toValues:s}=i;const{config:r}=i,o=fr(i.to);!o&&Me(i.to)&&(s=fe(Ae(i.to))),i.values.forEach((c,h)=>{if(c.done)return;const A=c.constructor==Gs?1:o?o[h].lastPosition:s[h];let u=i.immediate,d=A;if(!u){if(d=c.lastPosition,r.tension<=0){c.done=!0;return}let f=c.elapsedTime+=n;const g=i.fromValues[h],p=c.v0!=null?c.v0:c.v0=z.arr(r.velocity)?r.velocity[h]:r.velocity;let m;const C=r.precision||(g==A?.005:Math.min(1,Math.abs(A-g)*.001));if(z.und(r.duration))if(r.decay){const E=r.decay===!0?.998:r.decay,v=Math.exp(-(1-E)*f);d=g+p/(1-E)*(1-v),u=Math.abs(c.lastPosition-d)<=C,m=p*v}else{m=c.lastVelocity==null?p:c.lastVelocity;const E=r.restVelocity||C/10,v=r.clamp?0:r.bounce,y=!z.und(v),S=g==A?c.v0>0:g<A;let T,x=!1;const F=1,_=Math.ceil(n/F);for(let w=0;w<_&&(T=Math.abs(m)>E,!(!T&&(u=Math.abs(A-d)<=C,u)));++w){y&&(x=d==A||d>A==S,x&&(m=-m*v,d=A));const U=-r.tension*1e-6*(d-A),O=-r.friction*.001*m,W=(U+O)/r.mass;m=m+W*F,d=d+m*F}}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),d=g+r.easing(E)*(A-g),m=(d-c.lastPosition)/n,u=E==1}c.lastVelocity=m,Number.isNaN(d)&&(console.warn("Got NaN while animating:",this),u=!0)}o&&!o[h].done&&(u=!1),u?c.done=!0:t=!1,c.setValue(d,r.round)&&(e=!0)});const a=be(this),l=a.getValue();if(t){const c=Ae(i.to);(l!==c||e)&&!r.decay?(a.setValue(c),this._onChange(c)):e&&r.decay&&this._onChange(l),this._stop()}else e&&this._onChange(l)}set(n){return ut.batchedUpdates(()=>{this._stop(),this._focus(n),this._set(n)}),this}pause(){this._update({pause:!0})}resume(){this._update({pause:!1})}finish(){if(je(this)){const{to:n,config:t}=this.animation;ut.batchedUpdates(()=>{this._onStart(),t.decay||this._set(n,!1),this._stop()})}return this}update(n){return(this.queue||(this.queue=[])).push(n),this}start(n,t){let e;return z.und(n)?(e=this.queue||[],this.queue=[]):e=[z.obj(n)?n:{...t,to:n}],Promise.all(e.map(i=>this._update(i))).then(i=>Oa(this,i))}stop(n){const{to:t}=this.animation;return this._focus(this.get()),Ns(this._state,n&&this._lastCallId),ut.batchedUpdates(()=>this._stop(t,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 t=this.key||"";let{to:e,from:i}=n;e=z.obj(e)?e[t]:e,(e==null||Oo(e))&&(e=void 0),i=z.obj(i)?i[t]:i,i==null&&(i=void 0);const s={to:e,from:i};return Pr(this)||(n.reverse&&([e,i]=[i,e]),i=Ae(i),z.und(i)?be(this)||this._set(e):this._set(i)),s}_update({...n},t){const{key:e,defaultProps:i}=this;n.default&&Object.assign(i,Qa(n,(o,a)=>/^on/.test(a)?VA(o,e):o)),Ic(this,n,"onProps"),ds(this,"onProps",n,this);const s=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 $A(++this._lastCallId,{key:e,props:n,defaultProps:i,state:r,actions:{pause:()=>{As(this)||(Ec(this,!0),Ss(r.pauseQueue),ds(this,"onPause",Be(this,us(this,this.animation.to)),this))},resume:()=>{As(this)&&(Ec(this,!1),je(this)&&this._resume(),Ss(r.resumeQueue),ds(this,"onResume",Be(this,us(this,this.animation.to)),this))},start:this._merge.bind(this,s)}}).then(o=>{if(n.loop&&o.finished&&!(t&&o.noop)){const a=jA(n);if(a)return this._update(a,!0)}return o})}_merge(n,t,e){if(t.cancel)return this.stop(!0),e(Ji(this));const i=!z.und(n.to),s=!z.und(n.from);if(i||s)if(t.callId>this._lastToId)this._lastToId=t.callId;else return e(Ji(this));const{key:r,defaultProps:o,animation:a}=this,{to:l,from:c}=a;let{to:h=l,from:A=c}=n;s&&!i&&(!t.default||z.und(h))&&(h=A),t.reverse&&([h,A]=[A,h]);const u=!Ve(A,c);u&&(a.from=A),A=Ae(A);const d=!Ve(h,l);d&&this._focus(h);const f=Oo(t.to),{config:g}=a,{decay:p,velocity:m}=g;(i||s)&&(g.velocity=0),t.config&&!f&&LI(g,pi(t.config,r),t.config!==o.config?pi(o.config,r):void 0);let C=be(this);if(!C||z.und(h))return e(Be(this,!0));const E=z.und(t.reset)?s&&!t.default:!z.und(A)&&Fs(t.reset,r),v=E?A:this.get(),y=Us(h),S=z.num(y)||z.arr(y)||dr(y),T=!f&&(!S||Fs(o.immediate||t.immediate,r));if(d){const w=Qo(h);if(w!==C.constructor)if(T)C=this._set(y);else throw Error(`Cannot animate between ${C.constructor.name} and ${w.name}, as the "to" prop suggests`)}const x=C.constructor;let F=Me(h),_=!1;if(!F){const w=E||!Pr(this)&&u;(d||w)&&(_=Ve(Us(v),y),F=!_),(!Ve(a.immediate,T)&&!T||!Ve(g.decay,p)||!Ve(g.velocity,m))&&(F=!0)}if(_&&je(this)&&(a.changed&&!E?F=!0:F||this._stop(l)),!f&&((F||Me(l))&&(a.values=C.getPayload(),a.toValues=Me(h)?null:x==Gs?[1]:fe(y)),a.immediate!=T&&(a.immediate=T,!T&&!E&&this._set(l)),F)){const{onRest:w}=a;vt(kI,O=>Ic(this,t,O));const U=Be(this,us(this,l));Ss(this._pendingCalls,U),this._pendingCalls.add(e),a.changed&&ut.batchedUpdates(()=>{var O;a.changed=!E,w==null||w(U,this),E?pi(o.onRest,U):(O=a.onStart)==null||O.call(a,U,this)})}E&&this._set(v),f?e(XA(t.to,t,this._state,this)):F?this._start():je(this)&&!d?this._pendingCalls.add(e):e(qA(v))}_focus(n){const t=this.animation;n!==t.to&&(ac(this)&&this._detach(),t.to=n,ac(this)&&this._attach())}_attach(){let n=0;const{to:t}=this.animation;Me(t)&&($s(t,this),Uo(t)&&(n=t.priority+1)),this.priority=n}_detach(){const{to:n}=this.animation;Me(n)&&Jn(n,this)}_set(n,t=!0){const e=Ae(n);if(!z.und(e)){const i=be(this);if(!i||!Ve(e,i.getValue())){const s=Qo(e);!i||i.constructor!=s?Pa(this,s.create(e)):i.setValue(e),i&&ut.batchedUpdates(()=>{this._onChange(e,t)})}}return be(this)}_onStart(){const n=this.animation;n.changed||(n.changed=!0,ds(this,"onStart",Be(this,us(this,n.to)),this))}_onChange(n,t){t||(this._onStart(),pi(this.animation.onChange,n,this)),pi(this.defaultProps.onChange,n,this),super._onChange(n,t)}_start(){const n=this.animation;be(this).reset(Ae(n.to)),n.immediate||(n.fromValues=n.values.map(t=>t.lastPosition)),je(this)||(pc(this,!0),As(this)||this._resume())}_resume(){_e.skipAnimation?this.finish():hr.start(this)}_stop(n,t){if(je(this)){pc(this,!1);const e=this.animation;vt(e.values,s=>{s.done=!0}),e.toValues&&(e.onChange=e.onPause=e.onResume=void 0),Vn(this,{type:"idle",parent:this});const i=t?Ji(this.get()):Be(this.get(),us(this,n??e.to));Ss(this._pendingCalls,i),e.changed&&(e.changed=!1,ds(this,"onRest",i,this))}}};function us(n,t){const e=Us(t),i=Us(n.get());return Ve(i,e)}function jA(n,t=n.loop,e=n.to){const i=pi(t);if(i){const s=i!==!0&&zA(i),r=(s||n).reverse,o=!s||s.reset;return Hs({...n,loop:t,default:!1,pause:void 0,to:!r||Oo(e)?e:void 0,from:o?n.from:void 0,reset:o,...s})}}function Hs(n){const{to:t,from:e}=n=zA(n),i=new Set;return z.obj(t)&&Cc(t,i),z.obj(e)&&Cc(e,i),n.keys=i.size?Array.from(i):null,n}function PI(n){const t=Hs(n);return z.und(t.default)&&(t.default=Qa(t)),t}function Cc(n,t){We(n,(e,i)=>e!=null&&t.add(i))}var kI=["onStart","onRest","onChange","onPause","onResume"];function Ic(n,t,e){n.animation[e]=t[e]!==JA(t,e)?VA(t[e],n.key):void 0}function ds(n,t,...e){var i,s,r,o;(s=(i=n.animation)[t])==null||s.call(i,...e),(o=(r=n.defaultProps)[t])==null||o.call(r,...e)}var QI=["onStart","onChange","onRest"],OI=1,GI=class{constructor(n,t){this.id=OI++,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),t&&(this._flush=t),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((t,e)=>n[e]=t.get()),n}set(n){for(const t in n){const e=n[t];z.und(e)||this.springs[t].set(e)}}update(n){return n&&this.queue.push(Hs(n)),this}start(n){let{queue:t}=this;return n?t=fe(n).map(Hs):this.queue=[],this._flush?this._flush(this,t):(su(this,t),Ko(this,t))}stop(n,t){if(n!==!!n&&(t=n),t){const e=this.springs;vt(fe(t),i=>e[i].stop(!!n))}else Ns(this._state,this._lastAsyncId),this.each(e=>e.stop(!!n));return this}pause(n){if(z.und(n))this.start({pause:!0});else{const t=this.springs;vt(fe(n),e=>t[e].pause())}return this}resume(n){if(z.und(n))this.start({pause:!1});else{const t=this.springs;vt(fe(n),e=>t[e].resume())}return this}each(n){We(this.springs,n)}_onFrame(){const{onStart:n,onChange:t,onRest:e}=this._events,i=this._active.size>0,s=this._changed.size>0;(i&&!this._started||s&&!this._started)&&(this._started=!0,Ls(n,([a,l])=>{l.value=this.get(),a(l,this,this._item)}));const r=!i&&this._started,o=s||r&&e.size?this.get():null;s&&t.size&&Ls(t,([a,l])=>{l.value=o,a(l,this,this._item)}),r&&(this._started=!1,Ls(e,([a,l])=>{l.value=o,a(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;ut.onFrame(this._onFrame)}};function Ko(n,t){return Promise.all(t.map(e=>ZA(n,e))).then(e=>Oa(n,e))}async function ZA(n,t,e){const{keys:i,to:s,from:r,loop:o,onRest:a,onResolve:l}=t,c=z.obj(t.default)&&t.default;o&&(t.loop=!1),s===!1&&(t.to=null),r===!1&&(t.from=null);const h=z.arr(s)||z.fun(s)?s:void 0;h?(t.to=void 0,t.onRest=void 0,c&&(c.onRest=void 0)):vt(QI,g=>{const p=t[g];if(z.fun(p)){const m=n._events[g];t[g]=({finished:C,cancelled:E})=>{const v=m.get(p);v?(C||(v.finished=!1),E&&(v.cancelled=!0)):m.set(p,{value:null,finished:C||!1,cancelled:E||!1})},c&&(c[g]=t[g])}});const A=n._state;t.pause===!A.paused?(A.paused=t.pause,Ss(t.pause?A.pauseQueue:A.resumeQueue)):A.paused&&(t.pause=!0);const u=(i||Object.keys(n.springs)).map(g=>n.springs[g].start(t)),d=t.cancel===!0||JA(t,"cancel")===!0;(h||d&&A.asyncId)&&u.push($A(++n._lastAsyncId,{props:t,state:A,actions:{pause:Po,resume:Po,start(g,p){d?(Ns(A,n._lastAsyncId),p(Ji(n))):(g.onRest=a,p(XA(h,g,A,n)))}}})),A.paused&&await new Promise(g=>{A.resumeQueue.add(g)});const f=Oa(n,await Promise.all(u));if(o&&f.finished&&!(e&&f.noop)){const g=jA(t,o,s);if(g)return su(n,[g]),ZA(n,g,!0)}return l&&ut.batchedUpdates(()=>l(f,n,n.item)),f}function yc(n,t){const e={...n.springs};return t&&vt(fe(t),i=>{z.und(i.keys)&&(i=Hs(i)),z.obj(i.to)||(i={...i,to:void 0}),iu(e,i,s=>eu(s))}),tu(n,e),e}function tu(n,t){We(t,(e,i)=>{n.springs[i]||(n.springs[i]=e,$s(e,n))})}function eu(n,t){const e=new MI;return e.key=n,t&&$s(e,t),e}function iu(n,t,e){t.keys&&vt(t.keys,i=>{(n[i]||(n[i]=e(i)))._prepareNode(t)})}function su(n,t){vt(t,e=>{iu(n.springs,e,i=>eu(i,n))})}var gr=({children:n,...t})=>{const e=B.useContext($n),i=t.pause||!!e.pause,s=t.immediate||!!e.immediate;t=dI(()=>({pause:i,immediate:s}),[i,s]);const{Provider:r}=$n;return B.createElement(r,{value:t},n)},$n=UI(gr,{});gr.Provider=$n.Provider;gr.Consumer=$n.Consumer;function UI(n,t){return Object.assign(n,B.createContext(t)),n.Provider._context=n,n.Consumer._context=n,n}var NI=()=>{const n=[],t=function(i){AI();const s=[];return vt(n,(r,o)=>{if(z.und(i))s.push(r.start());else{const a=e(i,r,o);a&&s.push(r.start(a))}}),s};t.current=n,t.add=function(i){n.includes(i)||n.push(i)},t.delete=function(i){const s=n.indexOf(i);~s&&n.splice(s,1)},t.pause=function(){return vt(n,i=>i.pause(...arguments)),this},t.resume=function(){return vt(n,i=>i.resume(...arguments)),this},t.set=function(i){vt(n,(s,r)=>{const o=z.fun(i)?i(r,s):i;o&&s.set(o)})},t.start=function(i){const s=[];return vt(n,(r,o)=>{if(z.und(i))s.push(r.start());else{const a=this._getProps(i,r,o);a&&s.push(r.start(a))}}),s},t.stop=function(){return vt(n,i=>i.stop(...arguments)),this},t.update=function(i){return vt(n,(s,r)=>s.update(this._getProps(i,s,r))),this};const e=function(i,s,r){return z.fun(i)?i(r,s):i};return t._getProps=e,t};function HI(n,t,e){const i=z.fun(t)&&t;i&&!e&&(e=[]);const s=B.useMemo(()=>i||arguments.length==3?NI():void 0,[]),r=B.useRef(0),o=NA(),a=B.useMemo(()=>({ctrls:[],queue:[],flush(m,C){const E=yc(m,C);return r.current>0&&!a.queue.length&&!Object.keys(E).some(y=>!m.springs[y])?Ko(m,C):new Promise(y=>{tu(m,E),a.queue.push(()=>{y(Ko(m,C))}),o()})}}),[]),l=B.useRef([...a.ctrls]),c=[],h=cc(n)||0;B.useMemo(()=>{vt(l.current.slice(n,h),m=>{xI(m,s),m.stop(!0)}),l.current.length=n,A(h,n)},[n]),B.useMemo(()=>{A(0,Math.min(h,n))},e);function A(m,C){for(let E=m;E<C;E++){const v=l.current[E]||(l.current[E]=new GI(null,a.flush)),y=i?i(E,v):t[E];y&&(c[E]=PI(y))}}const u=l.current.map((m,C)=>yc(m,c[C])),d=B.useContext(gr),f=cc(d),g=d!==f&&_I(d);Ma(()=>{r.current++,a.ctrls=l.current;const{queue:m}=a;m.length&&(a.queue=[],vt(m,C=>C())),vt(l.current,(C,E)=>{s==null||s.add(C),g&&C.start({default:d});const v=c[E];v&&(DI(C,v.ref),C.ref?C.queue.push(v):C.start(v))})}),HA(()=>()=>{vt(a.ctrls,m=>m.stop(!0))});const p=u.map(m=>({...m}));return s?[p,s]:p}function KI(n,t){const e=z.fun(n),[[i],s]=HI(1,e?n:[n],e?[]:t);return e||arguments.length==2?[i,s]:i}var YI=class extends Ga{constructor(n,t){super(),this.source=n,this.idle=!0,this._active=new Set,this.calc=ks(...t);const e=this._get(),i=Qo(e);Pa(this,i.create(e))}advance(n){const t=this._get(),e=this.get();Ve(t,e)||(be(this).setValue(t),this._onChange(t,this.idle)),!this.idle&&Bc(this._active)&&kr(this)}_get(){const n=z.arr(this.source)?this.source.map(Ae):fe(Ae(this.source));return this.calc(...n)}_start(){this.idle&&!Bc(this._active)&&(this.idle=!1,vt(fr(this),n=>{n.done=!1}),_e.skipAnimation?(ut.batchedUpdates(()=>this.advance()),kr(this)):hr.start(this))}_attach(){let n=1;vt(fe(this.source),t=>{Me(t)&&$s(t,this),Uo(t)&&(t.idle||this._active.add(t),n=Math.max(n,t.priority+1))}),this.priority=n,this._start()}_detach(){vt(fe(this.source),n=>{Me(n)&&Jn(n,this)}),this._active.clear(),kr(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=fe(this.source).reduce((t,e)=>Math.max(t,(Uo(e)?e.priority:0)+1),0))}};function VI(n){return n.idle!==!1}function Bc(n){return!n.size||Array.from(n).every(VI)}function kr(n){n.idle||(n.idle=!0,vt(fr(n),t=>{t.done=!0}),Vn(n,{type:"idle",parent:n}))}_e.assign({createStringInterpolator:GA,to:(n,t)=>new YI(n,t)});var JI=["primitive"].concat(Object.keys(mf).filter(n=>/^[A-Z]/.test(n)).map(n=>n[0].toLowerCase()+n.slice(1)));_e.assign({createStringInterpolator:GA,colors:NC,frameLoop:"demand"});ha(()=>{ut.advance()});var zI=yI(JI,{applyAnimatedValues:Aa}),$I=zI.animated;function qI({enabled:n=!0,snap:t,global:e,domElement:i,cursor:s=!0,children:r,speed:o=1,rotation:a=[0,0,0],zoom:l=1,polar:c=[0,Math.PI/2],azimuth:h=[-1/0,1/0],config:A={mass:1,tension:170,friction:26}}){const u=$(S=>S.events),d=$(S=>S.gl),f=i||u.connected||d.domElement,{size:g}=$(),p=B.useMemo(()=>[a[0]+c[0],a[0]+c[1]],[a[0],c[0],c[1]]),m=B.useMemo(()=>[a[1]+h[0],a[1]+h[1]],[a[1],h[0],h[1]]),C=B.useMemo(()=>[ct.clamp(a[0],...p),ct.clamp(a[1],...m),a[2]],[a[0],a[1],a[2],p,m]),[E,v]=KI(()=>({scale:1,rotation:C,config:A}));B.useEffect(()=>void v.start({scale:1,rotation:C,config:A}),[C]),B.useEffect(()=>{if(e&&s&&n)return f.style.cursor="grab",d.domElement.style.cursor="",()=>{f.style.cursor="default",d.domElement.style.cursor="default"}},[e,s,f,n]);const y=eA({onHover:({last:S})=>{s&&!e&&n&&(f.style.cursor=S?"auto":"grab")},onDrag:({down:S,delta:[T,x],memo:[F,_]=E.rotation.animation.to||C})=>{if(!n)return[x,T];s&&(f.style.cursor=S?"grabbing":"grab"),T=ct.clamp(_+T/g.width*Math.PI*o,...m),x=ct.clamp(F+x/g.height*Math.PI*o,...p);const w=t&&!S&&typeof t!="boolean"?t:A;return v.start({scale:S&&x>p[1]/2?l:1,rotation:t&&!S?C:[x,T,0],config:U=>U==="scale"?{...w,friction:w.friction*3}:w}),[x,T]}},{target:e?f:void 0});return B.createElement($I.group,wt({},y==null?void 0:y(),E),r)}const XI=n=>(t,e,i)=>{const s=i.subscribe;return i.subscribe=(o,a,l)=>{let c=o;if(a){const h=(l==null?void 0:l.equalityFn)||Object.is;let A=o(i.getState());c=u=>{const d=o(u);if(!h(A,d)){const f=A;a(A=d,f)}},l!=null&&l.fireImmediately&&a(A,A)}return s(c)},n(t,e,i)},WI=XI,nu=B.createContext(null);function jI({map:n,children:t,onChange:e,domElement:i}){const s=n.map(l=>l.name+l.keys).join("-"),r=B.useMemo(()=>EA(WI(()=>n.reduce((l,c)=>({...l,[c.name]:!1}),{}))),[s]),o=B.useMemo(()=>[r.subscribe,r.getState,r],[s]),a=r.setState;return B.useEffect(()=>{const c=n.map(({name:d,keys:f,up:g})=>({keys:f,up:g,fn:p=>{a({[d]:p}),e&&e(d,p,o[1]())}})).reduce((d,{keys:f,fn:g,up:p=!0})=>(f.forEach(m=>d[m]={fn:g,pressed:!1,up:p}),d),{}),h=({key:d,code:f})=>{const g=c[d]||c[f];if(!g)return;const{fn:p,pressed:m,up:C}=g;g.pressed=!0,(C||!m)&&p(!0)},A=({key:d,code:f})=>{const g=c[d]||c[f];if(!g)return;const{fn:p,up:m}=g;g.pressed=!1,m&&p(!1)},u=i||window;return u.addEventListener("keydown",h,{passive:!0}),u.addEventListener("keyup",A,{passive:!0}),()=>{u.removeEventListener("keydown",h),u.removeEventListener("keyup",A)}},[i,s]),B.createElement(nu.Provider,{value:o,children:t})}function ZI(n){const[t,e,i]=B.useContext(nu);return n?i(n):[t,e]}var ty=Object.defineProperty,ey=(n,t,e)=>t in n?ty(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,At=(n,t,e)=>(ey(n,typeof t!="symbol"?t+"":t,e),e);const vc=new k;let iy=class extends ts{constructor(t,e){super(),At(this,"object"),At(this,"domElement"),At(this,"enabled",!0),At(this,"movementSpeed",1),At(this,"lookSpeed",.005),At(this,"lookVertical",!0),At(this,"autoForward",!1),At(this,"activeLook",!0),At(this,"heightSpeed",!1),At(this,"heightCoef",1),At(this,"heightMin",0),At(this,"heightMax",1),At(this,"constrainVertical",!1),At(this,"verticalMin",0),At(this,"verticalMax",Math.PI),At(this,"mouseDragOn",!1),At(this,"autoSpeedFactor",0),At(this,"mouseX",0),At(this,"mouseY",0),At(this,"moveForward",!1),At(this,"moveBackward",!1),At(this,"moveLeft",!1),At(this,"moveRight",!1),At(this,"moveUp",!1),At(this,"moveDown",!1),At(this,"viewHalfX",0),At(this,"viewHalfY",0),At(this,"lat",0),At(this,"lon",0),At(this,"lookDirection",new k),At(this,"spherical",new ca),At(this,"target",new k),At(this,"connect",i=>{i.setAttribute("tabindex","-1"),i.style.touchAction="none",i.addEventListener("contextmenu",this.contextmenu),i.addEventListener("mousemove",this.onMouseMove),i.addEventListener("mousedown",this.onMouseDown),i.addEventListener("mouseup",this.onMouseUp),this.domElement=i,window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),this.handleResize()}),At(this,"dispose",()=>{var i,s,r,o;(i=this.domElement)==null||i.removeEventListener("contextmenu",this.contextmenu),(s=this.domElement)==null||s.removeEventListener("mousedown",this.onMouseDown),(r=this.domElement)==null||r.removeEventListener("mousemove",this.onMouseMove),(o=this.domElement)==null||o.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}),At(this,"handleResize",()=>{this.domElement&&(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}),At(this,"onMouseDown",i=>{var s;if((s=this.domElement)==null||s.focus(),this.activeLook)switch(i.button){case 0:this.moveForward=!0;break;case 2:this.moveBackward=!0;break}this.mouseDragOn=!0}),At(this,"onMouseUp",i=>{if(this.activeLook)switch(i.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}),At(this,"onMouseMove",i=>{this.domElement&&(this.mouseX=i.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=i.pageY-this.domElement.offsetTop-this.viewHalfY)}),At(this,"onKeyDown",i=>{switch(i.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}}),At(this,"onKeyUp",i=>{switch(i.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}}),At(this,"lookAt",(i,s,r)=>(i instanceof k?this.target.copy(i):s&&r&&this.target.set(i,s,r),this.object.lookAt(this.target),this.setOrientation(),this)),At(this,"update",i=>{if(!this.enabled)return;if(this.heightSpeed){const A=ct.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=i*(A*this.heightCoef)}else this.autoSpeedFactor=0;const s=i*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(s+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(s),this.moveLeft&&this.object.translateX(-s),this.moveRight&&this.object.translateX(s),this.moveUp&&this.object.translateY(s),this.moveDown&&this.object.translateY(-s);let r=i*this.lookSpeed;this.activeLook||(r=0);let o=1;this.constrainVertical&&(o=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.mouseX*r,this.lookVertical&&(this.lat-=this.mouseY*r*o),this.lat=Math.max(-85,Math.min(85,this.lat));let a=ct.degToRad(90-this.lat);const l=ct.degToRad(this.lon);this.constrainVertical&&(a=ct.mapLinear(a,0,Math.PI,this.verticalMin,this.verticalMax));const c=this.object.position;vc.setFromSphericalCoords(1,a,l).add(c),this.object.lookAt(vc)}),At(this,"contextmenu",i=>i.preventDefault()),At(this,"setOrientation",()=>{this.lookDirection.set(0,0,-1).applyQuaternion(this.object.quaternion),this.spherical.setFromVector3(this.lookDirection),this.lat=90-ct.radToDeg(this.spherical.phi),this.lon=ct.radToDeg(this.spherical.theta)}),this.object=t,this.domElement=e,this.setOrientation(),e&&this.connect(e)}};var sy=Object.defineProperty,ny=(n,t,e)=>t in n?sy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,P=(n,t,e)=>(ny(n,typeof t!="symbol"?t+"":t,e),e);let ry=class extends jt{constructor(t,e){super(),P(this,"isTransformControls",!0),P(this,"visible",!1),P(this,"domElement"),P(this,"raycaster",new or),P(this,"gizmo"),P(this,"plane"),P(this,"tempVector",new k),P(this,"tempVector2",new k),P(this,"tempQuaternion",new It),P(this,"unit",{X:new k(1,0,0),Y:new k(0,1,0),Z:new k(0,0,1)}),P(this,"pointStart",new k),P(this,"pointEnd",new k),P(this,"offset",new k),P(this,"rotationAxis",new k),P(this,"startNorm",new k),P(this,"endNorm",new k),P(this,"rotationAngle",0),P(this,"cameraPosition",new k),P(this,"cameraQuaternion",new It),P(this,"cameraScale",new k),P(this,"parentPosition",new k),P(this,"parentQuaternion",new It),P(this,"parentQuaternionInv",new It),P(this,"parentScale",new k),P(this,"worldPositionStart",new k),P(this,"worldQuaternionStart",new It),P(this,"worldScaleStart",new k),P(this,"worldPosition",new k),P(this,"worldQuaternion",new It),P(this,"worldQuaternionInv",new It),P(this,"worldScale",new k),P(this,"eye",new k),P(this,"positionStart",new k),P(this,"quaternionStart",new It),P(this,"scaleStart",new k),P(this,"camera"),P(this,"object"),P(this,"enabled",!0),P(this,"axis",null),P(this,"mode","translate"),P(this,"translationSnap",null),P(this,"rotationSnap",null),P(this,"scaleSnap",null),P(this,"space","world"),P(this,"size",1),P(this,"dragging",!1),P(this,"showX",!0),P(this,"showY",!0),P(this,"showZ",!0),P(this,"changeEvent",{type:"change"}),P(this,"mouseDownEvent",{type:"mouseDown",mode:this.mode}),P(this,"mouseUpEvent",{type:"mouseUp",mode:this.mode}),P(this,"objectChangeEvent",{type:"objectChange"}),P(this,"intersectObjectWithRay",(s,r,o)=>{const a=r.intersectObject(s,!0);for(let l=0;l<a.length;l++)if(a[l].object.visible||o)return a[l];return!1}),P(this,"attach",s=>(this.object=s,this.visible=!0,this)),P(this,"detach",()=>(this.object=void 0,this.visible=!1,this.axis=null,this)),P(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),P(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()}),P(this,"pointerHover",s=>{if(this.object===void 0||this.dragging===!0)return;this.raycaster.setFromCamera(s,this.camera);const r=this.intersectObjectWithRay(this.gizmo.picker[this.mode],this.raycaster);r?this.axis=r.object.name:this.axis=null}),P(this,"pointerDown",s=>{if(!(this.object===void 0||this.dragging===!0||s.button!==0)&&this.axis!==null){this.raycaster.setFromCamera(s,this.camera);const r=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(r){let o=this.space;if(this.mode==="scale"?o="local":(this.axis==="E"||this.axis==="XYZE"||this.axis==="XYZ")&&(o="world"),o==="local"&&this.mode==="rotate"){const a=this.rotationSnap;this.axis==="X"&&a&&(this.object.rotation.x=Math.round(this.object.rotation.x/a)*a),this.axis==="Y"&&a&&(this.object.rotation.y=Math.round(this.object.rotation.y/a)*a),this.axis==="Z"&&a&&(this.object.rotation.z=Math.round(this.object.rotation.z/a)*a)}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)}}),P(this,"pointerMove",s=>{const r=this.axis,o=this.mode,a=this.object;let l=this.space;if(o==="scale"?l="local":(r==="E"||r==="XYZE"||r==="XYZ")&&(l="world"),a===void 0||r===null||this.dragging===!1||s.button!==-1)return;this.raycaster.setFromCamera(s,this.camera);const c=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(c){if(this.pointEnd.copy(c.point).sub(this.worldPositionStart),o==="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),a.position.copy(this.offset).add(this.positionStart),this.translationSnap&&(l==="local"&&(a.position.applyQuaternion(this.tempQuaternion.copy(this.quaternionStart).invert()),r.search("X")!==-1&&(a.position.x=Math.round(a.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(a.position.y=Math.round(a.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(a.position.z=Math.round(a.position.z/this.translationSnap)*this.translationSnap),a.position.applyQuaternion(this.quaternionStart)),l==="world"&&(a.parent&&a.position.add(this.tempVector.setFromMatrixPosition(a.parent.matrixWorld)),r.search("X")!==-1&&(a.position.x=Math.round(a.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(a.position.y=Math.round(a.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(a.position.z=Math.round(a.position.z/this.translationSnap)*this.translationSnap),a.parent&&a.position.sub(this.tempVector.setFromMatrixPosition(a.parent.matrixWorld))));else if(o==="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);a.scale.copy(this.scaleStart).multiply(this.tempVector2),this.scaleSnap&&this.object&&(r.search("X")!==-1&&(this.object.scale.x=Math.round(a.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Y")!==-1&&(a.scale.y=Math.round(a.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Z")!==-1&&(a.scale.z=Math.round(a.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(o==="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"?(a.quaternion.copy(this.quaternionStart),a.quaternion.multiply(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this.parentQuaternionInv),a.quaternion.copy(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),a.quaternion.multiply(this.quaternionStart).normalize())}this.dispatchEvent(this.changeEvent),this.dispatchEvent(this.objectChangeEvent)}}),P(this,"pointerUp",s=>{s.button===0&&(this.dragging&&this.axis!==null&&(this.mouseUpEvent.mode=this.mode,this.dispatchEvent(this.mouseUpEvent)),this.dragging=!1,this.axis=null)}),P(this,"getPointer",s=>{var r;if(this.domElement&&((r=this.domElement.ownerDocument)!=null&&r.pointerLockElement))return{x:0,y:0,button:s.button};{const o=s.changedTouches?s.changedTouches[0]:s,a=this.domElement.getBoundingClientRect();return{x:(o.clientX-a.left)/a.width*2-1,y:-(o.clientY-a.top)/a.height*2+1,button:s.button}}}),P(this,"onPointerHover",s=>{if(this.enabled)switch(s.pointerType){case"mouse":case"pen":this.pointerHover(this.getPointer(s));break}}),P(this,"onPointerDown",s=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="none",this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.pointerHover(this.getPointer(s)),this.pointerDown(this.getPointer(s)))}),P(this,"onPointerMove",s=>{this.enabled&&this.pointerMove(this.getPointer(s))}),P(this,"onPointerUp",s=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="",this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.pointerUp(this.getPointer(s)))}),P(this,"getMode",()=>this.mode),P(this,"setMode",s=>{this.mode=s}),P(this,"setTranslationSnap",s=>{this.translationSnap=s}),P(this,"setRotationSnap",s=>{this.rotationSnap=s}),P(this,"setScaleSnap",s=>{this.scaleSnap=s}),P(this,"setSize",s=>{this.size=s}),P(this,"setSpace",s=>{this.space=s}),P(this,"update",()=>{console.warn("THREE.TransformControls: update function has no more functionality and therefore has been deprecated.")}),P(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("pointerdown",this.onPointerDown),this.domElement.addEventListener("pointermove",this.onPointerHover),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp)}),P(this,"dispose",()=>{var s,r,o,a,l,c;(s=this.domElement)==null||s.removeEventListener("pointerdown",this.onPointerDown),(r=this.domElement)==null||r.removeEventListener("pointermove",this.onPointerHover),(a=(o=this.domElement)==null?void 0:o.ownerDocument)==null||a.removeEventListener("pointermove",this.onPointerMove),(c=(l=this.domElement)==null?void 0:l.ownerDocument)==null||c.removeEventListener("pointerup",this.onPointerUp),this.traverse(h=>{const A=h;A.geometry&&A.geometry.dispose(),A.material&&A.material.dispose()})}),this.domElement=e,this.camera=t,this.gizmo=new oy,this.add(this.gizmo),this.plane=new ay,this.add(this.plane);const i=(s,r)=>{let o=r;Object.defineProperty(this,s,{get:function(){return o!==void 0?o:r},set:function(a){o!==a&&(o=a,this.plane[s]=a,this.gizmo[s]=a,this.dispatchEvent({type:s+"-changed",value:a}),this.dispatchEvent(this.changeEvent))}}),this[s]=r,this.plane[s]=r,this.gizmo[s]=r};i("camera",this.camera),i("object",this.object),i("enabled",this.enabled),i("axis",this.axis),i("mode",this.mode),i("translationSnap",this.translationSnap),i("rotationSnap",this.rotationSnap),i("scaleSnap",this.scaleSnap),i("space",this.space),i("size",this.size),i("dragging",this.dragging),i("showX",this.showX),i("showY",this.showY),i("showZ",this.showZ),i("worldPosition",this.worldPosition),i("worldPositionStart",this.worldPositionStart),i("worldQuaternion",this.worldQuaternion),i("worldQuaternionStart",this.worldQuaternionStart),i("cameraPosition",this.cameraPosition),i("cameraQuaternion",this.cameraQuaternion),i("pointStart",this.pointStart),i("pointEnd",this.pointEnd),i("rotationAxis",this.rotationAxis),i("rotationAngle",this.rotationAngle),i("eye",this.eye),e!==void 0&&this.connect(e)}};class oy extends jt{constructor(){super(),P(this,"isTransformControlsGizmo",!0),P(this,"type","TransformControlsGizmo"),P(this,"tempVector",new k(0,0,0)),P(this,"tempEuler",new qe),P(this,"alignVector",new k(0,1,0)),P(this,"zeroVector",new k(0,0,0)),P(this,"lookAtMatrix",new dt),P(this,"tempQuaternion",new It),P(this,"tempQuaternion2",new It),P(this,"identityQuaternion",new It),P(this,"unitX",new k(1,0,0)),P(this,"unitY",new k(0,1,0)),P(this,"unitZ",new k(0,0,1)),P(this,"gizmo"),P(this,"picker"),P(this,"helper"),P(this,"rotationAxis",new k),P(this,"cameraPosition",new k),P(this,"worldPositionStart",new k),P(this,"worldQuaternionStart",new It),P(this,"worldPosition",new k),P(this,"worldQuaternion",new It),P(this,"eye",new k),P(this,"camera",null),P(this,"enabled",!0),P(this,"axis",null),P(this,"mode","translate"),P(this,"space","world"),P(this,"size",1),P(this,"dragging",!1),P(this,"showX",!0),P(this,"showY",!0),P(this,"showZ",!0),P(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 X=[];X=X.concat(this.picker[this.mode].children),X=X.concat(this.gizmo[this.mode].children),X=X.concat(this.helper[this.mode].children);for(let Y=0;Y<X.length;Y++){const D=X[Y];D.visible=!0,D.rotation.set(0,0,0),D.position.copy(this.worldPosition);let it;if(this.camera.isOrthographicCamera?it=(this.camera.top-this.camera.bottom)/this.camera.zoom:it=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),D.scale.set(1,1,1).multiplyScalar(it*this.size/7),D.tag==="helper"){D.visible=!1,D.name==="AXIS"?(D.position.copy(this.worldPositionStart),D.visible=!!this.axis,this.axis==="X"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,0)),D.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))>.9&&(D.visible=!1)),this.axis==="Y"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,Math.PI/2)),D.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))>.9&&(D.visible=!1)),this.axis==="Z"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),D.quaternion.copy(H).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))>.9&&(D.visible=!1)),this.axis==="XYZE"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),this.alignVector.copy(this.rotationAxis),D.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.zeroVector,this.alignVector,this.unitY)),D.quaternion.multiply(this.tempQuaternion),D.visible=this.dragging),this.axis==="E"&&(D.visible=!1)):D.name==="START"?(D.position.copy(this.worldPositionStart),D.visible=this.dragging):D.name==="END"?(D.position.copy(this.worldPosition),D.visible=this.dragging):D.name==="DELTA"?(D.position.copy(this.worldPositionStart),D.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()),D.scale.copy(this.tempVector),D.visible=this.dragging):(D.quaternion.copy(H),this.dragging?D.position.copy(this.worldPositionStart):D.position.copy(this.worldPosition),this.axis&&(D.visible=this.axis.search(D.name)!==-1));continue}D.quaternion.copy(H),this.mode==="translate"||this.mode==="scale"?((D.name==="X"||D.name==="XYZX")&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))>.99&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),(D.name==="Y"||D.name==="XYZY")&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))>.99&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),(D.name==="Z"||D.name==="XYZZ")&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))>.99&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),D.name==="XY"&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye))<.2&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),D.name==="YZ"&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye))<.2&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),D.name==="XZ"&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye))<.2&&(D.scale.set(1e-10,1e-10,1e-10),D.visible=!1),D.name.search("X")!==-1&&(this.alignVector.copy(this.unitX).applyQuaternion(H).dot(this.eye)<0?D.tag==="fwd"?D.visible=!1:D.scale.x*=-1:D.tag==="bwd"&&(D.visible=!1)),D.name.search("Y")!==-1&&(this.alignVector.copy(this.unitY).applyQuaternion(H).dot(this.eye)<0?D.tag==="fwd"?D.visible=!1:D.scale.y*=-1:D.tag==="bwd"&&(D.visible=!1)),D.name.search("Z")!==-1&&(this.alignVector.copy(this.unitZ).applyQuaternion(H).dot(this.eye)<0?D.tag==="fwd"?D.visible=!1:D.scale.z*=-1:D.tag==="bwd"&&(D.visible=!1))):this.mode==="rotate"&&(this.tempQuaternion2.copy(H),this.alignVector.copy(this.eye).applyQuaternion(this.tempQuaternion.copy(H).invert()),D.name.search("E")!==-1&&D.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.eye,this.zeroVector,this.unitY)),D.name==="X"&&(this.tempQuaternion.setFromAxisAngle(this.unitX,Math.atan2(-this.alignVector.y,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),D.quaternion.copy(this.tempQuaternion)),D.name==="Y"&&(this.tempQuaternion.setFromAxisAngle(this.unitY,Math.atan2(this.alignVector.x,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),D.quaternion.copy(this.tempQuaternion)),D.name==="Z"&&(this.tempQuaternion.setFromAxisAngle(this.unitZ,Math.atan2(this.alignVector.y,this.alignVector.x)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),D.quaternion.copy(this.tempQuaternion))),D.visible=D.visible&&(D.name.indexOf("X")===-1||this.showX),D.visible=D.visible&&(D.name.indexOf("Y")===-1||this.showY),D.visible=D.visible&&(D.name.indexOf("Z")===-1||this.showZ),D.visible=D.visible&&(D.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),D.material.tempOpacity=D.material.tempOpacity||D.material.opacity,D.material.tempColor=D.material.tempColor||D.material.color.clone(),D.material.color.copy(D.material.tempColor),D.material.opacity=D.material.tempOpacity,this.enabled?this.axis&&(D.name===this.axis?(D.material.opacity=1,D.material.color.lerp(new kt(1,1,1),.5)):this.axis.split("").some(function(at){return D.name===at})?(D.material.opacity=1,D.material.color.lerp(new kt(1,1,1),.5)):(D.material.opacity*=.25,D.material.color.lerp(new kt(1,1,1),.5))):(D.material.opacity*=.5,D.material.color.lerp(new kt(1,1,1),.5))}super.updateMatrixWorld()});const t=new ua({depthTest:!1,depthWrite:!1,transparent:!0,side:Vs,fog:!1,toneMapped:!1}),e=new Ds({depthTest:!1,depthWrite:!1,transparent:!0,linewidth:1,fog:!1,toneMapped:!1}),i=t.clone();i.opacity=.15;const s=t.clone();s.opacity=.33;const r=t.clone();r.color.set(16711680);const o=t.clone();o.color.set(65280);const a=t.clone();a.color.set(255);const l=t.clone();l.opacity=.25;const c=l.clone();c.color.set(16776960);const h=l.clone();h.color.set(65535);const A=l.clone();A.color.set(16711935),t.clone().color.set(16776960);const d=e.clone();d.color.set(16711680);const f=e.clone();f.color.set(65280);const g=e.clone();g.color.set(255);const p=e.clone();p.color.set(65535);const m=e.clone();m.color.set(16711935);const C=e.clone();C.color.set(16776960);const E=e.clone();E.color.set(7895160);const v=C.clone();v.opacity=.25;const y=new me(0,.05,.2,12,1,!1),S=new li(.125,.125,.125),T=new ve;T.setAttribute("position",new $e([0,0,0,1,0,0],3));const x=(G,H)=>{const X=new ve,Y=[];for(let D=0;D<=64*H;++D)Y.push(0,Math.cos(D/32*Math.PI)*G,Math.sin(D/32*Math.PI)*G);return X.setAttribute("position",new $e(Y,3)),X},F=()=>{const G=new ve;return G.setAttribute("position",new $e([0,0,0,1,1,1],3)),G},_={X:[[new nt(y,r),[1,0,0],[0,0,-Math.PI/2],null,"fwd"],[new nt(y,r),[1,0,0],[0,0,Math.PI/2],null,"bwd"],[new Et(T,d)]],Y:[[new nt(y,o),[0,1,0],null,null,"fwd"],[new nt(y,o),[0,1,0],[Math.PI,0,0],null,"bwd"],[new Et(T,f),null,[0,0,Math.PI/2]]],Z:[[new nt(y,a),[0,0,1],[Math.PI/2,0,0],null,"fwd"],[new nt(y,a),[0,0,1],[-Math.PI/2,0,0],null,"bwd"],[new Et(T,g),null,[0,-Math.PI/2,0]]],XYZ:[[new nt(new ci(.1,0),l.clone()),[0,0,0],[0,0,0]]],XY:[[new nt(new gi(.295,.295),c.clone()),[.15,.15,0]],[new Et(T,C),[.18,.3,0],null,[.125,1,1]],[new Et(T,C),[.3,.18,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new nt(new gi(.295,.295),h.clone()),[0,.15,.15],[0,Math.PI/2,0]],[new Et(T,p),[0,.18,.3],[0,0,Math.PI/2],[.125,1,1]],[new Et(T,p),[0,.3,.18],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new nt(new gi(.295,.295),A.clone()),[.15,0,.15],[-Math.PI/2,0,0]],[new Et(T,m),[.18,0,.3],null,[.125,1,1]],[new Et(T,m),[.3,0,.18],[0,-Math.PI/2,0],[.125,1,1]]]},w={X:[[new nt(new me(.2,0,1,4,1,!1),i),[.6,0,0],[0,0,-Math.PI/2]]],Y:[[new nt(new me(.2,0,1,4,1,!1),i),[0,.6,0]]],Z:[[new nt(new me(.2,0,1,4,1,!1),i),[0,0,.6],[Math.PI/2,0,0]]],XYZ:[[new nt(new ci(.2,0),i)]],XY:[[new nt(new gi(.4,.4),i),[.2,.2,0]]],YZ:[[new nt(new gi(.4,.4),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new nt(new gi(.4,.4),i),[.2,0,.2],[-Math.PI/2,0,0]]]},U={START:[[new nt(new ci(.01,2),s),null,null,null,"helper"]],END:[[new nt(new ci(.01,2),s),null,null,null,"helper"]],DELTA:[[new Et(F(),s),null,null,null,"helper"]],X:[[new Et(T,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Et(T,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Et(T,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},O={X:[[new Et(x(1,.5),d)],[new nt(new ci(.04,0),r),[0,0,.99],null,[1,3,1]]],Y:[[new Et(x(1,.5),f),null,[0,0,-Math.PI/2]],[new nt(new ci(.04,0),o),[0,0,.99],null,[3,1,1]]],Z:[[new Et(x(1,.5),g),null,[0,Math.PI/2,0]],[new nt(new ci(.04,0),a),[.99,0,0],null,[1,3,1]]],E:[[new Et(x(1.25,1),v),null,[0,Math.PI/2,0]],[new nt(new me(.03,0,.15,4,1,!1),v),[1.17,0,0],[0,0,-Math.PI/2],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),v),[-1.17,0,0],[0,0,Math.PI/2],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),v),[0,-1.17,0],[Math.PI,0,0],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),v),[0,1.17,0],[0,0,0],[1,1,.001]]],XYZE:[[new Et(x(1,1),E),null,[0,Math.PI/2,0]]]},W={AXIS:[[new Et(T,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},K={X:[[new nt(new Zs(1,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new nt(new Zs(1,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new nt(new Zs(1,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new nt(new Zs(1.25,.1,2,24),i)]],XYZE:[[new nt(new iA(.7,10,8),i)]]},q={X:[[new nt(S,r),[.8,0,0],[0,0,-Math.PI/2]],[new Et(T,d),null,null,[.8,1,1]]],Y:[[new nt(S,o),[0,.8,0]],[new Et(T,f),null,[0,0,Math.PI/2],[.8,1,1]]],Z:[[new nt(S,a),[0,0,.8],[Math.PI/2,0,0]],[new Et(T,g),null,[0,-Math.PI/2,0],[.8,1,1]]],XY:[[new nt(S,c),[.85,.85,0],null,[2,2,.2]],[new Et(T,C),[.855,.98,0],null,[.125,1,1]],[new Et(T,C),[.98,.855,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new nt(S,h),[0,.85,.85],null,[.2,2,2]],[new Et(T,p),[0,.855,.98],[0,0,Math.PI/2],[.125,1,1]],[new Et(T,p),[0,.98,.855],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new nt(S,A),[.85,0,.85],null,[2,.2,2]],[new Et(T,m),[.855,0,.98],null,[.125,1,1]],[new Et(T,m),[.98,0,.855],[0,-Math.PI/2,0],[.125,1,1]]],XYZX:[[new nt(new li(.125,.125,.125),l.clone()),[1.1,0,0]]],XYZY:[[new nt(new li(.125,.125,.125),l.clone()),[0,1.1,0]]],XYZZ:[[new nt(new li(.125,.125,.125),l.clone()),[0,0,1.1]]]},Z={X:[[new nt(new me(.2,0,.8,4,1,!1),i),[.5,0,0],[0,0,-Math.PI/2]]],Y:[[new nt(new me(.2,0,.8,4,1,!1),i),[0,.5,0]]],Z:[[new nt(new me(.2,0,.8,4,1,!1),i),[0,0,.5],[Math.PI/2,0,0]]],XY:[[new nt(S,i),[.85,.85,0],null,[3,3,.2]]],YZ:[[new nt(S,i),[0,.85,.85],null,[.2,3,3]]],XZ:[[new nt(S,i),[.85,0,.85],null,[3,.2,3]]],XYZX:[[new nt(new li(.2,.2,.2),i),[1.1,0,0]]],XYZY:[[new nt(new li(.2,.2,.2),i),[0,1.1,0]]],XYZZ:[[new nt(new li(.2,.2,.2),i),[0,0,1.1]]]},rt={X:[[new Et(T,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Et(T,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Et(T,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},V=G=>{const H=new jt;for(let X in G)for(let Y=G[X].length;Y--;){const D=G[X][Y][0].clone(),it=G[X][Y][1],at=G[X][Y][2],ht=G[X][Y][3],Vt=G[X][Y][4];D.name=X,D.tag=Vt,it&&D.position.set(it[0],it[1],it[2]),at&&D.rotation.set(at[0],at[1],at[2]),ht&&D.scale.set(ht[0],ht[1],ht[2]),D.updateMatrix();const ne=D.geometry.clone();ne.applyMatrix4(D.matrix),D.geometry=ne,D.renderOrder=1/0,D.position.set(0,0,0),D.rotation.set(0,0,0),D.scale.set(1,1,1),H.add(D)}return H};this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=V(_)),this.add(this.gizmo.rotate=V(O)),this.add(this.gizmo.scale=V(q)),this.add(this.picker.translate=V(w)),this.add(this.picker.rotate=V(K)),this.add(this.picker.scale=V(Z)),this.add(this.helper.translate=V(U)),this.add(this.helper.rotate=V(W)),this.add(this.helper.scale=V(rt)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}}class ay extends nt{constructor(){super(new gi(1e5,1e5,2,2),new ua({visible:!1,wireframe:!0,side:Vs,transparent:!0,opacity:.1,toneMapped:!1})),P(this,"isTransformControlsPlane",!0),P(this,"type","TransformControlsPlane"),P(this,"unitX",new k(1,0,0)),P(this,"unitY",new k(0,1,0)),P(this,"unitZ",new k(0,0,1)),P(this,"tempVector",new k),P(this,"dirVector",new k),P(this,"alignVector",new k),P(this,"tempMatrix",new dt),P(this,"identityQuaternion",new It),P(this,"cameraQuaternion",new It),P(this,"worldPosition",new k),P(this,"worldQuaternion",new It),P(this,"eye",new k),P(this,"axis",null),P(this,"mode","translate"),P(this,"space","world"),P(this,"updateMatrixWorld",()=>{let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),this.unitX.set(1,0,0).applyQuaternion(t==="local"?this.worldQuaternion:this.identityQuaternion),this.unitY.set(0,1,0).applyQuaternion(t==="local"?this.worldQuaternion:this.identityQuaternion),this.unitZ.set(0,0,1).applyQuaternion(t==="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 ly=Object.defineProperty,cy=(n,t,e)=>t in n?ly(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,Gt=(n,t,e)=>(cy(n,typeof t!="symbol"?t+"":t,e),e);const xi=new qe(0,0,0,"YXZ"),Di=new k,hy={type:"change"},Ay={type:"lock"},uy={type:"unlock"},Sc=Math.PI/2;let dy=class extends ts{constructor(t,e){super(),Gt(this,"camera"),Gt(this,"domElement"),Gt(this,"isLocked"),Gt(this,"minPolarAngle"),Gt(this,"maxPolarAngle"),Gt(this,"pointerSpeed"),Gt(this,"onMouseMove",i=>{!this.domElement||this.isLocked===!1||(xi.setFromQuaternion(this.camera.quaternion),xi.y-=i.movementX*.002*this.pointerSpeed,xi.x-=i.movementY*.002*this.pointerSpeed,xi.x=Math.max(Sc-this.maxPolarAngle,Math.min(Sc-this.minPolarAngle,xi.x)),this.camera.quaternion.setFromEuler(xi),this.dispatchEvent(hy))}),Gt(this,"onPointerlockChange",()=>{this.domElement&&(this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(Ay),this.isLocked=!0):(this.dispatchEvent(uy),this.isLocked=!1))}),Gt(this,"onPointerlockError",()=>{console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}),Gt(this,"connect",i=>{this.domElement=i||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))}),Gt(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))}),Gt(this,"dispose",()=>{this.disconnect()}),Gt(this,"getObject",()=>this.camera),Gt(this,"direction",new k(0,0,-1)),Gt(this,"getDirection",i=>i.copy(this.direction).applyQuaternion(this.camera.quaternion)),Gt(this,"moveForward",i=>{Di.setFromMatrixColumn(this.camera.matrix,0),Di.crossVectors(this.camera.up,Di),this.camera.position.addScaledVector(Di,i)}),Gt(this,"moveRight",i=>{Di.setFromMatrixColumn(this.camera.matrix,0),this.camera.position.addScaledVector(Di,i)}),Gt(this,"lock",()=>{this.domElement&&this.domElement.requestPointerLock()}),Gt(this,"unlock",()=>{this.domElement&&this.domElement.ownerDocument.exitPointerLock()}),this.camera=t,this.domElement=e,this.isLocked=!1,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.pointerSpeed=1,e&&this.connect(e)}};var fy=Object.defineProperty,gy=(n,t,e)=>t in n?fy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,Ut=(n,t,e)=>(gy(n,typeof t!="symbol"?t+"":t,e),e);let my=class extends ts{constructor(t){super(),Ut(this,"object"),Ut(this,"changeEvent",{type:"change"}),Ut(this,"EPS",1e-6),Ut(this,"enabled",!0),Ut(this,"deviceOrientation",{alpha:0,beta:0,gamma:0}),Ut(this,"screenOrientation",0),Ut(this,"alphaOffset",0),Ut(this,"onDeviceOrientationChangeEvent",e=>{this.deviceOrientation=e}),Ut(this,"onScreenOrientationChangeEvent",()=>{this.screenOrientation=window.orientation||0}),Ut(this,"zee",new k(0,0,1)),Ut(this,"euler",new qe),Ut(this,"q0",new It),Ut(this,"q1",new It(-Math.sqrt(.5),0,0,Math.sqrt(.5))),Ut(this,"setObjectQuaternion",(e,i,s,r,o)=>{this.euler.set(s,i,-r,"YXZ"),e.setFromEuler(this.euler),e.multiply(this.q1),e.multiply(this.q0.setFromAxisAngle(this.zee,-o))}),Ut(this,"connect",()=>{this.onScreenOrientationChangeEvent(),window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission=="function"?window.DeviceOrientationEvent.requestPermission().then(e=>{e=="granted"&&(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent))}).catch(e=>{console.error("THREE.DeviceOrientationControls: Unable to use DeviceOrientation API:",e)}):(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent)),this.enabled=!0}),Ut(this,"disconnect",()=>{window.removeEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.removeEventListener("deviceorientation",this.onDeviceOrientationChangeEvent),this.enabled=!1}),Ut(this,"lastQuaternion",new It),Ut(this,"update",()=>{if(this.enabled===!1)return;const e=this.deviceOrientation;if(e){const i=e.alpha?ct.degToRad(e.alpha)+this.alphaOffset:0,s=e.beta?ct.degToRad(e.beta):0,r=e.gamma?ct.degToRad(e.gamma):0,o=this.screenOrientation?ct.degToRad(this.screenOrientation):0;this.setObjectQuaternion(this.object.quaternion,i,s,r,o),8*(1-this.lastQuaternion.dot(this.object.quaternion))>this.EPS&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(this.changeEvent))}}),Ut(this,"dispose",()=>this.disconnect()),this.object=t,this.object.rotation.reorder("YXZ"),this.connect()}};var py=Object.defineProperty,Ey=(n,t,e)=>t in n?py(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,J=(n,t,e)=>(Ey(n,typeof t!="symbol"?t+"":t,e),e);let Cy=class extends ts{constructor(t,e){super(),J(this,"enabled",!0),J(this,"screen",{left:0,top:0,width:0,height:0}),J(this,"rotateSpeed",1),J(this,"zoomSpeed",1.2),J(this,"panSpeed",.3),J(this,"noRotate",!1),J(this,"noZoom",!1),J(this,"noPan",!1),J(this,"staticMoving",!1),J(this,"dynamicDampingFactor",.2),J(this,"minDistance",0),J(this,"maxDistance",1/0),J(this,"keys",["KeyA","KeyS","KeyD"]),J(this,"mouseButtons",{LEFT:_r.ROTATE,MIDDLE:_r.DOLLY,RIGHT:_r.PAN}),J(this,"object"),J(this,"domElement"),J(this,"cursorZoom",!1),J(this,"target",new k),J(this,"mousePosition",new Kt),J(this,"STATE",{NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4}),J(this,"EPS",1e-6),J(this,"lastZoom",1),J(this,"lastPosition",new k),J(this,"cursorVector",new k),J(this,"targetVector",new k),J(this,"_state",this.STATE.NONE),J(this,"_keyState",this.STATE.NONE),J(this,"_eye",new k),J(this,"_movePrev",new Kt),J(this,"_moveCurr",new Kt),J(this,"_lastAxis",new k),J(this,"_lastAngle",0),J(this,"_zoomStart",new Kt),J(this,"_zoomEnd",new Kt),J(this,"_touchZoomDistanceStart",0),J(this,"_touchZoomDistanceEnd",0),J(this,"_panStart",new Kt),J(this,"_panEnd",new Kt),J(this,"target0"),J(this,"position0"),J(this,"up0"),J(this,"zoom0"),J(this,"changeEvent",{type:"change"}),J(this,"startEvent",{type:"start"}),J(this,"endEvent",{type:"end"}),J(this,"onScreenVector",new Kt),J(this,"getMouseOnScreen",(i,s)=>(this.onScreenVector.set((i-this.screen.left)/this.screen.width,(s-this.screen.top)/this.screen.height),this.onScreenVector)),J(this,"onCircleVector",new Kt),J(this,"getMouseOnCircle",(i,s)=>(this.onCircleVector.set((i-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-s))/this.screen.width),this.onCircleVector)),J(this,"axis",new k),J(this,"quaternion",new It),J(this,"eyeDirection",new k),J(this,"objectUpDirection",new k),J(this,"objectSidewaysDirection",new k),J(this,"moveDirection",new k),J(this,"angle",0),J(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)}),J(this,"zoomCamera",()=>{let i;if(this._state===this.STATE.TOUCH_ZOOM_PAN)i=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(i):this.object.isOrthographicCamera?(this.object.zoom/=i,this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type");else{if(i=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,Math.abs(i-1)>this.EPS&&i>0&&(this.object.isPerspectiveCamera?(i>1&&this._eye.length()>=this.maxDistance-this.EPS&&(i=1),this._eye.multiplyScalar(i)):this.object.isOrthographicCamera?(i>1&&this.object.zoom<this.maxDistance*this.maxDistance&&(i=1),this.object.zoom/=i):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 s=this.cursorVector.set(this.mousePosition.x,this.mousePosition.y,this.targetVector.z).unproject(this.object);this.target.lerpVectors(s,this.target,i)}this.object.isOrthographicCamera&&this.object.updateProjectionMatrix()}}),J(this,"mouseChange",new Kt),J(this,"objectUp",new k),J(this,"pan",new k),J(this,"panCamera",()=>{if(this.domElement&&(this.mouseChange.copy(this._panEnd).sub(this._panStart),this.mouseChange.lengthSq()>this.EPS)){if(this.object.isOrthographicCamera){const i=this.object,s=(i.right-i.left)/this.object.zoom,r=(i.top-i.bottom)/this.object.zoom;this.mouseChange.x*=s,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))}}),J(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)))}),J(this,"handleResize",()=>{if(!this.domElement)return;const i=this.domElement.getBoundingClientRect(),s=this.domElement.ownerDocument.documentElement;this.screen.left=i.left+window.pageXOffset-s.clientLeft,this.screen.top=i.top+window.pageYOffset-s.clientTop,this.screen.width=i.width,this.screen.height=i.height}),J(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")}),J(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}),J(this,"keydown",i=>{this.enabled!==!1&&(window.removeEventListener("keydown",this.keydown),this._keyState===this.STATE.NONE&&(i.code===this.keys[this.STATE.ROTATE]&&!this.noRotate?this._keyState=this.STATE.ROTATE:i.code===this.keys[this.STATE.ZOOM]&&!this.noZoom?this._keyState=this.STATE.ZOOM:i.code===this.keys[this.STATE.PAN]&&!this.noPan&&(this._keyState=this.STATE.PAN)))}),J(this,"onPointerDown",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseDown(i);break}}),J(this,"onPointerMove",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseMove(i);break}}),J(this,"onPointerUp",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseUp();break}}),J(this,"keyup",()=>{this.enabled!==!1&&(this._keyState=this.STATE.NONE,window.addEventListener("keydown",this.keydown))}),J(this,"onMouseDown",i=>{if(!this.domElement)return;if(this._state===this.STATE.NONE)switch(i.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 s=this._keyState!==this.STATE.NONE?this._keyState:this._state;s===this.STATE.ROTATE&&!this.noRotate?(this._moveCurr.copy(this.getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr)):s===this.STATE.ZOOM&&!this.noZoom?(this._zoomStart.copy(this.getMouseOnScreen(i.pageX,i.pageY)),this._zoomEnd.copy(this._zoomStart)):s===this.STATE.PAN&&!this.noPan&&(this._panStart.copy(this.getMouseOnScreen(i.pageX,i.pageY)),this._panEnd.copy(this._panStart)),this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.startEvent)}),J(this,"onMouseMove",i=>{if(this.enabled===!1)return;const s=this._keyState!==this.STATE.NONE?this._keyState:this._state;s===this.STATE.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(i.pageX,i.pageY))):s===this.STATE.ZOOM&&!this.noZoom?this._zoomEnd.copy(this.getMouseOnScreen(i.pageX,i.pageY)):s===this.STATE.PAN&&!this.noPan&&this._panEnd.copy(this.getMouseOnScreen(i.pageX,i.pageY))}),J(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))}),J(this,"mousewheel",i=>{if(this.enabled!==!1&&this.noZoom!==!0){switch(i.preventDefault(),i.deltaMode){case 2:this._zoomStart.y-=i.deltaY*.025;break;case 1:this._zoomStart.y-=i.deltaY*.01;break;default:this._zoomStart.y-=i.deltaY*25e-5;break}this.mousePosition.x=i.offsetX/this.screen.width*2-1,this.mousePosition.y=-(i.offsetY/this.screen.height)*2+1,this.dispatchEvent(this.startEvent),this.dispatchEvent(this.endEvent)}}),J(this,"touchstart",i=>{if(this.enabled!==!1){switch(i.preventDefault(),i.touches.length){case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this._state=this.STATE.TOUCH_ZOOM_PAN;const s=i.touches[0].pageX-i.touches[1].pageX,r=i.touches[0].pageY-i.touches[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(s*s+r*r);const o=(i.touches[0].pageX+i.touches[1].pageX)/2,a=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panStart.copy(this.getMouseOnScreen(o,a)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(this.startEvent)}}),J(this,"touchmove",i=>{if(this.enabled!==!1)switch(i.preventDefault(),i.touches.length){case 1:this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY));break;default:const s=i.touches[0].pageX-i.touches[1].pageX,r=i.touches[0].pageY-i.touches[1].pageY;this._touchZoomDistanceEnd=Math.sqrt(s*s+r*r);const o=(i.touches[0].pageX+i.touches[1].pageX)/2,a=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panEnd.copy(this.getMouseOnScreen(o,a));break}}),J(this,"touchend",i=>{if(this.enabled!==!1){switch(i.touches.length){case 0:this._state=this.STATE.NONE;break;case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break}this.dispatchEvent(this.endEvent)}}),J(this,"contextmenu",i=>{this.enabled!==!1&&i.preventDefault()}),J(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("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()}),J(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=t,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.up0=this.object.up.clone(),this.zoom0=this.object.zoom,e!==void 0&&this.connect(e),this.update()}};var Iy=Object.defineProperty,yy=(n,t,e)=>t in n?Iy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,b=(n,t,e)=>(yy(n,typeof t!="symbol"?t+"":t,e),e);const tt={IDLE:Symbol(),ROTATE:Symbol(),PAN:Symbol(),SCALE:Symbol(),FOV:Symbol(),FOCUS:Symbol(),ZROTATE:Symbol(),TOUCH_MULTI:Symbol(),ANIMATION_FOCUS:Symbol(),ANIMATION_ROTATE:Symbol()},St={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()},gt={x:0,y:0},ie={camera:new dt,gizmos:new dt},Lt={type:"change"},Ee={type:"start"},oe={type:"end"};let By=class extends ts{constructor(t,e=null,i=null){super(),b(this,"camera"),b(this,"domElement"),b(this,"scene"),b(this,"mouseActions"),b(this,"_mouseOp"),b(this,"_v2_1"),b(this,"_v3_1"),b(this,"_v3_2"),b(this,"_m4_1"),b(this,"_m4_2"),b(this,"_quat"),b(this,"_translationMatrix"),b(this,"_rotationMatrix"),b(this,"_scaleMatrix"),b(this,"_rotationAxis"),b(this,"_cameraMatrixState"),b(this,"_cameraProjectionState"),b(this,"_fovState"),b(this,"_upState"),b(this,"_zoomState"),b(this,"_nearPos"),b(this,"_farPos"),b(this,"_gizmoMatrixState"),b(this,"_up0"),b(this,"_zoom0"),b(this,"_fov0"),b(this,"_initialNear"),b(this,"_nearPos0"),b(this,"_initialFar"),b(this,"_farPos0"),b(this,"_cameraMatrixState0"),b(this,"_gizmoMatrixState0"),b(this,"_button"),b(this,"_touchStart"),b(this,"_touchCurrent"),b(this,"_input"),b(this,"_switchSensibility"),b(this,"_startFingerDistance"),b(this,"_currentFingerDistance"),b(this,"_startFingerRotation"),b(this,"_currentFingerRotation"),b(this,"_devPxRatio"),b(this,"_downValid"),b(this,"_nclicks"),b(this,"_downEvents"),b(this,"_clickStart"),b(this,"_maxDownTime"),b(this,"_maxInterval"),b(this,"_posThreshold"),b(this,"_movementThreshold"),b(this,"_currentCursorPosition"),b(this,"_startCursorPosition"),b(this,"_grid"),b(this,"_gridPosition"),b(this,"_gizmos"),b(this,"_curvePts"),b(this,"_timeStart"),b(this,"_animationId"),b(this,"focusAnimationTime"),b(this,"_timePrev"),b(this,"_timeCurrent"),b(this,"_anglePrev"),b(this,"_angleCurrent"),b(this,"_cursorPosPrev"),b(this,"_cursorPosCurr"),b(this,"_wPrev"),b(this,"_wCurr"),b(this,"adjustNearFar"),b(this,"scaleFactor"),b(this,"dampingFactor"),b(this,"wMax"),b(this,"enableAnimations"),b(this,"enableGrid"),b(this,"cursorZoom"),b(this,"minFov"),b(this,"maxFov"),b(this,"enabled"),b(this,"enablePan"),b(this,"enableRotate"),b(this,"enableZoom"),b(this,"minDistance"),b(this,"maxDistance"),b(this,"minZoom"),b(this,"maxZoom"),b(this,"target"),b(this,"_currentTarget"),b(this,"_tbRadius"),b(this,"_state"),b(this,"onWindowResize",()=>{const s=(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/s,a=new xr(0,0,r,r).getPoints(this._curvePts),l=new ve().setFromPoints(a);for(const c in this._gizmos.children){const h=this._gizmos.children[c];h.geometry=l}this.dispatchEvent(Lt)}),b(this,"onContextMenu",s=>{if(this.enabled){for(let r=0;r<this.mouseActions.length;r++)if(this.mouseActions[r].mouse==2){s.preventDefault();break}}}),b(this,"onPointerCancel",()=>{this._touchStart.splice(0,this._touchStart.length),this._touchCurrent.splice(0,this._touchCurrent.length),this._input=St.NONE}),b(this,"onPointerDown",s=>{if(s.button==0&&s.isPrimary?(this._downValid=!0,this._downEvents.push(s)):this._downValid=!1,s.pointerType=="touch"&&this._input!=St.CURSOR)switch(this._touchStart.push(s),this._touchCurrent.push(s),this._input){case St.NONE:this._input=St.ONE_FINGER,this.onSinglePanStart(s,"ROTATE"),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp);break;case St.ONE_FINGER:case St.ONE_FINGER_SWITCHED:this._input=St.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case St.TWO_FINGER:this._input=St.MULT_FINGER,this.onTriplePanStart();break}else if(s.pointerType!="touch"&&this._input==St.NONE){let r=null;s.ctrlKey||s.metaKey?r="CTRL":s.shiftKey&&(r="SHIFT"),this._mouseOp=this.getOpFromAction(s.button,r),this._mouseOp&&(window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),this._input=St.CURSOR,this._button=s.button,this.onSinglePanStart(s,this._mouseOp))}}),b(this,"onPointerMove",s=>{if(s.pointerType=="touch"&&this._input!=St.CURSOR)switch(this._input){case St.ONE_FINGER:this.updateTouchEvent(s),this.onSinglePanMove(s,tt.ROTATE);break;case St.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],s)*this._devPxRatio>=this._switchSensibility){this._input=St.ONE_FINGER,this.updateTouchEvent(s),this.onSinglePanStart(s,"ROTATE");break}break;case St.TWO_FINGER:this.updateTouchEvent(s),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case St.MULT_FINGER:this.updateTouchEvent(s),this.onTriplePanMove();break}else if(s.pointerType!="touch"&&this._input==St.CURSOR){let r=null;s.ctrlKey||s.metaKey?r="CTRL":s.shiftKey&&(r="SHIFT");const o=this.getOpStateFromAction(this._button,r);o&&this.onSinglePanMove(s,o)}this._downValid&&this.calculatePointersDistance(this._downEvents[this._downEvents.length-1],s)*this._devPxRatio>this._movementThreshold&&(this._downValid=!1)}),b(this,"onPointerUp",s=>{if(s.pointerType=="touch"&&this._input!=St.CURSOR){const r=this._touchCurrent.length;for(let o=0;o<r;o++)if(this._touchCurrent[o].pointerId==s.pointerId){this._touchCurrent.splice(o,1),this._touchStart.splice(o,1);break}switch(this._input){case St.ONE_FINGER:case St.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=St.NONE,this.onSinglePanEnd();break;case St.TWO_FINGER:this.onDoublePanEnd(),this.onPinchEnd(),this.onRotateEnd(),this._input=St.ONE_FINGER_SWITCHED;break;case St.MULT_FINGER:this._touchCurrent.length==0&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=St.NONE,this.onTriplePanEnd());break}}else s.pointerType!="touch"&&this._input==St.CURSOR&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=St.NONE,this.onSinglePanEnd(),this._button=-1);if(s.isPrimary)if(this._downValid)if(s.timeStamp-this._downEvents[this._downEvents.length-1].timeStamp<=this._maxDownTime)if(this._nclicks==0)this._nclicks=1,this._clickStart=performance.now();else{const o=s.timeStamp-this._clickStart,a=this.calculatePointersDistance(this._downEvents[1],this._downEvents[0])*this._devPxRatio;o<=this._maxInterval&&a<=this._posThreshold?(this._nclicks=0,this._downEvents.splice(0,this._downEvents.length),this.onDoubleTap(s)):(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)}),b(this,"onWheel",s=>{var r,o;if(this.enabled&&this.enableZoom&&this.domElement){let a=null;s.ctrlKey||s.metaKey?a="CTRL":s.shiftKey&&(a="SHIFT");const l=this.getOpFromAction("WHEEL",a);if(l){s.preventDefault(),this.dispatchEvent(Ee);const c=125;let h=s.deltaY/c,A=1;switch(h>0?A=1/this.scaleFactor:h<0&&(A=this.scaleFactor),l){case"ZOOM":if(this.updateTbState(tt.SCALE,!0),h>0?A=1/Math.pow(this.scaleFactor,h):h<0&&(A=Math.pow(this.scaleFactor,-h)),this.cursorZoom&&this.enablePan){let u;this.camera instanceof se&&(u=(r=this.unprojectOnTbPlane(this.camera,s.clientX,s.clientY,this.domElement))==null?void 0:r.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position)),this.camera instanceof Pt&&(u=(o=this.unprojectOnTbPlane(this.camera,s.clientX,s.clientY,this.domElement))==null?void 0:o.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)),u!==void 0&&this.applyTransformMatrix(this.applyScale(A,u))}else this.applyTransformMatrix(this.applyScale(A,this._gizmos.position));this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt),this.dispatchEvent(oe);break;case"FOV":if(this.camera instanceof Pt){this.updateTbState(tt.FOV,!0),s.deltaX!=0&&(h=s.deltaX/c,A=1,h>0?A=1/Math.pow(this.scaleFactor,h):h<0&&(A=Math.pow(this.scaleFactor,-h))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const u=this._v3_1.distanceTo(this._gizmos.position);let d=u/A;d=ct.clamp(d,this.minDistance,this.maxDistance);const f=u*Math.tan(ct.DEG2RAD*this.camera.fov*.5);let g=ct.RAD2DEG*(Math.atan(f/d)*2);g>this.maxFov?g=this.maxFov:g<this.minFov&&(g=this.minFov);const p=f/Math.tan(ct.DEG2RAD*(g/2));A=u/p,this.setFov(g),this.applyTransformMatrix(this.applyScale(A,this._gizmos.position,!1))}this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt),this.dispatchEvent(oe);break}}}}),b(this,"onSinglePanStart",(s,r)=>{if(this.enabled&&this.domElement)switch(this.dispatchEvent(Ee),this.setCenter(s.clientX,s.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(Lt)),this.camera){this.updateTbState(tt.PAN,!0);const o=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement);o!==void 0&&this._startCursorPosition.copy(o),this.enableGrid&&(this.drawGrid(),this.dispatchEvent(Lt))}break;case"ROTATE":if(!this.enableRotate)return;if(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1),this.camera){this.updateTbState(tt.ROTATE,!0);const o=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);o!==void 0&&this._startCursorPosition.copy(o),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(Lt);break;case"FOV":if(!this.enableZoom)return;this.camera instanceof Pt&&(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(Lt)),this.updateTbState(tt.FOV,!0),this._startCursorPosition.setY(this.getCursorNDC(gt.x,gt.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(Lt)),this.updateTbState(tt.SCALE,!0),this._startCursorPosition.setY(this.getCursorNDC(gt.x,gt.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition);break}}),b(this,"onSinglePanMove",(s,r)=>{if(this.enabled&&this.domElement){const o=r!=this._state;switch(this.setCenter(s.clientX,s.clientY),r){case tt.PAN:if(this.enablePan&&this.camera)if(o){this.dispatchEvent(oe),this.dispatchEvent(Ee),this.updateTbState(r,!0);const a=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement);a!==void 0&&this._startCursorPosition.copy(a),this.enableGrid&&this.drawGrid(),this.activateGizmos(!1)}else{const a=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement);a!==void 0&&this._currentCursorPosition.copy(a),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition))}break;case tt.ROTATE:if(this.enableRotate&&this.camera)if(o){this.dispatchEvent(oe),this.dispatchEvent(Ee),this.updateTbState(r,!0);const a=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);a!==void 0&&this._startCursorPosition.copy(a),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!0)}else{const a=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);a!==void 0&&this._currentCursorPosition.copy(a);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 tt.SCALE:if(this.enableZoom)if(o)this.dispatchEvent(oe),this.dispatchEvent(Ee),this.updateTbState(r,!0),this._startCursorPosition.setY(this.getCursorNDC(gt.x,gt.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(gt.x,gt.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 tt.FOV:if(this.enableZoom&&this.camera instanceof Pt)if(o)this.dispatchEvent(oe),this.dispatchEvent(Ee),this.updateTbState(r,!0),this._startCursorPosition.setY(this.getCursorNDC(gt.x,gt.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(gt.x,gt.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 A=h/c;A=ct.clamp(A,this.minDistance,this.maxDistance);const u=h*Math.tan(ct.DEG2RAD*this._fovState*.5);let d=ct.RAD2DEG*(Math.atan(u/A)*2);d=ct.clamp(d,this.minFov,this.maxFov);const f=u/Math.tan(ct.DEG2RAD*(d/2));c=h/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(d),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(Lt)}}),b(this,"onSinglePanEnd",()=>{if(this._state==tt.ROTATE){if(!this.enableRotate)return;if(this.enableAnimations)if(performance.now()-this._timeCurrent<120){const r=Math.abs((this._wPrev+this._wCurr)/2),o=this;this._animationId=window.requestAnimationFrame(function(a){o.updateTbState(tt.ANIMATION_ROTATE,!0);const l=o.calculateRotationAxis(o._cursorPosPrev,o._cursorPosCurr);o.onRotationAnim(a,l,Math.min(r,o.wMax))})}else this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Lt);else this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Lt)}else(this._state==tt.PAN||this._state==tt.IDLE)&&(this.updateTbState(tt.IDLE,!1),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1),this.dispatchEvent(Lt));this.dispatchEvent(oe)}),b(this,"onDoubleTap",s=>{if(this.enabled&&this.enablePan&&this.scene&&this.camera&&this.domElement){this.dispatchEvent(Ee),this.setCenter(s.clientX,s.clientY);const r=this.unprojectOnObj(this.getCursorNDC(gt.x,gt.y,this.domElement),this.camera);if(r&&this.enableAnimations){const o=this;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),this._timeStart=-1,this._animationId=window.requestAnimationFrame(function(a){o.updateTbState(tt.ANIMATION_FOCUS,!0),o.onFocusAnim(a,r,o._cameraMatrixState,o._gizmoMatrixState)})}else r&&!this.enableAnimations&&(this.updateTbState(tt.FOCUS,!0),this.focus(r,this.scaleFactor),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt))}this.dispatchEvent(oe)}),b(this,"onDoublePanStart",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.dispatchEvent(Ee),this.updateTbState(tt.PAN,!0),this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2);const s=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement,!0);s!==void 0&&this._startCursorPosition.copy(s),this._currentCursorPosition.copy(this._startCursorPosition),this.activateGizmos(!1)}}),b(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!=tt.PAN&&(this.updateTbState(tt.PAN,!0),this._startCursorPosition.copy(this._currentCursorPosition));const s=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement,!0);s!==void 0&&this._currentCursorPosition.copy(s),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition,!0)),this.dispatchEvent(Lt)}}),b(this,"onDoublePanEnd",()=>{this.updateTbState(tt.IDLE,!1),this.dispatchEvent(oe)}),b(this,"onRotateStart",()=>{var s;this.enabled&&this.enableRotate&&(this.dispatchEvent(Ee),this.updateTbState(tt.ZROTATE,!0),this._startFingerRotation=this.getAngle(this._touchCurrent[1],this._touchCurrent[0])+this.getAngle(this._touchStart[1],this._touchStart[0]),this._currentFingerRotation=this._startFingerRotation,(s=this.camera)==null||s.getWorldDirection(this._rotationAxis),!this.enablePan&&!this.enableZoom&&this.activateGizmos(!0))}),b(this,"onRotateMove",()=>{var s;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!=tt.ZROTATE&&(this.updateTbState(tt.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=(s=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement))==null?void 0:s.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._v3_2)):r=new k().setFromMatrixPosition(this._gizmoMatrixState);const o=ct.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);r!==void 0&&this.applyTransformMatrix(this.zRotate(r,o)),this.dispatchEvent(Lt)}}),b(this,"onRotateEnd",()=>{this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(oe)}),b(this,"onPinchStart",()=>{this.enabled&&this.enableZoom&&(this.dispatchEvent(Ee),this.updateTbState(tt.SCALE,!0),this._startFingerDistance=this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),this._currentFingerDistance=this._startFingerDistance,this.activateGizmos(!1))}),b(this,"onPinchMove",()=>{var s,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 o=12;this._state!=tt.SCALE&&(this._startFingerDistance=this._currentFingerDistance,this.updateTbState(tt.SCALE,!0)),this._currentFingerDistance=Math.max(this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),o*this._devPxRatio);const a=this._currentFingerDistance/this._startFingerDistance;let l;this.enablePan?this.camera instanceof se?l=(s=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement))==null?void 0:s.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position):this.camera instanceof Pt&&(l=(r=this.unprojectOnTbPlane(this.camera,gt.x,gt.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(a,l)),this.dispatchEvent(Lt)}}),b(this,"onPinchEnd",()=>{this.updateTbState(tt.IDLE,!1),this.dispatchEvent(oe)}),b(this,"onTriplePanStart",()=>{if(this.enabled&&this.enableZoom&&this.domElement){this.dispatchEvent(Ee),this.updateTbState(tt.SCALE,!0);let s=0,r=0;const o=this._touchCurrent.length;for(let a=0;a<o;a++)s+=this._touchCurrent[a].clientX,r+=this._touchCurrent[a].clientY;this.setCenter(s/o,r/o),this._startCursorPosition.setY(this.getCursorNDC(gt.x,gt.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition)}}),b(this,"onTriplePanMove",()=>{if(this.enabled&&this.enableZoom&&this.camera&&this.domElement){let s=0,r=0;const o=this._touchCurrent.length;for(let p=0;p<o;p++)s+=this._touchCurrent[p].clientX,r+=this._touchCurrent[p].clientY;this.setCenter(s/o,r/o);const a=8;this._currentCursorPosition.setY(this.getCursorNDC(gt.x,gt.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*a):l>0&&(c=Math.pow(this.scaleFactor,l*a)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const h=this._v3_1.distanceTo(this._gizmos.position);let A=h/c;A=ct.clamp(A,this.minDistance,this.maxDistance);const u=h*Math.tan(ct.DEG2RAD*this._fovState*.5);let d=ct.RAD2DEG*(Math.atan(u/A)*2);d=ct.clamp(d,this.minFov,this.maxFov);const f=u/Math.tan(ct.DEG2RAD*(d/2));c=h/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(d),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(Lt)}}),b(this,"onTriplePanEnd",()=>{this.updateTbState(tt.IDLE,!1),this.dispatchEvent(oe)}),b(this,"setCenter",(s,r)=>{gt.x=s,gt.y=r}),b(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")}),b(this,"setMouseAction",(s,r,o=null)=>{const a=["PAN","ROTATE","ZOOM","FOV"],l=[0,1,2,"WHEEL"],c=["CTRL","SHIFT",null];let h;if(!a.includes(s)||!l.includes(r)||!c.includes(o)||r=="WHEEL"&&s!="ZOOM"&&s!="FOV")return!1;switch(s){case"PAN":h=tt.PAN;break;case"ROTATE":h=tt.ROTATE;break;case"ZOOM":h=tt.SCALE;break;case"FOV":h=tt.FOV;break}const A={operation:s,mouse:r,key:o,state:h};for(let u=0;u<this.mouseActions.length;u++)if(this.mouseActions[u].mouse==A.mouse&&this.mouseActions[u].key==A.key)return this.mouseActions.splice(u,1,A),!0;return this.mouseActions.push(A),!0}),b(this,"getOpFromAction",(s,r)=>{let o;for(let a=0;a<this.mouseActions.length;a++)if(o=this.mouseActions[a],o.mouse==s&&o.key==r)return o.operation;if(r){for(let a=0;a<this.mouseActions.length;a++)if(o=this.mouseActions[a],o.mouse==s&&o.key==null)return o.operation}return null}),b(this,"getOpStateFromAction",(s,r)=>{let o;for(let a=0;a<this.mouseActions.length;a++)if(o=this.mouseActions[a],o.mouse==s&&o.key==r)return o.state;if(r){for(let a=0;a<this.mouseActions.length;a++)if(o=this.mouseActions[a],o.mouse==s&&o.key==null)return o.state}return null}),b(this,"getAngle",(s,r)=>Math.atan2(r.clientY-s.clientY,r.clientX-s.clientX)*180/Math.PI),b(this,"updateTouchEvent",s=>{for(let r=0;r<this._touchCurrent.length;r++)if(this._touchCurrent[r].pointerId==s.pointerId){this._touchCurrent.splice(r,1,s);break}}),b(this,"calculateAngularSpeed",(s,r,o,a)=>{const l=r-s,c=(a-o)/1e3;return c==0?0:l/c}),b(this,"calculatePointersDistance",(s,r)=>Math.sqrt(Math.pow(r.clientX-s.clientX,2)+Math.pow(r.clientY-s.clientY,2))),b(this,"calculateRotationAxis",(s,r)=>(this._rotationMatrix.extractRotation(this._cameraMatrixState),this._quat.setFromRotationMatrix(this._rotationMatrix),this._rotationAxis.crossVectors(s,r).applyQuaternion(this._quat),this._rotationAxis.normalize().clone())),b(this,"calculateTbRadius",s=>{const o=s.position.distanceTo(this._gizmos.position);if(s instanceof Pt){const a=ct.DEG2RAD*s.fov*.5,l=Math.atan(s.aspect*Math.tan(a));return Math.tan(Math.min(a,l))*o*.67}else if(s instanceof se)return Math.min(s.top,s.right)*.67}),b(this,"focus",(s,r,o=1)=>{if(this.camera){const a=s.clone();a.sub(this._gizmos.position).multiplyScalar(o),this._translationMatrix.makeTranslation(a.x,a.y,a.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)}}),b(this,"drawGrid",()=>{if(this.scene){let o,a,l,c;if(this.camera instanceof se){const h=this.camera.right-this.camera.left,A=this.camera.bottom-this.camera.top;l=Math.max(h,A),c=l/20,o=l/this.camera.zoom*3,a=o/c*this.camera.zoom}else if(this.camera instanceof Pt){const h=this.camera.position.distanceTo(this._gizmos.position),A=ct.DEG2RAD*this.camera.fov*.5,u=Math.atan(this.camera.aspect*Math.tan(A));l=Math.tan(Math.max(A,u))*h*2,c=l/20,o=l*3,a=o/c}this._grid==null&&this.camera&&(this._grid=new pf(o,a,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))}}),b(this,"connect",s=>{s===document&&console.error('THREE.ArcballControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.domElement=s,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)}),b(this,"dispose",()=>{var s,r,o,a,l;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),(s=this.domElement)==null||s.removeEventListener("pointerdown",this.onPointerDown),(r=this.domElement)==null||r.removeEventListener("pointercancel",this.onPointerCancel),(o=this.domElement)==null||o.removeEventListener("wheel",this.onWheel),(a=this.domElement)==null||a.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()}),b(this,"disposeGrid",()=>{this._grid&&this.scene&&(this.scene.remove(this._grid),this._grid=null)}),b(this,"easeOutCubic",s=>1-Math.pow(1-s,3)),b(this,"activateGizmos",s=>{for(const r of this._gizmos.children)r.material.setValues({opacity:s?1:.6})}),b(this,"getCursorNDC",(s,r,o)=>{const a=o.getBoundingClientRect();return this._v2_1.setX((s-a.left)/a.width*2-1),this._v2_1.setY((a.bottom-r)/a.height*2-1),this._v2_1.clone()}),b(this,"getCursorPosition",(s,r,o)=>(this._v2_1.copy(this.getCursorNDC(s,r,o)),this.camera instanceof se&&(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())),b(this,"setCamera",s=>{if(s){s.lookAt(this.target),s.updateMatrix(),s instanceof Pt&&(this._fov0=s.fov,this._fovState=s.fov),this._cameraMatrixState0.copy(s.matrix),this._cameraMatrixState.copy(this._cameraMatrixState0),this._cameraProjectionState.copy(s.projectionMatrix),this._zoom0=s.zoom,this._zoomState=this._zoom0,this._initialNear=s.near,this._nearPos0=s.position.distanceTo(this.target)-s.near,this._nearPos=this._initialNear,this._initialFar=s.far,this._farPos0=s.position.distanceTo(this.target)-s.far,this._farPos=this._initialFar,this._up0.copy(s.up),this._upState.copy(s.up),this.camera=s,this.camera.updateProjectionMatrix();const r=this.calculateTbRadius(s);r!==void 0&&(this._tbRadius=r),this.makeGizmos(this.target,this._tbRadius)}}),b(this,"makeGizmos",(s,r)=>{const a=new xr(0,0,r,r).getPoints(this._curvePts),l=new ve().setFromPoints(a),c=new Ds({color:16744576,fog:!1,transparent:!0,opacity:.6}),h=new Ds({color:8454016,fog:!1,transparent:!0,opacity:.6}),A=new Ds({color:8421631,fog:!1,transparent:!0,opacity:.6}),u=new Et(l,c),d=new Et(l,h),f=new Et(l,A),g=Math.PI*.5;if(u.rotation.x=g,d.rotation.y=g,this._gizmoMatrixState0.identity().setPosition(s),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(-s.x,-s.y,-s.z),this._gizmoMatrixState.premultiply(this._translationMatrix).premultiply(this._scaleMatrix),this._translationMatrix.makeTranslation(s.x,s.y,s.z),this._gizmoMatrixState.premultiply(this._translationMatrix)}this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.clear(),this._gizmos.add(u),this._gizmos.add(d),this._gizmos.add(f)}),b(this,"onFocusAnim",(s,r,o,a)=>{if(this._timeStart==-1&&(this._timeStart=s),this._state==tt.ANIMATION_FOCUS){const c=(s-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(a),c>=1)this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,this.scaleFactor),this._timeStart=-1,this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Lt);else{const h=this.easeOutCubic(c),A=1-h+this.scaleFactor*h;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,A,h),this.dispatchEvent(Lt);const u=this;this._animationId=window.requestAnimationFrame(function(d){u.onFocusAnim(d,r,o,a.clone())})}}else this._animationId=-1,this._timeStart=-1}),b(this,"onRotationAnim",(s,r,o)=>{if(this._timeStart==-1&&(this._anglePrev=0,this._angleCurrent=0,this._timeStart=s),this._state==tt.ANIMATION_ROTATE){const a=(s-this._timeStart)/1e3;if(o+-this.dampingFactor*a>0){this._angleCurrent=.5*-this.dampingFactor*Math.pow(a,2)+o*a+0,this.applyTransformMatrix(this.rotate(r,this._angleCurrent)),this.dispatchEvent(Lt);const c=this;this._animationId=window.requestAnimationFrame(function(h){c.onRotationAnim(h,r,o)})}else this._animationId=-1,this._timeStart=-1,this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Lt)}else this._animationId=-1,this._timeStart=-1,this._state!=tt.ROTATE&&(this.activateGizmos(!1),this.dispatchEvent(Lt))}),b(this,"pan",(s,r,o=!1)=>{if(this.camera){const a=s.clone().sub(r);if(this.camera instanceof se&&a.multiplyScalar(1/this.camera.zoom),this.camera instanceof Pt&&o){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);a.multiplyScalar(1/l)}this._v3_1.set(a.x,a.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 ie}),b(this,"reset",()=>{if(this.camera){this.camera.zoom=this._zoom0,this.camera instanceof Pt&&(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 s=this.calculateTbRadius(this.camera);s!==void 0&&(this._tbRadius=s),this.makeGizmos(this._gizmos.position,this._tbRadius),this.camera.lookAt(this._gizmos.position),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt)}}),b(this,"rotate",(s,r)=>{const o=this._gizmos.position;return this._translationMatrix.makeTranslation(-o.x,-o.y,-o.z),this._rotationMatrix.makeRotationAxis(s,-r),this._m4_1.makeTranslation(o.x,o.y,o.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1),ie}),b(this,"copyState",()=>{if(this.camera){const s=JSON.stringify(this.camera instanceof se?{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(s)}}),b(this,"pasteState",()=>{const s=this;navigator.clipboard.readText().then(function(o){s.setStateFromJSON(o)})}),b(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 Pt&&(this._fov0=this.camera.fov))}),b(this,"applyScale",(s,r,o=!0)=>{if(!this.camera)return;const a=r.clone();let l=1/s;if(this.camera instanceof se){this.camera.zoom=this._zoomState,this.camera.zoom*=s,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),a.sub(this._v3_1);const c=a.clone().multiplyScalar(l);return a.sub(c),this._m4_1.makeTranslation(a.x,a.y,a.z),this._m4_2.premultiply(this._m4_1),this.setTransformationMatrices(this._m4_1,this._m4_2),ie}if(this.camera instanceof Pt){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let c=this._v3_1.distanceTo(a),h=c-c*l;const A=c-h;A<this.minDistance?(l=this.minDistance/c,h=c-c*l):A>this.maxDistance&&(l=this.maxDistance/c,h=c-c*l);let u=a.clone().sub(this._v3_1).normalize().multiplyScalar(h);if(this._m4_1.makeTranslation(u.x,u.y,u.z),o){const d=this._v3_2;c=d.distanceTo(a),h=c-c*l,u=a.clone().sub(this._v3_2).normalize().multiplyScalar(h),this._translationMatrix.makeTranslation(d.x,d.y,d.z),this._scaleMatrix.makeScale(l,l,l),this._m4_2.makeTranslation(u.x,u.y,u.z).multiply(this._translationMatrix),this._m4_2.multiply(this._scaleMatrix),this._translationMatrix.makeTranslation(-d.x,-d.y,-d.z),this._m4_2.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1,this._m4_2)}else this.setTransformationMatrices(this._m4_1);return ie}}),b(this,"setFov",s=>{this.camera instanceof Pt&&(this.camera.fov=ct.clamp(s,this.minFov,this.maxFov),this.camera.updateProjectionMatrix())}),b(this,"setTarget",(s,r,o)=>{if(this.camera){this.target.set(s,r,o),this._gizmos.position.set(s,r,o);const a=this.calculateTbRadius(this.camera);a!==void 0&&(this._tbRadius=a),this.makeGizmos(this.target,this._tbRadius),this.camera.lookAt(this.target)}}),b(this,"zRotate",(s,r)=>(this._rotationMatrix.makeRotationAxis(this._rotationAxis,r),this._translationMatrix.makeTranslation(-s.x,-s.y,-s.z),this._m4_1.makeTranslation(s.x,s.y,s.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState).sub(s),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),ie)),b(this,"unprojectOnObj",(s,r)=>{if(!this.scene)return null;const o=new or;o.near=r.near,o.far=r.far,o.setFromCamera(s,r);const a=o.intersectObjects(this.scene.children,!0);for(let l=0;l<a.length;l++)if(a[l].object.uuid!=this._gizmos.uuid&&a[l].face)return a[l].point.clone();return null}),b(this,"unprojectOnTbSurface",(s,r,o,a,l)=>{if(s instanceof se){this._v2_1.copy(this.getCursorPosition(r,o,a)),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),A=Math.pow(this._tbRadius,2);return c+h<=A*.5?this._v3_1.setZ(Math.sqrt(A-(c+h))):this._v3_1.setZ(A*.5/Math.sqrt(c+h)),this._v3_1}if(s instanceof Pt){this._v2_1.copy(this.getCursorNDC(r,o,a)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=s.position.distanceTo(this._gizmos.position),A=Math.pow(l,2),u=this._v3_1.z,d=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));if(d==0)return c.set(this._v3_1.x,this._v3_1.y,l),c;const f=u/d,g=h;let p=Math.pow(f,2)+1,m=2*f*g,C=Math.pow(g,2)-A,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),ct.RAD2DEG*this._v2_1.angle()>=45)){const S=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(h-this._v2_1.y,2));return c.multiplyScalar(S),c.z+=h,c}p=f,m=g,C=-A*.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 v=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(h-this._v2_1.y,2));return c.multiplyScalar(v),c.z+=h,c}}),b(this,"unprojectOnTbPlane",(s,r,o,a,l=!1)=>{if(s instanceof se)return this._v2_1.copy(this.getCursorPosition(r,o,a)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0),this._v3_1.clone();if(s instanceof Pt){this._v2_1.copy(this.getCursorNDC(r,o,a)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=this._v3_1.z,A=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let u;if(l?u=this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):u=s.position.distanceTo(this._gizmos.position),A==0)return c.set(0,0,0),c;const d=h/A,f=u,g=-f/d,p=Math.sqrt(Math.pow(f,2)+Math.pow(g,2));return c.multiplyScalar(p),c.z=0,c}}),b(this,"updateMatrixState",()=>{this.camera&&(this._cameraMatrixState.copy(this.camera.matrix),this._gizmoMatrixState.copy(this._gizmos.matrix),this.camera instanceof se&&(this._cameraProjectionState.copy(this.camera.projectionMatrix),this.camera.updateProjectionMatrix(),this._zoomState=this.camera.zoom),this.camera instanceof Pt&&(this._fovState=this.camera.fov))}),b(this,"updateTbState",(s,r)=>{this._state=s,r&&this.updateMatrixState()}),b(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 se&&(this.camera.zoom>this.maxZoom||this.camera.zoom<this.minZoom)){const r=ct.clamp(this.camera.zoom,this.minZoom,this.maxZoom);this.applyTransformMatrix(this.applyScale(r/this.camera.zoom,this._gizmos.position,!0))}if(this.camera instanceof Pt){const r=this.camera.position.distanceTo(this._gizmos.position);if(r>this.maxDistance+1e-6||r<this.minDistance-1e-6){const l=ct.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=ct.clamp(this.camera.fov,this.minFov,this.maxFov),this.camera.updateProjectionMatrix());const o=this._tbRadius,a=this.calculateTbRadius(this.camera);if(a!==void 0&&(this._tbRadius=a),o<this._tbRadius-1e-6||o>this._tbRadius+1e-6){const l=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,c=this._tbRadius/l,A=new xr(0,0,c,c).getPoints(this._curvePts),u=new ve().setFromPoints(A);for(const d in this._gizmos.children){const f=this._gizmos.children[d];f.geometry=u}}}this.camera.lookAt(this._gizmos.position)}}),b(this,"setStateFromJSON",s=>{const r=JSON.parse(s);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 Pt&&(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 o=this.calculateTbRadius(this.camera);o!==void 0&&(this._tbRadius=o);const a=new dt().copy(this._gizmoMatrixState0);this.makeGizmos(this._gizmos.position,this._tbRadius),this._gizmoMatrixState0.copy(a),this.camera.lookAt(this._gizmos.position),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt)}}),this.camera=null,this.domElement=e,this.scene=i,this.mouseActions=[],this._mouseOp=null,this._v2_1=new Kt,this._v3_1=new k,this._v3_2=new k,this._m4_1=new dt,this._m4_2=new dt,this._quat=new It,this._translationMatrix=new dt,this._rotationMatrix=new dt,this._scaleMatrix=new dt,this._rotationAxis=new k,this._cameraMatrixState=new dt,this._cameraProjectionState=new dt,this._fovState=1,this._upState=new k,this._zoomState=1,this._nearPos=0,this._farPos=0,this._gizmoMatrixState=new dt,this._up0=new k,this._zoom0=1,this._fov0=0,this._initialNear=0,this._nearPos0=0,this._initialFar=0,this._farPos0=0,this._cameraMatrixState0=new dt,this._gizmoMatrixState0=new dt,this._button=-1,this._touchStart=[],this._touchCurrent=[],this._input=St.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 k,this._startCursorPosition=new k,this._grid=null,this._gridPosition=new k,this._gizmos=new xo,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 k,this._cursorPosCurr=new k,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 k(0,0,0),this._currentTarget=new k(0,0,0),this._tbRadius=1,this._state=tt.IDLE,this.setCamera(t),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(t){if(t!=null&&t.camera&&this.camera&&(this._m4_1.copy(this._cameraMatrixState).premultiply(t.camera),this._m4_1.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.updateMatrix(),(this._state==tt.ROTATE||this._state==tt.ZROTATE||this._state==tt.ANIMATION_ROTATE)&&this.camera.up.copy(this._upState).applyQuaternion(this.camera.quaternion)),t!=null&&t.gizmos&&(this._m4_1.copy(this._gizmoMatrixState).premultiply(t.gizmos),this._m4_1.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.updateMatrix()),(this._state==tt.SCALE||this._state==tt.FOCUS||this._state==tt.ANIMATION_FOCUS)&&this.camera){const e=this.calculateTbRadius(this.camera);if(e!==void 0&&(this._tbRadius=e),this.adjustNearFar){const i=this.camera.position.distanceTo(this._gizmos.position),s=new sA;s.setFromObject(this._gizmos);const r=new da;s.getBoundingSphere(r);const o=Math.max(this._nearPos0,r.radius+r.center.length()),a=i-this._initialNear,l=Math.min(o,a);this.camera.near=i-l;const c=Math.min(this._farPos0,-r.radius+r.center.length()),h=i-this._initialFar,A=Math.min(c,h);this.camera.far=i-A,this.camera.updateProjectionMatrix()}else{let i=!1;this.camera.near!=this._initialNear&&(this.camera.near=this._initialNear,i=!0),this.camera.far!=this._initialFar&&(this.camera.far=this._initialFar,i=!0),i&&this.camera.updateProjectionMatrix()}}}setGizmosVisible(t){this._gizmos.visible=t,this.dispatchEvent(Lt)}setTransformationMatrices(t=null,e=null){t?ie.camera?ie.camera.copy(t):ie.camera=t.clone():ie.camera=null,e?ie.gizmos?ie.gizmos.copy(e):ie.gizmos=e.clone():ie.gizmos=null}};var vy=Object.defineProperty,Sy=(n,t,e)=>t in n?vy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,_t=(n,t,e)=>(Sy(n,typeof t!="symbol"?t+"":t,e),e);function Tc(n){n.preventDefault()}let Ty=class extends ts{constructor(t,e){super(),_t(this,"object"),_t(this,"domElement",null),_t(this,"movementSpeed",1),_t(this,"rollSpeed",.005),_t(this,"dragToLook",!1),_t(this,"autoForward",!1),_t(this,"changeEvent",{type:"change"}),_t(this,"EPS",1e-6),_t(this,"tmpQuaternion",new It),_t(this,"mouseStatus",0),_t(this,"movementSpeedMultiplier",1),_t(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}),_t(this,"moveVector",new k(0,0,0)),_t(this,"rotationVector",new k(0,0,0)),_t(this,"keydown",i=>{if(!i.altKey){switch(i.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()}}),_t(this,"keyup",i=>{switch(i.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()}),_t(this,"pointerdown",i=>{if(this.dragToLook)this.mouseStatus++;else{switch(i.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}}),_t(this,"pointermove",i=>{if(!this.dragToLook||this.mouseStatus>0){const s=this.getContainerDimensions(),r=s.size[0]/2,o=s.size[1]/2;this.moveState.yawLeft=-(i.pageX-s.offset[0]-r)/r,this.moveState.pitchDown=(i.pageY-s.offset[1]-o)/o,this.updateRotationVector()}}),_t(this,"pointerup",i=>{if(this.dragToLook)this.mouseStatus--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(i.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()}),_t(this,"lastQuaternion",new It),_t(this,"lastPosition",new k),_t(this,"update",i=>{const s=i*this.movementSpeed,r=i*this.rollSpeed;this.object.translateX(this.moveVector.x*s),this.object.translateY(this.moveVector.y*s),this.object.translateZ(this.moveVector.z*s),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))}),_t(this,"updateMovementVector",()=>{const i=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=-i+this.moveState.back}),_t(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}),_t(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]}),_t(this,"connect",i=>{this.domElement=i,i instanceof Document||i.setAttribute("tabindex",-1),this.domElement.addEventListener("contextmenu",Tc),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)}),_t(this,"dispose",()=>{this.domElement.removeEventListener("contextmenu",Tc),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=t,e!==void 0&&this.connect(e),this.updateMovementVector(),this.updateRotationVector()}};function ru(n,t,e){const i=e.length-n-1;if(t>=e[i])return i-1;if(t<=e[n])return n;let s=n,r=i,o=Math.floor((s+r)/2);for(;t<e[o]||t>=e[o+1];)t<e[o]?r=o:s=o,o=Math.floor((s+r)/2);return o}function _y(n,t,e,i){const s=[],r=[],o=[];s[0]=1;for(let a=1;a<=e;++a){r[a]=t-i[n+1-a],o[a]=i[n+a]-t;let l=0;for(let c=0;c<a;++c){const h=o[c+1],A=r[a-c],u=s[c]/(h+A);s[c]=l+h*u,l=A*u}s[a]=l}return s}function xy(n,t,e,i){const s=ru(n,i,t),r=_y(s,i,n,t),o=new Te(0,0,0,0);for(let a=0;a<=n;++a){const l=e[s-n+a],c=r[a],h=l.w*c;o.x+=l.x*h,o.y+=l.y*h,o.z+=l.z*h,o.w+=l.w*c}return o}function Dy(n,t,e,i,s){const r=[];for(let A=0;A<=e;++A)r[A]=0;const o=[];for(let A=0;A<=i;++A)o[A]=r.slice(0);const a=[];for(let A=0;A<=e;++A)a[A]=r.slice(0);a[0][0]=1;const l=r.slice(0),c=r.slice(0);for(let A=1;A<=e;++A){l[A]=t-s[n+1-A],c[A]=s[n+A]-t;let u=0;for(let d=0;d<A;++d){const f=c[d+1],g=l[A-d];a[A][d]=f+g;const p=a[d][A-1]/a[A][d];a[d][A]=u+f*p,u=g*p}a[A][A]=u}for(let A=0;A<=e;++A)o[0][A]=a[A][e];for(let A=0;A<=e;++A){let u=0,d=1;const f=[];for(let g=0;g<=e;++g)f[g]=r.slice(0);f[0][0]=1;for(let g=1;g<=i;++g){let p=0;const m=A-g,C=e-g;A>=g&&(f[d][0]=f[u][0]/a[C+1][m],p=f[d][0]*a[m][C]);const E=m>=-1?1:-m,v=A-1<=C?g-1:e-A;for(let S=E;S<=v;++S)f[d][S]=(f[u][S]-f[u][S-1])/a[C+1][m+S],p+=f[d][S]*a[m+S][C];A<=C&&(f[d][g]=-f[u][g-1]/a[C+1][A],p+=f[d][g]*a[A][C]),o[g][A]=p;const y=u;u=d,d=y}}let h=e;for(let A=1;A<=i;++A){for(let u=0;u<=e;++u)o[A][u]*=h;h*=e-A}return o}function Ry(n,t,e,i,s){const r=s<n?s:n,o=[],a=ru(n,i,t),l=Dy(a,i,n,r,t),c=[];for(let h=0;h<e.length;++h){const A=e[h].clone(),u=A.w;A.x*=u,A.y*=u,A.z*=u,c[h]=A}for(let h=0;h<=r;++h){const A=c[a-n].clone().multiplyScalar(l[h][0]);for(let u=1;u<=n;++u)A.add(c[a-n+u].clone().multiplyScalar(l[h][u]));o[h]=A}for(let h=r+1;h<=s+1;++h)o[h]=new Te(0,0,0);return o}function wy(n,t){let e=1;for(let s=2;s<=n;++s)e*=s;let i=1;for(let s=2;s<=t;++s)i*=s;for(let s=2;s<=n-t;++s)i*=s;return e/i}function Ly(n){const t=n.length,e=[],i=[];for(let r=0;r<t;++r){const o=n[r];e[r]=new k(o.x,o.y,o.z),i[r]=o.w}const s=[];for(let r=0;r<t;++r){const o=e[r].clone();for(let a=1;a<=r;++a)o.sub(s[r-a].clone().multiplyScalar(wy(r,a)*i[a]));s[r]=o.divideScalar(i[0])}return s}function by(n,t,e,i,s){const r=Ry(n,t,e,i,s);return Ly(r)}class _c extends Ef{constructor(t,e,i,s,r){super(),this.degree=t,this.knots=e,this.controlPoints=[],this.startKnot=s||0,this.endKnot=r||this.knots.length-1;for(let o=0;o<i.length;++o){const a=i[o];this.controlPoints[o]=new Te(a.x,a.y,a.z,a.w)}}getPoint(t,e){const i=e||new k,s=this.knots[this.startKnot]+t*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=xy(this.degree,this.knots,this.controlPoints,s);return r.w!=1&&r.divideScalar(r.w),i.set(r.x,r.y,r.z)}getTangent(t,e){const i=e||new k,s=this.knots[0]+t*(this.knots[this.knots.length-1]-this.knots[0]),r=by(this.degree,this.knots,this.controlPoints,s,1);return i.copy(r[1]).normalize(),i}}let pt,Mt,ee;class Ua extends fa{constructor(t){super(t)}load(t,e,i,s){const r=this,o=r.path===""?Cf.extractUrlBase(t):r.path,a=new Ki(this.manager);a.setPath(r.path),a.setResponseType("arraybuffer"),a.setRequestHeader(r.requestHeader),a.setWithCredentials(r.withCredentials),a.load(t,function(l){try{e(r.parse(l,o))}catch(c){s?s(c):console.error(c),r.manager.itemError(t)}},i,s)}parse(t,e){if(Oy(t))pt=new Qy().parse(t);else{const s=cu(t);if(!Gy(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Dc(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Dc(s));pt=new ky().parse(s)}const i=new If(this.manager).setPath(this.resourcePath||e).setCrossOrigin(this.crossOrigin);return new Fy(i,this.manager).parse(pt)}}class Fy{constructor(t,e){this.textureLoader=t,this.manager=e}parse(){Mt=this.parseConnections();const t=this.parseImages(),e=this.parseTextures(t),i=this.parseMaterials(e),s=this.parseDeformers(),r=new My().parse(s);return this.parseScene(s,r,i),ee}parseConnections(){const t=new Map;return"Connections"in pt&&pt.Connections.connections.forEach(function(i){const s=i[0],r=i[1],o=i[2];t.has(s)||t.set(s,{parents:[],children:[]});const a={ID:r,relationship:o};t.get(s).parents.push(a),t.has(r)||t.set(r,{parents:[],children:[]});const l={ID:s,relationship:o};t.get(r).children.push(l)}),t}parseImages(){const t={},e={};if("Video"in pt.Objects){const i=pt.Objects.Video;for(const s in i){const r=i[s],o=parseInt(s);if(t[o]=r.RelativeFilename||r.Filename,"Content"in r){const a=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,l=typeof r.Content=="string"&&r.Content!=="";if(a||l){const c=this.parseImage(i[s]);e[r.RelativeFilename||r.Filename]=c}}}}for(const i in t){const s=t[i];e[s]!==void 0?t[i]=e[s]:t[i]=t[i].split("\\").pop()}return t}parseImage(t){const e=t.Content,i=t.RelativeFilename||t.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let r;switch(s){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 ",i),r="image/tga";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof e=="string")return"data:"+r+";base64,"+e;{const o=new Uint8Array(e);return window.URL.createObjectURL(new Blob([o],{type:r}))}}parseTextures(t){const e=new Map;if("Texture"in pt.Objects){const i=pt.Objects.Texture;for(const s in i){const r=this.parseTexture(i[s],t);e.set(parseInt(s),r)}}return e}parseTexture(t,e){const i=this.loadTexture(t,e);i.ID=t.id,i.name=t.attrName;const s=t.WrapModeU,r=t.WrapModeV,o=s!==void 0?s.value:0,a=r!==void 0?r.value:0;if(i.wrapS=o===0?Do:kn,i.wrapT=a===0?Do:kn,"Scaling"in t){const l=t.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}return i}loadTexture(t,e){let i;const s=this.textureLoader.path,r=Mt.get(t.id).children;r!==void 0&&r.length>0&&e[r[0].ID]!==void 0&&(i=e[r[0].ID],(i.indexOf("blob:")===0||i.indexOf("data:")===0)&&this.textureLoader.setPath(void 0));let o;const a=t.FileName.slice(-3).toLowerCase();if(a==="tga"){const l=this.manager.getHandler(".tga");l===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",t.RelativeFilename),o=new Qn):(l.setPath(this.textureLoader.path),o=l.load(i))}else a==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",t.RelativeFilename),o=new Qn):o=this.textureLoader.load(i);return this.textureLoader.setPath(s),o}parseMaterials(t){const e=new Map;if("Material"in pt.Objects){const i=pt.Objects.Material;for(const s in i){const r=this.parseMaterial(i[s],t);r!==null&&e.set(parseInt(s),r)}}return e}parseMaterial(t,e){const i=t.id,s=t.attrName;let r=t.ShadingModel;if(typeof r=="object"&&(r=r.value),!Mt.has(i))return null;const o=this.parseParameters(t,e,i);let a;switch(r.toLowerCase()){case"phong":a=new Dr;break;case"lambert":a=new yf;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),a=new Dr;break}return a.setValues(o),a.name=s,a}parseParameters(t,e,i){const s={};t.BumpFactor&&(s.bumpScale=t.BumpFactor.value),t.Diffuse?s.color=new kt().fromArray(t.Diffuse.value):t.DiffuseColor&&(t.DiffuseColor.type==="Color"||t.DiffuseColor.type==="ColorRGB")&&(s.color=new kt().fromArray(t.DiffuseColor.value)),t.DisplacementFactor&&(s.displacementScale=t.DisplacementFactor.value),t.Emissive?s.emissive=new kt().fromArray(t.Emissive.value):t.EmissiveColor&&(t.EmissiveColor.type==="Color"||t.EmissiveColor.type==="ColorRGB")&&(s.emissive=new kt().fromArray(t.EmissiveColor.value)),t.EmissiveFactor&&(s.emissiveIntensity=parseFloat(t.EmissiveFactor.value)),t.Opacity&&(s.opacity=parseFloat(t.Opacity.value)),s.opacity<1&&(s.transparent=!0),t.ReflectionFactor&&(s.reflectivity=t.ReflectionFactor.value),t.Shininess&&(s.shininess=t.Shininess.value),t.Specular?s.specular=new kt().fromArray(t.Specular.value):t.SpecularColor&&t.SpecularColor.type==="Color"&&(s.specular=new kt().fromArray(t.SpecularColor.value));const r=this;return Mt.get(i).children.forEach(function(o){const a=o.relationship;switch(a){case"Bump":s.bumpMap=r.getTexture(e,o.ID);break;case"Maya|TEX_ao_map":s.aoMap=r.getTexture(e,o.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=r.getTexture(e,o.ID),s.map!==void 0&&("colorSpace"in s.map?s.map.colorSpace="srgb":s.map.encoding=3001);break;case"DisplacementColor":s.displacementMap=r.getTexture(e,o.ID);break;case"EmissiveColor":s.emissiveMap=r.getTexture(e,o.ID),s.emissiveMap!==void 0&&("colorSpace"in s.emissiveMap?s.emissiveMap.colorSpace="srgb":s.emissiveMap.encoding=3001);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=r.getTexture(e,o.ID);break;case"ReflectionColor":s.envMap=r.getTexture(e,o.ID),s.envMap!==void 0&&(s.envMap.mapping=Bf,"colorSpace"in s.envMap?s.envMap.colorSpace="srgb":s.envMap.encoding=3001);break;case"SpecularColor":s.specularMap=r.getTexture(e,o.ID),s.specularMap!==void 0&&("colorSpace"in s.specularMap?s.specularMap.colorSpace="srgb":s.specularMap.encoding=3001);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=r.getTexture(e,o.ID),s.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.",a);break}}),s}getTexture(t,e){return"LayeredTexture"in pt.Objects&&e in pt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),e=Mt.get(e).children[0].ID),t.get(e)}parseDeformers(){const t={},e={};if("Deformer"in pt.Objects){const i=pt.Objects.Deformer;for(const s in i){const r=i[s],o=Mt.get(parseInt(s));if(r.attrType==="Skin"){const a=this.parseSkeleton(o,i);a.ID=s,o.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),a.geometryID=o.parents[0].ID,t[s]=a}else if(r.attrType==="BlendShape"){const a={id:s};a.rawTargets=this.parseMorphTargets(o,i),a.id=s,o.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),e[s]=a}}}return{skeletons:t,morphTargets:e}}parseSkeleton(t,e){const i=[];return t.children.forEach(function(s){const r=e[s.ID];if(r.attrType!=="Cluster")return;const o={ID:s.ID,indices:[],weights:[],transformLink:new dt().fromArray(r.TransformLink.a)};"Indexes"in r&&(o.indices=r.Indexes.a,o.weights=r.Weights.a),i.push(o)}),{rawBones:i,bones:[]}}parseMorphTargets(t,e){const i=[];for(let s=0;s<t.children.length;s++){const r=t.children[s],o=e[r.ID],a={name:o.attrName,initialWeight:o.DeformPercent,id:o.id,fullWeights:o.FullWeights.a};if(o.attrType!=="BlendShapeChannel")return;a.geoID=Mt.get(parseInt(r.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,i.push(a)}return i}parseScene(t,e,i){ee=new xo;const s=this.parseModels(t.skeletons,e,i),r=pt.Objects.Model,o=this;s.forEach(function(l){const c=r[l.ID];o.setLookAtProperties(l,c),Mt.get(l.ID).parents.forEach(function(A){const u=s.get(A.ID);u!==void 0&&u.add(l)}),l.parent===null&&ee.add(l)}),this.bindSkeleton(t.skeletons,e,s),this.createAmbientLight(),ee.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=au(l.userData.transformData);l.applyMatrix4(c),l.updateWorldMatrix()}});const a=new Py().parse();ee.children.length===1&&ee.children[0].isGroup&&(ee.children[0].animations=a,ee=ee.children[0]),ee.animations=a}parseModels(t,e,i){const s=new Map,r=pt.Objects.Model;for(const o in r){const a=parseInt(o),l=r[o],c=Mt.get(a);let h=this.buildSkeleton(c,t,a,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,e,i);break;case"NurbsCurve":h=this.createCurve(c,e);break;case"LimbNode":case"Root":h=new al;break;case"Null":default:h=new xo;break}h.name=l.attrName?On.sanitizeNodeName(l.attrName):"",h.ID=a}this.getTransformData(h,l),s.set(a,h)}return s}buildSkeleton(t,e,i,s){let r=null;return t.parents.forEach(function(o){for(const a in e){const l=e[a];l.rawBones.forEach(function(c,h){if(c.ID===o.ID){const A=r;r=new al,r.matrixWorld.copy(c.transformLink),r.name=s?On.sanitizeNodeName(s):"",r.ID=i,l.bones[h]=r,A!==null&&r.add(A)}})}}),r}createCamera(t){let e,i;if(t.children.forEach(function(s){const r=pt.Objects.NodeAttribute[s.ID];r!==void 0&&(i=r)}),i===void 0)e=new jt;else{let s=0;i.CameraProjectionType!==void 0&&i.CameraProjectionType.value===1&&(s=1);let r=1;i.NearPlane!==void 0&&(r=i.NearPlane.value/1e3);let o=1e3;i.FarPlane!==void 0&&(o=i.FarPlane.value/1e3);let a=window.innerWidth,l=window.innerHeight;i.AspectWidth!==void 0&&i.AspectHeight!==void 0&&(a=i.AspectWidth.value,l=i.AspectHeight.value);const c=a/l;let h=45;i.FieldOfView!==void 0&&(h=i.FieldOfView.value);const A=i.FocalLength?i.FocalLength.value:null;switch(s){case 0:e=new Pt(h,c,r,o),A!==null&&e.setFocalLength(A);break;case 1:e=new se(-a/2,a/2,l/2,-l/2,r,o);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+s+"."),e=new jt;break}}return e}createLight(t){let e,i;if(t.children.forEach(function(s){const r=pt.Objects.NodeAttribute[s.ID];r!==void 0&&(i=r)}),i===void 0)e=new jt;else{let s;i.LightType===void 0?s=0:s=i.LightType.value;let r=16777215;i.Color!==void 0&&(r=new kt().fromArray(i.Color.value));let o=i.Intensity===void 0?1:i.Intensity.value/100;i.CastLightOnObject!==void 0&&i.CastLightOnObject.value===0&&(o=0);let a=0;i.FarAttenuationEnd!==void 0&&(i.EnableFarAttenuation!==void 0&&i.EnableFarAttenuation.value===0?a=0:a=i.FarAttenuationEnd.value);const l=1;switch(s){case 0:e=new ll(r,o,a,l);break;case 1:e=new Sf(r,o);break;case 2:let c=Math.PI/3;i.InnerAngle!==void 0&&(c=ct.degToRad(i.InnerAngle.value));let h=0;i.OuterAngle!==void 0&&(h=ct.degToRad(i.OuterAngle.value),h=Math.max(h,1)),e=new vf(r,o,a,c,h,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),e=new ll(r,o);break}i.CastShadows!==void 0&&i.CastShadows.value===1&&(e.castShadow=!0)}return e}createMesh(t,e,i){let s,r=null,o=null;const a=[];return t.children.forEach(function(l){e.has(l.ID)&&(r=e.get(l.ID)),i.has(l.ID)&&a.push(i.get(l.ID))}),a.length>1?o=a:a.length>0?o=a[0]:(o=new Dr({color:13421772}),a.push(o)),"color"in r.attributes&&a.forEach(function(l){l.vertexColors=!0}),r.FBX_Deformer?(s=new Tf(r,o),s.normalizeSkinWeights()):s=new nt(r,o),s}createCurve(t,e){const i=t.children.reduce(function(r,o){return e.has(o.ID)&&(r=e.get(o.ID)),r},null),s=new Ds({color:3342591,linewidth:1});return new Et(i,s)}getTransformData(t,e){const i={};"InheritType"in e&&(i.inheritType=parseInt(e.InheritType.value)),"RotationOrder"in e?i.eulerOrder=lu(e.RotationOrder.value):i.eulerOrder="ZYX","Lcl_Translation"in e&&(i.translation=e.Lcl_Translation.value),"PreRotation"in e&&(i.preRotation=e.PreRotation.value),"Lcl_Rotation"in e&&(i.rotation=e.Lcl_Rotation.value),"PostRotation"in e&&(i.postRotation=e.PostRotation.value),"Lcl_Scaling"in e&&(i.scale=e.Lcl_Scaling.value),"ScalingOffset"in e&&(i.scalingOffset=e.ScalingOffset.value),"ScalingPivot"in e&&(i.scalingPivot=e.ScalingPivot.value),"RotationOffset"in e&&(i.rotationOffset=e.RotationOffset.value),"RotationPivot"in e&&(i.rotationPivot=e.RotationPivot.value),t.userData.transformData=i}setLookAtProperties(t,e){"LookAtProperty"in e&&Mt.get(t.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const r=pt.Objects.Model[s.ID];if("Lcl_Translation"in r){const o=r.Lcl_Translation.value;t.target!==void 0?(t.target.position.fromArray(o),ee.add(t.target)):t.lookAt(new k().fromArray(o))}}})}bindSkeleton(t,e,i){const s=this.parsePoseNodes();for(const r in t){const o=t[r];Mt.get(parseInt(o.ID)).parents.forEach(function(l){if(e.has(l.ID)){const c=l.ID;Mt.get(c).parents.forEach(function(A){i.has(A.ID)&&i.get(A.ID).bind(new _f(o.bones),s[A.ID])})}})}}parsePoseNodes(){const t={};if("Pose"in pt.Objects){const e=pt.Objects.Pose;for(const i in e)if(e[i].attrType==="BindPose"&&e[i].NbPoseNodes>0){const s=e[i].PoseNode;Array.isArray(s)?s.forEach(function(r){t[r.Node]=new dt().fromArray(r.Matrix.a)}):t[s.Node]=new dt().fromArray(s.Matrix.a)}}return t}createAmbientLight(){if("GlobalSettings"in pt&&"AmbientColor"in pt.GlobalSettings){const t=pt.GlobalSettings.AmbientColor.value,e=t[0],i=t[1],s=t[2];if(e!==0||i!==0||s!==0){const r=new kt(e,i,s);ee.add(new xf(r,1))}}}}class My{parse(t){const e=new Map;if("Geometry"in pt.Objects){const i=pt.Objects.Geometry;for(const s in i){const r=Mt.get(parseInt(s)),o=this.parseGeometry(r,i[s],t);e.set(parseInt(s),o)}}return e}parseGeometry(t,e,i){switch(e.attrType){case"Mesh":return this.parseMeshGeometry(t,e,i);case"NurbsCurve":return this.parseNurbsGeometry(e)}}parseMeshGeometry(t,e,i){const s=i.skeletons,r=[],o=t.parents.map(function(A){return pt.Objects.Model[A.ID]});if(o.length===0)return;const a=t.children.reduce(function(A,u){return s[u.ID]!==void 0&&(A=s[u.ID]),A},null);t.children.forEach(function(A){i.morphTargets[A.ID]!==void 0&&r.push(i.morphTargets[A.ID])});const l=o[0],c={};"RotationOrder"in l&&(c.eulerOrder=lu(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=au(c);return this.genGeometry(e,a,r,h)}genGeometry(t,e,i,s){const r=new ve;t.attrName&&(r.name=t.attrName);const o=this.parseGeoNode(t,e),a=this.genBuffers(o),l=new $e(a.vertex,3);if(l.applyMatrix4(s),r.setAttribute("position",l),a.colors.length>0&&r.setAttribute("color",new $e(a.colors,3)),e&&(r.setAttribute("skinIndex",new Df(a.weightsIndices,4)),r.setAttribute("skinWeight",new $e(a.vertexWeights,4)),r.FBX_Deformer=e),a.normal.length>0){const c=new xs().getNormalMatrix(s),h=new $e(a.normal,3);h.applyNormalMatrix(c),r.setAttribute("normal",h)}if(a.uvs.forEach(function(c,h){Mf==="uv2"&&h++;const A=h===0?"uv":`uv${h}`;r.setAttribute(A,new $e(a.uvs[h],2))}),o.material&&o.material.mappingType!=="AllSame"){let c=a.materialIndex[0],h=0;if(a.materialIndex.forEach(function(A,u){A!==c&&(r.addGroup(h,u-h,c),c=A,h=u)}),r.groups.length>0){const A=r.groups[r.groups.length-1],u=A.start+A.count;u!==a.materialIndex.length&&r.addGroup(u,a.materialIndex.length-u,c)}r.groups.length===0&&r.addGroup(0,a.materialIndex.length,a.materialIndex[0])}return this.addMorphTargets(r,t,i,s),r}parseGeoNode(t,e){const i={};if(i.vertexPositions=t.Vertices!==void 0?t.Vertices.a:[],i.vertexIndices=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],t.LayerElementColor&&(i.color=this.parseVertexColors(t.LayerElementColor[0])),t.LayerElementMaterial&&(i.material=this.parseMaterialIndices(t.LayerElementMaterial[0])),t.LayerElementNormal&&(i.normal=this.parseNormals(t.LayerElementNormal[0])),t.LayerElementUV){i.uv=[];let s=0;for(;t.LayerElementUV[s];)t.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(t.LayerElementUV[s])),s++}return i.weightTable={},e!==null&&(i.skeleton=e,e.rawBones.forEach(function(s,r){s.indices.forEach(function(o,a){i.weightTable[o]===void 0&&(i.weightTable[o]=[]),i.weightTable[o].push({id:r,weight:s.weights[a]})})})),i}genBuffers(t){const e={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,r=!1,o=[],a=[],l=[],c=[],h=[],A=[];const u=this;return t.vertexIndices.forEach(function(d,f){let g,p=!1;d<0&&(d=d^-1,p=!0);let m=[],C=[];if(o.push(d*3,d*3+1,d*3+2),t.color){const E=an(f,i,d,t.color);l.push(E[0],E[1],E[2])}if(t.skeleton){if(t.weightTable[d]!==void 0&&t.weightTable[d].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],v=[0,0,0,0];C.forEach(function(y,S){let T=y,x=m[S];v.forEach(function(F,_,w){if(T>F){w[_]=T,T=F;const U=E[_];E[_]=x,x=U}})}),m=E,C=v}for(;C.length<4;)C.push(0),m.push(0);for(let E=0;E<4;++E)h.push(C[E]),A.push(m[E])}if(t.normal){const E=an(f,i,d,t.normal);a.push(E[0],E[1],E[2])}t.material&&t.material.mappingType!=="AllSame"&&(g=an(f,i,d,t.material)[0]),t.uv&&t.uv.forEach(function(E,v){const y=an(f,i,d,E);c[v]===void 0&&(c[v]=[]),c[v].push(y[0]),c[v].push(y[1])}),s++,p&&(u.genFace(e,t,o,g,a,l,c,h,A,s),i++,s=0,o=[],a=[],l=[],c=[],h=[],A=[])}),e}genFace(t,e,i,s,r,o,a,l,c,h){for(let A=2;A<h;A++)t.vertex.push(e.vertexPositions[i[0]]),t.vertex.push(e.vertexPositions[i[1]]),t.vertex.push(e.vertexPositions[i[2]]),t.vertex.push(e.vertexPositions[i[(A-1)*3]]),t.vertex.push(e.vertexPositions[i[(A-1)*3+1]]),t.vertex.push(e.vertexPositions[i[(A-1)*3+2]]),t.vertex.push(e.vertexPositions[i[A*3]]),t.vertex.push(e.vertexPositions[i[A*3+1]]),t.vertex.push(e.vertexPositions[i[A*3+2]]),e.skeleton&&(t.vertexWeights.push(l[0]),t.vertexWeights.push(l[1]),t.vertexWeights.push(l[2]),t.vertexWeights.push(l[3]),t.vertexWeights.push(l[(A-1)*4]),t.vertexWeights.push(l[(A-1)*4+1]),t.vertexWeights.push(l[(A-1)*4+2]),t.vertexWeights.push(l[(A-1)*4+3]),t.vertexWeights.push(l[A*4]),t.vertexWeights.push(l[A*4+1]),t.vertexWeights.push(l[A*4+2]),t.vertexWeights.push(l[A*4+3]),t.weightsIndices.push(c[0]),t.weightsIndices.push(c[1]),t.weightsIndices.push(c[2]),t.weightsIndices.push(c[3]),t.weightsIndices.push(c[(A-1)*4]),t.weightsIndices.push(c[(A-1)*4+1]),t.weightsIndices.push(c[(A-1)*4+2]),t.weightsIndices.push(c[(A-1)*4+3]),t.weightsIndices.push(c[A*4]),t.weightsIndices.push(c[A*4+1]),t.weightsIndices.push(c[A*4+2]),t.weightsIndices.push(c[A*4+3])),e.color&&(t.colors.push(o[0]),t.colors.push(o[1]),t.colors.push(o[2]),t.colors.push(o[(A-1)*3]),t.colors.push(o[(A-1)*3+1]),t.colors.push(o[(A-1)*3+2]),t.colors.push(o[A*3]),t.colors.push(o[A*3+1]),t.colors.push(o[A*3+2])),e.material&&e.material.mappingType!=="AllSame"&&(t.materialIndex.push(s),t.materialIndex.push(s),t.materialIndex.push(s)),e.normal&&(t.normal.push(r[0]),t.normal.push(r[1]),t.normal.push(r[2]),t.normal.push(r[(A-1)*3]),t.normal.push(r[(A-1)*3+1]),t.normal.push(r[(A-1)*3+2]),t.normal.push(r[A*3]),t.normal.push(r[A*3+1]),t.normal.push(r[A*3+2])),e.uv&&e.uv.forEach(function(u,d){t.uvs[d]===void 0&&(t.uvs[d]=[]),t.uvs[d].push(a[d][0]),t.uvs[d].push(a[d][1]),t.uvs[d].push(a[d][(A-1)*2]),t.uvs[d].push(a[d][(A-1)*2+1]),t.uvs[d].push(a[d][A*2]),t.uvs[d].push(a[d][A*2+1])})}addMorphTargets(t,e,i,s){if(i.length===0)return;t.morphTargetsRelative=!0,t.morphAttributes.position=[];const r=this;i.forEach(function(o){o.rawTargets.forEach(function(a){const l=pt.Objects.Geometry[a.geoID];l!==void 0&&r.genMorphGeometry(t,e,l,s,a.name)})})}genMorphGeometry(t,e,i,s,r){const o=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],a=i.Vertices!==void 0?i.Vertices.a:[],l=i.Indexes!==void 0?i.Indexes.a:[],c=t.attributes.position.count*3,h=new Float32Array(c);for(let f=0;f<l.length;f++){const g=l[f]*3;h[g]=a[f*3],h[g+1]=a[f*3+1],h[g+2]=a[f*3+2]}const A={vertexIndices:o,vertexPositions:h},u=this.genBuffers(A),d=new $e(u.vertex,3);d.name=r||i.attrName,d.applyMatrix4(s),t.morphAttributes.position.push(d)}parseNormals(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.Normals.a;let r=[];return i==="IndexToDirect"&&("NormalIndex"in t?r=t.NormalIndex.a:"NormalsIndex"in t&&(r=t.NormalsIndex.a)),{dataSize:3,buffer:s,indices:r,mappingType:e,referenceType:i}}parseUVs(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.UV.a;let r=[];return i==="IndexToDirect"&&(r=t.UVIndex.a),{dataSize:2,buffer:s,indices:r,mappingType:e,referenceType:i}}parseVertexColors(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.Colors.a;let r=[];return i==="IndexToDirect"&&(r=t.ColorIndex.a),{dataSize:4,buffer:s,indices:r,mappingType:e,referenceType:i}}parseMaterialIndices(t){const e=t.MappingInformationType,i=t.ReferenceInformationType;if(e==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:i};const s=t.Materials.a,r=[];for(let o=0;o<s.length;++o)r.push(o);return{dataSize:1,buffer:s,indices:r,mappingType:e,referenceType:i}}parseNurbsGeometry(t){if(_c===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 ve;const e=parseInt(t.Order);if(isNaN(e))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",t.Order,t.id),new ve;const i=e-1,s=t.KnotVector.a,r=[],o=t.Points.a;for(let A=0,u=o.length;A<u;A+=4)r.push(new Te().fromArray(o,A));let a,l;if(t.Form==="Closed")r.push(r[0]);else if(t.Form==="Periodic"){a=i,l=s.length-1-a;for(let A=0;A<i;++A)r.push(r[A])}const h=new _c(i,s,r,a,l).getPoints(r.length*12);return new ve().setFromPoints(h)}}class Py{parse(){const t=[],e=this.parseClips();if(e!==void 0)for(const i in e){const s=e[i],r=this.addClip(s);t.push(r)}return t}parseClips(){if(pt.Objects.AnimationCurve===void 0)return;const t=this.parseAnimationCurveNodes();this.parseAnimationCurves(t);const e=this.parseAnimationLayers(t);return this.parseAnimStacks(e)}parseAnimationCurveNodes(){const t=pt.Objects.AnimationCurveNode,e=new Map;for(const i in t){const s=t[i];if(s.attrName.match(/S|R|T|DeformPercent/)!==null){const r={id:s.id,attr:s.attrName,curves:{}};e.set(r.id,r)}}return e}parseAnimationCurves(t){const e=pt.Objects.AnimationCurve;for(const i in e){const s={id:e[i].id,times:e[i].KeyTime.a.map(Uy),values:e[i].KeyValueFloat.a},r=Mt.get(s.id);if(r!==void 0){const o=r.parents[0].ID,a=r.parents[0].relationship;a.match(/X/)?t.get(o).curves.x=s:a.match(/Y/)?t.get(o).curves.y=s:a.match(/Z/)?t.get(o).curves.z=s:a.match(/d|DeformPercent/)&&t.has(o)&&(t.get(o).curves.morph=s)}}}parseAnimationLayers(t){const e=pt.Objects.AnimationLayer,i=new Map;for(const s in e){const r=[],o=Mt.get(parseInt(s));o!==void 0&&(o.children.forEach(function(l,c){if(t.has(l.ID)){const h=t.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 A=Mt.get(l.ID).parents.filter(function(u){return u.relationship!==void 0})[0].ID;if(A!==void 0){const u=pt.Objects.Model[A.toString()];if(u===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const d={modelName:u.attrName?On.sanitizeNodeName(u.attrName):"",ID:u.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ee.traverse(function(f){f.ID===u.id&&(d.transform=f.matrix,f.userData.transformData&&(d.eulerOrder=f.userData.transformData.eulerOrder))}),d.transform||(d.transform=new dt),"PreRotation"in u&&(d.preRotation=u.PreRotation.value),"PostRotation"in u&&(d.postRotation=u.PostRotation.value),r[c]=d}}r[c]&&(r[c][h.attr]=h)}else if(h.curves.morph!==void 0){if(r[c]===void 0){const A=Mt.get(l.ID).parents.filter(function(m){return m.relationship!==void 0})[0].ID,u=Mt.get(A).parents[0].ID,d=Mt.get(u).parents[0].ID,f=Mt.get(d).parents[0].ID,g=pt.Objects.Model[f],p={modelName:g.attrName?On.sanitizeNodeName(g.attrName):"",morphName:pt.Objects.Deformer[A].attrName};r[c]=p}r[c][h.attr]=h}}}),i.set(parseInt(s),r))}return i}parseAnimStacks(t){const e=pt.Objects.AnimationStack,i={};for(const s in e){const r=Mt.get(parseInt(s)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const o=t.get(r[0].ID);i[s]={name:e[s].attrName,layer:o}}return i}addClip(t){let e=[];const i=this;return t.layer.forEach(function(s){e=e.concat(i.generateTracks(s))}),new Rf(t.name,-1,e)}generateTracks(t){const e=[];let i=new k,s=new It,r=new k;if(t.transform&&t.transform.decompose(i,s,r),i=i.toArray(),s=new qe().setFromQuaternion(s,t.eulerOrder).toArray(),r=r.toArray(),t.T!==void 0&&Object.keys(t.T.curves).length>0){const o=this.generateVectorTrack(t.modelName,t.T.curves,i,"position");o!==void 0&&e.push(o)}if(t.R!==void 0&&Object.keys(t.R.curves).length>0){const o=this.generateRotationTrack(t.modelName,t.R.curves,s,t.preRotation,t.postRotation,t.eulerOrder);o!==void 0&&e.push(o)}if(t.S!==void 0&&Object.keys(t.S.curves).length>0){const o=this.generateVectorTrack(t.modelName,t.S.curves,r,"scale");o!==void 0&&e.push(o)}if(t.DeformPercent!==void 0){const o=this.generateMorphTrack(t);o!==void 0&&e.push(o)}return e}generateVectorTrack(t,e,i,s){const r=this.getTimesForAllAxes(e),o=this.getKeyframeTrackValues(r,e,i);return new wf(t+"."+s,r,o)}generateRotationTrack(t,e,i,s,r,o){e.x!==void 0&&(this.interpolateRotations(e.x),e.x.values=e.x.values.map(ct.degToRad)),e.y!==void 0&&(this.interpolateRotations(e.y),e.y.values=e.y.values.map(ct.degToRad)),e.z!==void 0&&(this.interpolateRotations(e.z),e.z.values=e.z.values.map(ct.degToRad));const a=this.getTimesForAllAxes(e),l=this.getKeyframeTrackValues(a,e,i);s!==void 0&&(s=s.map(ct.degToRad),s.push(o),s=new qe().fromArray(s),s=new It().setFromEuler(s)),r!==void 0&&(r=r.map(ct.degToRad),r.push(o),r=new qe().fromArray(r),r=new It().setFromEuler(r).invert());const c=new It,h=new qe,A=[];for(let u=0;u<l.length;u+=3)h.set(l[u],l[u+1],l[u+2],o),c.setFromEuler(h),s!==void 0&&c.premultiply(s),r!==void 0&&c.multiply(r),c.toArray(A,u/3*4);return new Lf(t+".quaternion",a,A)}generateMorphTrack(t){const e=t.DeformPercent.curves.morph,i=e.values.map(function(r){return r/100}),s=ee.getObjectByName(t.modelName).morphTargetDictionary[t.morphName];return new bf(t.modelName+".morphTargetInfluences["+s+"]",e.times,i)}getTimesForAllAxes(t){let e=[];if(t.x!==void 0&&(e=e.concat(t.x.times)),t.y!==void 0&&(e=e.concat(t.y.times)),t.z!==void 0&&(e=e.concat(t.z.times)),e=e.sort(function(i,s){return i-s}),e.length>1){let i=1,s=e[0];for(let r=1;r<e.length;r++){const o=e[r];o!==s&&(e[i]=o,s=o,i++)}e=e.slice(0,i)}return e}getKeyframeTrackValues(t,e,i){const s=i,r=[];let o=-1,a=-1,l=-1;return t.forEach(function(c){if(e.x&&(o=e.x.times.indexOf(c)),e.y&&(a=e.y.times.indexOf(c)),e.z&&(l=e.z.times.indexOf(c)),o!==-1){const h=e.x.values[o];r.push(h),s[0]=h}else r.push(s[0]);if(a!==-1){const h=e.y.values[a];r.push(h),s[1]=h}else r.push(s[1]);if(l!==-1){const h=e.z.values[l];r.push(h),s[2]=h}else r.push(s[2])}),r}interpolateRotations(t){for(let e=1;e<t.values.length;e++){const i=t.values[e-1],s=t.values[e]-i,r=Math.abs(s);if(r>=180){const o=r/180,a=s/o;let l=i+a;const c=t.times[e-1],A=(t.times[e]-c)/o;let u=c+A;const d=[],f=[];for(;u<t.times[e];)d.push(u),u+=A,f.push(l),l+=a;t.times=Rc(t.times,e,d),t.values=Rc(t.values,e,f)}}}}class ky{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(t){this.nodeStack.push(t),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(t,e){this.currentProp=t,this.currentPropName=e}parse(t){this.currentIndent=0,this.allNodes=new ou,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const e=this,i=t.split(/[\r\n]+/);return i.forEach(function(s,r){const o=s.match(/^[\s\t]*;/),a=s.match(/^[\s\t]*$/);if(o||a)return;const l=s.match("^\\t{"+e.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+e.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=s.match("^\\t{"+(e.currentIndent-1)+"}}");l?e.parseNodeBegin(s,l):c?e.parseNodeProperty(s,c,i[++r]):h?e.popStack():s.match(/^[^\s\t}]/)&&e.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(t,e){const i=e[1].trim().replace(/^"/,"").replace(/"$/,""),s=e[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:i},o=this.parseNodeAttr(s),a=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,r):i in a?(i==="PoseNode"?a.PoseNode.push(r):a[i].id!==void 0&&(a[i]={},a[i][a[i].id]=a[i]),o.id!==""&&(a[i][o.id]=r)):typeof o.id=="number"?(a[i]={},a[i][o.id]=r):i!=="Properties70"&&(i==="PoseNode"?a[i]=[r]:a[i]=r),typeof o.id=="number"&&(r.id=o.id),o.name!==""&&(r.attrName=o.name),o.type!==""&&(r.attrType=o.type),this.pushStack(r)}parseNodeAttr(t){let e=t[0];t[0]!==""&&(e=parseInt(t[0]),isNaN(e)&&(e=t[0]));let i="",s="";return t.length>1&&(i=t[1].replace(/^(\w+)::/,""),s=t[2]),{id:e,name:i,type:s}}parseNodeProperty(t,e,i){let s=e[1].replace(/^"/,"").replace(/"$/,"").trim(),r=e[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&r===","&&(r=i.replace(/"/g,"").replace(/,$/,"").trim());const o=this.getCurrentNode();if(o.name==="Properties70"){this.parseNodeSpecialProperty(t,s,r);return}if(s==="C"){const l=r.split(",").slice(1),c=parseInt(l[0]),h=parseInt(l[1]);let A=r.split(",").slice(3);A=A.map(function(u){return u.trim().replace(/^"/,"")}),s="connections",r=[c,h],Hy(r,A),o[s]===void 0&&(o[s]=[])}s==="Node"&&(o.id=r),s in o&&Array.isArray(o[s])?o[s].push(r):s!=="a"?o[s]=r:o.a=r,this.setCurrentProp(o,s),s==="a"&&r.slice(-1)!==","&&(o.a=Or(r))}parseNodePropertyContinued(t){const e=this.getCurrentNode();e.a+=t,t.slice(-1)!==","&&(e.a=Or(e.a))}parseNodeSpecialProperty(t,e,i){const s=i.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=s[0],o=s[1],a=s[2],l=s[3];let c=s[4];switch(o){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=Or(c);break}this.getPrevNode()[r]={type:o,type2:a,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),r)}}class Qy{parse(t){const e=new xc(t);e.skip(23);const i=e.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new ou;for(;!this.endOfContent(e);){const r=this.parseNode(e,i);r!==null&&s.add(r.name,r)}return s}endOfContent(t){return t.size()%16===0?(t.getOffset()+160+16&-16)>=t.size():t.getOffset()+160+16>=t.size()}parseNode(t,e){const i={},s=e>=7500?t.getUint64():t.getUint32(),r=e>=7500?t.getUint64():t.getUint32();e>=7500?t.getUint64():t.getUint32();const o=t.getUint8(),a=t.getString(o);if(s===0)return null;const l=[];for(let u=0;u<r;u++)l.push(this.parseProperty(t));const c=l.length>0?l[0]:"",h=l.length>1?l[1]:"",A=l.length>2?l[2]:"";for(i.singleProperty=r===1&&t.getOffset()===s;s>t.getOffset();){const u=this.parseNode(t,e);u!==null&&this.parseSubNode(a,i,u)}return i.propertyList=l,typeof c=="number"&&(i.id=c),h!==""&&(i.attrName=h),A!==""&&(i.attrType=A),a!==""&&(i.name=a),i}parseSubNode(t,e,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(e[i.name]=i,i.a=s):e[i.name]=s}else if(t==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(r,o){o!==0&&s.push(r)}),e.connections===void 0&&(e.connections=[]),e.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(r){e[r]=i[r]});else if(t==="Properties70"&&i.name==="P"){let s=i.propertyList[0],r=i.propertyList[1];const o=i.propertyList[2],a=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.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=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],e[s]={type:r,type2:o,flag:a,value:l}}else e[i.name]===void 0?typeof i.id=="number"?(e[i.name]={},e[i.name][i.id]=i):e[i.name]=i:i.name==="PoseNode"?(Array.isArray(e[i.name])||(e[i.name]=[e[i.name]]),e[i.name].push(i)):e[i.name][i.id]===void 0&&(e[i.name][i.id]=i)}parseProperty(t){const e=t.getString(1);let i;switch(e){case"C":return t.getBoolean();case"D":return t.getFloat64();case"F":return t.getFloat32();case"I":return t.getInt32();case"L":return t.getInt64();case"R":return i=t.getUint32(),t.getArrayBuffer(i);case"S":return i=t.getUint32(),t.getString(i);case"Y":return t.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=t.getUint32(),r=t.getUint32(),o=t.getUint32();if(r===0)switch(e){case"b":case"c":return t.getBooleanArray(s);case"d":return t.getFloat64Array(s);case"f":return t.getFloat32Array(s);case"i":return t.getInt32Array(s);case"l":return t.getInt64Array(s)}const a=Ff(new Uint8Array(t.getArrayBuffer(o))),l=new xc(a.buffer);switch(e){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}default:throw new Error("THREE.FBXLoader: Unknown property type "+e)}}}class xc{constructor(t,e){this.dv=new DataView(t),this.offset=0,this.littleEndian=e!==void 0?e:!0}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(t){this.offset+=t}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(t){const e=[];for(let i=0;i<t;i++)e.push(this.getBoolean());return e}getUint8(){const t=this.dv.getUint8(this.offset);return this.offset+=1,t}getInt16(){const t=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}getInt32(){const t=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}getInt32Array(t){const e=[];for(let i=0;i<t;i++)e.push(this.getInt32());return e}getUint32(){const t=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}getInt64(){let t,e;return this.littleEndian?(t=this.getUint32(),e=this.getUint32()):(e=this.getUint32(),t=this.getUint32()),e&2147483648?(e=~e&4294967295,t=~t&4294967295,t===4294967295&&(e=e+1&4294967295),t=t+1&4294967295,-(e*4294967296+t)):e*4294967296+t}getInt64Array(t){const e=[];for(let i=0;i<t;i++)e.push(this.getInt64());return e}getUint64(){let t,e;return this.littleEndian?(t=this.getUint32(),e=this.getUint32()):(e=this.getUint32(),t=this.getUint32()),e*4294967296+t}getFloat32(){const t=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}getFloat32Array(t){const e=[];for(let i=0;i<t;i++)e.push(this.getFloat32());return e}getFloat64(){const t=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}getFloat64Array(t){const e=[];for(let i=0;i<t;i++)e.push(this.getFloat64());return e}getArrayBuffer(t){const e=this.dv.buffer.slice(this.offset,this.offset+t);return this.offset+=t,e}getString(t){let e=[];for(let s=0;s<t;s++)e[s]=this.getUint8();const i=e.indexOf(0);return i>=0&&(e=e.slice(0,i)),nA(new Uint8Array(e))}}class ou{add(t,e){this[t]=e}}function Oy(n){const t="Kaydara FBX Binary \0";return n.byteLength>=t.length&&t===cu(n,0,t.length)}function Gy(n){const t=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let e=0;function i(s){const r=n[s-1];return n=n.slice(e+s),e++,r}for(let s=0;s<t.length;++s)if(i(1)===t[s])return!1;return!0}function Dc(n){const t=/FBXVersion: (\d+)/,e=n.match(t);if(e)return parseInt(e[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function Uy(n){return n/46186158e3}const Ny=[];function an(n,t,e,i){let s;switch(i.mappingType){case"ByPolygonVertex":s=n;break;case"ByPolygon":s=t;break;case"ByVertice":s=e;break;case"AllSame":s=i.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+i.mappingType)}i.referenceType==="IndexToDirect"&&(s=i.indices[s]);const r=s*i.dataSize,o=r+i.dataSize;return Ky(Ny,i.buffer,r,o)}const Qr=new qe,Ri=new k;function au(n){const t=new dt,e=new dt,i=new dt,s=new dt,r=new dt,o=new dt,a=new dt,l=new dt,c=new dt,h=new dt,A=new dt,u=new dt,d=n.inheritType?n.inheritType:0;if(n.translation&&t.setPosition(Ri.fromArray(n.translation)),n.preRotation){const _=n.preRotation.map(ct.degToRad);_.push(n.eulerOrder),e.makeRotationFromEuler(Qr.fromArray(_))}if(n.rotation){const _=n.rotation.map(ct.degToRad);_.push(n.eulerOrder),i.makeRotationFromEuler(Qr.fromArray(_))}if(n.postRotation){const _=n.postRotation.map(ct.degToRad);_.push(n.eulerOrder),s.makeRotationFromEuler(Qr.fromArray(_)),s.invert()}n.scale&&r.scale(Ri.fromArray(n.scale)),n.scalingOffset&&a.setPosition(Ri.fromArray(n.scalingOffset)),n.scalingPivot&&o.setPosition(Ri.fromArray(n.scalingPivot)),n.rotationOffset&&l.setPosition(Ri.fromArray(n.rotationOffset)),n.rotationPivot&&c.setPosition(Ri.fromArray(n.rotationPivot)),n.parentMatrixWorld&&(A.copy(n.parentMatrix),h.copy(n.parentMatrixWorld));const f=e.clone().multiply(i).multiply(s),g=new dt;g.extractRotation(h);const p=new dt;p.copyPosition(h);const m=p.clone().invert().multiply(h),C=g.clone().invert().multiply(m),E=r,v=new dt;if(d===0)v.copy(g).multiply(f).multiply(C).multiply(E);else if(d===1)v.copy(g).multiply(C).multiply(f).multiply(E);else{const w=new dt().scale(new k().setFromMatrixScale(A)).clone().invert(),U=C.clone().multiply(w);v.copy(g).multiply(f).multiply(U).multiply(E)}const y=c.clone().invert(),S=o.clone().invert();let T=t.clone().multiply(l).multiply(c).multiply(e).multiply(i).multiply(s).multiply(y).multiply(a).multiply(o).multiply(r).multiply(S);const x=new dt().copyPosition(T),F=h.clone().multiply(x);return u.copyPosition(F),T=u.clone().multiply(v),T.premultiply(h.invert()),T}function lu(n){n=n||0;const t=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return n===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),t[0]):t[n]}function Or(n){return n.split(",").map(function(e){return parseFloat(e)})}function cu(n,t,e){return t===void 0&&(t=0),e===void 0&&(e=n.byteLength),nA(new Uint8Array(n,t,e))}function Hy(n,t){for(let e=0,i=n.length,s=t.length;e<s;e++,i++)n[i]=t[e]}function Ky(n,t,e,i){for(let s=e,r=0;s<i;s++,r++)n[r]=t[s];return n}function Rc(n,t,e){return n.slice(0,t).concat(e).concat(n.slice(t))}class Yy extends Qn{constructor(t=null,e=1,i=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:s},this.magFilter=cl,this.minFilter=cl,this.wrapR=kn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Vy{constructor(t=4){this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(t){if(!this.workers[t]){const e=this.workerCreator();e.addEventListener("message",this._onMessage.bind(this,t)),this.workers[t]=e}}_getIdleWorker(){for(let t=0;t<this.pool;t++)if(!(this.workerStatus&1<<t))return t;return-1}_onMessage(t,e){const i=this.workersResolve[t];if(i&&i(e),this.queue.length){const{resolve:s,msg:r,transfer:o}=this.queue.shift();this.workersResolve[t]=s,this.workers[t].postMessage(r,o)}else this.workerStatus^=1<<t}setWorkerCreator(t){this.workerCreator=t}setWorkerLimit(t){this.pool=t}postMessage(t,e){return new Promise(i=>{const s=this._getIdleWorker();s!==-1?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(t,e)):this.queue.push({resolve:i,msg:t,transfer:e})})}dispose(){this.workers.forEach(t=>t.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const hu=0,wc=2,Jy=0,zy=0,$y=2,qy=0,Xy=0,Wy=1,Yo=2,jy=0,Au=1,Zy=10,tB=64,uu=0,du=9,fu=15,gu=16,mu=22,pu=37,Eu=43,Cu=76,Iu=83,yu=97,Bu=100,vu=103,Su=109,Tu=165,_u=166;class eB{constructor(){this.vkFormat=uu,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=hu,this.levels=[],this.dataFormatDescriptor=[{vendorId:zy,descriptorType:Jy,descriptorBlockSize:0,versionNumber:$y,colorModel:qy,colorPrimaries:Au,transferFunction:Yo,flags:Xy,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class fs{constructor(t,e,i,s){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(t.buffer,t.byteOffset+e,i),this._littleEndian=s,this._offset=0}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian),e=this._dataView.getUint32(this._offset+4,this._littleEndian),i=t+2**32*e;return this._offset+=8,i}_nextInt32(){const t=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint8Array(t){const e=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,t);return this._offset+=t,e}_skip(t){return this._offset+=t,this}_scan(t,e){e===void 0&&(e=0);const i=this._offset;let s=0;for(;this._dataView.getUint8(this._offset)!==e&&s<t;)s++,this._offset++;return s<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+i,s)}}const Xt=[171,75,84,88,32,50,48,187,13,10,26,10];function Lc(n){return typeof TextDecoder<"u"?new TextDecoder().decode(n):Buffer.from(n).toString("utf8")}function iB(n){const t=new Uint8Array(n.buffer,n.byteOffset,Xt.length);if(t[0]!==Xt[0]||t[1]!==Xt[1]||t[2]!==Xt[2]||t[3]!==Xt[3]||t[4]!==Xt[4]||t[5]!==Xt[5]||t[6]!==Xt[6]||t[7]!==Xt[7]||t[8]!==Xt[8]||t[9]!==Xt[9]||t[10]!==Xt[10]||t[11]!==Xt[11])throw new Error("Missing KTX 2.0 identifier.");const e=new eB,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new fs(n,Xt.length,i,!0);e.vkFormat=s._nextUint32(),e.typeSize=s._nextUint32(),e.pixelWidth=s._nextUint32(),e.pixelHeight=s._nextUint32(),e.pixelDepth=s._nextUint32(),e.layerCount=s._nextUint32(),e.faceCount=s._nextUint32();const r=s._nextUint32();e.supercompressionScheme=s._nextUint32();const o=s._nextUint32(),a=s._nextUint32(),l=s._nextUint32(),c=s._nextUint32(),h=s._nextUint64(),A=s._nextUint64(),u=r*3*8,d=new fs(n,Xt.length+i,u,!0);for(let G=0;G<r;G++)e.levels.push({levelData:new Uint8Array(n.buffer,n.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const f=new fs(n,o,a,!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&tB?(H.sampleLower=f._nextInt32(),H.sampleUpper=f._nextInt32()):(H.sampleLower=f._nextUint32(),H.sampleUpper=f._nextUint32()),g.samples[G]=H}e.dataFormatDescriptor.length=0,e.dataFormatDescriptor.push(g);const E=new fs(n,l,c,!0);for(;E._offset<c;){const G=E._nextUint32(),H=E._scan(G),X=Lc(H);if(e.keyValue[X]=E._nextUint8Array(G-H.byteLength-1),X.match(/^ktx/i)){const D=Lc(e.keyValue[X]);e.keyValue[X]=D.substring(0,D.lastIndexOf("\0"))}const Y=G%4?4-G%4:0;E._skip(Y)}if(A<=0)return e;const v=new fs(n,h,A,!0),y=v._nextUint16(),S=v._nextUint16(),T=v._nextUint32(),x=v._nextUint32(),F=v._nextUint32(),_=v._nextUint32(),w=[];for(let G=0;G<r;G++)w.push({imageFlags:v._nextUint32(),rgbSliceByteOffset:v._nextUint32(),rgbSliceByteLength:v._nextUint32(),alphaSliceByteOffset:v._nextUint32(),alphaSliceByteLength:v._nextUint32()});const U=h+v._offset,O=U+T,W=O+x,K=W+F,q=new Uint8Array(n.buffer,n.byteOffset+U,T),Z=new Uint8Array(n.buffer,n.byteOffset+O,x),rt=new Uint8Array(n.buffer,n.byteOffset+W,F),V=new Uint8Array(n.buffer,n.byteOffset+K,_);return e.globalData={endpointCount:y,selectorCount:S,imageDescs:w,endpointsData:q,selectorsData:Z,tablesData:rt,extendedData:V},e}let gs,Ye,Vo;const Gr={env:{emscripten_notify_memory_growth:function(n){Vo=new Uint8Array(Ye.exports.memory.buffer)}}};class sB{init(){return gs||(typeof fetch<"u"?gs=fetch("data:application/wasm;base64,"+bc).then(t=>t.arrayBuffer()).then(t=>WebAssembly.instantiate(t,Gr)).then(this._init):gs=WebAssembly.instantiate(Buffer.from(bc,"base64"),Gr).then(this._init),gs)}_init(t){Ye=t.instance,Gr.env.emscripten_notify_memory_growth(0)}decode(t,e=0){if(!Ye)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=t.byteLength,s=Ye.exports.malloc(i);Vo.set(t,s),e=e||Number(Ye.exports.ZSTD_findDecompressedSize(s,i));const r=Ye.exports.malloc(e),o=Ye.exports.ZSTD_decompress(r,e,s,i),a=Vo.slice(r,r+o);return Ye.exports.free(s),Ye.exports.free(r),a}}const bc="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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+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 nB extends ar{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,Pf),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class rB extends ar{constructor(t,e,i,s,r,o){super(t,e,i,r,o),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=kn}}var oB=Object.defineProperty,aB=(n,t,e)=>t in n?oB(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,mr=(n,t,e)=>(aB(n,typeof t!="symbol"?t+"":t,e),e);const xu=3e3,Du=3001,Fc="",lB="display-p3",cB="display-p3-linear",hB="srgb-linear",Na="srgb",Ur=new WeakMap;let Nr=0,Hr;const Ts=class extends fa{constructor(n){super(n),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new Vy,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(n){return this.transcoderPath=n,this}setWorkerLimit(n){return this.workerPool.setWorkerLimit(n),this}detectSupport(n){return this.workerConfig={astcSupported:n.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:n.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:n.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:n.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:n.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:n.extensions.has("WEBGL_compressed_texture_pvrtc")||n.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},n.capabilities.isWebGL2&&(this.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){const n=new Ki(this.manager);n.setPath(this.transcoderPath),n.setWithCredentials(this.withCredentials);const t=n.loadAsync("basis_transcoder.js"),e=new Ki(this.manager);e.setPath(this.transcoderPath),e.setResponseType("arraybuffer"),e.setWithCredentials(this.withCredentials);const i=e.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,i]).then(([s,r])=>{const o=Ts.BasisWorker.toString(),a=["/* constants */","let _EngineFormat = "+JSON.stringify(Ts.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Ts.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Ts.BasisFormat),"/* basis_transcoder.js */",s,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
4
+ `);this.workerSourceURL=URL.createObjectURL(new Blob([a])),this.transcoderBinary=r,this.workerPool.setWorkerCreator(()=>{const l=new Worker(this.workerSourceURL),c=this.transcoderBinary.slice(0);return l.postMessage({type:"init",config:this.workerConfig,transcoderBinary:c},[c]),l})}),Nr>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),Nr++}return this.transcoderPending}load(n,t,e,i){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const s=new Ki(this.manager);s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials),s.load(n,r=>{if(Ur.has(r))return Ur.get(r).promise.then(t).catch(i);this._createTexture(r).then(o=>t?t(o):null).catch(i)},e,i)}_createTextureFrom(n,t){const{faces:e,width:i,height:s,format:r,type:o,error:a,dfdFlags:l}=n;if(o==="error")return Promise.reject(a);let c;if(t.faceCount===6)c=new nB(e,r,ye);else{const A=e[0].mipmaps;c=t.layerCount>1?new rB(A,i,s,t.layerCount,r,ye):new ar(A,i,s,r,ye)}c.minFilter=e[0].mipmaps.length===1?Gn:kf,c.magFilter=Gn,c.generateMipmaps=!1,c.needsUpdate=!0;const h=Ru(t);return"colorSpace"in c?c.colorSpace=h:c.encoding=h===Na?Du:xu,c.premultiplyAlpha=!!(l&Wy),c}async _createTexture(n,t={}){const e=iB(new Uint8Array(n));if(e.vkFormat!==uu)return uB(e);const i=t,s=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:n,taskConfig:i},[n])).then(r=>this._createTextureFrom(r.data,e));return Ur.set(n,{promise:s}),s}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),Nr--,this}};let vi=Ts;mr(vi,"BasisFormat",{ETC1S:0,UASTC_4x4:1});mr(vi,"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});mr(vi,"EngineFormat",{RGBAFormat:Ni,RGBA_ASTC_4x4_Format:Qf,RGBA_BPTC_Format:Of,RGBA_ETC2_EAC_Format:Gf,RGBA_PVRTC_4BPPV1_Format:Uf,RGBA_S3TC_DXT5_Format:Nf,RGB_ETC1_Format:Hf,RGB_ETC2_Format:Kf,RGB_PVRTC_4BPPV1_Format:Yf,RGB_S3TC_DXT1_Format:Vf});mr(vi,"BasisWorker",function(){let n,t,e;const i=_EngineFormat,s=_TranscoderFormat,r=_BasisFormat;self.addEventListener("message",function(f){const g=f.data;switch(g.type){case"init":n=g.config,o(g.transcoderBinary);break;case"transcode":t.then(()=>{try{const{faces:p,buffers:m,width:C,height:E,hasAlpha:v,format:y,dfdFlags:S}=a(g.buffer);self.postMessage({type:"transcode",id:g.id,faces:p,width:C,height:E,hasAlpha:v,format:y,dfdFlags:S},m)}catch(p){console.error(p),self.postMessage({type:"error",id:g.id,error:p.message})}});break}});function o(f){t=new Promise(g=>{e={wasmBinary:f,onRuntimeInitialized:g},BASIS(e)}).then(()=>{e.initializeBasis(),e.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function a(f){const g=new e.KTX2File(new Uint8Array(f));function p(){g.close(),g.delete()}if(!g.isValid())throw p(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");const m=g.isUASTC()?r.UASTC_4x4:r.ETC1S,C=g.getWidth(),E=g.getHeight(),v=g.getLayers()||1,y=g.getLevels(),S=g.getFaces(),T=g.getHasAlpha(),x=g.getDFDFlags(),{transcoderFormat:F,engineFormat:_}=A(m,C,E,T);if(!C||!E||!y)throw p(),new Error("THREE.KTX2Loader: Invalid texture");if(!g.startTranscoding())throw p(),new Error("THREE.KTX2Loader: .startTranscoding failed");const w=[],U=[];for(let O=0;O<S;O++){const W=[];for(let K=0;K<y;K++){const q=[];let Z,rt;for(let G=0;G<v;G++){const H=g.getImageLevelInfo(K,G,O);O===0&&K===0&&G===0&&(H.origWidth%4!==0||H.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),y>1?(Z=H.origWidth,rt=H.origHeight):(Z=H.width,rt=H.height);const X=new Uint8Array(g.getImageTranscodedSizeInBytes(K,G,0,F));if(!g.transcodeImage(X,K,G,O,F,0,-1,-1))throw p(),new Error("THREE.KTX2Loader: .transcodeImage failed.");q.push(X)}const V=d(q);W.push({data:V,width:Z,height:rt}),U.push(V.buffer)}w.push({mipmaps:W,width:C,height:E,format:_})}return p(),{faces:w,buffers:U,width:C,height:E,hasAlpha:T,format:_,dfdFlags:x}}const l=[{if:"astcSupported",basisFormat:[r.UASTC_4x4],transcoderFormat:[s.ASTC_4x4,s.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[r.ETC1S,r.UASTC_4x4],transcoderFormat:[s.BC7_M5,s.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[r.ETC1S,r.UASTC_4x4],transcoderFormat:[s.BC1,s.BC3],engineFormat:[i.RGB_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[r.ETC1S,r.UASTC_4x4],transcoderFormat:[s.ETC1,s.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[r.ETC1S,r.UASTC_4x4],transcoderFormat:[s.ETC1],engineFormat:[i.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[r.ETC1S,r.UASTC_4x4],transcoderFormat:[s.PVRTC1_4_RGB,s.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],c=l.sort(function(f,g){return f.priorityETC1S-g.priorityETC1S}),h=l.sort(function(f,g){return f.priorityUASTC-g.priorityUASTC});function A(f,g,p,m){let C,E;const v=f===r.ETC1S?c:h;for(let y=0;y<v.length;y++){const S=v[y];if(n[S.if]&&S.basisFormat.includes(f)&&!(m&&S.transcoderFormat.length<2)&&!(S.needsPowerOfTwo&&!(u(g)&&u(p))))return C=S.transcoderFormat[m?1:0],E=S.engineFormat[m?1:0],{transcoderFormat:C,engineFormat:E}}return console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."),C=s.RGBA32,E=i.RGBAFormat,{transcoderFormat:C,engineFormat:E}}function u(f){return f<=2?!0:(f&f-1)===0&&f!==0}function d(f){if(f.length===1)return f[0];let g=0;for(let C=0;C<f.length;C++){const E=f[C];g+=E.byteLength}const p=new Uint8Array(g);let m=0;for(let C=0;C<f.length;C++){const E=f[C];p.set(E,m),m+=E.byteLength}return p}});const AB=new Set([Ni,Bs,vs]),Kr={[Su]:Ni,[yu]:Ni,[pu]:Ni,[Eu]:Ni,[vu]:Bs,[Iu]:Bs,[gu]:Bs,[mu]:Bs,[Bu]:vs,[Cu]:vs,[fu]:vs,[du]:vs,[_u]:hl,[Tu]:hl},Yr={[Su]:Tn,[yu]:Rs,[pu]:ye,[Eu]:ye,[vu]:Tn,[Iu]:Rs,[gu]:ye,[mu]:ye,[Bu]:Tn,[Cu]:Rs,[fu]:ye,[du]:ye,[_u]:ye,[Tu]:ye};async function uB(n){const{vkFormat:t}=n;if(Kr[t]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let e;n.supercompressionScheme===wc&&(Hr||(Hr=new Promise(async o=>{const a=new sB;await a.init(),o(a)})),e=await Hr);const i=[];for(let o=0;o<n.levels.length;o++){const a=Math.max(1,n.pixelWidth>>o),l=Math.max(1,n.pixelHeight>>o),c=n.pixelDepth?Math.max(1,n.pixelDepth>>o):0,h=n.levels[o];let A;if(n.supercompressionScheme===hu)A=h.levelData;else if(n.supercompressionScheme===wc)A=e.decode(h.levelData,h.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let u;Yr[t]===Tn?u=new Float32Array(A.buffer,A.byteOffset,A.byteLength/Float32Array.BYTES_PER_ELEMENT):Yr[t]===Rs?u=new Uint16Array(A.buffer,A.byteOffset,A.byteLength/Uint16Array.BYTES_PER_ELEMENT):u=A,i.push({data:u,width:a,height:l,depth:c})}let s;if(AB.has(Kr[t]))s=n.pixelDepth===0?new Jf(i[0].data,n.pixelWidth,n.pixelHeight):new Yy(i[0].data,n.pixelWidth,n.pixelHeight,n.pixelDepth);else{if(n.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");s=new ar(i,n.pixelWidth,n.pixelHeight)}s.mipmaps=i,s.type=Yr[t],s.format=Kr[t],s.needsUpdate=!0;const r=Ru(n);return"colorSpace"in s?s.colorSpace=r:s.encoding=r===Na?Du:xu,Promise.resolve(s)}function Ru(n){const t=n.dataFormatDescriptor[0];return t.colorPrimaries===Au?t.transferFunction===Yo?Na:hB:t.colorPrimaries===Zy?t.transferFunction===Yo?lB:cB:(t.colorPrimaries===jy||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),Fc)}const Vr=new WeakMap;class dB extends fa{constructor(t){super(t),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(t){return this.decoderPath=t,this}setDecoderConfig(t){return this.decoderConfig=t,this}setWorkerLimit(t){return this.workerLimit=t,this}load(t,e,i,s){const r=new Ki(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(t,o=>{const a={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(o,a).then(e).catch(s)},i,s)}decodeDracoFile(t,e,i,s){const r={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i};this.decodeGeometry(t,r).then(e)}decodeGeometry(t,e){for(const l in e.attributeTypes){const c=e.attributeTypes[l];c.BYTES_PER_ELEMENT!==void 0&&(e.attributeTypes[l]=c.name)}const i=JSON.stringify(e);if(Vr.has(t)){const l=Vr.get(t);if(l.key===i)return l.promise;if(t.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const r=this.workerNextTaskID++,o=t.byteLength,a=this._getWorker(r,o).then(l=>(s=l,new Promise((c,h)=>{s._callbacks[r]={resolve:c,reject:h},s.postMessage({type:"decode",id:r,taskConfig:e,buffer:t},[t])}))).then(l=>this._createGeometry(l.geometry));return a.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),Vr.set(t,{key:i,promise:a}),a}_createGeometry(t){const e=new ve;t.index&&e.setIndex(new Ro(t.index.array,1));for(let i=0;i<t.attributes.length;i++){const s=t.attributes[i],r=s.name,o=s.array,a=s.itemSize;e.setAttribute(r,new Ro(o,a))}return e}_loadLibrary(t,e){const i=new Ki(this.manager);return i.setPath(this.decoderPath),i.setResponseType(e),i.setWithCredentials(this.withCredentials),new Promise((s,r)=>{i.load(t,s,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const t=typeof WebAssembly!="object"||this.decoderConfig.type==="js",e=[];return t?e.push(this._loadLibrary("draco_decoder.js","text")):(e.push(this._loadLibrary("draco_wasm_wrapper.js","text")),e.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(e).then(i=>{const s=i[0];t||(this.decoderConfig.wasmBinary=i[1]);const r=fB.toString(),o=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
5
+ `);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(t,e){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(r){const o=r.data;switch(o.type){case"decode":s._callbacks[o.id].resolve(o);break;case"error":s._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,r){return s._taskLoad>r._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[t]=e,i._taskLoad+=e,i})}_releaseTask(t,e){t._taskLoad-=t._taskCosts[e],delete t._callbacks[e],delete t._taskCosts[e]}debug(){console.log("Task load: ",this.workerPool.map(t=>t._taskLoad))}dispose(){for(let t=0;t<this.workerPool.length;++t)this.workerPool[t].terminate();return this.workerPool.length=0,this}}function fB(){let n,t;onmessage=function(o){const a=o.data;switch(a.type){case"init":n=a.decoderConfig,t=new Promise(function(h){n.onModuleLoaded=function(A){h({draco:A})},DracoDecoderModule(n)});break;case"decode":const l=a.buffer,c=a.taskConfig;t.then(h=>{const A=h.draco,u=new A.Decoder,d=new A.DecoderBuffer;d.Init(new Int8Array(l),l.byteLength);try{const f=e(A,u,d,c),g=f.attributes.map(p=>p.array.buffer);f.index&&g.push(f.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:f},g)}catch(f){console.error(f),self.postMessage({type:"error",id:a.id,error:f.message})}finally{A.destroy(d),A.destroy(u)}});break}};function e(o,a,l,c){const h=c.attributeIDs,A=c.attributeTypes;let u,d;const f=a.GetEncodedGeometryType(l);if(f===o.TRIANGULAR_MESH)u=new o.Mesh,d=a.DecodeBufferToMesh(l,u);else if(f===o.POINT_CLOUD)u=new o.PointCloud,d=a.DecodeBufferToPointCloud(l,u);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!d.ok()||u.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+d.error_msg());const g={index:null,attributes:[]};for(const p in h){const m=self[A[p]];let C,E;if(c.useUniqueIDs)E=h[p],C=a.GetAttributeByUniqueId(u,E);else{if(E=a.GetAttributeId(u,o[h[p]]),E===-1)continue;C=a.GetAttribute(u,E)}g.attributes.push(s(o,a,u,p,m,C))}return f===o.TRIANGULAR_MESH&&(g.index=i(o,a,u)),o.destroy(u),g}function i(o,a,l){const h=l.num_faces()*3,A=h*4,u=o._malloc(A);a.GetTrianglesUInt32Array(l,A,u);const d=new Uint32Array(o.HEAPF32.buffer,u,h).slice();return o._free(u),{array:d,itemSize:1}}function s(o,a,l,c,h,A){const u=A.num_components(),f=l.num_points()*u,g=f*h.BYTES_PER_ELEMENT,p=r(o,h),m=o._malloc(g);a.GetAttributeDataArrayForAllPoints(l,A,p,g,m);const C=new h(o.HEAPF32.buffer,m,f).slice();return o._free(m),{name:c,array:C,itemSize:u}}function r(o,a){switch(a){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}let ln;const Jr=()=>{if(ln)return ln;const n="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",t="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",e=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]),i=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 s=n;WebAssembly.validate(e)&&(s=t);let r;const o=WebAssembly.instantiate(a(s),{}).then(A=>{r=A.instance,r.exports.__wasm_call_ctors()});function a(A){const u=new Uint8Array(A.length);for(let f=0;f<A.length;++f){const g=A.charCodeAt(f);u[f]=g>96?g-71:g>64?g-65:g>47?g+4:g>46?63:62}let d=0;for(let f=0;f<A.length;++f)u[d++]=u[f]<60?i[u[f]]:(u[f]-60)*64+u[++f];return u.buffer.slice(0,d)}function l(A,u,d,f,g,p){const m=r.exports.sbrk,C=d+3&-4,E=m(C*f),v=m(g.length),y=new Uint8Array(r.exports.memory.buffer);y.set(g,v);const S=A(E,d,f,v,g.length);if(S===0&&p&&p(E,C,f),u.set(y.subarray(E,E+d*f)),m(E-m(0)),S!==0)throw new Error(`Malformed buffer data: ${S}`)}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 ln={ready:o,supported:!0,decodeVertexBuffer(A,u,d,f,g){l(r.exports.meshopt_decodeVertexBuffer,A,u,d,f,r.exports[c[g]])},decodeIndexBuffer(A,u,d,f){l(r.exports.meshopt_decodeIndexBuffer,A,u,d,f)},decodeIndexSequence(A,u,d,f){l(r.exports.meshopt_decodeIndexSequence,A,u,d,f)},decodeGltfBuffer(A,u,d,f,g,p){l(r.exports[h[g]],A,u,d,f,r.exports[c[p]])}},ln},gB=new k,mB=B.forwardRef(({scale:n=1,...t},e)=>{const i=B.useRef(null);return B.useImperativeHandle(e,()=>i.current,[]),Ot(s=>{const r=i.current;if(!r)return;const o=rA(r.getWorldPosition(gB),n,s.camera,s.size);r.scale.setScalar(o*n)}),B.createElement("object3D",wt({ref:i},t))});let cn=null,wu="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function Lu(n=!0,t=!0,e){return i=>{e&&e(i),n&&(cn||(cn=new dB),cn.setDecoderPath(typeof n=="string"?n:wu),i.setDRACOLoader(cn)),t&&i.setMeshoptDecoder(typeof Jr=="function"?Jr():Jr)}}const Xs=(n,t,e,i)=>xe(ga,n,Lu(t,e,i));Xs.preload=(n,t,e,i)=>xe.preload(ga,n,Lu(t,e,i));Xs.clear=n=>xe.clear(ga,n);Xs.setDecoderPath=n=>{wu=n};const pB=B.forwardRef(({src:n,useDraco:t,useMeshOpt:e,extendLoader:i,...s},r)=>{const{scene:o}=Xs(n,t,e,i);return B.createElement(ma,wt({ref:r},s,{object:o}))}),EB=B.forwardRef((n,t)=>{const{camera:e,onChange:i,makeDefault:s,...r}=n,o=$(u=>u.camera),a=$(u=>u.invalidate),l=$(u=>u.get),c=$(u=>u.set),h=e||o,A=B.useMemo(()=>new my(h),[h]);return B.useEffect(()=>{const u=d=>{a(),i&&i(d)};return A==null||A.addEventListener==null||A.addEventListener("change",u),()=>A==null||A.removeEventListener==null?void 0:A.removeEventListener("change",u)},[i,A,a]),Ot(()=>A==null?void 0:A.update(),-1),B.useEffect(()=>{const u=A;return u==null||u.connect(),()=>u==null?void 0:u.dispose()},[A]),B.useEffect(()=>{if(s){const u=l().controls;return c({controls:A}),()=>c({controls:u})}},[s,A]),A?B.createElement("primitive",wt({ref:t,object:A},r)):null}),CB=B.forwardRef(({domElement:n,...t},e)=>{const{onChange:i,makeDefault:s,...r}=t,o=$(f=>f.invalidate),a=$(f=>f.camera),l=$(f=>f.gl),c=$(f=>f.events),h=$(f=>f.get),A=$(f=>f.set),u=n||c.connected||l.domElement,d=B.useMemo(()=>new Ty(a),[a]);return B.useEffect(()=>(d.connect(u),()=>void d.dispose()),[u,d,o]),B.useEffect(()=>{const f=g=>{o(),i&&i(g)};return d.addEventListener==null||d.addEventListener("change",f),()=>d.removeEventListener==null?void 0:d.removeEventListener("change",f)},[i,o]),B.useEffect(()=>{if(s){const f=h().controls;return A({controls:d}),()=>A({controls:f})}},[s,d]),Ot((f,g)=>d.update(g)),B.createElement("primitive",wt({ref:e,object:d,args:[a,u]},r))}),IB=B.forwardRef((n={enableDamping:!0},t)=>{const{domElement:e,camera:i,makeDefault:s,onChange:r,onStart:o,onEnd:a,...l}=n,c=$(C=>C.invalidate),h=$(C=>C.camera),A=$(C=>C.gl),u=$(C=>C.events),d=$(C=>C.set),f=$(C=>C.get),g=e||u.connected||A.domElement,p=i||h,m=B.useMemo(()=>new zf(p),[p]);return B.useEffect(()=>{m.connect(g);const C=E=>{c(),r&&r(E)};return m.addEventListener("change",C),o&&m.addEventListener("start",o),a&&m.addEventListener("end",a),()=>{m.dispose(),m.removeEventListener("change",C),o&&m.removeEventListener("start",o),a&&m.removeEventListener("end",a)}},[r,o,a,m,c,g]),B.useEffect(()=>{if(s){const C=f().controls;return d({controls:m}),()=>d({controls:C})}},[s,m]),Ot(()=>m.update(),-1),B.createElement("primitive",wt({ref:t,object:m,enableDamping:!0},l))}),yB=B.forwardRef(({makeDefault:n,camera:t,domElement:e,regress:i,onChange:s,onStart:r,onEnd:o,...a},l)=>{const{invalidate:c,camera:h,gl:A,events:u,set:d,get:f,performance:g,viewport:p}=$(),m=t||h,C=e||u.connected||A.domElement,E=B.useMemo(()=>new Cy(m),[m]);return Ot(()=>{E.enabled&&E.update()},-1),B.useEffect(()=>(E.connect(C),()=>void E.dispose()),[C,i,E,c]),B.useEffect(()=>{const v=y=>{c(),i&&g.regress(),s&&s(y)};return E.addEventListener("change",v),r&&E.addEventListener("start",r),o&&E.addEventListener("end",o),()=>{r&&E.removeEventListener("start",r),o&&E.removeEventListener("end",o),E.removeEventListener("change",v)}},[s,r,o,E,c]),B.useEffect(()=>{E.handleResize()},[p]),B.useEffect(()=>{if(n){const v=f().controls;return d({controls:E}),()=>d({controls:v})}},[n,E]),B.createElement("primitive",wt({ref:l,object:E},a))}),BB=B.forwardRef(({camera:n,makeDefault:t,regress:e,domElement:i,onChange:s,onStart:r,onEnd:o,...a},l)=>{const c=$(E=>E.invalidate),h=$(E=>E.camera),A=$(E=>E.gl),u=$(E=>E.events),d=$(E=>E.set),f=$(E=>E.get),g=$(E=>E.performance),p=n||h,m=i||u.connected||A.domElement,C=B.useMemo(()=>new By(p),[p]);return Ot(()=>{C.enabled&&C.update()},-1),B.useEffect(()=>(C.connect(m),()=>void C.dispose()),[m,e,C,c]),B.useEffect(()=>{const E=v=>{c(),e&&g.regress(),s&&s(v)};return C.addEventListener("change",E),r&&C.addEventListener("start",r),o&&C.addEventListener("end",o),()=>{C.removeEventListener("change",E),r&&C.removeEventListener("start",r),o&&C.removeEventListener("end",o)}},[s,r,o]),B.useEffect(()=>{if(t){const E=f().controls;return d({controls:C}),()=>d({controls:E})}},[t,C]),B.createElement("primitive",wt({ref:l,object:C},a))}),vB=B.forwardRef(({children:n,domElement:t,onChange:e,onMouseDown:i,onMouseUp:s,onObjectChange:r,object:o,makeDefault:a,camera:l,enabled:c,axis:h,mode:A,translationSnap:u,rotationSnap:d,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E,...v},y)=>{const S=$(H=>H.controls),T=$(H=>H.gl),x=$(H=>H.events),F=$(H=>H.camera),_=$(H=>H.invalidate),w=$(H=>H.get),U=$(H=>H.set),O=l||F,W=t||x.connected||T.domElement,K=B.useMemo(()=>new ry(O,W),[O,W]),q=B.useRef(null);B.useLayoutEffect(()=>(o?K.attach(o instanceof jt?o:o.current):q.current instanceof jt&&K.attach(q.current),()=>void K.detach()),[o,n,K]),B.useEffect(()=>{if(S){const H=X=>S.enabled=!X.value;return K.addEventListener("dragging-changed",H),()=>K.removeEventListener("dragging-changed",H)}},[K,S]);const Z=B.useRef(),rt=B.useRef(),V=B.useRef(),G=B.useRef();return B.useLayoutEffect(()=>void(Z.current=e),[e]),B.useLayoutEffect(()=>void(rt.current=i),[i]),B.useLayoutEffect(()=>void(V.current=s),[s]),B.useLayoutEffect(()=>void(G.current=r),[r]),B.useEffect(()=>{const H=it=>{_(),Z.current==null||Z.current(it)},X=it=>rt.current==null?void 0:rt.current(it),Y=it=>V.current==null?void 0:V.current(it),D=it=>G.current==null?void 0:G.current(it);return K.addEventListener("change",H),K.addEventListener("mouseDown",X),K.addEventListener("mouseUp",Y),K.addEventListener("objectChange",D),()=>{K.removeEventListener("change",H),K.removeEventListener("mouseDown",X),K.removeEventListener("mouseUp",Y),K.removeEventListener("objectChange",D)}},[_,K]),B.useEffect(()=>{if(a){const H=w().controls;return U({controls:K}),()=>U({controls:H})}},[a,K]),B.createElement(B.Fragment,null,B.createElement("primitive",{ref:y,object:K,enabled:c,axis:h,mode:A,translationSnap:u,rotationSnap:d,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E}),B.createElement("group",wt({ref:q},v),n))}),SB=B.forwardRef(({domElement:n,selector:t,onChange:e,onLock:i,onUnlock:s,enabled:r=!0,makeDefault:o,...a},l)=>{const{camera:c,...h}=a,A=$(y=>y.setEvents),u=$(y=>y.gl),d=$(y=>y.camera),f=$(y=>y.invalidate),g=$(y=>y.events),p=$(y=>y.get),m=$(y=>y.set),C=c||d,E=n||g.connected||u.domElement,v=B.useMemo(()=>new dy(C),[C]);return B.useEffect(()=>{if(r){v.connect(E);const y=p().events.compute;return A({compute(S,T){const x=T.size.width/2,F=T.size.height/2;T.pointer.set(x/T.size.width*2-1,-(F/T.size.height)*2+1),T.raycaster.setFromCamera(T.pointer,T.camera)}}),()=>{v.disconnect(),A({compute:y})}}},[r,v]),B.useEffect(()=>{const y=x=>{f(),e&&e(x)};v.addEventListener("change",y),i&&v.addEventListener("lock",i),s&&v.addEventListener("unlock",s);const S=()=>v.lock(),T=t?Array.from(document.querySelectorAll(t)):[document];return T.forEach(x=>x&&x.addEventListener("click",S)),()=>{v.removeEventListener("change",y),i&&v.removeEventListener("lock",i),s&&v.removeEventListener("unlock",s),T.forEach(x=>x?x.removeEventListener("click",S):void 0)}},[e,i,s,t,v,f]),B.useEffect(()=>{if(o){const y=p().controls;return m({controls:v}),()=>m({controls:y})}},[o,v]),B.createElement("primitive",wt({ref:l,object:v},h))}),TB=B.forwardRef(({domElement:n,makeDefault:t,...e},i)=>{const s=$(A=>A.camera),r=$(A=>A.gl),o=$(A=>A.events),a=$(A=>A.get),l=$(A=>A.set),c=n||o.connected||r.domElement,[h]=B.useState(()=>new iy(s,c));return B.useEffect(()=>{if(t){const A=a().controls;return l({controls:h}),()=>l({controls:A})}},[t,h]),Ot((A,u)=>{h.update(u)},-1),h?B.createElement("primitive",wt({ref:i,object:h},e)):null});/*!
6
+ * camera-controls
7
+ * https://github.com/yomotsu/camera-controls
8
+ * (c) 2017 @yomotsu
9
+ * Released under the MIT License.
10
+ */const Ft={LEFT:1,RIGHT:2,MIDDLE:4},Q=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}),wi={NONE:0,IN:1,OUT:-1};function ui(n){return n.isPerspectiveCamera}function ti(n){return n.isOrthographicCamera}const Li=Math.PI*2,Mc=Math.PI/2,bu=1e-5,ms=Math.PI/180;function Ce(n,t,e){return Math.max(t,Math.min(e,n))}function Dt(n,t=bu){return Math.abs(n)<t}function Bt(n,t,e=bu){return Dt(n-t,e)}function Pc(n,t){return Math.round(n/t)*t}function ps(n){return isFinite(n)?n:n<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Es(n){return Math.abs(n)<Number.MAX_VALUE?n:n*(1/0)}function hn(n,t,e,i,s=1/0,r){i=Math.max(1e-4,i);const o=2/i,a=o*r,l=1/(1+a+.48*a*a+.235*a*a*a);let c=n-t;const h=t,A=s*i;c=Ce(c,-A,A),t=n-c;const u=(e.value+o*c)*r;e.value=(e.value-o*u)*l;let d=t+(c+u)*l;return h-n>0==d>h&&(d=h,e.value=(d-h)/r),d}function kc(n,t,e,i,s=1/0,r,o){i=Math.max(1e-4,i);const a=2/i,l=a*r,c=1/(1+l+.48*l*l+.235*l*l*l);let h=t.x,A=t.y,u=t.z,d=n.x-h,f=n.y-A,g=n.z-u;const p=h,m=A,C=u,E=s*i,v=E*E,y=d*d+f*f+g*g;if(y>v){const K=Math.sqrt(y);d=d/K*E,f=f/K*E,g=g/K*E}h=n.x-d,A=n.y-f,u=n.z-g;const S=(e.x+a*d)*r,T=(e.y+a*f)*r,x=(e.z+a*g)*r;e.x=(e.x-a*S)*c,e.y=(e.y-a*T)*c,e.z=(e.z-a*x)*c,o.x=h+(d+S)*c,o.y=A+(f+T)*c,o.z=u+(g+x)*c;const F=p-n.x,_=m-n.y,w=C-n.z,U=o.x-p,O=o.y-m,W=o.z-C;return F*U+_*O+w*W>0&&(o.x=p,o.y=m,o.z=C,e.x=(o.x-p)/r,e.y=(o.y-m)/r,e.z=(o.z-C)/r),o}function zr(n,t){t.set(0,0),n.forEach(e=>{t.x+=e.clientX,t.y+=e.clientY}),t.x/=n.length,t.y/=n.length}function $r(n,t){return ti(n)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}class _B{constructor(){this._listeners={}}addEventListener(t,e){const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const s=this._listeners[t];if(s!==void 0){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}}removeAllEventListeners(t){if(!t){this._listeners={};return}Array.isArray(this._listeners[t])&&(this._listeners[t].length=0)}dispatchEvent(t){const i=this._listeners[t.type];if(i!==void 0){t.target=this;const s=i.slice(0);for(let r=0,o=s.length;r<o;r++)s[r].call(this,t)}}}var qr;const xB="2.9.0",An=1/8,DB=/Mac/.test((qr=globalThis==null?void 0:globalThis.navigator)===null||qr===void 0?void 0:qr.platform);let lt,Qc,un,Xr,Zt,mt,yt,bi,Cs,De,Re,di,Oc,Gc,ae,Is,Fi,Uc,Wr,Nc,jr,Zr,dn,to=class Jo extends _B{static install(t){lt=t.THREE,Qc=Object.freeze(new lt.Vector3(0,0,0)),un=Object.freeze(new lt.Vector3(0,1,0)),Xr=Object.freeze(new lt.Vector3(0,0,1)),Zt=new lt.Vector2,mt=new lt.Vector3,yt=new lt.Vector3,bi=new lt.Vector3,Cs=new lt.Vector3,De=new lt.Vector3,Re=new lt.Vector3,di=new lt.Vector3,Oc=new lt.Vector3,Gc=new lt.Vector3,ae=new lt.Spherical,Is=new lt.Spherical,Fi=new lt.Box3,Uc=new lt.Box3,Wr=new lt.Sphere,Nc=new lt.Quaternion,jr=new lt.Quaternion,Zr=new lt.Matrix4,dn=new lt.Raycaster}static get ACTION(){return Q}constructor(t,e){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=Q.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=wi.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new lt.Vector3,this._focalOffsetVelocity=new lt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,C,E)=>{let v,y;if(ui(this._camera)){const S=mt.copy(this._camera.position).sub(this._target),T=this._camera.getEffectiveFOV()*ms,x=S.length()*Math.tan(T*.5);v=this.truckSpeed*m*x/this._elementRect.height,y=this.truckSpeed*C*x/this._elementRect.height}else if(ti(this._camera)){const S=this._camera;v=m*(S.right-S.left)/S.zoom/this._elementRect.width,y=C*(S.top-S.bottom)/S.zoom/this._elementRect.height}else return;this.verticalDragToForward?(E?this.setFocalOffset(this._focalOffsetEnd.x+v,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(v,0,!0),this.forward(-y,!0)):E?this.setFocalOffset(this._focalOffsetEnd.x+v,this._focalOffsetEnd.y+y,this._focalOffsetEnd.z,!0):this.truck(v,y,!0)},this._rotateInternal=(m,C)=>{const E=Li*this.azimuthRotateSpeed*m/this._elementRect.height,v=Li*this.polarRotateSpeed*C/this._elementRect.height;this.rotate(E,v,!0)},this._dollyInternal=(m,C,E)=>{const v=Math.pow(.95,-m*this.dollySpeed),y=this._sphericalEnd.radius,S=this._sphericalEnd.radius*v,T=Ce(S,this.minDistance,this.maxDistance),x=T-S;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(S,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(x,!0),this._dollyToNoClamp(T,!0)):this._dollyToNoClamp(T,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?S:T)-y,this._dollyControlCoord.set(C,E)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,C,E)=>{const v=Math.pow(.95,m*this.dollySpeed),y=this._zoom,S=this._zoom*v;this.zoomTo(S,!0),this.dollyToCursor&&(this._changedZoom+=S-y,this._dollyControlCoord.set(C,E))},typeof lt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=t,this._yAxisUpSpace=new lt.Quaternion().setFromUnitVectors(this._camera.up,un),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=Q.NONE,this._target=new lt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new lt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new lt.Spherical().setFromVector3(mt.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 lt.Vector3,new lt.Vector3,new lt.Vector3,new lt.Vector3],this._updateNearPlaneCorners(),this._boundary=new lt.Box3(new lt.Vector3(-1/0,-1/0,-1/0),new lt.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 lt.Vector2,this.mouseButtons={left:Q.ROTATE,middle:Q.DOLLY,right:Q.TRUCK,wheel:ui(this._camera)?Q.DOLLY:ti(this._camera)?Q.ZOOM:Q.NONE},this.touches={one:Q.TOUCH_ROTATE,two:ui(this._camera)?Q.TOUCH_DOLLY_TRUCK:ti(this._camera)?Q.TOUCH_ZOOM_TRUCK:Q.NONE,three:Q.TOUCH_TRUCK};const i=new lt.Vector2,s=new lt.Vector2,r=new lt.Vector2,o=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 v=this._domElement.getBoundingClientRect(),y=m.clientX/v.width,S=m.clientY/v.height;if(y<this._interactiveArea.left||y>this._interactiveArea.right||S<this._interactiveArea.top||S>this._interactiveArea.bottom)return}const C=m.pointerType!=="mouse"?null:(m.buttons&Ft.LEFT)===Ft.LEFT?Ft.LEFT:(m.buttons&Ft.MIDDLE)===Ft.MIDDLE?Ft.MIDDLE:(m.buttons&Ft.RIGHT)===Ft.RIGHT?Ft.RIGHT:null;if(C!==null){const v=this._findPointerByMouseButton(C);v&&this._disposePointer(v)}if((m.buttons&Ft.LEFT)===Ft.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",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,u(m)},a=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&Ft.LEFT)===Ft.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Ft.MIDDLE)===Ft.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Ft.RIGHT)===Ft.RIGHT&&(this._state=this._state|this.mouseButtons.right);d()}},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=Q.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=Q.NONE;f()}};let c=-1;const h=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===Q.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const S=this._domElement.getBoundingClientRect(),T=m.clientX/S.width,x=m.clientY/S.height;if(T<this._interactiveArea.left||T>this._interactiveArea.right||x<this._interactiveArea.top||x>this._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===Q.ROTATE||this.mouseButtons.wheel===Q.TRUCK){const S=performance.now();c-S<1e3&&this._getClientRect(this._elementRect),c=S}const C=DB?-1:-3,E=m.deltaMode===1?m.deltaY/C:m.deltaY/(C*10),v=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,y=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case Q.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case Q.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1),this._isUserControllingTruck=!0;break}case Q.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0),this._isUserControllingOffset=!0;break}case Q.DOLLY:{this._dollyInternal(-E,v,y),this._isUserControllingDolly=!0;break}case Q.ZOOM:{this._zoomInternal(-E,v,y),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},A=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Jo.ACTION.NONE){const C=m instanceof PointerEvent?m.pointerId:0,E=this._findPointerById(C);E&&this._disposePointer(E),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},u=m=>{if(!this._enabled)return;if(zr(this._activePointers,Zt),this._getClientRect(this._elementRect),i.copy(Zt),s.copy(Zt),this._activePointers.length>=2){const E=Zt.x-this._activePointers[1].clientX,v=Zt.y-this._activePointers[1].clientY,y=Math.sqrt(E*E+v*v);r.set(0,y);const S=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,T=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(S,T)}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&Ft.LEFT)===Ft.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Ft.MIDDLE)===Ft.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Ft.RIGHT)===Ft.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&Q.ROTATE)===Q.ROTATE||(this._state&Q.TOUCH_ROTATE)===Q.TOUCH_ROTATE||(this._state&Q.TOUCH_DOLLY_ROTATE)===Q.TOUCH_DOLLY_ROTATE||(this._state&Q.TOUCH_ZOOM_ROTATE)===Q.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&Q.TRUCK)===Q.TRUCK||(this._state&Q.TOUCH_TRUCK)===Q.TOUCH_TRUCK||(this._state&Q.TOUCH_DOLLY_TRUCK)===Q.TOUCH_DOLLY_TRUCK||(this._state&Q.TOUCH_ZOOM_TRUCK)===Q.TOUCH_ZOOM_TRUCK)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&Q.DOLLY)===Q.DOLLY||(this._state&Q.TOUCH_DOLLY)===Q.TOUCH_DOLLY||(this._state&Q.TOUCH_DOLLY_TRUCK)===Q.TOUCH_DOLLY_TRUCK||(this._state&Q.TOUCH_DOLLY_OFFSET)===Q.TOUCH_DOLLY_OFFSET||(this._state&Q.TOUCH_DOLLY_ROTATE)===Q.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&Q.ZOOM)===Q.ZOOM||(this._state&Q.TOUCH_ZOOM)===Q.TOUCH_ZOOM||(this._state&Q.TOUCH_ZOOM_TRUCK)===Q.TOUCH_ZOOM_TRUCK||(this._state&Q.TOUCH_ZOOM_OFFSET)===Q.TOUCH_ZOOM_OFFSET||(this._state&Q.TOUCH_ZOOM_ROTATE)===Q.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&Q.OFFSET)===Q.OFFSET||(this._state&Q.TOUCH_OFFSET)===Q.TOUCH_OFFSET||(this._state&Q.TOUCH_DOLLY_OFFSET)===Q.TOUCH_DOLLY_OFFSET||(this._state&Q.TOUCH_ZOOM_OFFSET)===Q.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},d=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,zr(this._activePointers,Zt);const C=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,E=C?-C.deltaX:s.x-Zt.x,v=C?-C.deltaY:s.y-Zt.y;if(s.copy(Zt),((this._state&Q.ROTATE)===Q.ROTATE||(this._state&Q.TOUCH_ROTATE)===Q.TOUCH_ROTATE||(this._state&Q.TOUCH_DOLLY_ROTATE)===Q.TOUCH_DOLLY_ROTATE||(this._state&Q.TOUCH_ZOOM_ROTATE)===Q.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(E,v),this._isUserControllingRotate=!0),(this._state&Q.DOLLY)===Q.DOLLY||(this._state&Q.ZOOM)===Q.ZOOM){const y=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,T=this.dollyDragInverted?-1:1;(this._state&Q.DOLLY)===Q.DOLLY?(this._dollyInternal(T*v*An,y,S),this._isUserControllingDolly=!0):(this._zoomInternal(T*v*An,y,S),this._isUserControllingZoom=!0)}if((this._state&Q.TOUCH_DOLLY)===Q.TOUCH_DOLLY||(this._state&Q.TOUCH_ZOOM)===Q.TOUCH_ZOOM||(this._state&Q.TOUCH_DOLLY_TRUCK)===Q.TOUCH_DOLLY_TRUCK||(this._state&Q.TOUCH_ZOOM_TRUCK)===Q.TOUCH_ZOOM_TRUCK||(this._state&Q.TOUCH_DOLLY_OFFSET)===Q.TOUCH_DOLLY_OFFSET||(this._state&Q.TOUCH_ZOOM_OFFSET)===Q.TOUCH_ZOOM_OFFSET||(this._state&Q.TOUCH_DOLLY_ROTATE)===Q.TOUCH_DOLLY_ROTATE||(this._state&Q.TOUCH_ZOOM_ROTATE)===Q.TOUCH_ZOOM_ROTATE){const y=Zt.x-this._activePointers[1].clientX,S=Zt.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+S*S),x=r.y-T;r.set(0,T);const F=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;(this._state&Q.TOUCH_DOLLY)===Q.TOUCH_DOLLY||(this._state&Q.TOUCH_DOLLY_ROTATE)===Q.TOUCH_DOLLY_ROTATE||(this._state&Q.TOUCH_DOLLY_TRUCK)===Q.TOUCH_DOLLY_TRUCK||(this._state&Q.TOUCH_DOLLY_OFFSET)===Q.TOUCH_DOLLY_OFFSET?(this._dollyInternal(x*An,F,_),this._isUserControllingDolly=!0):(this._zoomInternal(x*An,F,_),this._isUserControllingZoom=!0)}((this._state&Q.TRUCK)===Q.TRUCK||(this._state&Q.TOUCH_TRUCK)===Q.TOUCH_TRUCK||(this._state&Q.TOUCH_DOLLY_TRUCK)===Q.TOUCH_DOLLY_TRUCK||(this._state&Q.TOUCH_ZOOM_TRUCK)===Q.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(E,v,!1),this._isUserControllingTruck=!0),((this._state&Q.OFFSET)===Q.OFFSET||(this._state&Q.TOUCH_OFFSET)===Q.TOUCH_OFFSET||(this._state&Q.TOUCH_DOLLY_OFFSET)===Q.TOUCH_DOLLY_OFFSET||(this._state&Q.TOUCH_ZOOM_OFFSET)===Q.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(E,v,!0),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{zr(this._activePointers,Zt),s.copy(Zt),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",a,{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",a,{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",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),u())},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",o),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",A)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",o),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",A),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",p))},this.cancel=()=>{this._state!==Q.NONE&&(this._state=Q.NONE,this._activePointers.length=0,f())},e&&this.connect(e),this.update(0)}get camera(){return this._camera}set camera(t){this._camera=t,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._domElement&&(t?(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(t){this._spherical.radius===t&&this._sphericalEnd.radius===t||(this._spherical.radius=t,this._sphericalEnd.radius=t,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(t){this._spherical.theta===t&&this._sphericalEnd.theta===t||(this._spherical.theta=t,this._sphericalEnd.theta=t,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(t){this._spherical.phi===t&&this._sphericalEnd.phi===t||(this._spherical.phi=t,this._sphericalEnd.phi=t,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(t){this._boundaryEnclosesCamera=t,this._needsUpdate=!0}set interactiveArea(t){this._interactiveArea.width=Ce(t.width,0,1),this._interactiveArea.height=Ce(t.height,0,1),this._interactiveArea.x=Ce(t.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ce(t.y,0,1-this._interactiveArea.height)}addEventListener(t,e){super.addEventListener(t,e)}removeEventListener(t,e){super.removeEventListener(t,e)}rotate(t,e,i=!1){return this.rotateTo(this._sphericalEnd.theta+t,this._sphericalEnd.phi+e,i)}rotateAzimuthTo(t,e=!1){return this.rotateTo(t,this._sphericalEnd.phi,e)}rotatePolarTo(t,e=!1){return this.rotateTo(this._sphericalEnd.theta,t,e)}rotateTo(t,e,i=!1){this._isUserControllingRotate=!1;const s=Ce(t,this.minAzimuthAngle,this.maxAzimuthAngle),r=Ce(e,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=r,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const o=!i||Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(o)}dolly(t,e=!1){return this.dollyTo(this._sphericalEnd.radius-t,e)}dollyTo(t,e=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=wi.NONE,this._changedDolly=0,this._dollyToNoClamp(Ce(t,this.minDistance,this.maxDistance),e)}_dollyToNoClamp(t,e=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const o=this._collisionTest(),a=Bt(o,this._spherical.radius);if(!(i>t)&&a)return Promise.resolve();this._sphericalEnd.radius=Math.min(t,o)}else this._sphericalEnd.radius=t;this._needsUpdate=!0,e||(this._spherical.radius=this._sphericalEnd.radius);const r=!e||Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(Cs).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(t,e=!1){return this.zoomTo(this._zoomEnd+t,e)}zoomTo(t,e=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ce(t,this.minZoom,this.maxZoom),this._needsUpdate=!0,e||(this._zoom=this._zoomEnd);const i=!e||Bt(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(t,e,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(t,e,i)}truck(t,e,i=!1){this._camera.updateMatrix(),De.setFromMatrixColumn(this._camera.matrix,0),Re.setFromMatrixColumn(this._camera.matrix,1),De.multiplyScalar(t),Re.multiplyScalar(-e);const s=mt.copy(De).add(Re),r=yt.copy(this._targetEnd).add(s);return this.moveTo(r.x,r.y,r.z,i)}forward(t,e=!1){mt.setFromMatrixColumn(this._camera.matrix,0),mt.crossVectors(this._camera.up,mt),mt.multiplyScalar(t);const i=yt.copy(this._targetEnd).add(mt);return this.moveTo(i.x,i.y,i.z,e)}elevate(t,e=!1){return mt.copy(this._camera.up).multiplyScalar(t),this.moveTo(this._targetEnd.x+mt.x,this._targetEnd.y+mt.y,this._targetEnd.z+mt.z,e)}moveTo(t,e,i,s=!1){this._isUserControllingTruck=!1;const r=mt.set(t,e,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,r,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const o=!s||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(o)}lookInDirectionOf(t,e,i,s=!1){const a=mt.set(t,e,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(a.x,a.y,a.z,s)}fitToBox(t,e,{cover:i=!1,paddingLeft:s=0,paddingRight:r=0,paddingBottom:o=0,paddingTop:a=0}={}){const l=[],c=t.isBox3?Fi.copy(t):Fi.setFromObject(t);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=Pc(this._sphericalEnd.theta,Mc),A=Pc(this._sphericalEnd.phi,Mc);l.push(this.rotateTo(h,A,e));const u=mt.setFromSpherical(this._sphericalEnd).normalize(),d=Nc.setFromUnitVectors(u,Xr),f=Bt(Math.abs(u.y),1);f&&d.multiply(jr.setFromAxisAngle(un,h)),d.multiply(this._yAxisUpSpaceInverse);const g=Uc.makeEmpty();yt.copy(c.min).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.min).setX(c.max.x).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.min).setY(c.max.y).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.max).setZ(c.min.z).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.min).setZ(c.max.z).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.max).setY(c.min.y).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.max).setX(c.min.x).applyQuaternion(d),g.expandByPoint(yt),yt.copy(c.max).applyQuaternion(d),g.expandByPoint(yt),g.min.x-=s,g.min.y-=o,g.max.x+=r,g.max.y+=a,d.setFromUnitVectors(Xr,u),f&&d.premultiply(jr.invert()),d.premultiply(this._yAxisUpSpace);const p=g.getSize(mt),m=g.getCenter(yt).applyQuaternion(d);if(ui(this._camera)){const C=this.getDistanceToFitBox(p.x,p.y,p.z,i);l.push(this.moveTo(m.x,m.y,m.z,e)),l.push(this.dollyTo(C,e)),l.push(this.setFocalOffset(0,0,0,e))}else if(ti(this._camera)){const C=this._camera,E=C.right-C.left,v=C.top-C.bottom,y=i?Math.max(E/p.x,v/p.y):Math.min(E/p.x,v/p.y);l.push(this.moveTo(m.x,m.y,m.z,e)),l.push(this.zoomTo(y,e)),l.push(this.setFocalOffset(0,0,0,e))}return Promise.all(l)}fitToSphere(t,e){const i=[],r="isObject3D"in t?Jo.createBoundingSphere(t,Wr):Wr.copy(t);if(i.push(this.moveTo(r.center.x,r.center.y,r.center.z,e)),ui(this._camera)){const o=this.getDistanceToFitSphere(r.radius);i.push(this.dollyTo(o,e))}else if(ti(this._camera)){const o=this._camera.right-this._camera.left,a=this._camera.top-this._camera.bottom,l=2*r.radius,c=Math.min(o/l,a/l);i.push(this.zoomTo(c,e))}return i.push(this.setFocalOffset(0,0,0,e)),Promise.all(i)}setLookAt(t,e,i,s,r,o,a=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=wi.NONE,this._changedDolly=0;const l=yt.set(s,r,o),c=mt.set(t,e,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,a||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!a||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold)&&Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(t,e,i,s,r,o,a,l,c,h,A,u,d,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=wi.NONE,this._changedDolly=0;const g=mt.set(s,r,o),p=yt.set(t,e,i);ae.setFromVector3(p.sub(g).applyQuaternion(this._yAxisUpSpace));const m=bi.set(h,A,u),C=yt.set(a,l,c);Is.setFromVector3(C.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,d));const E=Is.theta-ae.theta,v=Is.phi-ae.phi,y=Is.radius-ae.radius;this._sphericalEnd.set(ae.radius+y*d,ae.phi+v*d,ae.theta+E*d),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const S=!f||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold)&&Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(S)}setPosition(t,e,i,s=!1){return this.setLookAt(t,e,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(t,e,i,s=!1){const r=this.getPosition(mt),o=this.setLookAt(r.x,r.y,r.z,t,e,i,s);return this._sphericalEnd.phi=Ce(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),o}setFocalOffset(t,e,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(t,e,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const r=!s||Bt(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Bt(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Bt(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}setOrbitPoint(t,e,i){this._camera.updateMatrixWorld(),De.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Re.setFromMatrixColumn(this._camera.matrixWorldInverse,1),di.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=mt.set(t,e,i),r=s.distanceTo(this._camera.position),o=s.sub(this._camera.position);De.multiplyScalar(o.x),Re.multiplyScalar(o.y),di.multiplyScalar(o.z),mt.copy(De).add(Re).add(di),mt.z=mt.z+r,this.dollyTo(r,!1),this.setFocalOffset(-mt.x,mt.y,-mt.z,!1),this.moveTo(t,e,i,!1)}setBoundary(t){if(!t){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(t),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(t,e,i,s){if(t===null){this._viewport=null;return}this._viewport=this._viewport||new lt.Vector4,typeof t=="number"?this._viewport.set(t,e,i,s):this._viewport.copy(t)}getDistanceToFitBox(t,e,i,s=!1){if($r(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const r=t/e,o=this._camera.getEffectiveFOV()*ms,a=this._camera.aspect;return((s?r>a:r<a)?e:t/a)*.5/Math.tan(o*.5)+i*.5}getDistanceToFitSphere(t){if($r(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*ms,i=Math.atan(Math.tan(e*.5)*this._camera.aspect)*2,s=1<this._camera.aspect?e:i;return t/Math.sin(s*.5)}getTarget(t,e=!0){return(t&&t.isVector3?t:new lt.Vector3).copy(e?this._targetEnd:this._target)}getPosition(t,e=!0){return(t&&t.isVector3?t:new lt.Vector3).setFromSpherical(e?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(e?this._targetEnd:this._target)}getSpherical(t,e=!0){return(t||new lt.Spherical).copy(e?this._sphericalEnd:this._spherical)}getFocalOffset(t,e=!0){return(t&&t.isVector3?t:new lt.Vector3).copy(e?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Li,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Li),this._spherical.theta+=Li*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Li)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!Bt(this._camera.up.x,this._cameraUp0.x)||!Bt(this._camera.up.y,this._cameraUp0.y)||!Bt(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const i=this.getPosition(mt);this.updateCameraUp(),this.setPosition(i.x,i.y,i.z)}const e=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,t),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,t),this.zoomTo(this._zoom0,t)];return Promise.all(e)}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,un),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const t=mt.subVectors(this._target,this._camera.position).normalize(),e=yt.crossVectors(t,this._camera.up);this._camera.up.crossVectors(e,t).normalize(),this._camera.updateMatrixWorld();const i=this.getPosition(mt);this.updateCameraUp(),this.setPosition(i.x,i.y,i.z)}update(t){const e=this._sphericalEnd.theta-this._spherical.theta,i=this._sphericalEnd.phi-this._spherical.phi,s=this._sphericalEnd.radius-this._spherical.radius,r=Oc.subVectors(this._targetEnd,this._target),o=Gc.subVectors(this._focalOffsetEnd,this._focalOffset),a=this._zoomEnd-this._zoom;if(Dt(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const A=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=hn(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,A,1/0,t),this._needsUpdate=!0}if(Dt(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const A=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=hn(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,A,1/0,t),this._needsUpdate=!0}if(Dt(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const A=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=hn(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,A,this.maxSpeed,t),this._needsUpdate=!0}if(Dt(r.x)&&Dt(r.y)&&Dt(r.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const A=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;kc(this._target,this._targetEnd,this._targetVelocity,A,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(Dt(o.x)&&Dt(o.y)&&Dt(o.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const A=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;kc(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,A,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(Dt(a))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const A=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=hn(this._zoom,this._zoomEnd,this._zoomVelocity,A,1/0,t)}if(this.dollyToCursor){if(ui(this._camera)&&this._changedDolly!==0){const A=this._spherical.radius-this._lastDistance,u=this._camera,d=this._getCameraDirection(Cs),f=mt.copy(d).cross(u.up).normalize();f.lengthSq()===0&&(f.x=1);const g=yt.crossVectors(f,d),p=this._sphericalEnd.radius*Math.tan(u.getEffectiveFOV()*ms*.5),C=(this._sphericalEnd.radius-A-this._sphericalEnd.radius)/this._sphericalEnd.radius,E=bi.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*p*u.aspect)).add(g.multiplyScalar(this._dollyControlCoord.y*p)),v=mt.copy(this._targetEnd).lerp(E,C),y=this._lastDollyDirection===wi.IN&&this._spherical.radius<=this.minDistance,S=this._lastDollyDirection===wi.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(y||S)){this._sphericalEnd.radius-=A,this._spherical.radius-=A;const x=yt.copy(d).multiplyScalar(-A);v.add(x)}this._boundary.clampPoint(v,v);const T=yt.subVectors(v,this._targetEnd);this._targetEnd.copy(v),this._target.add(T),this._changedDolly-=A,Dt(this._changedDolly)&&(this._changedDolly=0)}else if(ti(this._camera)&&this._changedZoom!==0){const A=this._zoom-this._lastZoom,u=this._camera,d=mt.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(u.near+u.far)/(u.near-u.far)).unproject(u),f=yt.set(0,0,-1).applyQuaternion(u.quaternion),g=bi.copy(d).add(f.multiplyScalar(-d.dot(u.up))),m=-(this._zoom-A-this._zoom)/this._zoom,C=this._getCameraDirection(Cs),E=this._targetEnd.dot(C),v=mt.copy(this._targetEnd).lerp(g,m),y=v.dot(C),S=C.multiplyScalar(y-E);v.sub(S),this._boundary.clampPoint(v,v);const T=yt.subVectors(v,this._targetEnd);this._targetEnd.copy(v),this._target.add(T),this._changedZoom-=A,Dt(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),(!Dt(this._focalOffset.x)||!Dt(this._focalOffset.y)||!Dt(this._focalOffset.z))&&(this._camera.updateMatrixWorld(),De.setFromMatrixColumn(this._camera.matrix,0),Re.setFromMatrixColumn(this._camera.matrix,1),di.setFromMatrixColumn(this._camera.matrix,2),De.multiplyScalar(this._focalOffset.x),Re.multiplyScalar(-this._focalOffset.y),di.multiplyScalar(this._focalOffset.z),mt.copy(De).add(Re).add(di),this._camera.position.add(mt)),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),mt.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"}),Dt(e,this.restThreshold)&&Dt(i,this.restThreshold)&&Dt(s,this.restThreshold)&&Dt(r.x,this.restThreshold)&&Dt(r.y,this.restThreshold)&&Dt(r.z,this.restThreshold)&&Dt(o.x,this.restThreshold)&&Dt(o.y,this.restThreshold)&&Dt(o.z,this.restThreshold)&&Dt(a,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:ps(this.maxDistance),minZoom:this.minZoom,maxZoom:ps(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:ps(this.maxPolarAngle),minAzimuthAngle:ps(this.minAzimuthAngle),maxAzimuthAngle:ps(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:mt.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(t,e=!1){const i=JSON.parse(t);this.enabled=i.enabled,this.minDistance=i.minDistance,this.maxDistance=Es(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=Es(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=Es(i.maxPolarAngle),this.minAzimuthAngle=Es(i.minAzimuthAngle),this.maxAzimuthAngle=Es(i.maxAzimuthAngle),this.smoothTime=i.smoothTime,this.draggingSmoothTime=i.draggingSmoothTime,this.dollySpeed=i.dollySpeed,this.truckSpeed=i.truckSpeed,this.dollyToCursor=i.dollyToCursor,this.verticalDragToForward=i.verticalDragToForward,this._target0.fromArray(i.target0),this._position0.fromArray(i.position0),this._zoom0=i.zoom0,this._focalOffset0.fromArray(i.focalOffset0),this.moveTo(i.target[0],i.target[1],i.target[2],e),ae.setFromVector3(mt.fromArray(i.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ae.theta,ae.phi,e),this.dollyTo(ae.radius,e),this.zoomTo(i.zoom,e),this.setFocalOffset(i.focalOffset[0],i.focalOffset[1],i.focalOffset[2],e),this._needsUpdate=!0}connect(t){if(this._domElement){console.warn("camera-controls is already connected.");return}t.setAttribute("data-camera-controls-version",xB),this._addAllEventListeners(t),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(t){return t.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(t){return this._getTargetDirection(t).negate()}_findPointerById(t){return this._activePointers.find(e=>e.pointerId===t)}_findPointerByMouseButton(t){return this._activePointers.find(e=>e.mouseButton===t)}_disposePointer(t){this._activePointers.splice(this._activePointers.indexOf(t),1)}_encloseToBoundary(t,e,i){const s=e.lengthSq();if(s===0)return t;const r=yt.copy(e).add(t),a=this._boundary.clampPoint(r,bi).sub(r),l=a.lengthSq();if(l===0)return t.add(e);if(l===s)return t;if(i===0)return t.add(e).add(a);{const c=1+i*l/e.dot(a);return t.add(yt.copy(e).multiplyScalar(c)).add(a.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(ui(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*ms,s=Math.tan(i*.5)*e,r=s*t.aspect;this._nearPlaneCorners[0].set(-r,-s,0),this._nearPlaneCorners[1].set(r,-s,0),this._nearPlaneCorners[2].set(r,s,0),this._nearPlaneCorners[3].set(-r,s,0)}else if(ti(this._camera)){const t=this._camera,e=1/t.zoom,i=t.left*e,s=t.right*e,r=t.top*e,o=t.bottom*e;this._nearPlaneCorners[0].set(i,r,0),this._nearPlaneCorners[1].set(s,r,0),this._nearPlaneCorners[2].set(s,o,0),this._nearPlaneCorners[3].set(i,o,0)}}_collisionTest(){let t=1/0;if(!(this.colliderMeshes.length>=1)||$r(this._camera,"_collisionTest"))return t;const i=this._getTargetDirection(Cs);Zr.lookAt(Qc,i,this._camera.up);for(let s=0;s<4;s++){const r=yt.copy(this._nearPlaneCorners[s]);r.applyMatrix4(Zr);const o=bi.addVectors(this._target,r);dn.set(o,i),dn.far=this._spherical.radius+1;const a=dn.intersectObjects(this.colliderMeshes);a.length!==0&&a[0].distance<t&&(t=a[0].distance)}return t}_getClientRect(t){if(!this._domElement)return;const e=this._domElement.getBoundingClientRect();return t.x=e.left,t.y=e.top,this._viewport?(t.x+=this._viewport.x,t.y+=e.height-this._viewport.w-this._viewport.y,t.width=this._viewport.z,t.height=this._viewport.w):(t.width=e.width,t.height=e.height),t}_createOnRestPromise(t){return t?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(e=>{const i=()=>{this.removeEventListener("rest",i),e()};this.addEventListener("rest",i)}))}_addAllEventListeners(t){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(t){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(t){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(t,e=new lt.Sphere){const i=e,s=i.center;Fi.makeEmpty(),t.traverseVisible(o=>{o.isMesh&&Fi.expandByObject(o)}),Fi.getCenter(s);let r=0;return t.traverseVisible(o=>{if(!o.isMesh)return;const a=o,l=a.geometry.clone();l.applyMatrix4(a.matrixWorld);const h=l.attributes.position;for(let A=0,u=h.count;A<u;A++)mt.fromBufferAttribute(h,A),r=Math.max(r,s.distanceToSquared(mt))}),i.radius=Math.sqrt(r),i}};const RB=B.forwardRef((n,t)=>{B.useMemo(()=>{const y={Box3:sA,MathUtils:{clamp:ct.clamp},Matrix4:dt,Quaternion:It,Raycaster:or,Sphere:da,Spherical:ca,Vector2:Kt,Vector3:k,Vector4:Te};to.install({THREE:y}),pa({CameraControlsImpl:to})},[]);const{camera:e,domElement:i,makeDefault:s,onStart:r,onEnd:o,onChange:a,regress:l,...c}=n,h=$(y=>y.camera),A=$(y=>y.gl),u=$(y=>y.invalidate),d=$(y=>y.events),f=$(y=>y.setEvents),g=$(y=>y.set),p=$(y=>y.get),m=$(y=>y.performance),C=e||h,E=i||d.connected||A.domElement,v=B.useMemo(()=>new to(C),[C]);return Ot((y,S)=>{v.enabled&&v.update(S)},-1),B.useEffect(()=>(v.connect(E),()=>void v.disconnect()),[E,v]),B.useEffect(()=>{const y=x=>{u(),l&&m.regress(),a&&a(x)},S=x=>{r&&r(x)},T=x=>{o&&o(x)};return v.addEventListener("update",y),v.addEventListener("controlstart",S),v.addEventListener("controlend",T),v.addEventListener("control",y),v.addEventListener("transitionstart",y),v.addEventListener("wake",y),()=>{v.removeEventListener("update",y),v.removeEventListener("controlstart",S),v.removeEventListener("controlend",T),v.removeEventListener("control",y),v.removeEventListener("transitionstart",y),v.removeEventListener("wake",y)}},[v,r,o,u,f,l,a]),B.useEffect(()=>{if(s){const y=p().controls;return g({controls:v}),()=>g({controls:y})}},[s,v]),B.createElement("primitive",wt({ref:t,object:v},c))}),wB=n=>(n==null?void 0:n.current)instanceof jt,Fu=B.createContext(null);function Mu(){return B.useContext(Fu)}function LB({points:n=50}){const{path:t}=Mu(),[e,i]=B.useState([]),[s]=B.useState(()=>new ua({color:"black"})),[r]=B.useState(()=>new iA(.025,16,16)),o=B.useRef([]);return B.useEffect(()=>{t.curves!==o.current&&(i(t.getPoints(n)),o.current=t.curves)}),B.createElement(B.Fragment,null,e.map((a,l)=>B.createElement("mesh",{key:l,material:s,geometry:r,position:[a.x,a.y,a.z]})))}const bB=B.forwardRef(({children:n,curves:t=[],object:e,debug:i=!1,smooth:s=!1,focus:r,offset:o=void 0,eps:a=1e-5,damping:l=.1,focusDamping:c=.1,maxSpeed:h=1/0,...A},u)=>{const{camera:d}=$(),f=B.useRef(),[g]=B.useState(()=>new $f),p=B.useRef(o??0),m=B.useMemo(()=>({focus:r,object:(e==null?void 0:e.current)instanceof jt?e:{current:d},path:g,current:p.current,offset:p.current,point:new k,tangent:new k,next:new k}),[r,e]);B.useLayoutEffect(()=>{var v;g.curves=[];const y=t.length>0?t:(v=f.current)==null?void 0:v.__r3f.objects;for(var S=0;S<y.length;S++)g.add(y[S]);if(s){const T=g.getPoints(typeof s=="number"?s:1),x=new qf(T);g.curves=[x]}g.updateArcLengths()}),B.useImperativeHandle(u,()=>f.current,[]),B.useLayoutEffect(()=>{p.current=wr.repeat(p.current,1)},[o]);let C=0;const[E]=B.useState(()=>new k);return Ot((v,y)=>{if(C=m.offset,$i.damp(p,"current",o!==void 0?o:m.current,l,y,h,void 0,a),m.offset=wr.repeat(p.current,1),g.getCurveLengths().length>0){g.getPointAt(m.offset,m.point),g.getTangentAt(m.offset,m.tangent).normalize(),g.getPointAt(wr.repeat(p.current-(C-m.offset),1),m.next);const S=(e==null?void 0:e.current)instanceof jt?e.current:d;S.position.copy(m.point),r&&$i.dampLookAt(S,wB(r)?r.current.getWorldPosition(E):r,c,y,h,void 0,a)}}),B.createElement("group",wt({ref:f},A),B.createElement(Fu.Provider,{value:m},n,i&&B.createElement(LB,null)))});function Ha(n,{path:t}){const[e]=xe(oA,[n],i=>i.setPath(t));return e}Ha.preload=(n,{path:t})=>xe.preload(oA,[n],e=>e.setPath(t));function FB({children:n,files:t,...e}){const i=Ha(t,{...e});return B.createElement(B.Fragment,null,n==null?void 0:n(i))}function pr(n){return xe(Ua,n)}pr.preload=n=>xe.preload(Ua,n);pr.clear=n=>xe.clear(Ua,n);function MB({path:n,...t}){const i=pr(n).children[0];return B.createElement(ma,wt({},t,{object:i}))}const Pu="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master";function Er(n,t=`${Pu}/basis/`){const e=$(s=>s.gl),i=xe(vi,wo(n)?Object.values(n):n,s=>{s.detectSupport(e),s.setTranscoderPath(t)});if(B.useEffect(()=>{(Array.isArray(i)?i:[i]).forEach(e.initTexture)},[e,i]),wo(n)){const s=Object.keys(n),r={};return s.forEach(o=>Object.assign(r,{[o]:i[s.indexOf(o)]})),r}else return i}Er.preload=(n,t=`${Pu}/basis/`)=>xe.preload(vi,n,e=>{e.setTranscoderPath(t)});Er.clear=n=>xe.clear(vi,n);const PB=({children:n,input:t,basisPath:e})=>{const i=Er(t,e);return B.createElement(B.Fragment,null,n==null?void 0:n(i))};function kB(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ku={exports:{}};(function(n,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var A=a.parseURL(l);if(!A)throw new Error("Error trying to parse base URL.");return A.path=a.normalizePath(A.path),a.buildURLFromParts(A)}var u=a.parseURL(c);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return h.alwaysNormalize?(u.path=a.normalizePath(u.path),a.buildURLFromParts(u)):c;var d=a.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");if(!d.netLoc&&d.path&&d.path[0]!=="/"){var f=s.exec(d.path);d.netLoc=f[1],d.path=f[2]}d.netLoc&&!d.path&&(d.path="/");var g={scheme:d.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=d.netLoc,u.path[0]!=="/"))if(!u.path)g.path=d.path,u.params||(g.params=d.params,u.query||(g.query=d.query));else{var p=d.path,m=p.substring(0,p.lastIndexOf("/")+1)+u.path;g.path=a.normalizePath(m)}return g.path===null&&(g.path=h.alwaysNormalize?a.normalizePath(u.path):u.path),a.buildURLFromParts(g)},parseURL:function(l){var c=i.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(o,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=a})()})(ku);var Ka=ku.exports;function Hc(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),e.push.apply(e,i)}return e}function $t(n){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Hc(Object(e),!0).forEach(function(i){GB(n,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)):Hc(Object(e)).forEach(function(i){Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(e,i))})}return n}function QB(n,t){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var i=e.call(n,t||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(n)}function OB(n){var t=QB(n,"string");return typeof t=="symbol"?t:String(t)}function GB(n,t,e){return t=OB(t),t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function Qt(){return Qt=Object.assign?Object.assign.bind():function(n){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i])}return n},Qt.apply(this,arguments)}const j=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},UB=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=NB},NB=Number.MAX_SAFE_INTEGER||9007199254740991;let I=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}({}),ot=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}({}),M=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 mi=function(){},zo={trace:mi,debug:mi,log:mi,warn:mi,info:mi,error:mi};let Ms=zo;function HB(n){const t=self.console[n];return t?t.bind(self.console,`[${n}] >`):mi}function KB(n,...t){t.forEach(function(e){Ms[e]=n[e]?n[e].bind(n):HB(e)})}function YB(n,t){if(typeof console=="object"&&n===!0||typeof n=="object"){KB(n,"debug","log","info","warn","error");try{Ms.log(`Debug logs enabled for "${t}" in hls.js version 1.5.18`)}catch{Ms=zo}}else Ms=zo}const R=Ms,VB=/^(\d+)x(\d+)$/,Kc=/(.+?)=(".*?"|.*?)(?:,|$)/g;class bt{constructor(t){typeof t=="string"&&(t=bt.parseAttrList(t)),Qt(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;const i=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)i[s]=parseInt(e.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return this[t]==="YES"}decimalResolution(t){const e=VB.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={},s='"';for(Kc.lastIndex=0;(e=Kc.exec(t))!==null;){let r=e[2];r.indexOf(s)===0&&r.lastIndexOf(s)===r.length-1&&(r=r.slice(1,-1));const o=e[1].trim();i[o]=r}return i}}function JB(n){return n!=="ID"&&n!=="CLASS"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function zB(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"}class Ya{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==i[s]){R.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=s;break}t=Qt(new bt({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);j(i.getTime())&&(this._endDate=i)}}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 t=this.duration;return t!==null?new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(j(t))return t}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&&j(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Ws{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 Tt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Va{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Tt.AUDIO]:null,[Tt.VIDEO]:null,[Tt.AUDIOVIDEO]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2);let s;i.length===1?s=(e==null?void 0:e.byteRangeEndOffset)||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}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=Ka.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Dn extends Va{constructor(t,e){super(e),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 Ws,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=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!j(this.programDateTime))return null;const t=j(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),i=e.length;if(i>1||i===1&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,i,s,r,o=!1){const{elementaryStreams:a}=this,l=a[t];if(!l){a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:o};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Tt.AUDIO]=null,t[Tt.VIDEO]=null,t[Tt.AUDIOVIDEO]=null}}class Qu extends Va{constructor(t,e,i,s,r){super(i),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 Ws,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const o=t.enumeratedString("BYTERANGE");o&&this.setByteRange(o,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:t}=this;return!!(t.audio||t.video||t.audiovideo)}}const $B=10;class Ou{constructor(t){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=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||e===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?j(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||$B}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return(t=this.fragments)!=null&&t.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 t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Ja(n){return Uint8Array.from(atob(n),t=>t.charCodeAt(0))}function qB(n){const t=$o(n).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function XB(n){const t=function(i,s,r){const o=i[s];i[s]=i[r],i[r]=o};t(n,0,3),t(n,1,2),t(n,4,5),t(n,6,7)}function WB(n){const t=n.split(":");let e=null;if(t[0]==="data"&&t.length===2){const i=t[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const r=s[0]==="base64",o=s[1];r?(i.splice(-1,1),e=Ja(o)):e=qB(o)}}return e}function $o(n){return Uint8Array.from(unescape(encodeURIComponent(n)),t=>t.charCodeAt(0))}const Xi=typeof self<"u"?self:void 0;var xt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Wt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Yc(n){switch(n){case Wt.FAIRPLAY:return xt.FAIRPLAY;case Wt.PLAYREADY:return xt.PLAYREADY;case Wt.WIDEVINE:return xt.WIDEVINE;case Wt.CLEARKEY:return xt.CLEARKEY}}var _s={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Vc(n){if(n===_s.WIDEVINE)return xt.WIDEVINE;if(n===_s.PLAYREADY)return xt.PLAYREADY;if(n===_s.CENC||n===_s.CLEARKEY)return xt.CLEARKEY}function Jc(n){switch(n){case xt.FAIRPLAY:return Wt.FAIRPLAY;case xt.PLAYREADY:return Wt.PLAYREADY;case xt.WIDEVINE:return Wt.WIDEVINE;case xt.CLEARKEY:return Wt.CLEARKEY}}function eo(n){const{drmSystems:t,widevineLicenseUrl:e}=n,i=t?[xt.FAIRPLAY,xt.WIDEVINE,xt.PLAYREADY,xt.CLEARKEY].filter(s=>!!t[s]):[];return!i[xt.WIDEVINE]&&e&&i.push(xt.WIDEVINE),i}const Gu=function(n){return Xi!=null&&(n=Xi.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function jB(n,t,e,i){let s;switch(n){case xt.FAIRPLAY:s=["cenc","sinf"];break;case xt.WIDEVINE:case xt.PLAYREADY:s=["cenc"];break;case xt.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return ZB(s,t,e,i)}function ZB(n,t,e,i){return[{initDataTypes:n,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:e.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Ci(n,t,e){return Uint8Array.prototype.slice?n.slice(t,e):new Uint8Array(Array.prototype.slice.call(n,t,e))}const za=(n,t)=>t+10<=n.length&&n[t]===73&&n[t+1]===68&&n[t+2]===51&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128,Uu=(n,t)=>t+10<=n.length&&n[t]===51&&n[t+1]===68&&n[t+2]===73&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128,Ks=(n,t)=>{const e=t;let i=0;for(;za(n,t);){i+=10;const s=Cr(n,t+6);i+=s,Uu(n,t+10)&&(i+=10),t+=i}if(i>0)return n.subarray(e,e+i)},Cr=(n,t)=>{let e=0;return e=(n[t]&127)<<21,e|=(n[t+1]&127)<<14,e|=(n[t+2]&127)<<7,e|=n[t+3]&127,e},tv=(n,t)=>za(n,t)&&Cr(n,t+6)+10<=n.length-t,$a=n=>{const t=Hu(n);for(let e=0;e<t.length;e++){const i=t[e];if(Nu(i))return ov(i)}},Nu=n=>n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp",ev=n=>{const t=String.fromCharCode(n[0],n[1],n[2],n[3]),e=Cr(n,4),i=10;return{type:t,size:e,data:n.subarray(i,i+e)}},Hu=n=>{let t=0;const e=[];for(;za(n,t);){const i=Cr(n,t+6);t+=10;const s=t+i;for(;t+8<s;){const r=ev(n.subarray(t)),o=iv(r);o&&e.push(o),t+=r.size+10}Uu(n,t)&&(t+=10)}return e},iv=n=>n.type==="PRIV"?sv(n):n.type[0]==="W"?rv(n):nv(n),sv=n=>{if(n.size<2)return;const t=Ge(n.data,!0),e=new Uint8Array(n.data.subarray(t.length+1));return{key:n.type,info:t,data:e.buffer}},nv=n=>{if(n.size<2)return;if(n.type==="TXXX"){let e=1;const i=Ge(n.data.subarray(e),!0);e+=i.length+1;const s=Ge(n.data.subarray(e));return{key:n.type,info:i,data:s}}const t=Ge(n.data.subarray(1));return{key:n.type,data:t}},rv=n=>{if(n.type==="WXXX"){if(n.size<2)return;let e=1;const i=Ge(n.data.subarray(e),!0);e+=i.length+1;const s=Ge(n.data.subarray(e));return{key:n.type,info:i,data:s}}const t=Ge(n.data);return{key:n.type,data:t}},ov=n=>{if(n.data.byteLength===8){const t=new Uint8Array(n.data),e=t[3]&1;let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,e&&(i+=4772185884e-2),Math.round(i)}},Ge=(n,t=!1)=>{const e=av();if(e){const c=e.decode(n);if(t){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const i=n.length;let s,r,o,a="",l=0;for(;l<i;){if(s=n[l++],s===0&&t)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=n[l++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=n[l++],o=n[l++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(o&63)<<0);break}}return a};let io;function av(){if(!navigator.userAgent.includes("PlayStation 4"))return!io&&typeof self.TextDecoder<"u"&&(io=new self.TextDecoder("utf-8")),io}const Fe={hexDump:function(n){let t="";for(let e=0;e<n.length;e++){let i=n[e].toString(16);i.length<2&&(i="0"+i),t+=i}return t}},qn=Math.pow(2,32)-1,lv=[].push,Ku={video:1,audio:2,id3:3,text:4};function Nt(n){return String.fromCharCode.apply(null,n)}function Yu(n,t){const e=n[t]<<8|n[t+1];return e<0?65536+e:e}function st(n,t){const e=Vu(n,t);return e<0?4294967296+e:e}function zc(n,t){let e=st(n,t);return e*=Math.pow(2,32),e+=st(n,t+4),e}function Vu(n,t){return n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3]}function so(n,t,e){n[t]=e>>24,n[t+1]=e>>16&255,n[t+2]=e>>8&255,n[t+3]=e&255}function cv(n){const t=n.byteLength;for(let e=0;e<t;){const i=st(n,e);if(i>8&&n[e+4]===109&&n[e+5]===111&&n[e+6]===111&&n[e+7]===102)return!0;e=i>1?e+i:t}return!1}function ft(n,t){const e=[];if(!t.length)return e;const i=n.byteLength;for(let s=0;s<i;){const r=st(n,s),o=Nt(n.subarray(s+4,s+8)),a=r>1?s+r:i;if(o===t[0])if(t.length===1)e.push(n.subarray(s+8,a));else{const l=ft(n.subarray(s+8,a),t.slice(1));l.length&&lv.apply(e,l)}s=a}return e}function hv(n){const t=[],e=n[0];let i=8;const s=st(n,i);i+=4;let r=0,o=0;e===0?(r=st(n,i),o=st(n,i+4),i+=8):(r=zc(n,i),o=zc(n,i+8),i+=16),i+=2;let a=n.length+o;const l=Yu(n,i);i+=2;for(let c=0;c<l;c++){let h=i;const A=st(n,h);h+=4;const u=A&2147483647;if((A&2147483648)>>>31===1)return R.warn("SIDX has hierarchical references (not supported)"),null;const f=st(n,h);h+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/s,start:a,end:a+u-1}}),a+=u,h+=4,i=h}return{earliestPresentationTime:r,timescale:s,version:e,referencesCount:l,references:t}}function Ju(n){const t=[],e=ft(n,["moov","trak"]);for(let s=0;s<e.length;s++){const r=e[s],o=ft(r,["tkhd"])[0];if(o){let a=o[0];const l=st(o,a===0?12:20),c=ft(r,["mdia","mdhd"])[0];if(c){a=c[0];const h=st(c,a===0?12:20),A=ft(r,["mdia","hdlr"])[0];if(A){const u=Nt(A.subarray(8,12)),d={soun:Tt.AUDIO,vide:Tt.VIDEO}[u];if(d){const f=ft(r,["mdia","minf","stbl","stsd"])[0],g=Av(f);t[l]={timescale:h,type:d},t[d]=$t({timescale:h,id:l},g)}}}}}return ft(n,["moov","mvex","trex"]).forEach(s=>{const r=st(s,4),o=t[r];o&&(o.default={duration:st(s,12),flags:st(s,20)})}),t}function Av(n){const t=n.subarray(8),e=t.subarray(86),i=Nt(t.subarray(4,8));let s=i;const r=i==="enca"||i==="encv";if(r){const a=ft(t,[i])[0].subarray(i==="enca"?28:78);ft(a,["sinf"]).forEach(c=>{const h=ft(c,["schm"])[0];if(h){const A=Nt(h.subarray(4,8));if(A==="cbcs"||A==="cenc"){const u=ft(c,["frma"])[0];u&&(s=Nt(u))}}})}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const o=ft(e,["avcC"])[0];s+="."+fn(o[1])+fn(o[2])+fn(o[3]);break}case"mp4a":{const o=ft(t,[i])[0],a=ft(o.subarray(28),["esds"])[0];if(a&&a.length>12){let l=4;if(a[l++]!==3)break;l=no(a,l),l+=2;const c=a[l++];if(c&128&&(l+=2),c&64&&(l+=a[l++]),a[l++]!==4)break;l=no(a,l);const h=a[l++];if(h===64)s+="."+fn(h);else break;if(l+=12,a[l++]!==5)break;l=no(a,l);const A=a[l++];let u=(A&248)>>3;u===31&&(u+=1+((A&7)<<3)+((a[l]&224)>>5)),s+="."+u}break}case"hvc1":case"hev1":{const o=ft(e,["hvcC"])[0],a=o[1],l=["","A","B","C"][a>>6],c=a&31,h=st(o,2),A=(a&32)>>5?"H":"L",u=o[12],d=o.subarray(6,12);s+="."+l+c,s+="."+h.toString(16).toUpperCase(),s+="."+A+u;let f="";for(let g=d.length;g--;){const p=d[g];(p||f)&&(f="."+p.toString(16).toUpperCase()+f)}s+=f;break}case"dvh1":case"dvhe":{const o=ft(e,["dvcC"])[0],a=o[2]>>1&127,l=o[2]<<5&32|o[3]>>3&31;s+="."+we(a)+"."+we(l);break}case"vp09":{const o=ft(e,["vpcC"])[0],a=o[4],l=o[5],c=o[6]>>4&15;s+="."+we(a)+"."+we(l)+"."+we(c);break}case"av01":{const o=ft(e,["av1C"])[0],a=o[1]>>>5,l=o[1]&31,c=o[2]>>>7?"H":"M",h=(o[2]&64)>>6,A=(o[2]&32)>>5,u=a===2&&h?A?12:10:h?10:8,d=(o[2]&16)>>4,f=(o[2]&8)>>3,g=(o[2]&4)>>2,p=o[2]&3;s+="."+a+"."+we(l)+c+"."+we(u)+"."+d+"."+f+g+p+"."+we(1)+"."+we(1)+"."+we(1)+"."+0;break}}return{codec:s,encrypted:r}}function no(n,t){const e=t+5;for(;n[t++]&128&&t<e;);return t}function fn(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function we(n){return(n<10?"0":"")+n}function uv(n,t){if(!n||!t)return n;const e=t.keyId;return e&&t.isCommonEncryption&&ft(n,["moov","trak"]).forEach(s=>{const o=ft(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let a=ft(o,["enca"]);const l=a.length>0;l||(a=ft(o,["encv"])),a.forEach(c=>{const h=l?c.subarray(28):c.subarray(78);ft(h,["sinf"]).forEach(u=>{const d=zu(u);if(d){const f=d.subarray(8,24);f.some(g=>g!==0)||(R.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Fe.hexDump(f)} -> ${Fe.hexDump(e)}`),d.set(e,8))}})})}),n}function zu(n){const t=ft(n,["schm"])[0];if(t){const e=Nt(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return ft(n,["schi","tenc"])[0]}return null}function dv(n,t){return ft(t,["moof","traf"]).reduce((e,i)=>{const s=ft(i,["tfdt"])[0],r=s[0],o=ft(i,["tfhd"]).reduce((a,l)=>{const c=st(l,4),h=n[c];if(h){let A=st(s,4);if(r===1){if(A===qn)return R.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),a;A*=qn+1,A+=st(s,8)}const u=h.timescale||9e4,d=A/u;if(j(d)&&(a===null||d<a))return d}return a},null);return o!==null&&j(o)&&(e===null||o<e)?o:e},null)}function fv(n,t){let e=0,i=0,s=0;const r=ft(n,["moof","traf"]);for(let o=0;o<r.length;o++){const a=r[o],l=ft(a,["tfhd"])[0],c=st(l,4),h=t[c];if(!h)continue;const A=h.default,u=st(l,0)|(A==null?void 0:A.flags);let d=A==null?void 0:A.duration;u&8&&(u&2?d=st(l,12):d=st(l,8));const f=h.timescale||9e4,g=ft(a,["trun"]);for(let p=0;p<g.length;p++){if(e=gv(g[p]),!e&&d){const m=st(g[p],4);e=d*m}h.type===Tt.VIDEO?i+=e/f:h.type===Tt.AUDIO&&(s+=e/f)}}if(i===0&&s===0){let o=1/0,a=0,l=0;const c=ft(n,["sidx"]);for(let h=0;h<c.length;h++){const A=hv(c[h]);if(A!=null&&A.references){o=Math.min(o,A.earliestPresentationTime/A.timescale);const u=A.references.reduce((d,f)=>d+f.info.duration||0,0);a=Math.max(a,u+A.earliestPresentationTime/A.timescale),l=a-o}}if(l&&j(l))return l}return i||s}function gv(n){const t=st(n,0);let e=8;t&1&&(e+=4),t&4&&(e+=4);let i=0;const s=st(n,4);for(let r=0;r<s;r++){if(t&256){const o=st(n,e);i+=o,e+=4}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4)}return i}function mv(n,t,e){ft(t,["moof","traf"]).forEach(i=>{ft(i,["tfhd"]).forEach(s=>{const r=st(s,4),o=n[r];if(!o)return;const a=o.timescale||9e4;ft(i,["tfdt"]).forEach(l=>{const c=l[0],h=e*a;if(h){let A=st(l,4);if(c===0)A-=h,A=Math.max(A,0),so(l,4,A);else{A*=Math.pow(2,32),A+=st(l,8),A-=h,A=Math.max(A,0);const u=Math.floor(A/(qn+1)),d=Math.floor(A%(qn+1));so(l,4,u),so(l,8,d)}}})})})}function pv(n){const t={valid:null,remainder:null},e=ft(n,["moof"]);if(e.length<2)return t.remainder=n,t;const i=e[e.length-1];return t.valid=Ci(n,0,i.byteOffset-8),t.remainder=Ci(n,i.byteOffset-8),t}function ge(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function $c(n,t){const e=[],i=t.samples,s=t.timescale,r=t.id;let o=!1;return ft(i,["moof"]).map(l=>{const c=l.byteOffset-8;ft(l,["traf"]).map(A=>{const u=ft(A,["tfdt"]).map(d=>{const f=d[0];let g=st(d,4);return f===1&&(g*=Math.pow(2,32),g+=st(d,8)),g/s})[0];return u!==void 0&&(n=u),ft(A,["tfhd"]).map(d=>{const f=st(d,4),g=st(d,0)&16777215,p=(g&1)!==0,m=(g&2)!==0,C=(g&8)!==0;let E=0;const v=(g&16)!==0;let y=0;const S=(g&32)!==0;let T=8;f===r&&(p&&(T+=8),m&&(T+=4),C&&(E=st(d,T),T+=4),v&&(y=st(d,T),T+=4),S&&(T+=4),t.type==="video"&&(o=Ev(t.codec)),ft(A,["trun"]).map(x=>{const F=x[0],_=st(x,0)&16777215,w=(_&1)!==0;let U=0;const O=(_&4)!==0,W=(_&256)!==0;let K=0;const q=(_&512)!==0;let Z=0;const rt=(_&1024)!==0,V=(_&2048)!==0;let G=0;const H=st(x,4);let X=8;w&&(U=st(x,X),X+=4),O&&(X+=4);let Y=U+c;for(let D=0;D<H;D++){if(W?(K=st(x,X),X+=4):K=E,q?(Z=st(x,X),X+=4):Z=y,rt&&(X+=4),V&&(F===0?G=st(x,X):G=Vu(x,X),X+=4),t.type===Tt.VIDEO){let it=0;for(;it<Z;){const at=st(i,Y);if(Y+=4,Cv(o,i[Y])){const ht=i.subarray(Y,Y+at);$u(ht,o?2:1,n+G/s,e)}Y+=at,it+=at+4}}n+=K/s}}))})})}),e}function Ev(n){if(!n)return!1;const t=n.indexOf("."),e=t<0?n:n.substring(0,t);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Cv(n,t){if(n){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function $u(n,t,e,i){const s=qu(n);let r=0;r+=t;let o=0,a=0,l=0;for(;r<s.length;){o=0;do{if(r>=s.length)break;l=s[r++],o+=l}while(l===255);a=0;do{if(r>=s.length)break;l=s[r++],a+=l}while(l===255);const c=s.length-r;let h=r;if(a<c)r+=a;else if(a>c){R.error(`Malformed SEI payload. ${a} is too small, only ${c} bytes left to parse.`);break}if(o===4){if(s[h++]===181){const u=Yu(s,h);if(h+=2,u===49){const d=st(s,h);if(h+=4,d===1195456820){const f=s[h++];if(f===3){const g=s[h++],p=31&g,m=64&g,C=m?2+p*3:0,E=new Uint8Array(C);if(m){E[0]=g;for(let v=1;v<C;v++)E[v]=s[h++]}i.push({type:f,payloadType:o,pts:e,bytes:E})}}}}}else if(o===5&&a>16){const A=[];for(let f=0;f<16;f++){const g=s[h++].toString(16);A.push(g.length==1?"0"+g:g),(f===3||f===5||f===7||f===9)&&A.push("-")}const u=a-16,d=new Uint8Array(u);for(let f=0;f<u;f++)d[f]=s[h++];i.push({payloadType:o,pts:e,uuid:A.join(""),userData:Ge(d),userDataBytes:d})}}}function qu(n){const t=n.byteLength,e=[];let i=1;for(;i<t-2;)n[i]===0&&n[i+1]===0&&n[i+2]===3?(e.push(i+2),i+=2):i++;if(e.length===0)return n;const s=t-e.length,r=new Uint8Array(s);let o=0;for(i=0;i<s;o++,i++)o===e[0]&&(o++,e.shift()),r[i]=n[o];return r}function Iv(n){const t=n[0];let e="",i="",s=0,r=0,o=0,a=0,l=0,c=0;if(t===0){for(;Nt(n.subarray(c,c+1))!=="\0";)e+=Nt(n.subarray(c,c+1)),c+=1;for(e+=Nt(n.subarray(c,c+1)),c+=1;Nt(n.subarray(c,c+1))!=="\0";)i+=Nt(n.subarray(c,c+1)),c+=1;i+=Nt(n.subarray(c,c+1)),c+=1,s=st(n,12),r=st(n,16),a=st(n,20),l=st(n,24),c=28}else if(t===1){c+=4,s=st(n,c),c+=4;const A=st(n,c);c+=4;const u=st(n,c);for(c+=4,o=2**32*A+u,UB(o)||(o=Number.MAX_SAFE_INTEGER,R.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=st(n,c),c+=4,l=st(n,c),c+=4;Nt(n.subarray(c,c+1))!=="\0";)e+=Nt(n.subarray(c,c+1)),c+=1;for(e+=Nt(n.subarray(c,c+1)),c+=1;Nt(n.subarray(c,c+1))!=="\0";)i+=Nt(n.subarray(c,c+1)),c+=1;i+=Nt(n.subarray(c,c+1)),c+=1}const h=n.subarray(c,n.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:o,presentationTimeDelta:r,eventDuration:a,id:l,payload:h}}function yv(n,...t){const e=t.length;let i=8,s=e;for(;s--;)i+=t[s].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(n,4),s=0,i=8;s<e;s++)r.set(t[s],i),i+=t[s].byteLength;return r}function Bv(n,t,e){if(n.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let r;i>0?(r=new Uint8Array(4),t.length>0&&new DataView(r.buffer).setUint32(0,t.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(o.buffer).setUint32(0,e.byteLength,!1),yv([112,115,115,104],new Uint8Array([i,0,0,0]),n,r,s,o,e||new Uint8Array)}function vv(n){const t=[];if(n instanceof ArrayBuffer){const e=n.byteLength;let i=0;for(;i+32<e;){const s=new DataView(n,i),r=Sv(s);t.push(r),i+=r.size}}return t}function Sv(n){const t=n.getUint32(0),e=n.byteOffset,i=n.byteLength;if(i<t)return{offset:e,size:i};if(n.getUint32(4)!==1886614376)return{offset:e,size:t};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:e,size:t};const o=n.buffer,a=Fe.hexDump(new Uint8Array(o,e+12,16)),l=n.getUint32(28);let c=null,h=null;if(r===0){if(t-32<l||l<22)return{offset:e,size:t};h=new Uint8Array(o,e+32,l)}else if(r===1){if(!l||i<e+32+l*16+16)return{offset:e,size:t};c=[];for(let A=0;A<l;A++)c.push(new Uint8Array(o,e+32+A*16,16))}return{version:r,systemId:a,kids:c,data:h,offset:e,size:t}}let gn={};class Wi{static clearKeyUriToKeyIdMap(){gn={}}constructor(t,e,i,s=[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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&t!=="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 Wt.FAIRPLAY:case Wt.WIDEVINE:case Wt.PLAYREADY:case Wt.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof t!="number"&&(this.method==="AES-128"&&!this.iv&&R.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=Tv(t);return new Wi(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=WB(this.uri);if(e)switch(this.keyFormat){case Wt.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case Wt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Bv(i,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(s)),o=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(c){const h=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(h){const A=Ja(h).subarray(0,16);XB(A),this.keyId=A}}break}default:{let i=e.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=gn[this.uri];if(!i){const s=Object.keys(gn).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),gn[this.uri]=i}this.keyId=i}return this}}function Tv(n){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=n>>8*(15-e)&255;return t}const Xu=/\{\$([a-zA-Z0-9-_]+)\}/g;function qc(n){return Xu.test(n)}function te(n,t,e){if(n.variableList!==null||n.hasVariableRefs)for(let i=e.length;i--;){const s=e[i],r=t[s];r&&(t[s]=qo(n,r))}}function qo(n,t){if(n.variableList!==null||n.hasVariableRefs){const e=n.variableList;return t.replace(Xu,i=>{const s=i.substring(2,i.length-1),r=e==null?void 0:e[s];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):r})}return t}function Xc(n,t,e){let i=n.variableList;i||(n.variableList=i={});let s,r;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const o=new self.URL(e).searchParams;if(o.has(s))r=o.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${e}"`)}catch(o){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else s=t.NAME,r=t.VALUE;s in i?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=r||""}function _v(n,t,e){const i=t.IMPORT;if(e&&i in e){let s=n.variableList;s||(n.variableList=s={}),s[i]=e[i]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function ai(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function xv(n){return typeof self<"u"&&n===self.ManagedMediaSource}const Xn={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 Dv(n,t){const e=Xn[t];return!!e&&!!e[n.slice(0,4)]}function ro(n,t,e=!0){return!n.split(",").some(i=>!Wu(i,t,e))}function Wu(n,t,e=!0){var i;const s=ai(e);return(i=s==null?void 0:s.isTypeSupported(Ys(n,t)))!=null?i:!1}function Ys(n,t){return`${t}/mp4;codecs="${n}"`}function Wc(n){if(n){const t=n.substring(0,4);return Xn.video[t]}return 2}function Wn(n){return n.split(",").reduce((t,e)=>{const i=Xn.video[e];return i?(i*2+t)/(t?3:2):(Xn.audio[e]+t)/(t?2:1)},0)}const oo={};function Rv(n,t=!0){if(oo[n])return oo[n];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[n];for(let i=0;i<e.length;i++)if(Wu(e[i],"audio",t))return oo[n]=e[i],e[i];return n}const wv=/flac|opus/i;function jn(n,t=!0){return n.replace(wv,e=>Rv(e.toLowerCase(),t))}function jc(n,t){return n&&n!=="mp4a"?n:t&&t.split(",")[0]}function Lv(n){const t=n.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");if(i.length>2){let s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[e]=s}}return t.join(",")}const Zc=/#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,th=/#EXT-X-MEDIA:(.*)/g,bv=/^#EXT(?:INF|-X-TARGETDURATION):/m,eh=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"),Fv=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 ke{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return Ka.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return bv.test(t)}static parseMasterPlaylist(t,e){const i=qc(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];Zc.lastIndex=0;let o;for(;(o=Zc.exec(t))!=null;)if(o[1]){var a;const c=new bt(o[1]);te(s,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=qo(s,o[2]),A={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:ke.resolve(h,e)},u=c.decimalResolution("RESOLUTION");u&&(A.width=u.width,A.height=u.height),Mv(c.CODECS,A),(a=A.unknownCodecs)!=null&&a.length||r.push(A),s.levels.push(A)}else if(o[3]){const c=o[3],h=o[4];switch(c){case"SESSION-DATA":{const A=new bt(h);te(s,A,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=A["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=A);break}case"SESSION-KEY":{const A=ih(h,e,s);A.encrypted&&A.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(A)):R.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const A=new bt(h);te(s,A,["NAME","VALUE","QUERYPARAM"]),Xc(s,A,e)}break}case"CONTENT-STEERING":{const A=new bt(h);te(s,A,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:ke.resolve(A["SERVER-URI"],e),pathwayId:A["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=sh(h);break}}}const l=r.length>0&&r.length<s.levels.length;return s.levels=l?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let s;const r={},o=i.levels,a={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(th.lastIndex=0;(s=th.exec(t))!==null;){const c=new bt(s[1]),h=c.TYPE;if(h){const A=a[h],u=r[h]||[];r[h]=u,te(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const d=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||d||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:d,url:c.URI?ke.resolve(c.URI,e):""};if(f&&(C.assocLang=f),g&&(C.channels=g),p&&(C.characteristics=p),m&&(C.instreamId=m),A!=null&&A.length){const E=ke.findGroup(A,C.groupId)||A[0];nh(C,E,"audioCodec"),nh(C,E,"textCodec")}u.push(C)}}return r}static parseLevelPlaylist(t,e,i,s,r,o){const a=new Ou(e),l=a.fragments;let c=null,h=0,A=0,u=0,d=0,f=null,g=new Dn(s,e),p,m,C,E=-1,v=!1,y=null;for(eh.lastIndex=0,a.m3u8=t,a.hasVariableRefs=qc(t);(p=eh.exec(t))!==null;){v&&(v=!1,g=new Dn(s,e),g.start=u,g.sn=h,g.cc=d,g.level=i,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,y&&(g.setByteRange(y),y=null)));const F=p[1];if(F){g.duration=parseFloat(F);const _=(" "+p[2]).slice(1);g.title=_||null,g.tagList.push(_?["INF",F,_]:["INF",F])}else if(p[3]){if(j(g.duration)){g.start=u,C&&ah(g,C,a),g.sn=h,g.level=i,g.cc=d,l.push(g);const _=(" "+p[3]).slice(1);g.relurl=qo(a,_),rh(g,f),f=g,u+=g.duration,h++,A=0,v=!0}}else if(p[4]){const _=(" "+p[4]).slice(1);f?g.setByteRange(_,f):g.setByteRange(_)}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(Fv),!p){R.warn("No matches on slow regex match for level playlist!");continue}for(m=1;m<p.length&&!(typeof p[m]<"u");m++);const _=(" "+p[m]).slice(1),w=(" "+p[m+1]).slice(1),U=p[m+2]?(" "+p[m+2]).slice(1):"";switch(_){case"PLAYLIST-TYPE":a.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(w);break;case"SKIP":{const O=new bt(w);te(a,O,["RECENTLY-REMOVED-DATERANGES"]);const W=O.decimalInteger("SKIPPED-SEGMENTS");if(j(W)){a.skippedSegments=W;for(let q=W;q--;)l.unshift(null);h+=W}const K=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(a.recentlyRemovedDateranges=K.split(" "));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(w),1);break;case"VERSION":a.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(w||U)&&g.tagList.push(U?[w,U]:[w]);break;case"DISCONTINUITY":d++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([_]);break;case"BITRATE":g.tagList.push([_,w]);break;case"DATERANGE":{const O=new bt(w);te(a,O,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),te(a,O,O.clientAttrs);const W=new Ya(O,a.dateRanges[O.ID]);W.isValid||a.skippedSegments?a.dateRanges[W.id]=W:R.warn(`Ignoring invalid DATERANGE tag: "${w}"`),g.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const O=new bt(w);te(a,O,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in O?_v(a,O,o):Xc(a,O,e)}break}case"DISCONTINUITY-SEQUENCE":d=parseInt(w);break;case"KEY":{const O=ih(w,e,a);if(O.isSupported()){if(O.method==="NONE"){C=void 0;break}C||(C={}),C[O.keyFormat]&&(C=Qt({},C)),C[O.keyFormat]=O}else R.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${w}"`);break}case"START":a.startTimeOffset=sh(w);break;case"MAP":{const O=new bt(w);if(te(a,O,["BYTERANGE","URI"]),g.duration){const W=new Dn(s,e);oh(W,O,i,C),c=W,g.initSegment=c,c.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=c.rawProgramDateTime)}else{const W=g.byteRangeEndOffset;if(W){const K=g.byteRangeStartOffset;y=`${W-K}@${K}`}else y=null;oh(g,O,i,C),c=g,v=!0}break}case"SERVER-CONTROL":{const O=new bt(w);a.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),a.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const O=new bt(w);a.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=a.partList;O||(O=a.partList=[]);const W=A>0?O[O.length-1]:void 0,K=A++,q=new bt(w);te(a,q,["BYTERANGE","URI"]);const Z=new Qu(q,g,e,K,W);O.push(Z),g.duration+=Z.duration;break}case"PRELOAD-HINT":{const O=new bt(w);te(a,O,["URI"]),a.preloadHint=O;break}case"RENDITION-REPORT":{const O=new bt(w);te(a,O,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(O);break}default:R.warn(`line parsed but not handled: ${p}`);break}}}f&&!f.relurl?(l.pop(),u-=f.duration,a.partList&&(a.fragmentHint=f)):a.partList&&(rh(g,f),g.cc=d,a.fragmentHint=g,C&&ah(g,C,a));const S=l.length,T=l[0],x=l[S-1];if(u+=a.skippedSegments*a.targetduration,u>0&&S&&x){a.averagetargetduration=u/S;const F=x.sn;a.endSN=F!=="initSegment"?F:0,a.live||(x.endList=!0),T&&(a.startCC=T.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(u+=a.fragmentHint.duration),a.totalduration=u,a.endCC=d,E>0&&Pv(l,E),a}}function ih(n,t,e){var i,s;const r=new bt(n);te(e,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(i=r.METHOD)!=null?i:"",a=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(s=r.KEYFORMAT)!=null?s:"identity";a&&r.IV&&!l&&R.error(`Invalid IV: ${r.IV}`);const A=a?ke.resolve(a,t):"",u=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Wi(o,A,h,u,l)}function sh(n){const e=new bt(n).decimalFloatingPoint("TIME-OFFSET");return j(e)?e:null}function Mv(n,t){let e=(n||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=e.filter(r=>Dv(r,i));s.length&&(t[`${i}Codec`]=s.join(","),e=e.filter(r=>s.indexOf(r)===-1))}),t.unknownCodecs=e}function nh(n,t,e){const i=t[e];i&&(n[e]=i)}function Pv(n,t){let e=n[t];for(let i=t;i--;){const s=n[i];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function rh(n,t){n.rawProgramDateTime?n.programDateTime=Date.parse(n.rawProgramDateTime):t!=null&&t.programDateTime&&(n.programDateTime=t.endProgramDateTime),j(n.programDateTime)||(n.programDateTime=null,n.rawProgramDateTime=null)}function oh(n,t,e,i){n.relurl=t.URI,t.BYTERANGE&&n.setByteRange(t.BYTERANGE),n.level=e,n.sn="initSegment",i&&(n.levelkeys=i),n.initSegment=null}function ah(n,t,e){n.levelkeys=t;const{encryptedFragments:i}=e;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&i.push(n)}var Ct={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},et={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function lh(n){const{type:t}=n;switch(t){case Ct.AUDIO_TRACK:return et.AUDIO;case Ct.SUBTITLE_TRACK:return et.SUBTITLE;default:return et.MAIN}}function ao(n,t){let e=n.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class kv{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=i||s,o=new r(e);return this.loaders[t.type]=o,o}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ct.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:o,deliveryDirectives:a}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:Ct.LEVEL,url:o,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:Ct.AUDIO_TRACK,url:r,deliveryDirectives:o})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:Ct.SUBTITLE_TRACK,url:r,deliveryDirectives:o})}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const c=s.context;if(c&&c.url===t.url&&c.level===t.level){R.trace("[playlist-loader]: playlist request ongoing");return}R.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let r;if(t.type===Ct.MANIFEST?r=i.manifestLoadPolicy.default:r=Qt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),j((e=t.deliveryDirectives)==null?void 0:e.part)){let c;if(t.type===Ct.LEVEL&&t.level!==null?c=this.hls.levels[t.level].details:t.type===Ct.AUDIO_TRACK&&t.id!==null?c=this.hls.audioTracks[t.id].details:t.type===Ct.SUBTITLE_TRACK&&t.id!==null&&(c=this.hls.subtitleTracks[t.id].details),c){const h=c.partTarget,A=c.targetduration;if(h&&A){const u=Math.max(h*3,A*.8)*1e3;r=Qt({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,h,A,u)=>{const d=this.getInternalLoader(A);this.resetInternalLoader(A.type);const f=c.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,A,new Error("no EXTM3U delimiter"),u||null,h);return}h.parsing.start=performance.now(),ke.isMediaPlaylist(f)?this.handleTrackOrLevelPlaylist(c,h,A,u||null,d):this.handleMasterPlaylist(c,h,A,u)},onError:(c,h,A,u)=>{this.handleNetworkError(h,A,!1,c,u)},onTimeout:(c,h,A)=>{this.handleNetworkError(h,A,!0,void 0,c)}};s.load(t,a,l)}handleMasterPlaylist(t,e,i,s){const r=this.hls,o=t.data,a=ao(t,i),l=ke.parseMasterPlaylist(o,a);if(l.playlistParsingError){this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}const{contentSteering:c,levels:h,sessionData:A,sessionKeys:u,startTimeOffset:d,variableList:f}=l;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=ke.parseMasterPlaylistMedia(o,a,l);g.length&&!g.some(E=>!E.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(R.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 bt({}),bitrate:0,url:""})),r.trigger(I.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:c,url:a,stats:e,networkDetails:s,sessionData:A,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,s,r){const o=this.hls,{id:a,level:l,type:c}=i,h=ao(t,i),A=0,u=j(l)?l:j(a)?a:0,d=lh(i),f=ke.parseLevelPlaylist(t.data,h,u,d,A,this.variableList);if(c===Ct.MANIFEST){const g={attrs:new bt({}),bitrate:0,details:f,name:"",url:h};o.trigger(I.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,t,e,i,s,r)}handleManifestParsingError(t,e,i,s,r){this.hls.trigger(I.ERROR,{type:ot.NETWORK_ERROR,details:M.MANIFEST_PARSING_ERROR,fatal:e.type===Ct.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:r})}handleNetworkError(t,e,i=!1,s,r){let o=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===Ct.LEVEL?o+=`: ${t.level} id: ${t.id}`:(t.type===Ct.AUDIO_TRACK||t.type===Ct.SUBTITLE_TRACK)&&(o+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(o);R.warn(`[playlist-loader]: ${o}`);let l=M.UNKNOWN,c=!1;const h=this.getInternalLoader(t);switch(t.type){case Ct.MANIFEST:l=i?M.MANIFEST_LOAD_TIMEOUT:M.MANIFEST_LOAD_ERROR,c=!0;break;case Ct.LEVEL:l=i?M.LEVEL_LOAD_TIMEOUT:M.LEVEL_LOAD_ERROR,c=!1;break;case Ct.AUDIO_TRACK:l=i?M.AUDIO_TRACK_LOAD_TIMEOUT:M.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Ct.SUBTITLE_TRACK:l=i?M.SUBTITLE_TRACK_LOAD_TIMEOUT:M.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(t.type);const A={type:ot.NETWORK_ERROR,details:l,fatal:c,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(s){const u=(e==null?void 0:e.url)||t.url;A.response=$t({url:u,data:void 0},s)}this.hls.trigger(I.ERROR,A)}handlePlaylistLoaded(t,e,i,s,r,o){const a=this.hls,{type:l,level:c,id:h,groupId:A,deliveryDirectives:u}=s,d=ao(e,s),f=lh(s),g=typeof s.level=="number"&&f===et.MAIN?c:void 0;if(!t.fragments.length){const m=new Error("No Segments found in Playlist");a.trigger(I.ERROR,{type:ot.NETWORK_ERROR,details:M.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:m,reason:m.message,response:e,context:s,level:g,parent:f,networkDetails:r,stats:i});return}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const p=t.playlistParsingError;if(p){a.trigger(I.ERROR,{type:ot.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:e,context:s,level:g,parent:f,networkDetails:r,stats:i});return}switch(t.live&&o&&(o.getCacheAge&&(t.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case Ct.MANIFEST:case Ct.LEVEL:a.trigger(I.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:u});break;case Ct.AUDIO_TRACK:a.trigger(I.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:A||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case Ct.SUBTITLE_TRACK:a.trigger(I.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:A||"",stats:i,networkDetails:r,deliveryDirectives:u});break}}}function ju(n,t){let e;try{e=new Event("addtrack")}catch{e=document.createEvent("Event"),e.initEvent("addtrack",!1,!1)}e.track=n,t.dispatchEvent(e)}function Zu(n,t){const e=n.mode;if(e==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(t.id))try{if(n.addCue(t),!n.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){R.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,n.addCue(s)}catch(s){R.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}e==="disabled"&&(n.mode=e)}function Hi(n){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues)for(let e=n.cues.length;e--;)n.removeCue(n.cues[e]);t==="disabled"&&(n.mode=t)}function Xo(n,t,e,i){const s=n.mode;if(s==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=Ov(n.cues,t,e);for(let o=0;o<r.length;o++)(!i||i(r[o]))&&n.removeCue(r[o])}s==="disabled"&&(n.mode=s)}function Qv(n,t){if(t<n[0].startTime)return 0;const e=n.length-1;if(t>n[e].endTime)return-1;let i=0,s=e;for(;i<=s;){const r=Math.floor((s+i)/2);if(t<n[r].startTime)s=r-1;else if(t>n[r].startTime&&i<e)i=r+1;else return r}return n[i].startTime-t<t-n[s].startTime?i:s}function Ov(n,t,e){const i=[],s=Qv(n,t);if(s>-1)for(let r=s,o=n.length;r<o;r++){const a=n[r];if(a.startTime>=t&&a.endTime<=e)i.push(a);else if(a.startTime>e)return i}return i}function Rn(n){const t=[];for(let e=0;e<n.length;e++){const i=n[e];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&t.push(n[e])}return t}var ue={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const Gv=.25;function Wo(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ch(n,t,e,i,s){let r=new n(t,e,"");try{r.value=i,s&&(r.type=s)}catch{r=new n(t,e,JSON.stringify(s?$t({type:s},i):i))}return r}const mn=(()=>{const n=Wo();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function lo(n,t){return n.getTime()/1e3-t}function Uv(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Nv{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(Hi(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if(i.kind==="metadata"&&i.label==="id3")return ju(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Wo();if(o)for(let a=0;a<r.length;a++){const l=r[a].type;if(l===ue.emsg&&!i||!s)continue;const c=Hu(r[a].data);if(c){const h=r[a].pts;let A=h+r[a].duration;A>mn&&(A=mn),A-h<=0&&(A=h+Gv);for(let d=0;d<c.length;d++){const f=c[d];if(!Nu(f)){this.updateId3CueEnds(h,l);const g=ch(o,h,A,f,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(t,e){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const o=s[r];o.type===e&&o.startTime<t&&o.endTime===mn&&(o.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(r&&(a||l)){let c;s==="audio"?c=h=>h.type===ue.audioId3&&l:s==="video"?c=h=>h.type===ue.emsg&&a:c=h=>h.type===ue.audioId3&&l||h.type===ue.emsg&&a,Xo(r,e,i,c)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:r}=e,o=Object.keys(r);if(s){const h=Object.keys(i).filter(A=>!o.includes(A));for(let A=h.length;A--;){const u=h[A];Object.keys(i[u].cues).forEach(d=>{s.removeCue(i[u].cues[d])}),delete i[u]}}const a=e.fragments[e.fragments.length-1];if(o.length===0||!j(a==null?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=a.programDateTime/1e3-a.start,c=Wo();for(let h=0;h<o.length;h++){const A=o[h],u=r[A],d=lo(u.startDate,l),f=i[A],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1,m=mn;const C=u.endDate;if(C)m=lo(C,l),p=!0;else if(u.endOnNext&&!p){const v=o.reduce((y,S)=>{if(S!==u.id){const T=r[S];if(T.class===u.class&&T.startDate>u.startDate&&(!y||u.startDate<y.startDate))return T}return y},null);v&&(m=lo(v.startDate,l),p=!0)}const E=Object.keys(u.attr);for(let v=0;v<E.length;v++){const y=E[v];if(!JB(y))continue;const S=g[y];if(S)p&&!f.durationKnown&&(S.endTime=m);else if(c){let T=u.attr[y];zB(y)&&(T=Uv(T));const x=ch(c,d,m,{key:y,data:T},ue.dateRange);x&&(x.id=A,this.id3Track.addCue(x),g[y]=x)}}i[A]={cues:g,dateRange:u,durationKnown:p}}}}class Hv{constructor(t){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=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(t===null)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let c=a&&i||e;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:o*s);const h=s;return c+Math.min(this.stallCount*1,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(t===null||e===null||i===null)return null;const s=i.edge,r=t-e-this.edgeStalled,o=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,r),a)}get drift(){const{levelDetails:t}=this;return t===null?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(t===null)return 0;const e=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(I.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(I.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===M.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&R.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||r===1||!e.live)return;const o=this.targetLatency;if(o===null)return;const a=i-o,l=Math.min(this.maxLatency,o+e.targetduration);if(a<l&&a>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),A=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(h,Math.max(1,A))}else t.playbackRate!==1&&t.playbackRate!==0&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const jo=["NONE","TYPE-0","TYPE-1",null];function Kv(n){return jo.indexOf(n)>-1}const Zn=["SDR","PQ","HLG"];function Yv(n){return!!n&&Zn.indexOf(n)>-1}var Ps={No:"",Yes:"YES",v2:"v2"};function hh(n){const{canSkipUntil:t,canSkipDateRanges:e,age:i}=n,s=i<t/2;return t&&s?e?Ps.v2:Ps.Yes:Ps.No}class Zo{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return this.msn!==void 0&&e.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Bi{constructor(t){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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return Ah(this._audioGroups,t)}hasSubtitleGroup(t){return Ah(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if(t==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(e)===-1&&i.push(e)}else if(t==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(e)===-1&&i.push(e)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function Ah(n,t){return!t||!n?!1:n.indexOf(t)!==-1}function co(n,t){const e=t.startPTS;if(j(e)){let i=0,s;t.sn>n.sn?(i=e-n.start,s=n):(i=n.start-e,s=t),s.duration!==i&&(s.duration=i)}else t.sn>n.sn?n.cc===t.cc&&n.minEndPTS?t.start=n.start+(n.minEndPTS-n.start):t.start=n.start+n.duration:t.start=Math.max(n.start-t.duration,0)}function td(n,t,e,i,s,r){i-e<=0&&(R.warn("Fragment should have a positive duration",t),i=e+t.duration,r=s+t.duration);let a=e,l=i;const c=t.startPTS,h=t.endPTS;if(j(c)){const p=Math.abs(c-e);j(t.deltaPTS)?t.deltaPTS=Math.max(p,t.deltaPTS):t.deltaPTS=p,a=Math.max(e,c),e=Math.min(e,c),s=Math.min(s,t.startDTS),l=Math.min(i,h),i=Math.max(i,h),r=Math.max(r,t.endDTS)}const A=e-t.start;t.start!==0&&(t.start=e),t.duration=i-t.start,t.startPTS=e,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=l,t.endDTS=r;const u=t.sn;if(!n||u<n.startSN||u>n.endSN)return 0;let d;const f=u-n.startSN,g=n.fragments;for(g[f]=t,d=f;d>0;d--)co(g[d],g[d-1]);for(d=f;d<g.length-1;d++)co(g[d],g[d+1]);return n.fragmentHint&&co(g[g.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,A}function Vv(n,t){let e=null;const i=n.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){e=c;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let s=0,r;if($v(n,t,(l,c)=>{l.relurl&&(s=l.cc-c.cc),j(l.startPTS)&&j(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),t.PTSKnown=t.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,e=l.initSegment)}),e&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=e)==null?void 0:h.relurl))&&(c.initSegment=e)}),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some(l=>!l),t.deltaUpdateFailed){R.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=t.skippedSegments;l--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=Jv(n.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const o=t.fragments;if(s){R.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<o.length;l++)o[l].cc+=s}t.skippedSegments&&(t.startCC=t.fragments[0].cc),zv(n.partList,t.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?td(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):ed(n,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=n.driftStartTime,t.driftStart=n.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const l=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=l),t.driftEndTime=a,t.driftEnd=l}else t.driftEndTime=n.driftEndTime,t.driftEnd=n.driftEnd,t.advancedDateTime=n.advancedDateTime}function Jv(n,t,e){const i=Qt({},n);return e&&e.forEach(s=>{delete i[s]}),Object.keys(t).forEach(s=>{const r=new Ya(t[s].attr,i[s]);r.isValid?i[s]=r:R.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[s].attr)}"`)}),i}function zv(n,t,e){if(n&&t){let i=0;for(let s=0,r=n.length;s<=r;s++){const o=n[s],a=t[s+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?e(o,a):i--}}}function $v(n,t,e){const i=t.skippedSegments,s=Math.max(n.startSN,t.startSN)-t.startSN,r=(n.fragmentHint?1:0)+(i?t.endSN:Math.min(n.endSN,t.endSN))-t.startSN,o=t.startSN-n.startSN,a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let c=s;c<=r;c++){const h=l[o+c];let A=a[c];i&&!A&&c<i&&(A=t.fragments[c]=h),h&&A&&e(h,A)}}function ed(n,t){const e=t.startSN+t.skippedSegments-n.startSN,i=n.fragments;e<0||e>=i.length||ta(t,i[e].start)}function ta(n,t){if(t){const e=n.fragments;for(let i=n.skippedSegments;i<e.length;i++)e[i].start+=t;n.fragmentHint&&(n.fragmentHint.start+=t)}}function qv(n,t=1/0){let e=1e3*n.targetduration;if(n.updated){const i=n.fragments;if(i.length&&e*4>t){const r=i[i.length-1].duration*1e3;r<e&&(e=r)}}else e/=2;return Math.round(e)}function Xv(n,t,e){if(!(n!=null&&n.details))return null;const i=n.details;let s=i.fragments[t-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===t)?s:t<i.startSN&&e&&e.sn===t?e:null}function uh(n,t,e){var i;return n!=null&&n.details?id((i=n.details)==null?void 0:i.partList,t,e):null}function id(n,t,e){if(n)for(let i=n.length;i--;){const s=n[i];if(s.index===e&&s.fragment.sn===t)return s}return null}function sd(n){n.forEach((t,e)=>{const{details:i}=t;i!=null&&i.fragments&&i.fragments.forEach(s=>{s.level=e})})}function tr(n){switch(n.details){case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_TIMEOUT:case M.LEVEL_LOAD_TIMEOUT:case M.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function dh(n,t){const e=tr(t);return n.default[`${e?"timeout":"error"}Retry`]}function qa(n,t){const e=n.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*n.retryDelayMs,n.maxRetryDelayMs)}function fh(n){return $t($t({},n),{errorRetry:null,timeoutRetry:null})}function er(n,t,e,i){if(!n)return!1;const s=i==null?void 0:i.code,r=t<n.maxNumRetry&&(Wv(s)||!!e);return n.shouldRetry?n.shouldRetry(n,t,e,i,r):r}function Wv(n){return n===0&&navigator.onLine===!1||!!n&&(n<400||n>499)}const nd={search:function(n,t){let e=0,i=n.length-1,s=null,r=null;for(;e<=i;){s=(e+i)/2|0,r=n[s];const o=t(r);if(o>0)e=s+1;else if(o<0)i=s-1;else return r}return null}};function jv(n,t,e){if(t===null||!Array.isArray(n)||!n.length||!j(t))return null;const i=n[0].programDateTime;if(t<(i||0))return null;const s=n[n.length-1].endProgramDateTime;if(t>=(s||0))return null;e=e||0;for(let r=0;r<n.length;++r){const o=n[r];if(tS(t,e,o))return o}return null}function ir(n,t,e=0,i=0,s=.005){let r=null;if(n){r=t[n.sn-t[0].sn+1]||null;const a=n.endDTS-e;a>0&&a<15e-7&&(e+=15e-7)}else e===0&&t[0].start===0&&(r=t[0]);if(r&&((!n||n.level===r.level)&&ea(e,i,r)===0||Zv(r,n,Math.min(s,i))))return r;const o=nd.search(t,ea.bind(null,e,i));return o&&(o!==n||!r)?o:r}function Zv(n,t,e){if(t&&t.start===0&&t.level<n.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((s,r)=>(r[0]==="INF"&&(s+=parseFloat(r[1])),s),e);return n.start<=i}return!1}function ea(n=0,t=0,e){if(e.start<=n&&e.start+e.duration>n)return 0;const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-i<=n?1:e.start-i>n&&e.start?-1:0}function tS(n,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>n}function eS(n,t){return nd.search(n,e=>e.cc<t?1:e.cc>t?-1:0)}var Ht={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ce={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class rd{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=R.log.bind(R,"[info]:"),this.warn=R.warn.bind(R,"[warning]:"),this.error=R.error.bind(R,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(I.ERROR,this.onError,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(I.ERROR,this.onError,this),t.off(I.ERROR,this.onErrorOut,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(t==null?void 0:t.type)===et.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,s;if(e.fatal)return;const r=this.hls,o=e.context;switch(e.details){case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case M.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction={action:Ht.DoNothing,flags:ce.None};return}case M.FRAG_GAP:case M.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Ht.SendAlternateToPenaltyBox;return}case M.LEVEL_EMPTY_ERROR:case M.LEVEL_PARSING_ERROR:{var a,l;const c=e.parent===et.MAIN?e.level:r.loadLevel;e.details===M.LEVEL_EMPTY_ERROR&&((a=e.context)!=null&&(l=a.levelDetails)!=null&&l.live)?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,c):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,c))}return;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:typeof(o==null?void 0:o.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,o.level));return;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.SUBTITLE_LOAD_ERROR:case M.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const c=r.levels[r.loadLevel];if(c&&(o.type===Ct.AUDIO_TRACK&&c.hasAudioGroup(o.groupId)||o.type===Ct.SUBTITLE_TRACK&&c.hasSubtitleGroup(o.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ht.SendAlternateToPenaltyBox,e.errorAction.flags=ce.MoveAllAlternatesMatchingHost;return}}return;case M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],h=c==null?void 0:c.attrs["HDCP-LEVEL"];h?e.errorAction={action:Ht.SendAlternateToPenaltyBox,flags:ce.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(e)}return;case M.BUFFER_ADD_CODEC_ERROR:case M.REMUX_ALLOC_ERROR:case M.BUFFER_APPEND_ERROR:e.errorAction=this.getLevelSwitchAction(e,(s=e.level)!=null?s:r.loadLevel);return;case M.INTERNAL_EXCEPTION:case M.BUFFER_APPENDING_ERROR:case M.BUFFER_FULL_ERROR:case M.LEVEL_SWITCH_ERROR:case M.BUFFER_STALLED_ERROR:case M.BUFFER_SEEK_OVER_HOLE:case M.BUFFER_NUDGE_ON_STALL:e.errorAction={action:Ht.DoNothing,flags:ce.None};return}e.type===ot.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const i=this.hls,s=dh(i.config.playlistLoadPolicy,t),r=this.playlistError++;if(er(s,r,tr(t),t.response))return{action:Ht.RetryRequest,flags:ce.None,retryConfig:s,retryCount:r};const a=this.getLevelSwitchAction(t,e);return s&&(a.retryConfig=s,a.retryCount=r),a}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:o}=e.config,a=dh(t.details.startsWith("key")?o:r,t),l=e.levels.reduce((h,A)=>h+A.fragmentError,0);if(s&&(t.details!==M.FRAG_GAP&&s.fragmentError++,er(a,l,tr(t),t.response)))return{action:Ht.RetryRequest,flags:ce.None,retryConfig:a,retryCount:l};const c=this.getLevelSwitchAction(t,i);return a&&(c.retryConfig=a,c.retryCount=l),c}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,o;const c=t.details;s.loadError++,c===M.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:A,loadLevel:u,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(r=t.frag)==null?void 0:r.type,m=(g===et.AUDIO&&c===M.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(c===M.BUFFER_ADD_CODEC_ERROR||c===M.BUFFER_APPEND_ERROR))&&A.some(({audioCodec:S})=>s.audioCodec!==S),E=t.sourceBufferName==="video"&&(c===M.BUFFER_ADD_CODEC_ERROR||c===M.BUFFER_APPEND_ERROR)&&A.some(({codecSet:S,audioCodec:T})=>s.codecSet!==S&&s.audioCodec===T),{type:v,groupId:y}=(o=t.context)!=null?o:{};for(let S=A.length;S--;){const T=(S+u)%A.length;if(T!==u&&T>=d&&T<=f&&A[T].loadError===0){var a,l;const x=A[T];if(c===M.FRAG_GAP&&g===et.MAIN&&t.frag){const F=A[T].details;if(F){const _=ir(t.frag,F.fragments,t.frag.start);if(_!=null&&_.gap)continue}}else{if(v===Ct.AUDIO_TRACK&&x.hasAudioGroup(y)||v===Ct.SUBTITLE_TRACK&&x.hasSubtitleGroup(y))continue;if(g===et.AUDIO&&(a=s.audioGroups)!=null&&a.some(F=>x.hasAudioGroup(F))||g===et.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(F=>x.hasSubtitleGroup(F))||m&&s.audioCodec===x.audioCodec||!m&&s.audioCodec!==x.audioCodec||E&&s.codecSet===x.codecSet)continue}h=T;break}}if(h>-1&&i.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:Ht.SendAlternateToPenaltyBox,flags:ce.None,nextAutoLevel:h}}return{action:Ht.SendAlternateToPenaltyBox,flags:ce.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case Ht.DoNothing:break;case Ht.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==M.FRAG_GAP?e.fatal=!0:/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case Ht.RetryRequest:break}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s,hdcpLevel:r,nextAutoLevel:o}=i;switch(s){case ce.None:this.switchLevel(t,o);break;case ce.MoveAllAlternatesMatchingHDCP:r&&(e.maxHdcpLevel=jo[jo.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(t,o)}switchLevel(t,e){e!==void 0&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Ir{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=R.log.bind(R,`${e}:`),this.warn=R.warn.bind(R,`${e}:`),this.hls=t}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(t,e,i){const s=e==null?void 0:e.renditionReports;if(s){let r=-1;for(let o=0;o<s.length;o++){const a=s[o];let l;try{l=new self.URL(a.URI,e.url).href}catch(c){R.warn(`Could not construct new URL for Rendition Report: ${c}`),l=a.URI||""}if(l===t){r=o;break}else l===t.substring(0,l.length)&&(r=o)}if(r!==-1){const o=s[r],a=parseInt(o["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let l=parseInt(o["LAST-PART"])||(e==null?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const h=Math.min(e.age-e.partTarget,e.targetduration);l>=0&&h>e.partTarget&&(l+=1)}const c=i&&hh(i);return new Zo(a,l>=0?l:void 0,c)}}}loadPlaylist(t){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:s,stats:r}=e,o=self.performance.now(),a=r.loading.first?Math.max(0,o-r.loading.first):0;if(s.advancedDateTime=Date.now()-a,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&Vv(i,s),!this.canLoad||!s.live)return;let l,c,h;if(s.canBlockReload&&s.endSN&&s.advanced){const p=this.hls.config.lowLatencyMode,m=s.lastPartSn,C=s.endSN,E=s.lastPartIndex,v=E!==-1,y=m===C,S=p?0:E;v?(c=y?C+1:m,h=y?S:E+1):c=C+1;const T=s.age,x=T+s.ageHeader;let F=Math.min(x-s.partTarget,s.targetduration*1.5);if(F>0){if(i&&F>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${F} with playlist age: ${s.age}`),F=0;else{const _=Math.floor(F/s.targetduration);if(c+=_,h!==void 0){const w=Math.round(F%s.targetduration/s.partTarget);h+=w}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${T.toFixed(2)}s goal: ${F} skip sn ${_} to part ${h}`)}s.tuneInGoal=F}if(l=this.getDeliveryDirectives(s,e.deliveryDirectives,c,h),p||!y){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,e.deliveryDirectives,c,h));const A=this.hls.mainForwardBufferInfo,u=A?A.end-A.len:0,d=(s.edge-u)*1e3,f=qv(s,d);s.updated&&o>this.requestScheduled+f&&(this.requestScheduled=r.loading.start),c!==void 0&&s.canBlockReload?this.requestScheduled=r.loading.first+f-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+f<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=f);let g=this.requestScheduled-o;g=Math.max(0,g),this.log(`reload live playlist ${t} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(t,e,i,s){let r=hh(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Ps.No),new Zo(i,s,r)}checkRetry(t){const e=t.details,i=tr(t),s=t.errorAction,{action:r,retryCount:o=0,retryConfig:a}=s||{},l=!!s&&!!a&&(r===Ht.RetryRequest||!s.resolved&&r===Ht.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,o>=a.maxNumRetry)return!1;if(i&&(c=t.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const h=qa(a,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${e}" in ${h}ms`)}t.levelRetry=!0,s.resolved=!0}return l}}class Mi{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class iS{constructor(t,e,i,s=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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Mi(t),this.fast_=new Mi(e),this.defaultTTFB_=s,this.ttfb_=new Mi(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new Mi(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Mi(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Mi(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){t=Math.max(t,this.minDelayMs_);const i=8*e,s=t/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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 od={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},gh={};function sS(n,t,e,i,s,r){const o=n.audioCodec?n.audioGroups:null,a=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,c=l?parseInt(l):a?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((A,u)=>{if(u){const d=t.groups[u];if(!d)throw new Error(`Audio track group ${u} not found`);Object.keys(d.channels).forEach(f=>{A[f]=(A[f]||0)+d.channels[f]})}return A},{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(i,30)||n.videoRange!=="SDR"&&n.videoRange!==e||n.bitrate>Math.max(s,8e6))||!!h&&j(c)&&Object.keys(h).some(A=>parseInt(A)>c)}function nS(n,t,e){const i=n.videoCodec,s=n.audioCodec;if(!i||!s||!e)return Promise.resolve(od);const r={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)),framerate:n.frameRate||30},o=n.videoRange;o!=="SDR"&&(r.transferFunction=o.toLowerCase());const a=i.split(",").map(l=>({type:"media-source",video:$t($t({},r),{},{contentType:Ys(l,"video")})}));return s&&n.audioGroups&&n.audioGroups.forEach(l=>{var c;l&&((c=t.groups[l])==null||c.tracks.forEach(h=>{if(h.groupId===l){const A=h.channels||"",u=parseFloat(A);j(u)&&u>2&&a.push.apply(a,s.split(",").map(d=>({type:"media-source",audio:{contentType:Ys(d,"audio"),channels:""+u}})))}}))}),Promise.all(a.map(l=>{const c=rS(l);return gh[c]||(gh[c]=e.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:a,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:a,decodingInfoResults:[],error:l}))}function rS(n){const{audio:t,video:e}=n,i=e||t;if(i){const s=i.contentType.split('"')[1];if(e)return`r${e.height}x${e.width}f${Math.ceil(e.framerate)}${e.transferFunction||"sd"}_${s}_${Math.ceil(e.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${s}`}return""}function oS(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(n.media!==t.media)return n.matches===!0}return!1}function aS(n,t){let e=!1,i=[];return n&&(e=n!=="SDR",i=[n]),t&&(i=t.allowedVideoRanges||Zn.slice(0),e=t.preferHDR!==void 0?t.preferHDR:oS(),e?i=i.filter(s=>s!=="SDR"):i=["SDR"]),{preferHDR:e,allowedVideoRanges:i}}function lS(n,t,e,i,s){const r=Object.keys(n),o=i==null?void 0:i.channels,a=i==null?void 0:i.audioCodec,l=o&&parseInt(o)===2;let c=!0,h=!1,A=1/0,u=1/0,d=1/0,f=0,g=[];const{preferHDR:p,allowedVideoRanges:m}=aS(t,s);for(let y=r.length;y--;){const S=n[r[y]];c=S.channels[2]>0,A=Math.min(A,S.minHeight),u=Math.min(u,S.minFramerate),d=Math.min(d,S.minBitrate);const T=m.filter(x=>S.videoRanges[x]>0);T.length>0&&(h=!0,g=T)}A=j(A)?A:0,u=j(u)?u:0;const C=Math.max(1080,A),E=Math.max(30,u);return d=j(d)?d:e,e=Math.max(d,e),h||(t=void 0,g=[]),{codecSet:r.reduce((y,S)=>{const T=n[S];if(S===y)return y;if(T.minBitrate>e)return He(S,`min bitrate of ${T.minBitrate} > current estimate of ${e}`),y;if(!T.hasDefaultAudio)return He(S,"no renditions with default or auto-select sound found"),y;if(a&&S.indexOf(a.substring(0,4))%5!==0)return He(S,`audio codec preference "${a}" not found`),y;if(o&&!l){if(!T.channels[o])return He(S,`no renditions with ${o} channel sound found (channels options: ${Object.keys(T.channels)})`),y}else if((!a||l)&&c&&T.channels[2]===0)return He(S,"no renditions with stereo sound found"),y;return T.minHeight>C?(He(S,`min resolution of ${T.minHeight} > maximum of ${C}`),y):T.minFramerate>E?(He(S,`min framerate of ${T.minFramerate} > maximum of ${E}`),y):g.some(x=>T.videoRanges[x]>0)?T.maxScore<f?(He(S,`max score of ${T.maxScore} < selected max of ${f}`),y):y&&(Wn(S)>=Wn(y)||T.fragmentError>n[y].fragmentError)?y:(f=T.maxScore,S):(He(S,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),y)},void 0),videoRanges:g,preferHDR:p,minFramerate:u,minBitrate:d}}function He(n,t){R.log(`[abr] start candidates with "${n}" ignored because ${t}`)}function cS(n){return n.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function hS(n,t,e,i){return n.slice(e,i+1).reduce((s,r)=>{if(!r.codecSet)return s;const o=r.audioGroups;let a=s[r.codecSet];a||(s[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,l),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const h=t.groups[c];h&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(A=>{a.channels[A]=(a.channels[A]||0)+h.channels[A]}))}),s},{})}function Qe(n,t,e){if("attrs"in n){const i=t.indexOf(n);if(i!==-1)return i}for(let i=0;i<t.length;i++){const s=t[i];if(zi(n,s,e))return i}return-1}function zi(n,t,e){const{groupId:i,name:s,lang:r,assocLang:o,characteristics:a,default:l}=n,c=n.forced;return(i===void 0||t.groupId===i)&&(s===void 0||t.name===s)&&(r===void 0||t.lang===r)&&(r===void 0||t.assocLang===o)&&(l===void 0||t.default===l)&&(c===void 0||t.forced===c)&&(a===void 0||AS(a,t.characteristics))&&(e===void 0||e(n,t))}function AS(n,t=""){const e=n.split(","),i=t.split(",");return e.length===i.length&&!e.some(s=>i.indexOf(s)===-1)}function Pi(n,t){const{audioCodec:e,channels:i}=n;return(e===void 0||(t.audioCodec||"").substring(0,4)===e.substring(0,4))&&(i===void 0||i===(t.channels||"2"))}function uS(n,t,e,i,s){const r=t[i],a=t.reduce((u,d,f)=>{const g=d.uri;return(u[g]||(u[g]=[])).push(f),u},{})[r.uri];a.length>1&&(i=Math.max.apply(Math,a));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),A=mh(t,i,u=>{if(u.videoRange!==l||u.frameRate!==c||u.codecSet.substring(0,4)!==h)return!1;const d=u.audioGroups,f=e.filter(g=>!d||d.indexOf(g.groupId)!==-1);return Qe(n,f,s)>-1});return A>-1?A:mh(t,i,u=>{const d=u.audioGroups,f=e.filter(g=>!d||d.indexOf(g.groupId)!==-1);return Qe(n,f,s)>-1})}function mh(n,t,e){for(let i=t;i>-1;i--)if(e(n[i]))return i;for(let i=t+1;i<n.length;i++)if(e(n[i]))return i;return-1}class ad{constructor(t){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:e,partCurrent:i,hls:s}=this,{autoLevelEnabled:r,media:o}=s;if(!e||!o)return;const a=performance.now(),l=i?i.stats:e.stats,c=i?i.duration:e.duration,h=a-l.loading.start,A=s.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||e.level<=A){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||o.paused||!o.playbackRate||!o.readyState)return;const u=s.mainForwardBufferInfo;if(u===null)return;const d=this.bwEstimator.getEstimateTTFB(),f=Math.abs(o.playbackRate);if(h<=Math.max(d,1e3*(c/(f*2))))return;const g=u.len/f,p=l.loading.first?l.loading.first-l.loading.start:-1,m=l.loaded&&p>-1,C=this.getBwEstimate(),E=s.levels,v=E[e.level],y=l.total||Math.max(l.loaded,Math.round(c*v.averageBitrate/8));let S=m?h-p:h;S<1&&m&&(S=Math.min(h,l.loaded*8/C));const T=m?l.loaded*1e3/S:0,x=T?(y-l.loaded)/T:y*8/C+d/1e3;if(x<=g)return;const F=T?T*8:C;let _=Number.POSITIVE_INFINITY,w;for(w=e.level-1;w>A;w--){const O=E[w].maxBitrate;if(_=this.getTimeToLoadFrag(d/1e3,F,c*O,!E[w].details),_<g)break}if(_>=x||_>c*10)return;s.nextLoadLevel=s.nextAutoLevel=w,m?this.bwEstimator.sample(h-Math.min(d,p),l.loaded):this.bwEstimator.sampleTTFB(h);const U=E[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>U&&this.resetEstimator(U),this.clearTimer(),R.warn(`[abr] Fragment ${e.sn}${i?" part "+i.index:""} of level ${e.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: ${_.toFixed(3)} s
14
+ TTFB estimate: ${p|0} ms
15
+ Current BW estimate: ${j(C)?C|0:"Unknown"} bps
16
+ New BW estimate: ${this.getBwEstimate()|0} bps
17
+ Switching to level ${w} @ ${U|0} bps`),s.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(R.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new iS(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){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(t,e){const i=e.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=e.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case M.FRAG_LOAD_TIMEOUT:{const i=e.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const o=performance.now(),a=r?r.stats:i.stats,l=o-a.loading.start,c=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&c>-1){const A=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(A,c),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,i,s){const r=t+i/e,o=s?this.lastLevelLoadSec:0;return r+o}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,r=s.end-s.start;j(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===et.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:e.duration,o=this.hls.levels[e.level],a=(o.loaded?o.loaded.bytes:0)+s.loaded,l=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(e.bitrateTest){const r={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(I.FRAG_BUFFERED,r),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==et.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const o=this.hls.firstLevel,a=Math.min(Math.max(o,e),t);return R.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(t!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const o=this.hls.levels;if(o.length>Math.max(t,r)&&o[t].loadError<=o[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:s,config:r,minAutoLevel:o}=i,a=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,A=r.abrBandWidthUpFactor;if(c){const p=this.findBestLevel(l,o,s,c,0,h,A);if(p>=0)return p}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const p=this.bitrateTestDelay;p&&(u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-p,R.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=A=1)}const d=this.findBestLevel(l,o,s,c,u,h,A);if(R.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`),d>-1)return d;const f=i.levels[o],g=i.levels[i.loadLevel];return(f==null?void 0:f.bitrate)<(g==null?void 0:g.bitrate)?o:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,s,r,o,a){var l;const c=s+r,h=this.lastLoadedFragLevel,A=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(f.length===1)return 0;const C=f[A],E=!!(C!=null&&(l=C.details)!=null&&l.live),v=p===-1||h===-1;let y,S="SDR",T=(C==null?void 0:C.frameRate)||0;const{audioPreference:x,videoPreference:F}=m,_=this.audioTracksByGroup||(this.audioTracksByGroup=cS(g));if(v){if(this.firstSelection!==-1)return this.firstSelection;const K=this.codecTiers||(this.codecTiers=hS(f,_,e,i)),q=lS(K,S,t,x,F),{codecSet:Z,videoRanges:rt,minFramerate:V,minBitrate:G,preferHDR:H}=q;y=Z,S=H?rt[rt.length-1]:rt[0],T=V,t=Math.max(t,G),R.log(`[abr] picked start tier ${JSON.stringify(q)}`)}else y=C==null?void 0:C.codecSet,S=C==null?void 0:C.videoRange;const w=d?d.duration:u?u.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let K=i;K>=e;K--){var W;const q=f[K],Z=K>A;if(!q)continue;if(m.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const D=navigator.mediaCapabilities;typeof(D==null?void 0:D.decodingInfo)=="function"&&sS(q,_,S,T,t,x)?(q.supportedPromise=nS(q,_,D),q.supportedPromise.then(it=>{if(!this.hls)return;q.supportedResult=it;const at=this.hls.levels,ht=at.indexOf(q);it.error?R.warn(`[abr] MediaCapabilities decodingInfo error: "${it.error}" for level ${ht} ${JSON.stringify(it)}`):it.supported||(R.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${ht} ${JSON.stringify(it)}`),ht>-1&&at.length>1&&(R.log(`[abr] Removing unsupported level ${ht}`),this.hls.removeLevel(ht)))})):q.supportedResult=od}if(y&&q.codecSet!==y||S&&q.videoRange!==S||Z&&T>q.frameRate||!Z&&T>0&&T<q.frameRate||q.supportedResult&&!((W=q.supportedResult.decodingInfoResults)!=null&&W[0].smooth)){O.push(K);continue}const rt=q.details,V=(d?rt==null?void 0:rt.partTarget:rt==null?void 0:rt.averagetargetduration)||w;let G;Z?G=a*t:G=o*t;const H=w&&s>=w*2&&r===0?f[K].averageBitrate:f[K].maxBitrate,X=this.getTimeToLoadFrag(U,G,H*V,rt===void 0);if(G>=H&&(K===h||q.loadError===0&&q.fragmentError===0)&&(X<=U||!j(X)||E&&!this.bitrateTestDelay||X<c)){const D=this.forcedAutoLevel;return K!==p&&(D===-1||D!==p)&&(O.length&&R.trace(`[abr] Skipped level(s) ${O.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[O[0]].codecs}" ${f[O[0]].videoRange}; not compatible with "${C.codecs}" ${S}`),R.info(`[abr] switch candidate:${A}->${K} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-H)} ttfb:${U.toFixed(1)} avgDuration:${V.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${v} codecSet:${y} videoRange:${S} hls.loadLevel:${p}`)),v&&(this.firstSelection=K),K}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls,s=Math.min(Math.max(t,i),e);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}class dS{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(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!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 zt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class fS{constructor(t){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=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(I.BUFFER_APPENDED,this.onBufferAppended,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.BUFFER_APPENDED,this.onBufferAppended,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;const o=r.end;if(r.start<=t&&o!==null&&t<=o)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,s=Object.keys(i);for(let r=s.length;r--;){const o=i[s[r]];if((o==null?void 0:o.body.type)===e&&o.buffered){const a=o.body;if(a.start<=t&&t<=a.end)return a}}return null}detectEvictedFragments(t,e,i,s){this.timeRanges&&(this.timeRanges[t]=e);const r=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a||r>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===i&&this.removeFragment(a.body);return}const l=a.range[t];l&&l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,e);return h&&this.removeFragment(a.body),h})})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s}=t;if(!e||i.sn==="initSegment")return;const r=ki(i),o=this.fragments[r];if(!o||o.buffered&&i.gap)return;const a=!i.relurl;Object.keys(e).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const h=e[l],A=a||c.partial===!0;o.range[l]=this.getBufferedTimes(i,s,A,h)}),o.loaded=null,Object.keys(o.range).length?(o.buffered=!0,(o.body.endList=i.endList||o.body.endList)&&(this.endListFragments[o.body.type]=o),pn(o)||this.removeParts(i.sn-1,i.type)):this.removeFragment(o.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter(s=>s.fragment.sn>=t))}fragBuffered(t,e){const i=ki(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},o=t.start,a=t.end,l=t.minEndPTS||a,c=t.maxStartPTS||o;for(let h=0;h<s.length;h++){const A=s.start(h)-this.bufferPadding,u=s.end(h)+this.bufferPadding;if(c>=A&&l<=u){r.time.push({startPTS:Math.max(o,s.start(h)),endPTS:Math.min(a,s.end(h))});break}else if(o<u&&a>A){const d=Math.max(o,s.start(h)),f=Math.min(a,s.end(h));f>d&&(r.partial=!0,r.time.push({startPTS:d,endPTS:f}))}else if(a<=A)break}return r}getPartialFragment(t){let e=null,i,s,r,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&pn(h)&&(s=h.body.start-a,r=h.body.end+a,t>=s&&t<=r&&(i=Math.min(t-s,r-t),o<=i&&(e=h.body,o=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||pn(e))}getState(t){const e=ki(t),i=this.fragments[e];return i?i.buffered?pn(i)?zt.PARTIAL:zt.OK:zt.APPENDING:zt.NOT_LOADED}isTimeBuffered(t,e,i){let s,r;for(let o=0;o<i.length;o++){if(s=i.start(o)-this.bufferPadding,r=i.end(o)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:s}=e;if(i.sn==="initSegment"||i.bitrateTest)return;const r=s?null:e,o=ki(i);this.fragments[o]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r}=e;if(i.sn==="initSegment")return;const o=i.type;if(s){let a=this.activePartLists[o];a||(this.activePartLists[o]=a=[]),a.push(s)}this.timeRanges=r,Object.keys(r).forEach(a=>{const l=r[a];this.detectEvictedFragments(a,l,o,s)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ki(t);return!!this.fragments[e]}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||s&&!l.gap||l.start<e&&l.end>t&&(a.buffered||r)&&this.removeFragment(l)})}removeFragment(t){const e=ki(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const s=t.sn;this.activePartLists[t.type]=i.filter(r=>r.fragment.sn!==s)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function pn(n){var t,e,i;return n.buffered&&(n.body.gap||((t=n.range.video)==null?void 0:t.partial)||((e=n.range.audio)==null?void 0:e.partial)||((i=n.range.audiovideo)==null?void 0:i.partial))}function ki(n){return`${n.type}_${n.level}_${n.sn}`}const gS={length:0,start:()=>0,end:()=>0};class Rt{static isBuffered(t,e){try{if(t){const i=Rt.getBuffered(t);for(let s=0;s<i.length;s++)if(e>=i.start(s)&&e<=i.end(s))return!0}}catch{}return!1}static bufferInfo(t,e,i){try{if(t){const s=Rt.getBuffered(t),r=[];let o;for(o=0;o<s.length;o++)r.push({start:s.start(o),end:s.end(o)});return this.bufferedInfo(r,e,i)}}catch{}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.sort(function(c,h){const A=c.start-h.start;return A||h.end-c.end});let s=[];if(i)for(let c=0;c<t.length;c++){const h=s.length;if(h){const A=s[h-1].end;t[c].start-A<i?t[c].end>A&&(s[h-1].end=t[c].end):s.push(t[c])}else s.push(t[c])}else s=t;let r=0,o,a=e,l=e;for(let c=0;c<s.length;c++){const h=s[c].start,A=s[c].end;if(e+i>=h&&e<A)a=h,l=A,r=l-e;else if(e+i<h){o=h;break}}return{len:r,start:a||0,end:l||0,nextStart:o}}static getBuffered(t){try{return t.buffered}catch(e){return R.log("failed to get media.buffered",e),gS}}}class yr{constructor(t,e,i,s=0,r=-1,o=!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=En(),this.buffering={audio:En(),video:En(),audiovideo:En()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=o}}function En(){return{start:0,executeStart:0,executeEnd:0,end:0}}function wn(n,t){for(let i=0,s=n.length;i<s;i++){var e;if(((e=n[i])==null?void 0:e.cc)===t)return n[i]}return null}function mS(n,t,e){return!!(t&&(e.endCC>e.startCC||n&&n.cc<e.startCC))}function pS(n,t){const e=n.fragments,i=t.fragments;if(!i.length||!e.length){R.log("No fragments to align");return}const s=wn(e,i[0].cc);if(!s||s&&!s.startPTS){R.log("No frag in previous level to align on");return}return s}function ph(n,t){if(n){const e=n.start+t;n.start=n.startPTS=e,n.endPTS=e+n.duration}}function ld(n,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)ph(e[i],n);t.fragmentHint&&ph(t.fragmentHint,n),t.alignedSliding=!0}function ES(n,t,e){t&&(CS(n,e,t),!e.alignedSliding&&t&&sr(e,t),!e.alignedSliding&&t&&!e.skippedSegments&&ed(t,e))}function CS(n,t,e){if(mS(n,e,t)){const i=pS(e,t);i&&j(i.start)&&(R.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),ld(i.start,t))}}function sr(n,t){if(!n.hasProgramDateTime||!t.hasProgramDateTime)return;const e=n.fragments,i=t.fragments;if(!e.length||!i.length)return;let s,r;const o=Math.min(t.endCC,n.endCC);t.startCC<o&&n.startCC<o&&(s=wn(i,o),r=wn(e,o)),(!s||!r)&&(s=i[Math.floor(i.length/2)],r=wn(e,s.cc)||e[Math.floor(e.length/2)]);const a=s.programDateTime,l=r.programDateTime;if(!a||!l)return;const c=(l-a)/1e3-(r.start-s.start);ld(c,n)}const Eh=Math.pow(2,17);class IS{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new Je({type:ot.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(d=>d[0]==="GAP")){l(Ih(t));return}else t.gap=!1;const c=this.loader=t.loader=r?new r(s):new o(s),h=Ch(t),A=fh(s.fragLoadPolicy.default),u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Eh};t.stats=c.stats,c.load(h,u,{onSuccess:(d,f,g,p)=>{this.resetLoader(t,c);let m=d.data;g.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(m.slice(0,16)),m=m.slice(16)),a({frag:t,part:null,payload:m,networkDetails:p})},onError:(d,f,g,p)=>{this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:$t({url:i,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:d}))},onProgress:(d,f,g,p)=>{e&&e({frag:t,part:null,payload:g,networkDetails:p})}})})}loadPart(t,e,i){this.abort();const s=this.config,r=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(Ih(t,e));return}const c=this.loader=t.loader=r?new r(s):new o(s),h=Ch(t,e),A=fh(s.fragLoadPolicy.default),u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Eh};e.stats=c.stats,c.load(h,u,{onSuccess:(d,f,g,p)=>{this.resetLoader(t,c),this.updateStatsFromPart(t,e);const m={frag:t,part:e,payload:d.data,networkDetails:p};i(m),a(m)},onError:(d,f,g,p)=>{this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:$t({url:h.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(t,c),l(new Je({type:ot.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:d}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const l=Math.round(t.duration/e.duration),c=Math.min(Math.round(i.loaded/r),l),A=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+A}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=s.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Ch(n,t=null){const e=t||n,i={frag:n,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},s=e.byteRangeStartOffset,r=e.byteRangeEndOffset;if(j(s)&&j(r)){var o;let a=s,l=r;if(n.sn==="initSegment"&&((o=n.decryptdata)==null?void 0:o.method)==="AES-128"){const c=r-s;c%16&&(l=r+(16-c%16)),s!==0&&(i.resetIV=!0,a=s-16)}i.rangeStart=a,i.rangeEnd=l}return i}function Ih(n,t){const e=new Error(`GAP ${n.gap?"tag":"attribute"} found`),i={type:ot.MEDIA_ERROR,details:M.FRAG_GAP,fatal:!1,frag:n,error:e,networkDetails:null};return t&&(i.part=t),(t||n).stats.aborted=!0,new Je(i)}class Je extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class yS{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class BS{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function vS(n){const t=n.byteLength,e=t&&new DataView(n.buffer).getUint8(t-1);return e?Ci(n,0,t-e):n}class SS{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=e.getUint32(s*4);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],o=i[2],a=i[3],l=this.invSubMix,c=l[0],h=l[1],A=l[2],u=l[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[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,t[f]=m,e[m]=f;const C=d[f],E=d[C],v=d[E];let y=d[m]*257^m*16843008;s[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,o[f]=y<<8|y>>>24,a[f]=y,y=v*16843009^E*65537^C*257^f*16843008,c[m]=y<<24|y>>>8,h[m]=y<<16|y>>>16,A[m]=y<<8|y>>>24,u[m]=y,f?(f=C^d[d[d[v^C]]],g^=d[d[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const o=this.ksRows=(r+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),h=this.invKeySchedule=new Uint32Array(o),A=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let C,E;for(a=0;a<o;a++){if(a<r){C=c[a]=e[a];continue}E=C,a%r===0?(E=E<<8|E>>>24,E=A[E>>>24]<<24|A[E>>>16&255]<<16|A[E>>>8&255]<<8|A[E&255],E^=u[a/r|0]<<24):r>6&&a%r===4&&(E=A[E>>>24]<<24|A[E>>>16&255]<<16|A[E>>>8&255]<<8|A[E&255]),c[a]=C=(c[a-r]^E)>>>0}for(l=0;l<o;l++)a=o-l,l&3?E=c[a]:E=c[a-4],l<4||a<=4?h[l]=E:h[l]=f[A[E>>>24]]^g[A[E>>>16&255]]^p[A[E>>>8&255]]^m[A[E&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],h=a[2],A=a[3],u=this.uint8ArrayToUint32Array_(i);let d=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(t),C=new Int32Array(m.length);let E,v,y,S,T,x,F,_,w,U,O,W,K,q;const Z=this.networkToHostOrderSwap;for(;e<m.length;){for(w=Z(m[e]),U=Z(m[e+1]),O=Z(m[e+2]),W=Z(m[e+3]),T=w^r[0],x=W^r[1],F=O^r[2],_=U^r[3],K=4,q=1;q<s;q++)E=l[T>>>24]^c[x>>16&255]^h[F>>8&255]^A[_&255]^r[K],v=l[x>>>24]^c[F>>16&255]^h[_>>8&255]^A[T&255]^r[K+1],y=l[F>>>24]^c[_>>16&255]^h[T>>8&255]^A[x&255]^r[K+2],S=l[_>>>24]^c[T>>16&255]^h[x>>8&255]^A[F&255]^r[K+3],T=E,x=v,F=y,_=S,K=K+4;E=o[T>>>24]<<24^o[x>>16&255]<<16^o[F>>8&255]<<8^o[_&255]^r[K],v=o[x>>>24]<<24^o[F>>16&255]<<16^o[_>>8&255]<<8^o[T&255]^r[K+1],y=o[F>>>24]<<24^o[_>>16&255]<<16^o[T>>8&255]<<8^o[x&255]^r[K+2],S=o[_>>>24]<<24^o[T>>16&255]<<16^o[x>>8&255]<<8^o[F&255]^r[K+3],C[e]=Z(E^d),C[e+1]=Z(S^f),C[e+2]=Z(y^g),C[e+3]=Z(v^p),d=w,f=U,g=O,p=W,e=e+4}return C.buffer}}const TS=16;class Xa{constructor(t,{removePKCS7Padding:e=!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=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?vS(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i){return this.useSoftware?new Promise((s,r)=>{this.softwareDecrypt(new Uint8Array(t),e,i);const o=this.flush();o?s(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i)}softwareDecrypt(t,e,i){const{currentIV:s,currentResult:r,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(t=ge(o,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new SS),l.expandKey(e);const c=r;return this.currentResult=l.decrypt(a.buffer,0,i),this.currentIV=Ci(a,-16).buffer,c||null}webCryptoDecrypt(t,e,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i));this.key=e,this.fastAesKey=new BS(this.subtle,e)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new yS(this.subtle,new Uint8Array(i)).decrypt(t.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(R.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,i)))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%TS;return i!==t.length&&(e=Ci(t,0,i),this.remainderData=Ci(t,i)),e}logOnce(t){this.logEnabled&&(R.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const _S={toString:function(n){let t="";const e=n.length;for(let i=0;i<e;i++)t+=`[${n.start(i).toFixed(3)}-${n.end(i).toFixed(3)}]`;return t}},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 Br extends dS{constructor(t,e,i,s,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=s,this.log=R.log.bind(R,`${s}:`),this.warn=R.warn.bind(R,`${s}:`),this.hls=t,this.fragmentLoader=new IS(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Xa(t.config),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),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(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const i=e.partList;if(i!=null&&i.length){const r=i[i.length-1];return Rt.isBuffered(this.media,r.start+r.duration/2)}const s=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var t;return(t=this.levelLastLoaded)==null?void 0:t.details}}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===N.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const t=this.media;t!=null&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.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:t,fragCurrent:e,media:i,mediaBuffer:s,state:r}=this,o=i?i.currentTime:0,a=Rt.bufferInfo(s||i,o,t.maxBufferHole);if(this.log(`media seeking to ${j(o)?o.toFixed(3):o}, state: ${r}`),this.state===N.ENDED)this.resetLoadingState();else if(e){const l=t.maxFragLookUpTolerance,c=e.start-l,h=e.start+e.duration+l;if(!a.len||h<a.start||c>a.end){const A=o>h;(o<c||A)&&(A&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,!0),this.lastCurrentTime=o),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(I.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(t,e,i){this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){const s=r=>{if(this.fragContextChanged(t)){this.warn(`Fragment ${t.sn}${r.part?" p: "+r.part.index:""} of level ${t.level} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(t,e,i,s).then(r=>{if(!r)return;const o=this.state;if(this.fragContextChanged(t)){(o===N.FRAG_LOADING||!this.fragCurrent&&o===N.PARSING)&&(this.fragmentTracker.removeFragment(t),this.state=N.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(I.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(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===zt.APPENDING){const r=t.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),a=Math.max(t.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?t.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,t.duration))&&i.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===zt.PARTIAL&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(I.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(i=>{if(!i||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:r}=i,o=t.decryptdata;if(r&&r.byteLength>0&&o!=null&&o.key&&o.iv&&o.method==="AES-128"){const a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer).catch(l=>{throw s.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const c=self.performance.now();return s.trigger(I.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:a,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===N.STOPPED||this.state===N.ERROR||(this.warn(i),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state=N.IDLE,t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var i,s,r,o;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===et.MAIN?"level":"track"} ${t.level} (frag:[${((i=t.startPTS)!=null?i:NaN).toFixed(3)}-${((s=t.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${a?_S.toString(Rt.getBuffered(a)):"(detached)"})`),t.sn!=="initSegment"){var l;if(t.type!==et.SUBTITLE){const h=t.elementaryStreams;if(!Object.keys(h).some(A=>!!h[A])){this.state=N.IDLE;return}}const c=(l=this.levels)==null?void 0:l[t.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,a&&(!this.loadedmetadata&&t.type==et.MAIN&&a.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,o=!r||r.length===0||r.some(l=>!l),a=new yr(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!o);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var r;const o=e==null?void 0:e.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(t.encrypted&&!((r=t.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${t.level}`),this.state=N.KEY_LOADING,this.fragCurrent=t,a=this.keyLoader.load(t).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(I.KEY_LOADED,h),this.state===N.KEY_LOADING&&(this.state=N.IDLE),h}),this.hls.trigger(I.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(t,o.encryptedFragments),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){const h=o.partList;if(h&&s){i>t.end&&o.fragmentHint&&(t=o.fragmentHint);const A=this.getNextPart(h,t,i);if(A>-1){const u=h[A];this.log(`Loading part sn: ${t.sn} p: ${u.index} cc: ${t.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${A}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=N.FRAG_LOADING;let d;return a?d=a.then(f=>!f||this.fragContextChanged(f.frag)?null:this.doFragPartsLoad(t,u,e,s)).catch(f=>this.handleFragLoadError(f)):d=this.doFragPartsLoad(t,u,e,s).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(I.FRAG_LOADING,{frag:t,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}else if(!t.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),j(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=N.FRAG_LOADING;const l=this.config.progressive;let c;return l&&a?c=a.then(h=>!h||this.fragContextChanged(h==null?void 0:h.frag)?null:this.fragmentLoader.load(t,s)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(t,l?s:void 0),a]).then(([h])=>(!l&&h&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(I.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,i,s){return new Promise((r,o)=>{var a;const l=[],c=(a=i.details)==null?void 0:a.partList,h=A=>{this.fragmentLoader.loadPart(t,A,s).then(u=>{l[A.index]=u;const d=u.part;this.hls.trigger(I.FRAG_LOADED,u);const f=uh(i,t.sn,A.index+1)||id(c,t.sn,A.index+1);if(f)h(f);else return r({frag:t,part:d,partsLoaded:l})}).catch(o)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===M.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(I.ERROR,e)}else this.hls.trigger(I.ERROR,{type:ot.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==N.PARSING){!this.fragCurrent&&this.state!==N.STOPPED&&this.state!==N.ERROR&&(this.state=N.IDLE);return}const{frag:i,part:s,level:r}=e,o=self.performance.now();i.stats.parsing.end=o,s&&(s.stats.parsing.end=o),this.updateLevelTiming(i,s,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:o}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${s}. The current chunk will not be buffered.`),null;const a=e[s],l=o>-1?uh(a,r,o):null,c=l?l.fragment:Xv(a,r,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){var o;if(!t||this.state!==N.PARSING)return;const{data1:a,data2:l}=t;let c=a;if(a&&l&&(c=ge(a,l)),!((o=c)!=null&&o.length))return;const h={type:t.type,frag:e,part:i,chunkMeta:s,parent:e.type,data:c};if(this.hls.trigger(I.BUFFER_APPENDING,h),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Rt.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=Rt.bufferInfo(e,i,0),r=t.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),a=Math.max(Math.min(t.start-o,s.end-o),i+o);t.start-a>o&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return j(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:s}}=this,r=Rt.bufferInfo(t,e,s);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(e,i);if(o&&r.nextStart<o.end)return Rt.bufferInfo(t,e,Math.max(r.nextStart,s))}return r}getMaxBufferLength(t){const{config:e}=this;let i;return t?i=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):i=e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-e*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(t,e=et.MAIN){const i=this.fragmentTracker.getAppendedFrag(t,et.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,o=i[0].start;let a;if(e.live){const l=r.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<o)&&(a=this.getInitialLiveFragment(e,i),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=o&&(a=i[0]);if(!a){const l=r.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===zt.OK||i===zt.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,r){const o=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(a===null)return a;if(t=a,o&&t&&!t.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=r)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!(t!=null&&t.initSegment.data)&&!this.bitrateTest?t.initSegment:t}getNextPart(t,e,i){let s=-1,r=!1,o=!0;for(let a=0,l=t.length;a<l;a++){const c=t[a];if(o=o&&!c.independent,s>-1&&i<c.start)break;const h=c.loaded;h?s=-1:(r||c.independent||o)&&c.fragment===e&&(s=a),r=h}return s}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=jv(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const o=e[r-t.startSN];i.cc===o.cc&&(s=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=eS(e,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=s,h=i.partList,A=!!(s.lowLatencyMode&&h!=null&&h.length&&l);A&&l&&!this.bitrateTest&&(o=o.concat(l),a=l.sn);let u;if(t<e){const d=t>e-c?0:c;u=ir(r,o,t,d)}else u=o[o.length-1];if(u){const d=u.sn-i.startSN,f=this.fragmentTracker.getState(u);if((f===zt.OK||f===zt.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!A||h[0].fragment.sn>u.sn)&&r&&u.level===r.level){const p=o[d+1];u.sn<a&&this.fragmentTracker.getState(p)!==zt.OK?u=p:u=null}}return u}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=i.currentTime,o=t.fragments[0].start,a=t.edge,l=r>=o-e.maxFragLookUpTolerance&&r<=a;if(s!==null&&i.duration>s&&(r<s||!l)){const c=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!l&&i.readyState<4||r<a-c)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(t,e,i){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=t.fragments[0].start,o=!e,a=t.alignedSliding&&j(r);if(o||!a&&!r){const{fragPrevious:l}=this;ES(l,i,t);const c=t.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${s}`),c}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let i=this.startPosition;if(i<e&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,r=s?this.startTimeOffset:t.startTimeOffset;r!==null&&j(r)?(i=e+r,r<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Start time offset ${r} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&t.sn!=="initSegment"&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==N.FRAG_LOADING_WAITING_RETRY)&&(this.state=N.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const h=this.getCurrentContext(e.chunkMeta);h&&(e.frag=h.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const r=e.details===M.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const o=e.errorAction,{action:a,retryCount:l=0,retryConfig:c}=o||{};if(o&&a===Ht.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=qa(c,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),o.resolved=!0,this.retryDate=self.performance.now()+h,this.state=N.FRAG_LOADING_WAITING_RETRY}else if(c&&o)if(this.resetFragmentErrors(t),l<c.maxNumRetry)!r&&a!==Ht.RemoveAlternatePermanently&&(o.resolved=!0);else{R.warn(`${e.details} reached or exceeded max retry (${l})`);return}else(o==null?void 0:o.action)===Ht.SendAlternateToPenaltyBox?this.state=N.WAITING_LEVEL:this.state=N.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===N.PARSING||this.state===N.PARSED){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(e==null?void 0:e.duration)||10);const o=!r;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(t){t===et.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==N.STOPPED&&(this.state=N.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=Rt.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===N.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=N.IDLE}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;e!=null&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){var r;const o=i.details;if(!o){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((l,c)=>{const h=t.elementaryStreams[c];if(h){const A=h.endPTS-h.startPTS;if(A<=0)return this.warn(`Could not parse fragment ${t.sn} ${c} duration reliably (${A})`),l||!1;const u=s?0:td(o,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:o,level:i,drift:u,type:c,frag:t,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 ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(l.message),this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=N.PARSED,this.hls.trigger(I.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class cd{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;if(t.length)t.length===1?i=t[0]:i=xS(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function xS(n,t){const e=new Uint8Array(t);let i=0;for(let s=0;s<n.length;s++){const r=n[s];e.set(r,i),i+=r.length}return e}function DS(){return typeof __HLS_WORKER_BUNDLE__=="function"}function RS(){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"}),t=self.URL.createObjectURL(n);return{worker:new self.Worker(t),objectURL:t}}function wS(n){const t=new self.URL(n,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}function Pe(n="",t=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Wa{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(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=ge(this.cachedData,t),this.cachedData=null);let i=Ks(t,0),s=i?i.length:0,r;const o=this._audioTrack,a=this._id3Track,l=i?$a(i):void 0,c=t.length;for((this.basePTS===null||this.frameIndex===0&&j(l))&&(this.basePTS=LS(l,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ue.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(t,s)){const h=this.appendFrame(o,t,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,r=s):s=c}else tv(t,s)?(i=Ks(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ue.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===c&&r!==c){const h=Ci(t,r);this.cachedData?this.cachedData=ge(this.cachedData,h):this.cachedData=h}}return{audioTrack:o,videoTrack:Pe(),id3Track:a,textTrack:Pe()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Pe(),id3Track:this._id3Track,textTrack:Pe()}}destroy(){}}const LS=(n,t,e)=>{if(j(n))return n*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};function bS(n,t,e,i){let s,r,o,a;const l=navigator.userAgent.toLowerCase(),c=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((t[e+2]&192)>>>6)+1;const A=(t[e+2]&60)>>>2;if(A>h.length-1){const u=new Error(`invalid ADTS sampling index:${A}`);n.emit(I.ERROR,I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!0,error:u,reason:u.message});return}return o=(t[e+2]&1)<<2,o|=(t[e+3]&192)>>>6,R.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${A}`),/firefox/i.test(l)?A>=6?(s=5,a=new Array(4),r=A-3):(s=2,a=new Array(2),r=A):l.indexOf("android")!==-1?(s=2,a=new Array(2),r=A):(s=5,a=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&A>=6?r=A-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(A>=6&&o===1||/vivaldi/i.test(l))||!i&&o===1)&&(s=2,a=new Array(2)),r=A)),a[0]=s<<3,a[0]|=(A&14)>>1,a[1]|=(A&1)<<7,a[1]|=o<<3,s===5&&(a[1]|=(r&14)>>1,a[2]=(r&1)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:h[A],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c}}function hd(n,t){return n[t]===255&&(n[t+1]&246)===240}function Ad(n,t){return n[t+1]&1?7:9}function ja(n,t){return(n[t+3]&3)<<11|n[t+4]<<3|(n[t+5]&224)>>>5}function FS(n,t){return t+5<n.length}function nr(n,t){return t+1<n.length&&hd(n,t)}function MS(n,t){return FS(n,t)&&hd(n,t)&&ja(n,t)<=n.length-t}function PS(n,t){if(nr(n,t)){const e=Ad(n,t);if(t+e>=n.length)return!1;const i=ja(n,t);if(i<=e)return!1;const s=t+i;return s===n.length||nr(n,s)}return!1}function ud(n,t,e,i,s){if(!n.samplerate){const r=bS(t,e,i,s);if(!r)return;n.config=r.config,n.samplerate=r.samplerate,n.channelCount=r.channelCount,n.codec=r.codec,n.manifestCodec=r.manifestCodec,R.log(`parsed codec:${n.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function dd(n){return 1024*9e4/n}function kS(n,t){const e=Ad(n,t);if(t+e<=n.length){const i=ja(n,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function fd(n,t,e,i,s){const r=dd(n.samplerate),o=i+s*r,a=kS(t,e);let l;if(a){const{frameLength:A,headerLength:u}=a,d=u+A,f=Math.max(0,e+d-t.length);f?(l=new Uint8Array(d-u),l.set(t.subarray(e+u,t.length),0)):l=t.subarray(e+u,e+d);const g={unit:l,pts:o};return f||n.samples.push(g),{sample:g,length:d,missing:f}}const c=t.length-e;return l=new Uint8Array(c),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}let Cn=null;const QS=[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],OS=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],GS=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],US=[0,1,1,4];function gd(n,t,e,i,s){if(e+24>t.length)return;const r=md(t,e);if(r&&e+r.frameLength<=t.length){const o=r.samplesPerFrame*9e4/r.sampleRate,a=i+s*o,l={unit:t.subarray(e,e+r.frameLength),pts:a,dts:a};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function md(n,t){const e=n[t+1]>>3&3,i=n[t+1]>>1&3,s=n[t+2]>>4&15,r=n[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&r!==3){const o=n[t+2]>>1&1,a=n[t+3]>>6,l=e===3?3-i:i===3?3:4,c=QS[l*14+s-1]*1e3,A=OS[(e===3?0:e===2?1:2)*3+r],u=a===3?1:2,d=GS[e][i],f=US[i],g=d*8*f,p=Math.floor(d*c/A+o)*f;if(Cn===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Cn=E?parseInt(E[1]):0}return!!Cn&&Cn<=87&&i===2&&c>=224e3&&a===0&&(n[t+3]=n[t+3]|128),{sampleRate:A,channelCount:u,frameLength:p,samplesPerFrame:g}}}function Za(n,t){return n[t]===255&&(n[t+1]&224)===224&&(n[t+1]&6)!==0}function pd(n,t){return t+1<n.length&&Za(n,t)}function NS(n,t){return Za(n,t)&&4<=n.length-t}function Ed(n,t){if(t+1<n.length&&Za(n,t)){const i=md(n,t);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=t+s;return r===n.length||pd(n,r)}return!1}class HS extends Wa{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Ks(t,0);let i=(e==null?void 0:e.length)||0;if(Ed(t,i))return!1;for(let s=t.length;i<s;i++)if(PS(t,i))return R.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return MS(t,e)}appendFrame(t,e,i){ud(t,this.observer,e,i,t.manifestCodec);const s=fd(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const KS=/\/emsg[-/]ID3/i;class YS{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=Pe("video",1),o=this.audioTrack=Pe("audio",1),a=this.txtTrack=Pe("text",1);if(this.id3Track=Pe("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=Ju(t);if(l.video){const{id:c,timescale:h,codec:A}=l.video;r.id=c,r.timescale=a.timescale=h,r.codec=A}if(l.audio){const{id:c,timescale:h,codec:A}=l.audio;o.id=c,o.timescale=h,o.codec=A}a.id=Ku.text,r.sampleDuration=0,r.duration=o.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return cv(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ge(this.remainderData,t));const a=pv(i);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=i;const o=this.extractID3Track(s,e);return r.samples=$c(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=$c(t,e),{videoTrack:e,audioTrack:Pe(),id3Track:s,textTrack:Pe()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=ft(t.samples,["emsg"]);s&&s.forEach(r=>{const o=Iv(r);if(KS.test(o.schemeIdUri)){const a=j(o.presentationTime)?o.presentationTime/o.timeScale:e+o.presentationTimeDelta/o.timeScale;let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;i.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:ue.emsg,duration:l})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const Cd=(n,t)=>{let e=0,i=5;t+=i;const s=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=n[t];const a=Math.min(i,8),l=8-a;r[0]=4278190080>>>24+l<<l,s[0]=(o[0]&r[0])>>l,e=e?e<<a|s[0]:s[0],t+=1,i-=a}return e};class VS extends Wa{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=Id(t,e,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:t.samples[t.samples.length-1],length:s,missing:0}}static probe(t){if(!t)return!1;const e=Ks(t,0);if(!e)return!1;const i=e.length;return t[i]===11&&t[i+1]===119&&$a(e)!==void 0&&Cd(t,i)<16}}function Id(n,t,e,i,s){if(e+8>t.length||t[e]!==11||t[e+1]!==119)return-1;const r=t[e+4]>>6;if(r>=3)return-1;const a=[48e3,44100,32e3][r],l=t[e+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(e+h>t.length)return-1;const A=t[e+6]>>5;let u=0;A===2?u+=2:(A&1&&A!==1&&(u+=2),A&4&&(u+=2));const d=(t[e+6]<<8|t[e+7])>>12-u&1,g=[2,1,2,3,3,4,4,5][A]+d,p=t[e+5]>>3,m=t[e+5]&7,C=new Uint8Array([r<<6|p<<1|m>>2,(m&3)<<6|A<<3|d<<2|l>>4,l<<4&224]),E=1536/a*9e4,v=i+s*E,y=t.subarray(e,e+h);return n.config=C,n.channelCount=g,n.samplerate=a,n.samples.push({unit:y,pts:v}),h}class JS{constructor(){this.VideoSample=null}createVideoSample(t,e,i,s){return{key:t,frame:!1,pts:e,dts:i,units:[],debug:s,length:0}}getLastNalUnit(t){var e;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=t[t.length-1]),(e=i)!=null&&e.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const i=e.samples,s=i.length;if(s){const r=i[s-1];t.pts=r.pts,t.dts=r.dts}else{e.dropped++;return}}e.samples.push(t)}t.debug.length&&R.log(t.pts+"/"+t.dts+":"+t.debug)}}class yh{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(r===0)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&R.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e=8,i=8,s;for(let r=0;r<t;r++)i!==0&&(s=this.readEG(),i=(e+s+256)%256),e=i===0?e:i}readSPS(){let t=0,e=0,i=0,s=0,r,o,a;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),A=this.readBoolean.bind(this),u=this.skipBits.bind(this),d=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const p=l();if(c(5),u(3),l(),f(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const S=h();if(S===3&&u(1),f(),f(),u(1),A())for(o=S!==3?8:12,a=0;a<o;a++)A()&&(a<6?g(16):g(64))}f();const m=h();if(m===0)h();else if(m===1)for(u(1),d(),d(),r=h(),a=0;a<r;a++)d();f(),u(1);const C=h(),E=h(),v=c(1);v===0&&u(1),u(1),A()&&(t=h(),e=h(),i=h(),s=h());let y=[1,1];if(A()&&A())switch(l()){case 1:y=[1,1];break;case 2:y=[12,11];break;case 3:y=[10,11];break;case 4:y=[16,11];break;case 5:y=[40,33];break;case 6:y=[24,11];break;case 7:y=[20,11];break;case 8:y=[32,11];break;case 9:y=[80,33];break;case 10:y=[18,11];break;case 11:y=[15,11];break;case 12:y=[64,33];break;case 13:y=[160,99];break;case 14:y=[4,3];break;case 15:y=[3,2];break;case 16:y=[2,1];break;case 255:{y=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((C+1)*16-t*2-e*2),height:(2-v)*(E+1)*16-(v?2:4)*(i+s),pixelRatio:y}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class zS extends JS{parseAVCPES(t,e,i,s,r){const o=this.parseAVCNALu(t,i.data);let a=this.VideoSample,l,c=!1;i.data=null,a&&o.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),o.forEach(h=>{var A;switch(h.type){case 1:{let g=!1;l=!0;const p=h.data;if(c&&p.length>4){const m=new yh(p).readSliceType();(m===2||m===4||m===7||m===9)&&(g=!0)}if(g){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),a.frame=!0,a.key=g;break}case 5:l=!0,(A=a)!=null&&A.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),a.key=!0,a.frame=!0;break;case 6:{l=!0,$u(h.data,1,i.pts,e.samples);break}case 7:{var d,f;l=!0,c=!0;const g=h.data,m=new yh(g).readSPS();if(!t.sps||t.width!==m.width||t.height!==m.height||((d=t.pixelRatio)==null?void 0:d[0])!==m.pixelRatio[0]||((f=t.pixelRatio)==null?void 0:f[1])!==m.pixelRatio[1]){t.width=m.width,t.height=m.height,t.pixelRatio=m.pixelRatio,t.sps=[g],t.duration=r;const C=g.subarray(1,4);let E="avc1.";for(let v=0;v<3;v++){let y=C[v].toString(16);y.length<2&&(y="0"+y),E+=y}t.codec=E}break}case 8:l=!0,t.pps=[h.data];break;case 9:l=!0,t.audFound=!0,a&&this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,a&&(a.debug+="unknown NAL "+h.type+" ");break}a&&l&&a.units.push(h)}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}parseAVCNALu(t,e){const i=e.byteLength;let s=t.naluState||0;const r=s,o=[];let a=0,l,c,h,A=-1,u=0;for(s===-1&&(A=0,u=e[0]&31,s=0,a=1);a<i;){if(l=e[a++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(c=a-s-1,A>=0){const d={data:e.subarray(A,c),type:u};o.push(d)}else{const d=this.getLastNalUnit(t.samples);d&&(r&&a<=4-r&&d.state&&(d.data=d.data.subarray(0,d.data.byteLength-r)),c>0&&(d.data=ge(d.data,e.subarray(0,c)),d.state=0))}a<i?(h=e[a]&31,A=a,u=h,s=0):s=-1}else s=0}if(A>=0&&s>=0){const d={data:e.subarray(A,i),type:u,state:s};o.push(d)}if(o.length===0){const d=this.getLastNalUnit(t.samples);d&&(d.data=ge(d.data,e))}return t.naluState=s,o}}class $S{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Xa(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)})}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,i=new Int8Array(e);let s=0;for(let r=32;r<t.length-16;r+=160,s+=16)i.set(t.subarray(r,r+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let r=32;r<t.length-16;r+=160,s+=16)t.set(i.subarray(s,s+16),r);return t}decryptAvcSample(t,e,i,s,r){const o=qu(r.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)})}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){s();return}const r=t[e].units;for(;!(i>=r.length);i++){const o=r[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(t,e,i,s,o),!this.decrypter.isSync()))return}}}}const Jt=188;class ei{constructor(t,e,i){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=t,this.config=e,this.typeSupported=i,this.videoParser=new zS}static probe(t){const e=ei.syncOffset(t);return e>0&&R.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),e!==-1}static syncOffset(t){const e=t.length;let i=Math.min(Jt*5,e-Jt)+1,s=0;for(;s<i;){let r=!1,o=-1,a=0;for(let l=s;l<e;l+=Jt)if(t[l]===71&&(e-l===Jt||t[l+Jt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Jt*99,t.length-Jt)+1)),r||(r=ia(t,l)===0),r&&a>1&&(o===0&&a>2||l+Jt>i))return o}else{if(a)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Ku[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ei.createTrack("video"),this._audioTrack=ei.createTrack("audio",s),this._id3Track=ei.createTrack("id3"),this._txtTrack=ei.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,s=!1){i||(this.sampleAes=null);let r;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=o.pid,A=o.pesData,u=a.pid,d=l.pid,f=a.pesData,g=l.pesData,p=null,m=this.pmtParsed,C=this._pmtId,E=t.length;if(this.remainderData&&(t=ge(this.remainderData,t),E=t.length,this.remainderData=null),E<Jt&&!s)return this.remainderData=t,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const v=Math.max(0,ei.syncOffset(t));E-=(E-v)%Jt,E<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));let y=0;for(let T=v;T<E;T+=Jt)if(t[T]===71){const x=!!(t[T+1]&64),F=ia(t,T),_=(t[T+3]&48)>>4;let w;if(_>1){if(w=T+5+t[T+4],w===T+Jt)continue}else w=T+4;switch(F){case h:x&&(A&&(r=Qi(A))&&this.videoParser.parseAVCPES(o,c,r,!1,this._duration),A={data:[],size:0}),A&&(A.data.push(t.subarray(w,T+Jt)),A.size+=T+Jt-w);break;case u:if(x){if(f&&(r=Qi(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r);break}f={data:[],size:0}}f&&(f.data.push(t.subarray(w,T+Jt)),f.size+=T+Jt-w);break;case d:x&&(g&&(r=Qi(g))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(w,T+Jt)),g.size+=T+Jt-w);break;case 0:x&&(w+=t[w]+1),C=this._pmtId=qS(t,w);break;case C:{x&&(w+=t[w]+1);const U=XS(t,w,this.typeSupported,i,this.observer);h=U.videoPid,h>0&&(o.pid=h,o.segmentCodec=U.segmentVideoCodec),u=U.audioPid,u>0&&(a.pid=u,a.segmentCodec=U.segmentAudioCodec),d=U.id3Pid,d>0&&(l.pid=d),p!==null&&!m&&(R.warn(`MPEG-TS PMT found at ${T} after unknown PID '${p}'. Backtracking to sync byte @${v} to parse all TS packets.`),p=null,T=v-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=F;break}}else y++;y>0&&rr(this.observer,new Error(`Found ${y} TS packet/s that do not start with 0x47`)),o.pesData=A,a.pesData=f,l.pesData=g;const S={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;this.remainderData=null;let e;return t?e=this.demux(t,-1,!1,!0):e={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:r}=t,o=i.pesData,a=e.pesData,l=s.pesData;let c;if(o&&(c=Qi(o))?(this.videoParser.parseAVCPES(i,r,c,!0,this._duration),i.pesData=null):i.pesData=o,a&&(c=Qi(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,c);break;case"mp3":this.parseMPEGPES(e,c);break;case"ac3":this.parseAC3PES(e,c);break}e.pesData=null}else a!=null&&a.size&&R.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;l&&(c=Qi(l))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=l}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new $S(this.observer,this.config,e);return this.decrypt(s,r)}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}destroy(){this._duration=0}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let r=e.data;if(s){this.aacOverFlow=null;const A=s.missing,u=s.sample.unit.byteLength;if(A===-1)r=ge(s.sample.unit,r);else{const d=u-A;s.sample.unit.set(r.subarray(0,A),d),t.samples.push(s.sample),i=s.missing}}let o,a;for(o=i,a=r.length;o<a-1&&!nr(r,o);o++);if(o!==i){let A;const u=o<a-1;if(u?A=`AAC PES did not start with ADTS header,offset:${o}`:A="No ADTS header found in AAC PES",rr(this.observer,new Error(A),u),!u)return}ud(t,this.observer,r,o,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(s){const A=dd(t.samplerate);l=s.sample.pts+A}else{R.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;o<a;)if(h=fd(t,r,o,l,c),o+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;o<a-1&&!nr(r,o);o++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,o=0;const a=e.pts;if(a===void 0){R.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<s;)if(pd(i,o)){const l=gd(t,i,o,a,r);if(l)o+=l.length,r++;else break}else o++}parseAC3PES(t,e){{const i=e.data,s=e.pts;if(s===void 0){R.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let o=0,a=0,l;for(;a<r&&(l=Id(t,i,a,s,o++))>0;)a+=l}}parseID3PES(t,e){if(e.pts===void 0){R.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Qt({},e,{type:this._videoTrack?ue.emsg:ue.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function ia(n,t){return((n[t+1]&31)<<8)+n[t+2]}function qS(n,t){return(n[t+10]&31)<<8|n[t+11]}function XS(n,t,e,i,s){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(n[t+1]&15)<<8|n[t+2],a=t+3+o-4,l=(n[t+10]&15)<<8|n[t+11];for(t+=12+l;t<a;){const c=ia(n,t),h=(n[t+3]&15)<<8|n[t+4];switch(n[t]){case 207:if(!i){ho("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=c);break;case 21:r.id3Pid===-1&&(r.id3Pid=c);break;case 219:if(!i){ho("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=c,r.segmentVideoCodec="avc");break;case 3:case 4:!e.mpeg&&!e.mp3?R.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="mp3");break;case 193:if(!i){ho("AC-3");break}case 129:e.ac3?r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="ac3"):R.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&h>0){let A=t+5,u=h;for(;u>2;){switch(n[A]){case 106:e.ac3!==!0?R.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3");break}const f=n[A+1]+2;A+=f,u-=f}}break;case 194:case 135:return rr(s,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return rr(s,new Error("Unsupported HEVC in M2TS found")),r}t+=h+5}return r}function rr(n,t,e){R.warn(`parsing error: ${t.message}`),n.emit(I.ERROR,I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:t,reason:t.message})}function ho(n){R.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Qi(n){let t=0,e,i,s,r,o;const a=n.data;if(!n||n.size===0)return null;for(;a[0].length<19&&a.length>1;)a[0]=ge(a[0],a[1]),a.splice(1,1);if(e=a[0],(e[0]<<16)+(e[1]<<8)+e[2]===1){if(i=(e[4]<<8)+e[5],i&&i>n.size-6)return null;const c=e[7];c&192&&(r=(e[9]&14)*536870912+(e[10]&255)*4194304+(e[11]&254)*16384+(e[12]&255)*128+(e[13]&254)/2,c&64?(o=(e[14]&14)*536870912+(e[15]&255)*4194304+(e[16]&254)*16384+(e[17]&255)*128+(e[18]&254)/2,r-o>60*9e4&&(R.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),s=e[8];let h=s+9;if(n.size<=h)return null;n.size-=h;const A=new Uint8Array(n.size);for(let u=0,d=a.length;u<d;u++){e=a[u];let f=e.byteLength;if(h)if(h>f){h-=f;continue}else e=e.subarray(h),f-=h,h=0;A.set(e,t),t+=f}return i&&(i-=s+3),{data:A,pts:r,dts:o,len:i}}return null}class WS extends Wa{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Ks(t,0);let i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&$a(e)!==void 0&&Cd(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(Ed(t,i))return R.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return NS(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return gd(t,e,i,this.basePTS,this.frameIndex)}}class Bh{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===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(e===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(e===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(e===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(e===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 Ze=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 t;for(t in L.types)L.types.hasOwnProperty(t)&&(L.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]),i=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:e,audio:i};const s=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 o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,o,l,o,a),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(t,4),s=0,i=8;s<r;s++)o.set(e[s],i),i+=e[s].byteLength;return o}static hdlr(t){return L.box(L.types.hdlr,L.HDLR_TYPES[t])}static mdat(t){return L.box(L.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Ze+1)),s=Math.floor(e%(Ze+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,t>>24&255,t>>16&255,t>>8&255,t&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return L.box(L.types.mdia,L.mdhd(t.timescale,t.duration),L.hdlr(t.type),L.minf(t))}static mfhd(t){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(t)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(t))}static moof(t,e,i){return L.box(L.types.moof,L.mfhd(t),L.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=L.trak(t[e]);return L.box.apply(null,[L.types.moov,L.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(L.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=L.trex(t[e]);return L.box.apply(null,[L.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Ze+1)),s=Math.floor(e%(Ze+1)),r=new Uint8Array([1,0,0,0,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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&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(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,i)}static stbl(t){return L.box(L.types.stbl,L.stsd(t),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(t){let e=[],i=[],s,r,o;for(s=0;s<t.sps.length;s++)r=t.sps[s],o=r.byteLength,e.push(o>>>8&255),e.push(o&255),e=e.concat(Array.prototype.slice.call(r));for(s=0;s<t.pps.length;s++)r=t.pps[s],o=r.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const a=L.box(L.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),l=t.width,c=t.height,h=t.pixelRatio[0],A=t.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]),a,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,A>>24,A>>16&255,A>>8&255,A&255])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0])}static mp4a(t){return L.box(L.types.mp4a,L.audioStsd(t),L.box(L.types.esds,L.esds(t)))}static mp3(t){return L.box(L.types[".mp3"],L.audioStsd(t))}static ac3(t){return L.box(L.types["ac-3"],L.audioStsd(t),L.box(L.types.dac3,t.config))}static stsd(t){return t.type==="audio"?t.segmentCodec==="mp3"&&t.codec==="mp3"?L.box(L.types.stsd,L.STSD,L.mp3(t)):t.segmentCodec==="ac3"?L.box(L.types.stsd,L.STSD,L.ac3(t)):L.box(L.types.stsd,L.STSD,L.mp4a(t)):L.box(L.types.stsd,L.STSD,L.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,s=t.width,r=t.height,o=Math.floor(i/(Ze+1)),a=Math.floor(i%(Ze+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,e>>24&255,e>>16&255,e>>8&255,e&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&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,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(t,e){const i=L.sdtp(t),s=t.id,r=Math.floor(e/(Ze+1)),o=Math.floor(e%(Ze+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),L.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,L.box(L.types.trak,L.tkhd(t),L.mdia(t))}static trex(t){const e=t.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,o=new Uint8Array(r);let a,l,c,h,A,u;for(e+=8+r,o.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),a=0;a<s;a++)l=i[a],c=l.duration,h=l.size,A=l.flags,u=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,A.isLeading<<2|A.dependsOn,A.isDependedOn<<6|A.hasRedundancy<<4|A.paddingValue<<1|A.isNonSync,A.degradPrio&61440,A.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*a);return L.box(L.types.trun,o)}static initSegment(t){L.types||L.init();const e=L.moov(t);return ge(L.FTYP,e)}}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 yd=9e4;function tl(n,t,e=1,i=!1){const s=n*t*e;return i?Math.round(s):s}function jS(n,t,e=1,i=!1){return tl(n,t,1/e,i)}function ys(n,t=!1){return tl(n,1e3,1/yd,t)}function ZS(n,t=1){return tl(n,yd,1/t)}const tT=10*1e3,vh=1024,eT=1152,iT=1536;let Oi=null,Ao=null;class Ln{constructor(t,e,i,s=""){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=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,Oi===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Oi=o?parseInt(o[1]):0}if(Ao===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Ao=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){R.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){R.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){R.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,s=t.reduce((r,o)=>{let a=o.pts,l=a-r;return l<-4294967296&&(e=!0,a=he(a,i),l=a-r),l>0?r:a},i);return e&&R.debug("PTS rollover detected"),s}remux(t,e,i,s,r,o,a,l){let c,h,A,u,d,f,g=r,p=r;const m=t.pid>-1,C=e.pid>-1,E=e.samples.length,v=t.samples.length>0,y=a&&E>0||E>1;if((!m||v)&&(!C||y)||this.ISGenerated||a){if(this.ISGenerated){var T,x,F,_;const W=this.videoTrackConfig;W&&(e.width!==W.width||e.height!==W.height||((T=e.pixelRatio)==null?void 0:T[0])!==((x=W.pixelRatio)==null?void 0:x[0])||((F=e.pixelRatio)==null?void 0:F[1])!==((_=W.pixelRatio)==null?void 0:_[1]))&&this.resetInitSegment()}else A=this.generateIS(t,e,r,o);const w=this.isVideoContiguous;let U=-1,O;if(y&&(U=sT(e.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,U>0){R.warn(`[mp4-remuxer]: Dropped ${U} out of ${E} video samples due to a missing keyframe`);const W=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(U),e.dropped+=U,p+=(e.samples[0].pts-W)/e.inputTimeScale,O=p}else U===-1&&(R.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(v&&y){const W=this.getVideoStartPts(e.samples),q=(he(t.samples[0].pts,W)-W)/e.inputTimeScale;g+=Math.max(0,q),p+=Math.max(0,-q)}if(v){if(t.samplerate||(R.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),A=this.generateIS(t,e,r,o)),h=this.remuxAudio(t,g,this.isAudioContiguous,o,C||y||l===et.AUDIO?p:void 0),y){const W=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(R.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),A=this.generateIS(t,e,r,o)),c=this.remuxVideo(e,p,w,W)}}else y&&(c=this.remuxVideo(e,p,w,0));c&&(c.firstKeyFrame=U,c.independent=U!==-1,c.firstKeyFramePTS=O)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=Bd(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=vd(s,r,this._initPTS))),{audio:h,video:c,initSegment:A,independent:f,text:u,id3:d}}generateIS(t,e,i,s){const r=t.samples,o=e.samples,a=this.typeSupported,l={},c=this._initPTS;let h=!c||s,A="audio/mp4",u,d,f;if(h&&(u=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(A="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}l.audio={id:"audio",container:A,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):L.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(f=t.inputTimeScale,!c||f!==c.timescale?u=d=r[0].pts-Math.round(f*i):h=!1)}if(e.sps&&e.pps&&o.length){if(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:L.initSegment([e]),metadata:{width:e.width,height:e.height}},h)if(f=e.inputTimeScale,!c||f!==c.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*i);d=Math.min(d,he(o[0].dts,g)-p),u=Math.min(u,g-p)}else h=!1;this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:u,timescale:f},this._initDTS={baseTime:d,timescale:f}):u=f=void 0,{tracks:l,initPTS:u,timescale:f}}remuxVideo(t,e,i,s){const r=t.inputTimeScale,o=t.samples,a=[],l=o.length,c=this._initPTS;let h=this.nextAvcDts,A=8,u=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!i||h===null){const V=e*r,G=o[0].pts-he(o[0].dts,o[0].pts);Oi&&h!==null&&Math.abs(V-G-h)<15e3?i=!0:h=V-G}const C=c.baseTime*r/c.timescale;for(let V=0;V<l;V++){const G=o[V];G.pts=he(G.pts-C,h),G.dts=he(G.dts-C,h),G.dts<o[V>0?V-1:V].dts&&(m=!0)}m&&o.sort(function(V,G){const H=V.dts-G.dts,X=V.pts-G.pts;return H||X}),d=o[0].dts,f=o[o.length-1].dts;const E=f-d,v=E?Math.round(E/(l-1)):u||t.inputTimeScale/30;if(i){const V=d-h,G=V>v,H=V<-1;if((G||H)&&(G?R.warn(`AVC: ${ys(V,!0)} ms (${V}dts) hole between fragments detected at ${e.toFixed(3)}`):R.warn(`AVC: ${ys(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!H||h>=o[0].pts||Oi)){d=h;const X=o[0].pts-V;if(G)o[0].dts=d,o[0].pts=X;else for(let Y=0;Y<o.length&&!(o[Y].dts>X);Y++)o[Y].dts-=V,o[Y].pts-=V;R.log(`Video: Initial PTS/DTS adjusted: ${ys(X,!0)}/${ys(d,!0)}, delta: ${ys(V,!0)} ms`)}}d=Math.max(0,d);let y=0,S=0,T=d;for(let V=0;V<l;V++){const G=o[V],H=G.units,X=H.length;let Y=0;for(let D=0;D<X;D++)Y+=H[D].data.length;S+=Y,y+=X,G.length=Y,G.dts<T?(G.dts=T,T+=v/4|0||1):T=G.dts,g=Math.min(G.pts,g),p=Math.max(G.pts,p)}f=o[l-1].dts;const x=S+4*y+8;let F;try{F=new Uint8Array(x)}catch(V){this.observer.emit(I.ERROR,I.ERROR,{type:ot.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:x,reason:`fail allocating video mdat ${x}`});return}const _=new DataView(F.buffer);_.setUint32(0,x),F.set(L.types.mdat,4);let w=!1,U=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,W=Number.NEGATIVE_INFINITY,K=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){const G=o[V],H=G.units;let X=0;for(let it=0,at=H.length;it<at;it++){const ht=H[it],Vt=ht.data,ne=ht.data.byteLength;_.setUint32(A,ne),A+=4,F.set(Vt,A),A+=ne,X+=4+ne}let Y;if(V<l-1)u=o[V+1].dts-G.dts,Y=o[V+1].pts-G.pts;else{const it=this.config,at=V>0?G.dts-o[V-1].dts:v;if(Y=V>0?G.pts-o[V-1].pts:v,it.stretchShortVideoTrack&&this.nextAudioPts!==null){const ht=Math.floor(it.maxBufferHole*r),Vt=(s?g+s*r:this.nextAudioPts)-G.pts;Vt>ht?(u=Vt-at,u<0?u=at:w=!0,R.log(`[mp4-remuxer]: It is approximately ${Vt/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=at}else u=at}const D=Math.round(G.pts-G.dts);U=Math.min(U,u),W=Math.max(W,u),O=Math.min(O,Y),K=Math.max(K,Y),a.push(new Sh(G.key,u,X,D))}if(a.length){if(Oi){if(Oi<70){const V=a[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(Ao&&K-O<W-U&&v/W<.025&&a[0].cts===0){R.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let V=d;for(let G=0,H=a.length;G<H;G++){const X=V+a[G].duration,Y=V+a[G].cts;if(G<H-1){const D=X+a[G+1].cts;a[G].duration=D-Y}else a[G].duration=G?a[G-1].duration:v;a[G].cts=0,V=X}}}u=w||!u?v:u,this.nextAvcDts=h=f+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const rt={data1:L.moof(t.sequenceNumber++,d,Qt({},t,{samples:a})),data2:F,startPTS:g/r,endPTS:(p+u)/r,startDTS:d/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,rt}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return eT;case"ac3":return iT;default:return vh}}remuxAudio(t,e,i,s,r){const o=t.inputTimeScale,a=t.samplerate?t.samplerate:o,l=o/a,c=this.getSamplesPerFrame(t),h=c*l,A=this._initPTS,u=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=r!==void 0;let g=t.samples,p=u?0:8,m=this.nextAudioPts||-1;const C=e*o,E=A.baseTime*o/A.timescale;if(this.isAudioContiguous=i=i||g.length&&m>0&&(s&&Math.abs(C-m)<9e3||Math.abs(he(g[0].pts-E,C)-m)<20*h),g.forEach(function(q){q.pts=he(q.pts-E,C)}),!i||m<0){if(g=g.filter(q=>q.pts>=0),!g.length)return;r===0?m=0:s&&!f?m=Math.max(0,C):m=g[0].pts}if(t.segmentCodec==="aac"){const q=this.config.maxAudioFramesDrift;for(let Z=0,rt=m;Z<g.length;Z++){const V=g[Z],G=V.pts,H=G-rt,X=Math.abs(1e3*H/o);if(H<=-q*h&&f)Z===0&&(R.warn(`Audio frame @ ${(G/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*H/o)} ms.`),this.nextAudioPts=m=rt=G);else if(H>=q*h&&X<tT&&f){let Y=Math.round(H/h);rt=G-Y*h,rt<0&&(Y--,rt+=h),Z===0&&(this.nextAudioPts=m=rt),R.warn(`[mp4-remuxer]: Injecting ${Y} audio frame @ ${(rt/o).toFixed(3)}s due to ${Math.round(1e3*H/o)} ms gap.`);for(let D=0;D<Y;D++){const it=Math.max(rt,0);let at=Bh.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);at||(R.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),at=V.unit.subarray()),g.splice(Z,0,{unit:at,pts:it}),rt+=h,Z++}}V.pts=rt,rt+=h}}let v=null,y=null,S,T=0,x=g.length;for(;x--;)T+=g[x].unit.byteLength;for(let q=0,Z=g.length;q<Z;q++){const rt=g[q],V=rt.unit;let G=rt.pts;if(y!==null){const X=d[q-1];X.duration=Math.round((G-y)/l)}else if(i&&t.segmentCodec==="aac"&&(G=m),v=G,T>0){T+=p;try{S=new Uint8Array(T)}catch(X){this.observer.emit(I.ERROR,I.ERROR,{type:ot.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:X,bytes:T,reason:`fail allocating audio mdat ${T}`});return}u||(new DataView(S.buffer).setUint32(0,T),S.set(L.types.mdat,4))}else return;S.set(V,p);const H=V.byteLength;p+=H,d.push(new Sh(!0,c,H,0)),y=G}const F=d.length;if(!F)return;const _=d[d.length-1];this.nextAudioPts=m=y+l*_.duration;const w=u?new Uint8Array(0):L.moof(t.sequenceNumber++,v/l,Qt({},t,{samples:d}));t.samples=[];const U=v/o,O=m/o,K={data1:w,data2:S,startPTS:U,endPTS:O,startDTS:U,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,K}remuxEmptyAudio(t,e,i,s){const r=t.inputTimeScale,o=t.samplerate?t.samplerate:r,a=r/o,l=this.nextAudioPts,c=this._initDTS,h=c.baseTime*9e4/c.timescale,A=(l!==null?l:s.startDTS*r)+h,u=s.endDTS*r+h,d=a*vh,f=Math.ceil((u-A)/d),g=Bh.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(R.warn("[mp4-remuxer]: remux empty Audio"),!g){R.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=A+m*d;p.push({unit:g,pts:C,dts:C})}return t.samples=p,this.remuxAudio(t,e,i,!1)}}function he(n,t){let e;if(t===null)return n;for(t<n?e=-8589934592:e=8589934592;Math.abs(n-t)>4294967296;)n+=e;return n}function sT(n){for(let t=0;t<n.length;t++)if(n[t].key)return t;return-1}function Bd(n,t,e,i){const s=n.samples.length;if(!s)return;const r=n.inputTimeScale;for(let a=0;a<s;a++){const l=n.samples[a];l.pts=he(l.pts-e.baseTime*r/e.timescale,t*r)/r,l.dts=he(l.dts-i.baseTime*r/i.timescale,t*r)/r}const o=n.samples;return n.samples=[],{samples:o}}function vd(n,t,e){const i=n.samples.length;if(!i)return;const s=n.inputTimeScale;for(let o=0;o<i;o++){const a=n.samples[o];a.pts=he(a.pts-e.baseTime*s/e.timescale,t*s)/s}n.samples.sort((o,a)=>o.pts-a.pts);const r=n.samples;return n.samples=[],{samples:r}}class Sh{constructor(t,e,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class nT{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(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(uv(t,s)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=Ju(t);s.audio&&(e=Th(s.audio,Tt.AUDIO)),s.video&&(i=Th(s.video,Tt.VIDEO));const r={};s.audio&&s.video?r.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:s.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?r.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:R.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,i,s,r,o){var a,l;let{initPTS:c,lastEndTime:h}=this;const A={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};j(h)||(h=this.lastEndTime=r||0);const u=e.samples;if(!(u!=null&&u.length))return A;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(u),f=this.initData),!((l=f)!=null&&l.length))return R.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),A;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=fv(u,f),p=dv(f,u),m=p===null?r:p;(rT(c,m,r,g)||d.timescale!==c.timescale&&o)&&(d.initPTS=m-r,c&&c.timescale===1&&R.warn(`Adjusting initPTS by ${d.initPTS-c.baseTime}`),this.initPTS=c={baseTime:d.initPTS,timescale:1});const C=t?m-c.baseTime/c.timescale:h,E=C+g;mv(f,u,c.baseTime/c.timescale),g>0?this.lastEndTime=E:(R.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const v=!!f.audio,y=!!f.video;let S="";v&&(S+="audio"),y&&(S+="video");const T={data1:u,startPTS:C,startDTS:C,endPTS:E,endDTS:E,type:S,hasAudio:v,hasVideo:y,nb:1,dropped:0};return A.audio=T.type==="audio"?T:void 0,A.video=T.type!=="audio"?T:void 0,A.initSegment=d,A.id3=Bd(i,r,c,c),s.samples.length&&(A.text=vd(s,r,c)),A}}function rT(n,t,e,i){if(n===null)return!0;const s=Math.max(i,1),r=t-n.baseTime/n.timescale;return Math.abs(r-e)>s}function Th(n,t){const e=n==null?void 0:n.codec;if(e&&e.length>4)return e;if(t===Tt.AUDIO){if(e==="ec-3"||e==="ac-3"||e==="alac")return e;if(e==="fLaC"||e==="Opus")return jn(e,!1);const i="mp4a.40.5";return R.info(`Parsed audio codec "${e}" or audio object type not handled. Using "${i}"`),i}return R.warn(`Unhandled video codec "${e}"`),e==="hvc1"||e==="hev1"?"hvc1.1.6.L120.90":e==="av01"?"av01.0.04M.08":"avc1.42e01e"}let ze;try{ze=self.performance.now.bind(self.performance)}catch{R.debug("Unable to use Performance API on this environment"),ze=Xi==null?void 0:Xi.Date.now}const bn=[{demux:YS,remux:nT},{demux:ei,remux:Ln},{demux:HS,remux:Ln},{demux:WS,remux:Ln}];bn.splice(2,0,{demux:VS,remux:Ln});class _h{constructor(t,e,i,s,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=t,this.typeSupported=e,this.config=i,this.vendor=s,this.id=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const r=i.transmuxing;r.executeStart=ze();let o=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:h,trackSwitch:A,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:C,initSegmentData:E}=l,v=oT(o,e);if(v&&v.method==="AES-128"){const x=this.getDecrypter();if(x.isSync()){let F=x.softwareDecrypt(o,v.key.buffer,v.iv.buffer);if(i.part>-1&&(F=x.flush()),!F)return r.executeEnd=ze(),uo(i);o=new Uint8Array(F)}else return this.decryptionPromise=x.webCryptoDecrypt(o,v.key.buffer,v.iv.buffer).then(F=>{const _=this.push(F,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}const y=this.needsProbing(h,A);if(y){const x=this.configureTransmuxer(o);if(x)return R.warn(`[transmuxer] ${x.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),r.executeEnd=ze(),uo(i)}(h||A||f||y)&&this.resetInitSegment(E,g,p,C,e),(h||f||y)&&this.resetInitialTimestamp(m),c||this.resetContiguity();const S=this.transmux(o,v,d,u,i),T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,r.executeEnd=ze(),S}flush(t){const e=t.transmuxing;e.executeStart=ze();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(t));const o=[],{timeOffset:a}=s;if(i){const A=i.flush();A&&o.push(this.push(A,null,t))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return e.executeEnd=ze(),[uo(t)];const h=l.flush(a);return Fn(h)?h.then(A=>(this.flushRemux(o,A,t),o)):(this.flushRemux(o,h,t),o)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:o,textTrack:a}=e,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;R.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(s,r,o,a,c,l,!0,this.id);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=ze()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;!e||!i||(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;!t||!e||(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(t,e,i,s),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let o;return e&&e.method==="SAMPLE-AES"?o=this.transmuxSampleAes(t,e,i,s,r):o=this.transmuxUnencrypted(t,i,s,r),o}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,a,l,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s,vendor:r}=this;let o;for(let u=0,d=bn.length;u<d;u++){var a;if((a=bn[u].demux)!=null&&a.probe(t)){o=bn[u];break}}if(!o)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=o.remux,A=o.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(i,e,s,r)),(!l||!(l instanceof A))&&(this.demuxer=new A(i,e,s),this.probe=A.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Xa(this.config)),t}}function oT(n,t){let e=null;return n.byteLength>0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const uo=n=>({remuxResult:{},chunkMeta:n});function Fn(n){return"then"in n&&n.then instanceof Function}class aT{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class lT{constructor(t,e,i,s,r,o){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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=o}}var Sd={exports:{}};(function(n){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,A,u){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new s(h,A||l,u),f=e?e+c:c;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],d]:l._events[f].push(d):(l._events[f]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,A;if(this._eventsCount===0)return c;for(A in h=this._events)t.call(h,A)&&c.push(e?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=e?e+c:c,A=this._events[h];if(!A)return[];if(A.fn)return[A.fn];for(var u=0,d=A.length,f=new Array(d);u<d;u++)f[u]=A[u].fn;return f},a.prototype.listenerCount=function(c){var h=e?e+c:c,A=this._events[h];return A?A.fn?1:A.length:0},a.prototype.emit=function(c,h,A,u,d,f){var g=e?e+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,A),!0;case 4:return p.fn.call(p.context,h,A,u),!0;case 5:return p.fn.call(p.context,h,A,u,d),!0;case 6:return p.fn.call(p.context,h,A,u,d,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 v=p.length,y;for(E=0;E<v;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,A);break;case 4:p[E].fn.call(p[E].context,h,A,u);break;default:if(!C)for(y=1,C=new Array(m-1);y<m;y++)C[y-1]=arguments[y];p[E].fn.apply(p[E].context,C)}}return!0},a.prototype.on=function(c,h,A){return r(this,c,h,A,!1)},a.prototype.once=function(c,h,A){return r(this,c,h,A,!0)},a.prototype.removeListener=function(c,h,A,u){var d=e?e+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var f=this._events[d];if(f.fn)f.fn===h&&(!u||f.once)&&(!A||f.context===A)&&o(this,d);else{for(var g=0,p=[],m=f.length;g<m;g++)(f[g].fn!==h||u&&!f[g].once||A&&f[g].context!==A)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=e?e+c:c,this._events[h]&&o(this,h)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,n.exports=a})(Sd);var cT=Sd.exports,el=kB(cT);class Td{constructor(t,e,i,s){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=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const o=(c,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,c===I.ERROR&&(this.error=h.error),this.hls.trigger(c,h)};this.observer=new el,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=ai(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||DS())){try{r.workerPath?(R.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=wS(r.workerPath)):(R.log(`injecting Web Worker for "${e}"`),this.workerContext=RS()),this.onwmsg=A=>this.onWorkerMessage(A);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=A=>{const u=new Error(`${A.message} (${A.filename}:${A.lineno})`);r.enableWorker=!1,R.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:ot.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:e,config:JSON.stringify(r)})}catch(h){R.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new _h(this.observer,l,r,"",e)}return}this.transmuxer=new _h(this.observer,l,r,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,s,r,o,a,l,c,h){var A,u;c.transmuxing.start=self.performance.now();const{transmuxer:d}=this,f=o?o.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,v=this.part?c.part-this.part.index:-1,y=E===0&&c.id>1&&c.id===(p==null?void 0:p.stats.chunkCount),S=!C&&(E===1||E===0&&(v===1||y&&v<=0)),T=self.performance.now();(C||E||r.stats.parsing.start===0)&&(r.stats.parsing.start=T),o&&(v||!S)&&(o.stats.parsing.start=T);const x=!(p&&((A=r.initSegment)==null?void 0:A.url)===((u=p.initSegment)==null?void 0:u.url)),F=new lT(m,S,l,C,f,x);if(!S||m||x){R.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: ${S}
21
+ accurateTimeOffset: ${l}
22
+ timeOffset: ${f}
23
+ initSegmentChange: ${x}`);const _=new aT(i,s,e,a,h);this.configureTransmuxer(_)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:c,state:F},t instanceof ArrayBuffer?[t]:[]);else if(d){const _=d.push(t,g,c,F);Fn(_)?(d.async=!0,_.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,c,"transmuxer-interface push error")})):(d.async=!1,this.handleTransmuxComplete(_))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Fn(i)||e.async?(Fn(i)||(i=Promise.resolve(i)),i.then(r=>{this.handleFlushResult(r,t)}).catch(r=>{this.transmuxerError(r,t,"transmuxer-interface flush error")})):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(!(e!=null&&e.event)){R.warn(`worker message received with no ${e?"event name":"data"}`);return}const i=this.hls;if(this.hls)switch(e.event){case"init":{var s;const r=(s=this.workerContext)==null?void 0:s.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(e.data);break}case"flush":{this.onFlush(e.data);break}case"workerLog":R[e.data.logType]&&R[e.data.logType](e.data.message);break;default:{e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data);break}}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function _d(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(!ji(n[e].attrs,t[e].attrs))return!1;return!0}function ji(n,t,e){const i=n["STABLE-RENDITION-ID"];return i&&!e?i===t["STABLE-RENDITION-ID"]:!(e||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>n[s]!==t[s])}function sa(n,t){return t.label.toLowerCase()===n.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(n.lang||"").toLowerCase())}const xh=100;class xd extends Br{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",et.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:t}=this;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.ERROR,this.onError,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.ERROR,this.onError,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r}){if(i==="main"){const o=e.cc;this.initPTS[e.cc]={baseTime:s,timescale:r},this.log(`InitPTS for cc: ${o} found from main: ${s}`),this.videoTrackCC=o,this.state===N.WAITING_INIT_PTS&&this.tick()}}startLoad(t){if(!this.levels){this.startPosition=t,this.state=N.STOPPED;return}const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(xh),e>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=N.IDLE):(this.loadedmetadata=!1,this.state=N.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case N.IDLE:this.doTickIdle();break;case N.WAITING_TRACK:{var t;const{levels:i,trackId:s}=this,r=i==null||(t=i[s])==null?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=N.WAITING_INIT_PTS}break}case N.FRAG_LOADING_WAITING_RETRY:{var e;const i=performance.now(),s=this.retryDate;if(!s||i>=s||(e=this.media)!=null&&e.seeking){const{levels:r,trackId:o}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((r==null?void 0:r[o])||null),this.state=N.IDLE}break}case N.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:r,cache:o,complete:a}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=N.FRAG_LOADING;const l=o.flush(),c={frag:s,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),a&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=Rt.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);ea(c.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=N.IDLE}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=N.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:s}=this,r=t.config;if(!this.buffering||!i&&(this.startFragRequested||!r.startFragPrefetch)||!(e!=null&&e[s]))return;const o=e[s],a=o.details;if(!a||a.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(a)){this.state=N.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Tt.AUDIO,et.AUDIO));const c=this.getFwdBufferInfo(l,et.AUDIO);if(c===null)return;const{bufferedTrack:h,switchingTrack:A}=this;if(!A&&this._streamEnded(c,a)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=N.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,et.MAIN),d=c.len,f=this.getMaxBufferLength(u==null?void 0:u.len),g=a.fragments,p=g[0].start;let m=this.flushing?this.getLoadPosition():c.end;if(A&&i){const y=this.getLoadPosition();h&&!ji(A.attrs,h.attrs)&&(m=y),a.PTSKnown&&y<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(d>=f&&!A&&m<g[g.length-1].start)return;let C=this.getNextFragment(m,a),E=!1;if(C&&this.isLoopLoading(C,m)&&(E=!!C.gap,C=this.getNextFragmentLoopLoading(C,a,c,et.MAIN,f)),!C){this.bufferFlushed=!0;return}const v=u&&C.start>u.end+a.targetduration;if(v||!(u!=null&&u.len)&&c.len){const y=this.getAppendedFrag(C.start,et.MAIN);if(y===null||(E||(E=!!y.gap||!!v&&u.len===0),v&&!E||E&&c.nextStart&&c.nextStart<y.end))return}this.loadFragment(C,o,m)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(i=>new Bi(i))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(xh):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=N.IDLE,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,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(t,e){this.mainDetails=e.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(I.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=e;return}const{levels:s}=this,{details:r,id:o}=e;if(!s){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Audio track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=s[o];let l=0;if(r.live||(i=a.details)!=null&&i.live){this.checkLiveUpdate(r);const h=this.mainDetails;if(r.deltaUpdateFailed||!h)return;if(!a.details&&r.hasProgramDateTime&&h.hasProgramDateTime)sr(r,h),l=r.fragments[0].start;else{var c;l=this.alignPlaylists(r,a.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}a.details=r,this.levelLastLoaded=a,!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(t){var e;const{frag:i,part:s,payload:r}=t,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[a];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(i.start);return}const A=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Td(this.hls,et.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=(e=i.initSegment)==null?void 0:e.data;if(d!==void 0){const p=s?s.index:-1,m=p!==-1,C=new yr(i.level,i.sn,i.stats.chunkCount,r.byteLength,p,m);u.push(r,f,A,"",i,s,h.totalduration,!1,C,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new cd,complete:!1};g.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=N.WAITING_INIT_PTS}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type!==et.AUDIO){if(!this.loadedmetadata&&i.type===et.MAIN){const r=this.videoBuffer||this.media;r&&Rt.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,$t({},r)))}this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=N.ERROR;return}switch(e.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(et.AUDIO,e);break;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===N.WAITING_TRACK&&((i=e.context)==null?void 0:i.type)===Ct.AUDIO_TRACK&&(this.state=N.IDLE);break;case M.BUFFER_APPEND_ERROR:case M.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="audio")return;if(e.details===M.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushing(t,{type:e}){e!==Tt.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Tt.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===N.ENDED&&(this.state=N.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,e,et.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:o}=t,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:h}=a,{details:A}=h,{audio:u,text:d,id3:f,initSegment:g}=r;if(this.fragContextChanged(l)||!A){this.fragmentTracker.removeFragment(l);return}if(this.state=N.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(h,g.tracks,p,o),s.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(u){const{startPTS:p,endPTS:m,startDTS:C,endDTS:E}=u;c&&(c.elementaryStreams[Tt.AUDIO]={startPTS:p,endPTS:m,startDTS:C,endDTS:E}),l.setElementaryStreamInfo(Tt.AUDIO,p,m,C,E),this.bufferFragmentData(u,l,c,o)}if(f!=null&&(e=f.samples)!=null&&e.length){const p=Qt({id:i,frag:l,details:A},f);s.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=Qt({id:i,frag:l,details:A},d);s.trigger(I.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(t,e,i,s){if(this.state!==N.PARSING)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.id="audio";const o=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${o}/${r.codec}]`),o&&o.split(",").length===1&&(r.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,e);const a=r.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);if(this.fragCurrent=t,this.switchingTrack||s===zt.NOT_LOADED||s===zt.PARTIAL){var r;if(t.sn==="initSegment")this._loadInitSegment(t,e);else if((r=e.details)!=null&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=N.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragments[0].start!==e.details.fragments[0].start&&sr(e.details,o)}else this.startFragRequested=!0,super.loadFragment(t,e,i)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:i}=this,s=i==null?void 0:i.attrs,r=t.attrs;e&&s&&(s.CHANNELS!==r.CHANNELS||i.name!==t.name||i.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(I.AUDIO_TRACK_SWITCHED,$t({},t))}}class Dd extends Ir{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.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(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,o=this.tracksInGroup[i];if(!o||o.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=e.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,d)=>{u.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!r&&l){const u=Qe(l,a,Pi);if(u>-1)r=a[u];else{const d=Qe(l,this.tracks);r=this.tracks[d]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,h);const A=this.trackId;if(c!==-1&&A===-1)this.setAudioTrack(c);else if(a.length&&A===-1){var o;const u=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(u.message),this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(t,e){e.fatal||!e.context||e.context.type===Ct.AUDIO_TRACK&&e.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(e.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&zi(t,s,Pi))return s;const r=Qe(t,this.tracksInGroup,Pi);if(r>-1){const o=this.tracksInGroup[r];return this.setAudioTrack(r),o}else if(s){let o=e.loadLevel;o===-1&&(o=e.firstAutoLevel);const a=uS(t,e.levels,i,o,Pi);if(a===-1)return null;e.nextLoadLevel=a}if(t.channels||t.audioCodec){const o=Qe(t,i);if(o>-1)return i[o]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length){this.warn(`Invalid audio track id: ${t}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],r=s.details&&!s.details.live;if(t===this.trackId&&s===i&&r||(this.log(`Switching to audio-track ${t} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=t,this.currentTrack=s,this.hls.trigger(I.AUDIO_TRACK_SWITCHING,$t({},s)),r))return;const o=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(o)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if(!(this.selectDefaultTrack&&!s.default)&&(!t||zi(t,s,Pi)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:o,audioCodec:a,channels:l}=t;for(let c=0;c<e.length;c++){const h=e[c];if(zi({name:i,lang:s,assocLang:r,characteristics:o,audioCodec:a,channels:l},h,Pi))return c}for(let c=0;c<e.length;c++){const h=e[c];if(ji(t.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<e.length;c++){const h=e[c];if(ji(t.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const i=e.id,s=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`loading audio-track playlist ${i} "${e.name}" lang:${e.lang} group:${s}`),this.clearTimer(),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null})}}}const Dh=500;class Rd extends Br{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",et.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.ERROR,this.onError,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.ERROR,this.onError,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=N.IDLE,this.setInterval(Dh),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragPrevious=i,this.state=N.IDLE,!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const a=i.start;for(let c=0;c<r.length;c++)if(a>=r[c].start&&a<=r[c].end){o=r[c];break}const l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(i===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;e.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=r){o.shift();continue}else if(o[a].start<r)o[a].start=r;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(i,r,et.SUBTITLE)}}onFragBuffered(t,e){if(!this.loadedmetadata&&e.frag.type===et.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(t,e){const i=e.frag;(i==null?void 0:i.type)===et.SUBTITLE&&(e.details===M.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==N.STOPPED&&(this.state=N.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(this.levels&&_d(this.levels,e)){this.levels=e.map(i=>new Bi(i));return}this.tracksBuffered=[],this.levels=e.map(i=>{const s=new Bi(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,et.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(Dh)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:o,id:a}=e;if(!r){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=r[a];if(a>=r.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(o.live||(i=l.details)!=null&&i.live){const A=this.mainDetails;if(o.deltaUpdateFailed||!A)return;const u=A.fragments[0];if(!l.details)o.hasProgramDateTime&&A.hasProgramDateTime?(sr(o,A),c=o.fragments[0].start):u&&(c=u.start,ta(o,c));else{var h;c=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&u&&(c=u.start,ta(o,c))}}l.details=o,this.levelLastLoaded=l,a===s&&(!this.startFragRequested&&(this.mainDetails||!o.live)&&this.setStartPosition(this.mainDetails||o,c),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===N.IDLE&&(ir(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&s.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(a=>{throw r.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:e}),a}).then(a=>{const l=performance.now();r.trigger(I.FRAG_DECRYPTED,{frag:e,payload:a,stats:{tstart:o,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=N.IDLE})}}doTick(){if(!this.media){this.state=N.IDLE;return}if(this.state===N.IDLE){const{currentTrackId:t,levels:e}=this,i=e==null?void 0:e[t];if(!i||!e.length||!i.details)return;const{config:s}=this,r=this.getLoadPosition(),o=Rt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:l}=o,c=this.getFwdBufferInfo(this.media,et.MAIN),h=i.details,A=this.getMaxBufferLength(c==null?void 0:c.len)+h.levelTargetDuration;if(l>A)return;const u=h.fragments,d=u.length,f=h.edge;let g=null;const p=this.fragPrevious;if(a<f){const m=s.maxFragLookUpTolerance,C=a>f-m?0:m;g=ir(p,u,Math.max(u[0].start,a),C),!g&&p&&p.start<u[0].start&&(g=u[0])}else g=u[d-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const m=g.sn-h.startSN,C=u[m-1];C&&C.cc===g.cc&&this.fragmentTracker.getState(C)===zt.NOT_LOADED&&(g=C)}this.fragmentTracker.getState(g)===zt.NOT_LOADED&&this.loadFragment(g,i,a)}}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,i){this.fragCurrent=t,t.sn==="initSegment"?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,i))}get mediaBufferTimeRanges(){return new hT(this.tracksBuffered[this.currentTrackId]||[])}}class hT{constructor(t){this.buffered=void 0;const e=(i,s,r)=>{if(s=s>>>0,s>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return t[s][i]};this.buffered={get length(){return t.length},end(i){return e("end",i,t.length)},start(i){return e("start",i,t.length)}}}}class wd extends Ir{constructor(t){super(t,"[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 e=null;const i=Rn(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")e=i[r];else if(i[r].mode==="showing"){e=i[r];break}const s=this.findTrackForTextTrack(e);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},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(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}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),Rn(this.media.textTracks).forEach(e=>{Hi(e)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,o=this.tracksInGroup[i];if(!o||o.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=e.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,A)=>{h.id=A});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!r&&a){this.selectDefaultTrack=!1;const h=Qe(a,o);if(h>-1)r=o[h];else{const A=Qe(a,this.tracks);r=this.tracks[A]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if(!(i&&!r.default||!i&&!t)&&(!t||zi(r,t)))return s}if(t){for(let s=0;s<e.length;s++){const r=e[s];if(ji(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(ji(t.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if(sa(s,t))return i}}return-1}onError(t,e){e.fatal||!e.context||e.context.type===Ct.SUBTITLE_TRACK&&e.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(e.context.groupId)!==-1)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&zi(t,i))return i;const s=Qe(t,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s),r}else{if(i)return null;{const r=Qe(t,e);if(r>-1)return e[r]}}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const i=e.id,s=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Rn(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(r=>sa(i,r))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(r=>{r.mode!=="disabled"&&r!==s&&(r.mode="disabled")}),s){const r=this.subtitleDisplay?"showing":"hidden";s.mode!==r&&(s.mode=r)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=e.length||!j(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t]||null;if(this.trackId=t,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:t});return}const r=!!s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${t}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:o,groupId:a="",name:l,type:c,url:h}=s;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:h});const A=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(A)}}class AT{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,i){const s=this.queues[e];s.push(t),s.length===1&&!i&&this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise(r=>{e=r}),s={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,t),i}executeNext(t){const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(s){R.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${s}`),i.onError(s);const r=this.buffers[t];r!=null&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Rh=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class Ld{constructor(t){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=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:s}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(I.MEDIA_ATTACHED,{media:i,mediaSource:s})),s&&s.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&R.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=t;const e="[buffer-controller]";this.appendSource=xv(ai(t.config.preferManagedMediaSource)),this.log=R.log.bind(R,e),this.warn=R.warn.bind(R,e),this.error=R.error.bind(R,e),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:t}=this;t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_APPENDING,this.onBufferAppending,this),t.on(I.BUFFER_CODECS,this.onBufferCodecs,this),t.on(I.BUFFER_EOS,this.onBufferEos,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(I.FRAG_PARSED,this.onFragParsed,this),t.on(I.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_APPENDING,this.onBufferAppending,this),t.off(I.BUFFER_CODECS,this.onBufferCodecs,this),t.off(I.BUFFER_EOS,this.onBufferEos,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(I.FRAG_PARSED,this.onFragParsed,this),t.off(I.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new AT(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(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media,s=ai(this.appendSource);if(i&&s){var r;const o=this.mediaSource=new s;this.log(`created media source: ${(r=o.constructor)==null?void 0:r.name}`),o.addEventListener("sourceopen",this._onMediaSourceOpen),o.addEventListener("sourceended",this._onMediaSourceEnded),o.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(o.addEventListener("startstreaming",this._onStartStreaming),o.addEventListener("endstreaming",this._onEndStreaming));const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&o instanceof l,wh(i),uT(i,a),i.load()}catch{i.src=a}else i.src=a;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(this.log("media source detaching"),e.readyState==="open")try{e.endOfStream()}catch(s){this.warn(`onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(t.removeAttribute("src"),this.appendSource&&wh(t),t.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(I.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{this.resetBuffer(t)}),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(t){const e=this.sourceBuffer[t];try{if(e){var i;this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}}catch(s){this.warn(`onBufferReset ${t}`,s)}}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length,s=Object.keys(e);if(s.forEach(o=>{if(i){const l=this.tracks[o];if(l&&typeof l.buffer.changeType=="function"){var a;const{id:c,codec:h,levelCodec:A,container:u,metadata:d}=e[o],f=jc(l.codec,l.levelCodec),g=f==null?void 0:f.replace(Rh,"$1");let p=jc(h,A);const m=(a=p)==null?void 0:a.replace(Rh,"$1");if(p&&g!==m){o.slice(0,5)==="audio"&&(p=jn(p,this.appendSource));const C=`${u};codecs=${p}`;this.appendChangeType(o,C),this.log(`switching codec ${f} to ${p}`),this.tracks[o]={buffer:l.buffer,codec:h,container:u,levelCodec:A,metadata:d,id:c}}}}else this.pendingTracks[o]=e[o]}),i)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:i}=this,s={execute:()=>{const r=this.sourceBuffer[t];r&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${t} SourceBuffer type`,r)}};i.append(s,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:i,operationQueue:s,tracks:r}=this,{data:o,type:a,frag:l,part:c,chunkMeta:h}=e,A=h.buffering[a],u=self.performance.now();A.start=u;const d=l.stats.buffering,f=c?c.stats.buffering:null;d.start===0&&(d.start=u),f&&f.start===0&&(f.start=u);const g=r.audio;let p=!1;a==="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(A.executeStart=self.performance.now(),p){const E=this.sourceBuffer[a];if(E){const v=m-E.timestampOffset;Math.abs(v)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${m} (delta: ${v}) sn: ${l.sn})`),E.timestampOffset=m)}}this.appendExecutor(o,a)},onStart:()=>{},onComplete:()=>{const E=self.performance.now();A.executeEnd=A.end=E,d.first===0&&(d.first=E),f&&f.first===0&&(f.first=E);const{sourceBuffer:v}=this,y={};for(const S in v)y[S]=Rt.getBuffered(v[S]);this.appendErrors[a]=0,a==="audio"||a==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:a,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:y})},onError:E=>{const v={type:ot.MEDIA_ERROR,parent:l.type,details:M.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:l,part:c,chunkMeta:h,error:E,err:E,fatal:!1};if(E.code===DOMException.QUOTA_EXCEEDED_ERR)v.details=M.BUFFER_FULL_ERROR;else{const y=++this.appendErrors[a];v.details=M.BUFFER_APPEND_ERROR,this.warn(`Failed ${y}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),y>=i.config.appendErrorMaxRetry&&(v.fatal=!0)}i.trigger(I.ERROR,v)}};s.append(C,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:i}=this,s=r=>({execute:this.removeExecutor.bind(this,r,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:r})},onError:o=>{this.warn(`Failed to remove from ${r} SourceBuffer`,o)}});e.type?i.append(s(e.type),e.type):this.getSourceBufferTypes().forEach(r=>{i.append(s(r),r)})}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],o=s?s.elementaryStreams:i.elementaryStreams;o[Tt.AUDIOVIDEO]?r.push("audiovideo"):(o[Tt.AUDIO]&&r.push("audio"),o[Tt.VIDEO]&&r.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const c=s?s.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((s,r)=>{const o=this.sourceBuffer[r];return o&&(!e.type||e.type===r)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${r} sourceBuffer now EOS`))),s&&!!(!o||o.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const o=this.sourceBuffer[r];o&&(o.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream()}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||e===null||!this.getSourceBufferTypes().length)return;const r=t.config,o=i.currentTime,a=e.levelTargetDuration,l=e.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(j(l)&&l>0){const c=Math.max(l,a),h=Math.floor(o/a)*a-c;this.flushBackBuffer(o,a,h)}if(j(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(c,a),A=Math.floor(o/a)*a+h;this.flushFrontBuffer(o,a,A)}}flushBackBuffer(t,e,i){const{details:s,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(a=>{const l=r[a];if(l){const c=Rt.getBuffered(l);if(c.length>0&&i>c.start(0)){if(this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i}),s!=null&&s.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&c.end(c.length-1)-t<e*2){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:a})}}})}flushFrontBuffer(t,e,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(o=>{const a=s[o];if(a){const l=Rt.getBuffered(a),c=l.length;if(c<2)return;const h=l.start(c-1),A=l.end(c-1);if(i>h||t>=h&&t<=A)return;if(a.ended&&t-A<2*e){this.log(`Cannot flush ${o} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:o})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:t,hls:e,media:i,mediaSource:s}=this,r=t.fragments[0].start+t.totalduration,o=i.duration,a=j(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(t)):(r>a&&r>o||!j(o))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),s.duration=r)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&e!=null&&e.setLiveSeekableRange){const r=Math.max(0,i[0].start),o=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${o}.`),e.setLiveSeekableRange(r,o)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&(!t||s===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(I.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(o=>{e.executeNext(o)});else{const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:o,reason:o.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){var s;const o=t[r];if(!o)throw Error(`source buffer exists for track ${r}, however track does not`);let a=((s=o.levelCodec)==null?void 0:s.indexOf(","))===-1?o.levelCodec:o.codec;a&&r.slice(0,5)==="audio"&&(a=jn(a,this.appendSource));const l=`${o.container};codecs=${a}`;this.log(`creating sourceBuffer(${l})`);try{const c=e[r]=i.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",(A,u)=>{const d=u.removedRanges;d!=null&&d.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:a,container:o.container,levelCodec:o.levelCodec,metadata:o.metadata,id:o.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var t,e;const i=((t=this.media)==null||(e=t.querySelector)==null?void 0:e.call(t,"source"))||this.media;return i==null?void 0:i.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const{operationQueue:i}=this;i.current(t).onComplete(),i.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(s)}removeExecutor(t,e,i){const{media:s,mediaSource:r,operationQueue:o,sourceBuffer:a}=this,l=a[t];if(!s||!r||!l){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(t);return}const c=j(s.duration)?s.duration:1/0,h=j(r.duration)?r.duration:1/0,A=Math.max(0,e),u=Math.min(i,c,h);u>A&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${A},${u}] from the ${t} SourceBuffer`),l.remove(A,u)):o.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.sourceBuffer[e];if(!i){if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);return}const{operationQueue:i}=this,s=e.map(r=>i.appendBlocker(r));Promise.all(s).then(()=>{t(),e.forEach(r=>{const o=this.sourceBuffer[r];o!=null&&o.updating||i.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const s=this.sourceBuffer[t];if(!s)return;const r=i.bind(this,t);this.listeners[t].push({event:e,listener:r}),s.addEventListener(e,r)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(i=>{e.removeEventListener(i.event,i.listener)})}}function wh(n){const t=n.querySelectorAll("source");[].slice.call(t).forEach(e=>{n.removeChild(e)})}function uT(n,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,n.appendChild(e)}const dT={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},bd=n=>String.fromCharCode(dT[n]||n),Ie=15,Ke=100,fT={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},gT={17:2,18:4,21:6,22:8,23:10,19:13,20:15},mT={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},pT={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ET=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CT{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i=typeof e=="function"?e():e;R.log(`${this.time} [${t}] ${i}`)}}}const fi=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class Fd{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(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class IT{constructor(){this.uchar=" ",this.penState=new Fd}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class yT{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Fd,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Ke;e++)this.chars.push(new IT);this.logger=t}equals(t){for(let e=0;e<Ke;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Ke;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Ke;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ke)}moveCursor(t){const e=this.pos+t;if(t>1)for(let i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=bd(t);if(this.pos>=Ke){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<Ke;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Ke;i++){const s=this.chars[i].uchar;s!==" "&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class fo{constructor(t){this.rows=[],this.currRow=Ie-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Ie;e++)this.rows.push(new yT(t));this.logger=t}reset(){for(let t=0;t<Ie;t++)this.rows[t].clear();this.currRow=Ie-1}equals(t){let e=!0;for(let i=0;i<Ie;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Ie;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Ie;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let a=0;a<Ie;a++)this.rows[a].clear();const r=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[r].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[e-this.nrRollUpRows+c+1].copy(o.rows[r+c])}}this.currRow=e;const i=this.rows[this.currRow];if(t.indent!==null){const r=t.indent,o=Math.max(r-1,0);i.setCursor(t.indent),t.color=i.chars[o].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let r=0;r<Ie;r++){const o=this.rows[r].getTextString();o&&(s=r+1,t?e.push("Row "+s+": '"+o+"'"):e.push(o.trim()))}return e.length>0&&(t?i="["+e.join(" | ")+"]":i=e.join(`
24
+ `)),i}getTextAndFormat(){return this.rows}}class Lh{constructor(t,e,i){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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new fo(i),this.nonDisplayedMemory=new fo(i),this.lastOutputScreen=new fo(i),this.currRollUpRow=this.displayedMemory.rows[Ie-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ie-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),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=t)}insertChars(t){for(let i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}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 t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2===1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class bh{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=vT(),this.logger=void 0;const s=this.logger=new CT;this.channels=[null,new Lh(t,e,s),new Lh(t+1,i,s)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let i=0;i<e.length;i+=2){const s=e[i]&127,r=e[i+1]&127;let o=!1,a=null;if(s===0&&r===0)continue;this.logger.log(3,()=>"["+fi([e[i],e[i+1]])+"] -> ("+fi([s,r])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(BT(s,r,l)){In(null,null,l),this.logger.log(3,()=>"Repeated command ("+fi([s,r])+") is dropped");continue}In(s,r,this.cmdHistory),o=this.parseCmd(s,r),o||(o=this.parseMidrow(s,r)),o||(o=this.parsePAC(s,r)),o||(o=this.parseBackgroundAttributes(s,r))}else In(null,null,l);if(!o&&(a=this.parseChars(s,r),a)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+fi([s,r])+" orig: "+fi([e[i],e[i+1]]))}}parseCmd(t,e){const i=(t===20||t===28||t===21||t===29)&&e>=32&&e<=47,s=(t===23||t===31)&&e>=33&&e<=35;if(!(i||s))return!1;const r=t===20||t===21||t===23?1:2,o=this.channels[r];return t===20||t===21||t===28||t===29?e===32?o.ccRCL():e===33?o.ccBS():e===34?o.ccAOF():e===35?o.ccAON():e===36?o.ccDER():e===37?o.ccRU(2):e===38?o.ccRU(3):e===39?o.ccRU(4):e===40?o.ccFON():e===41?o.ccRDC():e===42?o.ccTR():e===43?o.ccRTD():e===44?o.ccEDM():e===45?o.ccCR():e===46?o.ccENM():e===47&&o.ccEOC():o.ccTO(e-32),this.currentChannel=r,!0}parseMidrow(t,e){let i=0;if((t===17||t===25)&&e>=32&&e<=47){if(t===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+fi([t,e])+")"),!0):!1}return!1}parsePAC(t,e){let i;const s=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,r=(t===16||t===24)&&e>=64&&e<=95;if(!(s||r))return!1;const o=t<=23?1:2;e>=64&&e<=95?i=o===1?fT[t]:mT[t]:i=o===1?gT[t]:pT[t];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(i,e)),this.currentChannel=o,!0):!1}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return e>95?i=e-96:i=e-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let o;r===17?o=e+80:r===18?o=e+112:o=e+144,this.logger.log(2,()=>"Special char '"+bd(o)+"' in channel "+i),s=[o]}else t>=32&&t<=127&&(s=e===0?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+fi(s).join(",")),s}parseBackgroundAttributes(t,e){const i=(t===16||t===24)&&e>=32&&e<=47,s=(t===23||t===31)&&e>=45&&e<=47;if(!(i||s))return!1;let r;const o={};t===16||t===24?(r=Math.floor((e-32)/2),o.background=ET[r],e%2===1&&(o.background=o.background+"_semi")):e===45?o.background="transparent":(o.foreground="black",e===47&&(o.underline=!0));const a=t<=23?1:2;return this.channels[a].setBkgData(o),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}In(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function In(n,t,e){e.a=n,e.b=t}function BT(n,t,e){return e.a===n&&e.b===t}function vT(){return{a:null,b:null}}class yn{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var il=function(){if(Xi!=null&&Xi.VTTCue)return self.VTTCue;const n=["","lr","rl"],t=["start","middle","end","left","right"];function e(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const c=l.toLowerCase();return~a.indexOf(c)?c:!1}function i(a){return e(n,a)}function s(a){return e(t,a)}function r(a,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const A in h)a[A]=h[A]}return a}function o(a,l,c){const h=this,A={enumerable:!0};h.hasBeenReset=!1;let u="",d=!1,f=a,g=l,p=c,m=null,C="",E=!0,v="auto",y="start",S=50,T="middle",x=50,F="middle";Object.defineProperty(h,"id",r({},A,{get:function(){return u},set:function(_){u=""+_}})),Object.defineProperty(h,"pauseOnExit",r({},A,{get:function(){return d},set:function(_){d=!!_}})),Object.defineProperty(h,"startTime",r({},A,{get:function(){return f},set:function(_){if(typeof _!="number")throw new TypeError("Start time must be set to a number.");f=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},A,{get:function(){return g},set:function(_){if(typeof _!="number")throw new TypeError("End time must be set to a number.");g=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},A,{get:function(){return p},set:function(_){p=""+_,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},A,{get:function(){return m},set:function(_){m=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},A,{get:function(){return C},set:function(_){const w=i(_);if(w===!1)throw new SyntaxError("An invalid or illegal string was specified.");C=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},A,{get:function(){return E},set:function(_){E=!!_,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},A,{get:function(){return v},set:function(_){if(typeof _!="number"&&_!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},A,{get:function(){return y},set:function(_){const w=s(_);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");y=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},A,{get:function(){return S},set:function(_){if(_<0||_>100)throw new Error("Position must be between 0 and 100.");S=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},A,{get:function(){return T},set:function(_){const w=s(_);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");T=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},A,{get:function(){return x},set:function(_){if(_<0||_>100)throw new Error("Size must be between 0 and 100.");x=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},A,{get:function(){return F},set:function(_){const w=s(_);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");F=w,this.hasBeenReset=!0}})),h.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class ST{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Md(n){function t(i,s,r,o){return(i|0)*3600+(s|0)*60+(r|0)+parseFloat(o||0)}const e=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return e?parseFloat(e[2])>59?t(e[2],e[3],0,e[4]):t(e[1],e[2],e[3],e[4]):null}class TT{constructor(){this.values=Object.create(null)}set(t,e){!this.get(t)&&e!==""&&(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function Pd(n,t,e,i){const s=i?n.split(i):[n];for(const r in s){if(typeof s[r]!="string")continue;const o=s[r].split(e);if(o.length!==2)continue;const a=o[0],l=o[1];t(a,l)}}const na=new il(0,0,""),Bn=na.align==="middle"?"middle":"center";function _T(n,t,e){const i=n;function s(){const a=Md(n);if(a===null)throw new Error("Malformed timestamp: "+i);return n=n.replace(/^[^\sa-zA-Z-]+/,""),a}function r(a,l){const c=new TT;Pd(a,function(u,d){let f;switch(u){case"region":for(let g=e.length-1;g>=0;g--)if(e[g].id===d){c.set(u,e[g].region);break}break;case"vertical":c.alt(u,d,["rl","lr"]);break;case"line":f=d.split(","),c.integer(u,f[0]),c.percent(u,f[0])&&c.set("snapToLines",!1),c.alt(u,f[0],["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start",Bn,"end"]);break;case"position":f=d.split(","),c.percent(u,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start",Bn,"end","line-left","line-right","auto"]);break;case"size":c.percent(u,d);break;case"align":c.alt(u,d,["start",Bn,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&na.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",Bn);let A=c.get("position","auto");A==="auto"&&na.position===50&&(A=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=A}function o(){n=n.replace(/^\s+/,"")}if(o(),t.startTime=s(),o(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);n=n.slice(3),o(),t.endTime=s(),o(),r(n,t)}function kd(n){return n.replace(/<br(?: \/)?>/gi,`
25
+ `)}class xT{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ST,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));function i(){let r=e.buffer,o=0;for(r=kd(r);o<r.length&&r[o]!=="\r"&&r[o]!==`
26
+ `;)++o;const a=r.slice(0,o);return r[o]==="\r"&&++o,r[o]===`
27
+ `&&++o,e.buffer=r.slice(o),a}function s(r){Pd(r,function(o,a){},/:/)}try{let r="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;r=i();const a=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let o=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(o?o=!1:r=i(),e.state){case"HEADER":/:/.test(r)?s(r):r||(e.state="ID");continue;case"NOTE":r||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){e.state="NOTE";break}if(!r)continue;if(e.cue=new il(0,0,""),e.state="CUE",r.indexOf("-->")===-1){e.cue.id=r;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{_T(r,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const a=r.indexOf("-->")!==-1;if(!r||a&&(o=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(e.cue===null)continue;e.cue.text&&(e.cue.text+=`
28
+ `),e.cue.text+=r}continue;case"BADCUE":r||(e.state="ID")}}}catch{e.state==="CUETEXT"&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state=e.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=`
29
+
30
+ `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const DT=/\r\n|\n\r|\n|\r/g,go=function(t,e,i=0){return t.slice(i,i+e.length)===e},RT=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!j(e)||!j(i)||!j(s)||!j(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=60*1e3*s,e+=60*60*1e3*r,e},mo=function(t){let e=5381,i=t.length;for(;i;)e=e*33^t.charCodeAt(--i);return(e>>>0).toString()};function sl(n,t,e){return mo(n.toString())+mo(t.toString())+mo(e)}const wT=function(t,e,i){let s=t[e],r=t[s.prevCC];if(!r||!r.new&&s.new){t.ccOffset=t.presentationOffset=s.start,s.new=!1;return}for(;(o=r)!=null&&o.new;){var o;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i};function LT(n,t,e,i,s,r,o){const a=new xT,l=Ge(new Uint8Array(n)).trim().replace(DT,`
31
+ `).split(`
32
+ `),c=[],h=t?ZS(t.baseTime,t.timescale):0;let A="00:00.000",u=0,d=0,f,g=!0;a.oncue=function(p){const m=e[i];let C=e.ccOffset;const E=(u-h)/9e4;if(m!=null&&m.new&&(d!==void 0?C=e.ccOffset=m.start:wT(e,i,E)),E){if(!t){f=new Error("Missing initPTS for VTT MPEGTS");return}C=E-e.presentationOffset}const v=p.endTime-p.startTime,y=he((p.startTime+C-d)*9e4,s*9e4)/9e4;p.startTime=Math.max(y,0),p.endTime=Math.max(y+v,0);const S=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(S)),p.id||(p.id=sl(p.startTime,p.endTime,S)),p.endTime>0&&c.push(p)},a.onparsingerror=function(p){f=p},a.onflush=function(){if(f){o(f);return}r(c)},l.forEach(p=>{if(g)if(go(p,"X-TIMESTAMP-MAP=")){g=!1,p.slice(16).split(",").forEach(m=>{go(m,"LOCAL:")?A=m.slice(6):go(m,"MPEGTS:")&&(u=parseInt(m.slice(7)))});try{d=RT(A)/1e3}catch(m){f=m}return}else p===""&&(g=!1);a.parse(p+`
33
+ `)}),a.flush()}const po="stpp.ttml.im1t",Qd=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Od=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bT={left:"start",center:"center",right:"end",start:"start",end:"end"};function Fh(n,t,e,i){const s=ft(new Uint8Array(n),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=s.map(a=>Ge(a)),o=jS(t.baseTime,1,t.timescale);try{r.forEach(a=>e(FT(a,o)))}catch(a){i(a)}}function FT(n,t){const s=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((A,u)=>(A[u]=s.getAttribute(`ttp:${u}`)||r[u],A),{}),a=s.getAttribute("xml:space")!=="preserve",l=Mh(Eo(s,"styling","style")),c=Mh(Eo(s,"layout","region")),h=Eo(s,"body","[begin]");return[].map.call(h,A=>{const u=Gd(A,a);if(!u||!A.hasAttribute("begin"))return null;const d=Io(A.getAttribute("begin"),o),f=Io(A.getAttribute("dur"),o);let g=Io(A.getAttribute("end"),o);if(d===null)throw Ph(A);if(g===null){if(f===null)throw Ph(A);g=d+f}const p=new il(d-t,g-t,u);p.id=sl(p.startTime,p.endTime,p.text);const m=c[A.getAttribute("region")],C=l[A.getAttribute("style")],E=MT(m,C,l),{textAlign:v}=E;if(v){const y=bT[v];y&&(p.lineAlign=y),p.align=v}return Qt(p,E),p}).filter(A=>A!==null)}function Eo(n,t,e){const i=n.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function Mh(n){return n.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Gd(n,t){return[].slice.call(n.childNodes).reduce((e,i,s)=>{var r;return i.nodeName==="br"&&s?e+`
34
+ `:(r=i.childNodes)!=null&&r.length?Gd(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function MT(n,t,e){const i="http://www.w3.org/ns/ttml#styling";let s=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return o&&e.hasOwnProperty(o)&&(s=e[o]),r.reduce((a,l)=>{const c=Co(t,i,l)||Co(n,i,l)||Co(s,i,l);return c&&(a[l]=c),a},{})}function Co(n,t,e){return n&&n.hasAttributeNS(t,e)?n.getAttributeNS(t,e):null}function Ph(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Io(n,t){if(!n)return null;let e=Md(n);return e===null&&(Qd.test(n)?e=PT(n,t):Od.test(n)&&(e=kT(n,t))),e}function PT(n,t){const e=Qd.exec(n),i=(e[4]|0)+(e[5]|0)/t.subFrameRate;return(e[1]|0)*3600+(e[2]|0)*60+(e[3]|0)+i/t.frameRate}function kT(n,t){const e=Od.exec(n),i=Number(e[1]);switch(e[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}class Ud{constructor(t){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=Qh(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.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}},t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this),t.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this),t.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(I.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 t=new yn(this,"textTrack1"),e=new yn(this,"textTrack2"),i=new yn(this,"textTrack3"),s=new yn(this,"textTrack4");this.cea608Parser1=new bh(1,t,e),this.cea608Parser2=new bh(3,i,s)}}addCues(t,e,i,s,r){let o=!1;for(let a=r.length;a--;){const l=r[a],c=QT(l[0],l[1],e,i);if(c>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],i),o=!0,c/(i-e)>.5))return}if(o||r.push([e,i]),this.config.renderTextTracksNatively){const a=this.captionsTracks[t];this.Cues.newCue(a,e,i,s)}else{const a=this.Cues.newCue(null,e,i,s);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:a,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r}){const{unparsedVttFrags:o}=this;i==="main"&&(this.initPTS[e.cc]={baseTime:s,timescale:r}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(I.FRAG_LOADED,a)}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(kh(r,{name:t,lang:e,attrs:{}}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:r,languageCode:o}=e[t],a=this.getExistingTrack(r,o);if(a)i[t]=a,Hi(i[t]),ju(i[t],s);else{const l=this.createTextTrack("captions",r,o);l&&(l[t]=!0,i[t]=l)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i=e.label,s={_id:t,label:i,kind:"captions",default:e.media?!!e.media.default:!1,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{Hi(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Qh(),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:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let i=0;i<e.length;i++)Hi(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(r=>r.textCodec===po);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(_d(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,a=o?Rn(o.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(a){let A=null;for(let u=0;u<a.length;u++)if(a[u]&&kh(a[u],l)){A=a[u],a[u]=null;break}A&&(h=A)}if(h)Hi(h);else{const A=Nd(l);h=this.createTextTrack(A,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),a!=null&&a.length){const l=a.filter(c=>c!==null).map(c=>c.label);l.length&&R.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 o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const r=`textTrack${s[1]}`,o=this.captionsProperties[r];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return e==null?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===et.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:o,lastSn:a}=this,{cc:l,sn:c}=e.frag,h=(i=(s=e.part)==null?void 0:s.index)!=null?i:-1;r&&o&&(c!==a+1||c===a&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===et.SUBTITLE)if(s.byteLength){const r=i.decryptdata,o="stats"in e;if(r==null||!r.encrypted||o){const a=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===po?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;Fh(e,this.initPTS[t.cc],s=>{this._appendCues(s,t.level),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{R.log(`Failed to parse IMSC1: ${s}`),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:r,unparsedVttFrags:o}=this,a=r.length-1;if(!r[i.cc]&&a===-1){o.push(t);return}const l=this.hls,c=(e=i.initSegment)!=null&&e.data?ge(i.initSegment.data,new Uint8Array(s)):s;LT(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,h=>{this._appendCues(h,i.level),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},h=>{const A=h.message==="Missing initPTS for VTT MPEGTS";A?o.push(t):this._fallbackToIMSC1(i,s),R.log(`Failed to parse VTT cue: ${h}`),!(A&&a>i.cc)&&l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:h})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||Fh(e,this.initPTS[t.cc],()=>{i.textCodec=po,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||s.mode==="disabled")return;t.forEach(r=>Zu(s,r))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(I.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===et.SUBTITLE&&this.onFragLoaded(I.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;const{frag:r,samples:o}=e;if(!(r.type===et.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let a=0;a<o.length;a++){const l=o[a].bytes;if(l){const c=this.extractCea608Data(l);i.addData(o[a].pts,c[0]),s.addData(o[a].pts,c[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:o}=this;if(!(!o||o.currentTime<i)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>Xo(a[l],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>Xo(a[l],e,s))}}}extractCea608Data(t){const e=[[],[]],i=t[0]&31;let s=2;for(let r=0;r<i;r++){const o=t[s++],a=127&t[s++],l=127&t[s++];if(a===0&&l===0)continue;if((4&o)!==0){const h=3&o;(h===0||h===1)&&(e[h].push(a),e[h].push(l))}}return e}}function Nd(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function kh(n,t){return!!n&&n.kind===Nd(t)&&sa(t,n)}function QT(n,t,e,i){return Math.min(t,i)-Math.max(n,e)}function Qh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class vr{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.BUFFER_CODECS,this.onBufferCodecs,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.BUFFER_CODECS,this.onBufferCodecs,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&j(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&R.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((s,r)=>this.isLevelAllowed(s)&&r<=t);return this.clientRect=null,vr.getMaxLevelByMediaSize(i,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 t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,!e.width&&!e.height&&(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return t}isLevelAllowed(t){return!this.restrictedLevels.some(i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height)}static getMaxLevelByMediaSize(t,e,i){if(!(t!=null&&t.length))return-1;const s=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let r=t.length-1;const o=Math.max(e,i);for(let a=0;a<t.length;a+=1){const l=t[a];if((l.width>=o||l.height>=o)&&s(l,t[a+1])){r=a;break}}return r}}class Hd{constructor(t){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=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const r=s-this.lastTime,o=i-this.lastDroppedFrames,a=e-this.lastDecodedFrames,l=1e3*o/r,c=this.hls;if(c.trigger(I.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let h=c.currentLevel;R.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(I.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}const vn="[eme]";class Ii{constructor(t){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=Ii.CDMCleanupPromise?[Ii.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=R.debug.bind(R,vn),this.log=R.log.bind(R,vn),this.warn=R.warn.bind(R,vn),this.error=R.error.bind(R,vn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=e[t];if(s)return s.licenseUrl;if(t===xt.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,s=e.map(o=>o.audioCodec).filter(i),r=e.map(o=>o.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,s,r).then(A=>o({keySystem:h,mediaKeys:A})).catch(A=>{c.length?l(c):A instanceof le?a(A):a(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_ACCESS,error:A,fatal:!0},A.message))})};l(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Gu===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(t,e)}getMediaKeysPromise(t,e,i){const s=jB(t,e,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let o=r==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(s)}`),o=this.requestMediaKeySystemAccess(t,s);const a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),a.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${t}"`),c.then(A=>A?this.setMediaKeysServerCertificate(h,t,A):h))),a.mediaKeys.catch(h=>{this.error(`Failed to create media-keys for "${t}"}: ${h}`)}),a.mediaKeys})}return o.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Fe.hexDump(t.keyId||[])}`);const s=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Fe.hexDump(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Fe.hexDump(((i=t.decryptdata)==null?void 0:i.keyId)||[])}
35
+ } (data length: ${e&&e.byteLength})`),s.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,i)=>{const s=eo(this.config),r=t.map(Yc).filter(o=>!!o&&s.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:o})=>{const a=Jc(o);a?e(a):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),s=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${s}`);let r=this.keyIdToKeySessionPromise[i];return r||(r=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then(({keySystem:o,mediaKeys:a})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,a).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:o,mediaKeys:a,decryptdata:e});return this.generateRequestWithPreferredKeySession(l,"cenc",e.pssh,"playlist-key")}))),r.catch(o=>this.handleError(o))),r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof le?this.hls.trigger(I.ERROR,t.data):this.hls.trigger(I.ERROR,{type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const s=Yc(t.keyFormat),r=s?[s]:eo(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=eo(this.config)),t.length===0)throw new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.debug(s),i===null)return;let r,o;if(e==="sinf"&&this.config.drmSystems[xt.FAIRPLAY]){const A=Nt(new Uint8Array(i));try{const u=Ja(JSON.parse(A).sinf),d=zu(new Uint8Array(u));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");r=d.subarray(8,24),o=xt.FAIRPLAY}catch(u){this.warn(`${s} Failed to parse sinf: ${u}`);return}}else{const A=vv(i),u=A.filter(d=>d.systemId===_s.WIDEVINE)[0];if(!u){A.length===0||A.some(d=>!d.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${A.map(d=>Vc(d.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(o=Vc(u.systemId),u.version===0&&u.data){const d=u.data.length-22;r=u.data.subarray(d,d+16)}}if(!o||!r)return;const a=Fe.hexDump(r),{keyIdToKeySessionPromise:l,mediaKeySessions:c}=this;let h=l[a];for(let A=0;A<c.length;A++){const u=c[A],d=u.decryptdata;if(!d.keyId)continue;const f=Fe.hexDump(d.keyId);if(a===f||d.uri.replace(/-/g,"").indexOf(a)!==-1){if(h=l[f],d.pssh)break;delete l[f],d.pssh=new Uint8Array(i),d.keyId=r,h=l[a]=h.then(()=>this.generateRequestWithPreferredKeySession(u,e,i,"encrypted-event-key-match"));break}}h||(h=l[a]=this.getKeySystemSelectionPromise([o]).then(({keySystem:A,mediaKeys:u})=>{var d;this.throwIfDestroyed();const f=new Wi("ISO-23001-7",a,(d=Jc(A))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=r,this.attemptSetMediaKeys(A,u).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:A,mediaKeys:u});return this.generateRequestWithPreferredKeySession(g,e,i,"encrypted-event-no-match")})})),h.catch(A=>this.handleError(A))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(t,e,i,s){var r,o;const a=(r=this.config.drmSystems)==null||(o=r[t.keySystem])==null?void 0:o.generateRequest;if(a)try{const f=a.call(this.hls,e,i,t);if(!f)throw new Error("Invalid response from configured generateRequest filter");e=f.initDataType,i=t.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(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const c=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${c} (init data type: ${e} length: ${i?i.byteLength:null})`);const h=new el,A=t._onmessage=f=>{const g=t.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(t,m).catch(C=>{this.handleError(C),h.emit("error",C)}):p==="license-release"?t.keySystem===xt.FAIRPLAY&&(this.updateKeySession(t,$o("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${p}"`)},u=t._onkeystatuseschange=f=>{if(!t.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const p=t.keyStatus;h.emit("keyStatus",p),p==="expired"&&(this.warn(`${t.keySystem} expired for key ${c}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",A),t.mediaKeysSession.addEventListener("keystatuseschange",u);const d=new Promise((f,g)=>{h.on("error",g),h.on("keyStatus",p=>{p.startsWith("usable")?f():p==="output-restricted"?g(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new le({type:ot.KEY_SYSTEM_ERROR,details:M.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 t.mediaKeysSession.generateRequest(e,i).then(()=>{var f;this.log(`Request generated for key-session "${(f=t.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c}`)}).catch(f=>{throw new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{throw h.removeAllListeners(),this.removeSession(t),f}).then(()=>(h.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Fe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Fe.hexDump(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,i=e.loader,s=new i(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:r},c=e.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(u,d,f,g)=>{o(u.data)},onError:(u,d,f,g)=>{a(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:$t({url:l.url,data:void 0},u)},`"${t}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,d,f)=>{a(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(u,d,f)=>{a(new Error("aborted"))}};s.load(l,h,A)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,r)=>{t.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${e}"`),s(t)}).catch(o=>{r(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(s=>{throw new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=new DOMParser().parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let A=0,u=r.length;A<u;A++){var o,a;h=r[A];const d=(o=h.querySelector("name"))==null?void 0:o.textContent,f=(a=h.querySelector("value"))==null?void 0:a.textContent;d&&f&&t.setRequestHeader(d,f)}}const l=s.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return $o(atob(c))}setupLicenseXHR(t,e,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,i,s)}).catch(o=>{if(!i.decryptdata)throw o;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)}).then(o=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:o||s})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const o=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,t)}catch(h){this.error(h)}s(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)r(new le({type:ot.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,e).then(s,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,o,t,e).then(({xhr:l,licenseChallenge:c})=>{t.keySystem==xt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Wi.clearKeyUriToKeyIdMap();const i=e.length;Ii.CDMCleanupPromise=Promise.all(e.map(s=>this.removeSession(s)).concat(t==null?void 0:t.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=e.reduce((s,r)=>(s.indexOf(r.keyFormat)===-1&&s.push(r.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),e.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>e.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Ii.CDMCleanupPromise=void 0;class le extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var qt;(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"})(qt||(qt={}));var ra;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(ra||(ra={}));var Ei;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(Ei||(Ei={}));const OT={[Ei.OBJECT]:["br","d","ot","tb"],[Ei.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ei.SESSION]:["cid","pr","sf","sid","st","v"],[Ei.STATUS]:["bs","rtp"]};class Zi{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map(i=>i instanceof Zi?i:new Zi(i))),this.value=t,this.params=e}}class Kd{constructor(t){this.description=void 0,this.description=t}}const GT="Dict";function UT(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 NT(n,t,e,i){return new Error(`failed to ${n} "${UT(t)}" as ${e}`,{cause:i})}const Oh="Bare Item",HT="Boolean",KT="Byte Sequence",YT="Decimal",VT="Integer";function JT(n){return n<-999999999999999||999999999999999<n}const zT=/[\x00-\x1f\x7f]+/,$T="Token",qT="Key";function Ue(n,t,e){return NT("serialize",n,t,e)}function XT(n){if(typeof n!="boolean")throw Ue(n,HT);return n?"?1":"?0"}function WT(n){return btoa(String.fromCharCode(...n))}function jT(n){if(ArrayBuffer.isView(n)===!1)throw Ue(n,KT);return`:${WT(n)}:`}function Yd(n){if(JT(n))throw Ue(n,VT);return n.toString()}function ZT(n){return`@${Yd(n.getTime()/1e3)}`}function Vd(n,t){if(n<0)return-Vd(-n,t);const e=Math.pow(10,t);if(Math.abs(n*e%1-.5)<Number.EPSILON){const s=Math.floor(n*e);return(s%2===0?s:s+1)/e}else return Math.round(n*e)/e}function t_(n){const t=Vd(n,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ue(n,YT);const e=t.toString();return e.includes(".")?e:`${e}.0`}const e_="String";function i_(n){if(zT.test(n))throw Ue(n,e_);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function s_(n){return n.description||n.toString().slice(7,-1)}function Gh(n){const t=s_(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ue(t,$T);return t}function oa(n){switch(typeof n){case"number":if(!j(n))throw Ue(n,Oh);return Number.isInteger(n)?Yd(n):t_(n);case"string":return i_(n);case"symbol":return Gh(n);case"boolean":return XT(n);case"object":if(n instanceof Date)return ZT(n);if(n instanceof Uint8Array)return jT(n);if(n instanceof Kd)return Gh(n);default:throw Ue(n,Oh)}}function aa(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Ue(n,qT);return n}function nl(n){return n==null?"":Object.entries(n).map(([t,e])=>e===!0?`;${aa(t)}`:`;${aa(t)}=${oa(e)}`).join("")}function Jd(n){return n instanceof Zi?`${oa(n.value)}${nl(n.params)}`:oa(n)}function n_(n){return`(${n.value.map(Jd).join(" ")})${nl(n.params)}`}function r_(n,t={whitespace:!0}){if(typeof n!="object")throw Ue(n,GT);const e=n instanceof Map?n.entries():Object.entries(n),i=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([s,r])=>{r instanceof Zi||(r=new Zi(r));let o=aa(s);return r.value===!0?o+=nl(r.params):(o+="=",Array.isArray(r.value)?o+=n_(r):o+=Jd(r)),o}).join(`,${i}`)}function o_(n,t){return r_(n,t)}const a_=n=>n==="ot"||n==="sf"||n==="st",l_=n=>typeof n=="number"?j(n):n!=null&&n!==""&&n!==!1;function c_(n,t){const e=new URL(n),i=new URL(t);if(e.origin!==i.origin)return n;const s=e.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;s[0]===r[0];)s.shift(),r.shift();for(;r.length;)r.shift(),s.unshift("..");return s.join("/")}function h_(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const r=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(s=="x"?r:r&3|8).toString(16)})}}}const Mn=n=>Math.round(n),A_=(n,t)=>(t!=null&&t.baseUrl&&(n=c_(n,t.baseUrl)),encodeURIComponent(n)),Sn=n=>Mn(n/100)*100,u_={br:Mn,d:Mn,bl:Sn,dl:Sn,mtp:Sn,nor:A_,rtp:Sn,tb:Mn};function d_(n,t){const e={};if(n==null||typeof n!="object")return e;const i=Object.keys(n).sort(),s=Qt({},u_,t==null?void 0:t.formatters),r=t==null?void 0:t.filter;return i.forEach(o=>{if(r!=null&&r(o))return;let a=n[o];const l=s[o];l&&(a=l(a,t)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||l_(a)&&(a_(o)&&typeof a=="string"&&(a=new Kd(a)),e[o]=a))}),e}function zd(n,t={}){return n?o_(d_(n,t),Qt({whitespace:!1},t)):""}function f_(n,t={}){if(!n)return{};const e=Object.entries(n),i=Object.entries(OT).concat(Object.entries((t==null?void 0:t.customHeaderMap)||{})),s=e.reduce((r,o)=>{var a,l;const[c,h]=o,A=((a=i.find(u=>u[1].includes(c)))==null?void 0:a[0])||Ei.REQUEST;return(l=r[A])!=null||(r[A]={}),r[A][c]=h,r},{});return Object.entries(s).reduce((r,[o,a])=>(r[o]=zd(a,t),r),{})}function g_(n,t,e){return Qt(n,f_(t,e))}const m_="CMCD";function p_(n,t={}){if(!n)return"";const e=zd(n,t);return`${m_}=${encodeURIComponent(e)}`}const Uh=/CMCD=[^&#]+/;function E_(n,t,e){const i=p_(t,e);if(!i)return n;if(Uh.test(n))return n.replace(Uh,i);const s=n.includes("?")?"&":"?";return`${n}${s}${i}`}class $d{constructor(t){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=s=>{try{this.apply(s,{ot:qt.MANIFEST,su:!this.initialized})}catch(r){R.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const r=s.frag,o=this.hls.levels[r.level],a=this.getObjectType(r),l={d:r.duration*1e3,ot:a};(a===qt.VIDEO||a===qt.AUDIO||a==qt.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(a)/1e3,l.bl=this.getBufferLength(a)),this.apply(s,l)}catch(r){R.warn("Could not generate segment CMCD data.",r)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;i!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||h_(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHED,this.onMediaDetached,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHED,this.onMediaDetached,this),t.off(I.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(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=(i=e.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=e.tracks.video)==null?void 0:s.buffer}createData(){var t;return{v:1,sf:ra.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){Qt(e,this.createData());const i=e.ot===qt.INIT||e.ot===qt.VIDEO||e.ot===qt.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((r,o)=>(s.includes(o)&&(r[o]=e[o]),r),{})),this.useHeaders?(t.headers||(t.headers={}),g_(t.headers,e)):t.url=E_(t.url,e)}getObjectType(t){const{type:e}=t;if(e==="subtitle")return qt.TIMED_TEXT;if(t.sn==="initSegment")return qt.INIT;if(e==="audio")return qt.AUDIO;if(e==="main")return this.hls.audioTracks.length?qt.VIDEO:qt.MUXED}getTopBandwidth(t){let e=0,i;const s=this.hls;if(t===qt.AUDIO)i=s.audioTracks;else{const r=s.maxAutoLevel,o=r>-1?r+1:s.levels.length;i=s.levels.slice(0,o)}for(const r of i)r.bitrate>e&&(e=r.bitrate);return e>0?e:NaN}getBufferLength(t){const e=this.hls.media,i=t===qt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!e?NaN:Rt.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,a){e(r),this.loader.load(r,o,a)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,a){e(r),this.loader.load(r,o,a)}}}}const C_=3e5;class qd{constructor(t){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=t,this.log=R.log.bind(R,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);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(t){const e=this.levels;e&&(this.levels=e.filter(i=>i!==t))}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(t,e){const{contentSteering:i}=e;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((i==null?void 0:i.action)===Ht.SendAlternateToPenaltyBox&&i.flags===ce.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this.pathwayPriority,o=this.pathwayId;if(e.context){const{groupId:a,pathwayId:l,type:c}=e.context;a&&s?o=this.getPathwayForGroupId(a,c,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&s&&(r=s.reduce((a,l)=>(a.indexOf(l.pathwayId)===-1&&a.push(l.pathwayId),a),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),i.resolved||R.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${o} levels: ${s&&s.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this.pathwayPriority=t;let e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>C_&&delete i[r]});for(let r=0;r<t.length;r++){const o=t[r];if(o in i)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(e=this.getLevelsForPathway(o),e.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,sd(e),this.hls.trigger(I.LEVELS_UPDATED,{levels:e});const c=this.hls.levels[a];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=a);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(e===Ct.AUDIO_TRACK&&s[r].hasAudioGroup(t)||e===Ct.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(t))return s[r].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(r=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=r;if(e.some(h=>h.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(h=>{const A=new bt(h.attrs);A["PATHWAY-ID"]=o;const u=A.AUDIO&&`${A.AUDIO}_clone_${o}`,d=A.SUBTITLES&&`${A.SUBTITLES}_clone_${o}`;u&&(i[A.AUDIO]=u,A.AUDIO=u),d&&(s[A.SUBTITLES]=d,A.SUBTITLES=d);const f=Xd(h.uri,A["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Bi({attrs:A,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_${o}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)g.addGroupId("text",`${h.subtitleGroups[p]}_clone_${o}`);return g});e.push(...c),Nh(this.audioTracks,i,l,o),Nh(this.subtitleTracks,s,l,o)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;this.loader&&this.loader.destroy(),this.loader=new i(e);let s;try{s=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:s.href},o=e.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(h,A,u,d)=>{this.log(`Loaded steering manifest: "${s}"`);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,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);const C={steeringManifest:f,url:s.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,C),m&&this.updatePathwayPriority(m)},onError:(h,A,u,d)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${A.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${A.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 ${A.url} rate limited`);return}this.scheduleRefresh(this.uri||A.url,f)},onTimeout:(h,A,u)=>{this.log(`Timeout loading steering manifest (${A.url})`),this.scheduleRefresh(this.uri||A.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,c)}scheduleRefresh(t,e=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},e)}}function Nh(n,t,e,i){n&&Object.keys(t).forEach(s=>{const r=n.filter(o=>o.groupId===s).map(o=>{const a=Qt({},o);return a.details=void 0,a.attrs=new bt(a.attrs),a.url=a.attrs.URI=Xd(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=i,a});n.push(...r)})}function Xd(n,t,e,i){const{HOST:s,PARAMS:r,[e]:o}=i;let a;t&&(a=o==null?void 0:o[t],a&&(n=a));const l=new self.URL(n);return s&&!a&&(l.host=s),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const I_=/^age:\s*[\d.]+\s*$/im;class Wd{constructor(t){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=t&&t.xhrSetup||null,this.stats=new Ws,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,e.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(o=>{this.callbacks.onError({code:i.status,text:o.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=i.loadPolicy;if(s)for(const a in s)t.setRequestHeader(a,s[a]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&j(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const o=e.status,a=e.responseType==="text"?e.responseText:null;if(o>=200&&o<300){const A=a??e.response;if(A!=null){i.loading.end=Math.max(self.performance.now(),i.loading.first);const u=e.responseType==="arraybuffer"?A.byteLength:A.length;if(i.loaded=i.total=u,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(i,t,A,e),!this.callbacks)return;const f={url:e.responseURL,data:A,code:o};this.callbacks.onSuccess(f,i,t,e);return}}const l=r.loadPolicy.errorRetry,c=i.retry,h={url:t.url,data:void 0,code:o};er(l,c,!1,h)?this.retry(l):(R.error(`${o} while loading ${t.url}`),this.callbacks.onError({code:o,text:e.statusText},t,e,i))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(er(t,e,!0))this.retry(t);else{var i;R.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=qa(t,i.retry),i.retry++,R.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e==null?void 0:e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&I_.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}function y_(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const B_=/(\d+)-(\d+)\/(\d+)/;class Hh{constructor(t){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=t.fetchSetup||__,this.controller=new self.AbortController,this.stats=new Ws}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 t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=v_(t,this.controller.signal),o=i.onProgress,a=t.responseType==="arraybuffer",l=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=c&&j(c)?c:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},e.timeout),self.fetch(this.request).then(A=>{this.response=this.loader=A;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},h-(u-s.loading.start)),!A.ok){const{status:d,statusText:f}=A;throw new x_(f||"fetch, bad network response",d,A)}return s.loading.first=u,s.total=T_(A.headers)||s.total,o&&j(e.highWaterMark)?this.loadProgressively(A,s,t,e.highWaterMark,o):a?A.arrayBuffer():t.responseType==="json"?A.json():A.text()}).then(A=>{const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const d=A[l];d&&(s.loaded=s.total=d);const f={url:u.url,data:A,code:u.status};o&&!j(e.highWaterMark)&&o(s,t,A,u),i.onSuccess(f,s,t,u)}).catch(A=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=A&&A.code||0,d=A?A.message:null;i.onError({code:u,text:d},t,A?A.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const o=new cd,a=t.body.getReader(),l=()=>a.read().then(c=>{if(c.done)return o.dataLength&&r(e,i,o.flush(),t),Promise.resolve(new ArrayBuffer(0));const h=c.value,A=h.length;return e.loaded+=A,A<s||o.dataLength?(o.push(h),o.dataLength>=s&&r(e,i,o.flush(),t)):r(e,i,h,t),l()}).catch(()=>Promise.reject());return l()}}function v_(n,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Qt({},n.headers))};return n.rangeEnd&&e.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),e}function S_(n){const t=B_.exec(n);if(t)return parseInt(t[2])-parseInt(t[1])+1}function T_(n){const t=n.get("Content-Range");if(t){const i=S_(t);if(j(i))return i}const e=n.get("Content-Length");if(e)return parseInt(e)}function __(n,t){return new self.Request(n.url,t)}class x_ extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const D_=/\s/,R_={newCue(n,t,e,i){const s=[];let r,o,a,l,c;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(r=i.rows[u],a=!0,l=0,c="",!r.isEmpty()){var A;for(let g=0;g<r.chars.length;g++)D_.test(r.chars[g].uchar)&&a?l++:(c+=r.chars[g].uchar,a=!1);r.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const d=kd(c.trim()),f=sl(t,e,d);n!=null&&(A=n.cues)!=null&&A.getCueById(f)||(o=new h(t,e,d),o.id=f,o.line=u+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(o))}return n&&s.length&&(s.sort((u,d)=>u.line==="auto"||d.line==="auto"?0:u.line>8&&d.line>8?d.line-u.line:u.line-d.line),s.forEach(u=>Zu(n,u))),s}},w_={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},jd=$t($t({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:Wd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ad,bufferController:Ld,capLevelController:vr,errorController:rd,fpsController:Hd,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:Gu,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:w_},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},L_()),{},{subtitleStreamController:Rd,subtitleTrackController:wd,timelineController:Ud,audioStreamController:xd,audioTrackController:Dd,emeController:Ii,cmcdController:$d,contentSteeringController:qd});function L_(){return{cueHandler:R_,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 b_(n,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const e=la(n),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,a=t[o]===void 0,l=[];s.forEach(c=>{const h=`${r}Loading${c}`,A=t[h];if(A!==void 0&&a){l.push(h);const u=e[o].default;switch(t[o]={default:u},c){case"TimeOut":u.maxLoadTimeMs=A,u.maxTimeToFirstByteMs=A;break;case"MaxRetry":u.errorRetry.maxNumRetry=A,u.timeoutRetry.maxNumRetry=A;break;case"RetryDelay":u.errorRetry.retryDelayMs=A,u.timeoutRetry.retryDelayMs=A;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=A,u.timeoutRetry.maxRetryDelayMs=A;break}}}),l.length&&R.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(t[o])}`)}),$t($t({},e),t)}function la(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(la):Object.keys(n).reduce((t,e)=>(t[e]=la(n[e]),t),{}):n}function F_(n){const t=n.loader;t!==Hh&&t!==Wd?(R.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):y_()&&(n.loader=Hh,n.progressive=!0,n.enableSoftwareAES=!0,R.log("[config]: Progressive streaming enabled, using FetchLoader"))}let yo;class M_ extends Ir{constructor(t,e){super(t,"[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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this),t.on(I.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this),t.off(I.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},o={};let a=!1,l=!1,c=!1;e.levels.forEach(h=>{var A,u;const d=h.attrs;let{audioCodec:f,videoCodec:g}=h;((A=f)==null?void 0:A.indexOf("mp4a.40.34"))!==-1&&(yo||(yo=/chrome|firefox/i.test(navigator.userAgent)),yo&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=jn(f,i)),((u=g)==null?void 0:u.indexOf("avc1"))===0&&(g=h.videoCodec=Lv(g));const{width:p,height:m,unknownCodecs:C}=h;if(a||(a=!!(p&&m)),l||(l=!!g),c||(c=!!f),C!=null&&C.length||f&&!ro(f,"audio",i)||g&&!ro(g,"video",i))return;const{CODECS:E,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":S,RESOLUTION:T,"VIDEO-RANGE":x}=d,_=`${`${S||"."}-`}${h.bitrate}-${T}-${v}-${E}-${x}-${y}`;if(r[_])if(r[_].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const w=o[_]+=1;h.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const U=new Bi(h);r[_]=U,s.push(U)}else r[_].addGroupId("audio",d.AUDIO),r[_].addGroupId("text",d.SUBTITLES);else{const w=new Bi(h);r[_]=w,o[_]=1,s.push(w)}}),this.filterAndSortMediaOptions(s,e,a,l,c)}filterAndSortMediaOptions(t,e,i,s,r){let o=[],a=[],l=t;if((i||s)&&r&&(l=l.filter(({videoCodec:f,videoRange:g,width:p,height:m})=>(!!f||!!(p&&m))&&Yv(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:f,reason:f.message})}});return}if(e.audioTracks){const{preferManagedMediaSource:f}=this.hls.config;o=e.audioTracks.filter(g=>!g.audioCodec||ro(g.audioCodec,"audio",f)),Kh(o)}e.subtitles&&(a=e.subtitles,Kh(a));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(i&&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 Zn.indexOf(f.videoRange)-Zn.indexOf(g.videoRange);if(f.videoCodec!==g.videoCodec){const p=Wc(f.videoCodec),m=Wc(g.videoCodec);if(p!==m)return m-p}if(f.uri===g.uri&&f.codecSet!==g.codecSet){const p=Wn(f.codecSet),m=Wn(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 A;this._firstLevel=f;const g=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((A=this.hls.userConfig)==null?void 0:A.abrEwmaDefaultEstimate)===void 0){const m=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);m>p&&p===jd.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}const u=r&&!s,d={levels:l,audioTracks:o,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:!u&&o.some(f=>!!f.url)};this.hls.trigger(I.MANIFEST_PARSED,d),(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(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const h=new Error("invalid level idx"),A=t<0;if(this.hls.trigger(I.ERROR,{type:ot.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:t,fatal:A,error:h,reason:h.message}),A)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,o=e[t],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=o,i===t&&o.details&&s&&r===a)return;this.log(`Switching to level ${t} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:t,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,l);const c=o.details;if(!c||c.live){const h=this.switchParams(o.uri,s==null?void 0:s.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){e.fatal||!e.context||e.context.type===Ct.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e!==void 0&&e.type===et.MAIN){const i=e.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[e.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,o=this._levels[s];if(!o){var a;this.warn(`Invalid level index ${s}`),(a=e.deliveryDirectives)!=null&&a.skip&&(r.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(o.fragmentError===0&&(o.loadError=0),this.playlistLoaded(s,e,o.details)):(i=e.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(t)try{s=t.addDirectives(s)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}const r=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""} with${r?" Pathway "+r:""} ${s}`),this.clearTimer(),this.hls.trigger(I.LEVEL_LOADING,{url:s,level:e,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const i=this._levels.filter((s,r)=>r!==t?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(o=>o.level=-1)),!1));sd(i),this._levels=i,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(I.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Kh(n){const t={};n.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}class P_{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var e;if(t&&t!==((e=s.context)==null?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=M.KEY_LOAD_ERROR,i,s,r){return new Je({type:ot.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=t;for(let r=0;r<e.length;r++){const o=e[r];if(s<=o.cc&&(i==="initSegment"||o.sn==="initSegment"||i<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const c=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,c))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((i=a)!=null&&i.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});if((s=a)!=null&&s.keyLoadPromise){var l;switch((l=a.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:t,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={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(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(t.keyLoadPromise=s.then(r=>(t.mediaKeySessionContext=r,i))).catch(r=>{throw t.keyLoadPromise=null,r})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=i.loader,r=new s(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((o,a)=>{const l={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},c=i.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(u,d,f,g)=>{const{frag:p,keyInfo:m,url:C}=f;if(!p.decryptdata||m!==this.keyUriToKeyInfo[C])return a(this.createKeyLoadError(p,M.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));m.decryptdata.key=p.decryptdata.key=new Uint8Array(u.data),p.keyLoader=null,m.loader=null,o({frag:p,keyInfo:m})},onError:(u,d,f,g)=>{this.resetLoader(d),a(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),f,$t({url:l.url,data:void 0},u)))},onTimeout:(u,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(e,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(u,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(e,M.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,A)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],r&&r.destroy()}}function Zd(){return self.SourceBuffer||self.WebKitSourceBuffer}function rl(){if(!ai())return!1;const t=Zd();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function tf(){if(!rl())return!1;const n=ai();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>n.isTypeSupported(Ys(t,"video")))||["mp4a.40.2","fLaC"].some(t=>n.isTypeSupported(Ys(t,"audio"))))}function k_(){var n;const t=Zd();return typeof(t==null||(n=t.prototype)==null?void 0:n.changeType)=="function"}const Q_=250,Pn=2,O_=.1,G_=.05;class U_{constructor(t,e,i,s){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=t,this.media=e,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:s,stalled:r}=this;if(s===null)return;const{currentTime:o,seeking:a}=s,l=this.seeking&&!a,c=!this.seeking&&a;if(this.seeking=a,o!==t){if(this.moved=!0,a||(this.nudgeRetry=0),r!==null){if(this.stallReported){const p=self.performance.now()-r;R.warn(`playback not stuck anymore @${o}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(s.paused&&!a||s.ended||s.playbackRate===0||!Rt.getBuffered(s).length){this.nudgeRetry=0;return}const h=Rt.bufferInfo(s,o,0),A=h.nextStart||0;if(a){const p=h.len>Pn,m=!A||e&&e.start<=o||A-o>Pn&&!this.fragmentTracker.getPartialFragment(o);if(p||m)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var u;if(!(h.len>0)&&!A)return;const m=Math.max(A,h.start||0)-o,C=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,v=(C==null||(u=C.details)==null?void 0:u.live)?C.details.targetduration*2:Pn,y=this.fragmentTracker.getPartialFragment(o);if(m>0&&(m<=v||y)){s.paused||this._trySkipBufferHole(y);return}}const d=self.performance.now();if(r===null){this.stalled=d;return}const f=d-r;if(!a&&f>=Q_&&(this._reportStall(h),!this.media))return;const g=Rt.bufferInfo(s,o,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:s,media:r}=this;if(r===null)return;const o=r.currentTime,a=s.getPartialFragment(o);a&&(this._trySkipBufferHole(a)||!this.media)||(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-o<i.maxBufferHole)&&e>i.highBufferWatchdogPeriod*1e3&&(R.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);R.warn(r.message),e.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:s}=this;if(s===null)return 0;const r=s.currentTime,o=Rt.bufferInfo(s,r,0),a=r<o.start?o.start:o.nextStart;if(a){const l=o.len<=e.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,h=a-r;if(h>0&&(l||c)){if(h>e.maxBufferHole){const{fragmentTracker:u}=this;let d=!1;if(r===0){const f=u.getAppendedFrag(0,et.MAIN);f&&a<f.end&&(d=!0)}if(!d){const f=t||u.getAppendedFrag(r,et.MAIN);if(f){let g=!1,p=f.end;for(;p<a;){const m=u.getPartialFragment(p);if(m)p+=m.duration;else{g=!0;break}}if(g)return 0}}}const A=Math.max(a+G_,r+O_);if(R.warn(`skipping hole, adjusting currentTime from ${r} to ${A}`),this.moved=!0,this.stalled=null,s.currentTime=A,t&&!t.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${A}`);i.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:t})}return A}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:i,nudgeRetry:s}=this;if(i===null)return;const r=i.currentTime;if(this.nudgeRetry++,s<t.nudgeMaxRetry){const o=r+(s+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${r} to ${o}`);R.warn(a.message),i.currentTime=o,e.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const o=new Error(`Playhead still not moving while enough data buffered @${r} after ${t.nudgeMaxRetry} nudges`);R.error(o.message),e.trigger(I.ERROR,{type:ot.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const N_=100;class H_ extends Br{constructor(t,e,i){super(t,e,i,"[stream-controller]",et.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:t}=this;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(I.ERROR,this.onError,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(I.ERROR,this.onError,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:i}=this;if(this.stopLoad(),this.setInterval(N_),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this.loadedmetadata=!1}e>0&&t===-1&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=N.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,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:e,level:i}=this,s=e==null?void 0:e[i],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s)){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 t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||(t=this.media)!=null&&t.seeking){const{levels:s,level:r}=this,o=s==null?void 0:s[r];this.resetStartWhenNotLoaded(o||null),this.state=N.IDLE}}break}this.state===N.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(e===null||!s&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(i!=null&&i[r]))return;const o=i[r],a=this.getMainFwdBufferInfo();if(a===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(I.BUFFER_EOS,g),this.state=N.ENDED;return}if(!this.buffering)return;t.loadLevel!==r&&t.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const c=o.details;if(!c||this.state===N.WAITING_LEVEL||c.live&&this.levelLastLoaded!==o){this.level=r,this.state=N.WAITING_LEVEL;return}const h=a.len,A=this.getMaxBufferLength(o.maxBitrate);if(h>=A)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(u,c);if(this.couldBacktrack&&!this.fragPrevious&&d&&d.sn!=="initSegment"&&this.fragmentTracker.getState(d)!==zt.OK){var f;const p=((f=this.backtrackFragment)!=null?f:d).sn-c.startSN,m=c.fragments[p-1];m&&d.cc===m.cc&&(d=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const p=this.audioOnly&&!this.altAudio?Tt.AUDIO:Tt.VIDEO,m=(p===Tt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,p,et.MAIN)}d=this.getNextFragmentLoopLoading(d,c,a,et.MAIN,A)}d&&(d.initSegment&&!d.initSegment.data&&!this.bitrateTest&&(d=d.initSegment),this.loadFragment(d,o,u))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);this.fragCurrent=t,s===zt.NOT_LOADED||s===zt.PARTIAL?t.sn==="initSegment"?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,et.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(e!=null&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<r.targetduration*2)return}if(!e.paused&&t){const a=this.hls.nextLoadLevel,l=t[a],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const o=this.getBufferedFrag(e.currentTime+i);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,c=a.duration,h=Math.max(o.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 t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),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(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new U_(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.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 t=this.media,e=t?t.currentTime:null;j(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.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(t,e){let i=!1,s=!1;e.levels.forEach(r=>{const o=r.audioCodec;o&&(i=i||o.indexOf("mp4a.40.2")!==-1,s=s||o.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!k_(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==N.IDLE)return;const s=i[e.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=N.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s}=this,r=e.level,o=e.details,a=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${a}`);const l=s[r],c=this.fragCurrent;c&&(this.state===N.FRAG_LOADING||this.state===N.FRAG_LOADING_WAITING_RETRY)&&c.level!==e.level&&c.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=l.details)!=null&&i.live){var A;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(A=this.levelLastLoaded)==null?void 0:A.details)}if(l.details=o,this.levelLastLoaded=l,this.hls.trigger(I.LEVEL_UPDATED,{details:o,level:r}),this.state===N.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=N.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:r}=t,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const a=o[i.level],l=a.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=a.videoCodec,h=l.PTSKnown||!l.live,A=(e=i.initSegment)==null?void 0:e.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Td(this.hls,et.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=f!==-1,p=new yr(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[i.cc];d.push(r,A,u,c,i,s,l.totalduration,h,p,m)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!!!e.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 o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;i&&(r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(I.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,s=!!this.hls.audioTracks[i].url;if(s){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=s,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,o=!1;for(const a in i){const l=i[a];if(l.id==="main"){if(r=a,s=l,a==="video"){const c=i[a];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i&&i.type!==et.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===N.PARSED&&(this.state=N.IDLE);return}const r=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=N.ERROR;return}switch(e.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(et.MAIN,e);break;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===N.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===Ct.LEVEL&&(this.state=N.IDLE);break;case M.BUFFER_APPEND_ERROR:case M.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="main")return;if(e.details===M.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}checkBuffer(){const{media:t,gapController:e}=this;if(!(!t||!e||!t.readyState)){if(this.loadedmetadata||!Rt.getBuffered(t).length){const i=this.state!==N.IDLE?this.fragCurrent:null;e.poll(this.lastCurrentTime,i)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=N.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Tt.AUDIO||this.audioOnly&&!this.altAudio){const i=(e===Tt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,e,et.MAIN),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking){this.log(`could not seek to ${i}, already seeking at ${e}`);return}const s=Rt.getBuffered(t),o=(s.length?s.start(0):0)-i;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${e}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=N.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=t.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(I.FRAG_LOADED,i),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const i="main",{hls:s}=this,{remuxResult:r,chunkMeta:o}=t,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:h}=a,{video:A,text:u,id3:d,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,o),s.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:f.tracks})}const m=f.initPTS,C=f.timescale;j(m)&&(this.initPTS[l.cc]={baseTime:m,timescale:C},s.trigger(I.INIT_PTS_FOUND,{frag:l,id:i,initPTS:m,timescale:C}))}if(A&&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:v,endPTS:y,startDTS:S,endDTS:T}=A;if(c)c.elementaryStreams[A.type]={startPTS:v,endPTS:y,startDTS:S,endDTS:T};else if(A.firstKeyFrame&&A.independent&&o.id===1&&!E&&(this.couldBacktrack=!0),A.dropped&&A.independent){const x=this.getMainFwdBufferInfo(),F=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,_=A.firstKeyFramePTS?A.firstKeyFramePTS:v;if(!C&&F<_-this.config.maxBufferHole&&!E){this.backtrack(l);return}else E&&(l.gap=!0);l.setElementaryStreamInfo(A.type,l.start,y,l.start,T,!0)}else C&&v>Pn&&(l.gap=!0);l.setElementaryStreamInfo(A.type,v,y,S,T),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(A,l,c,o,C||E)}else if(C||E)l.gap=!0;else{this.backtrack(l);return}}if(p){const{startPTS:m,endPTS:C,startDTS:E,endDTS:v}=p;c&&(c.elementaryStreams[Tt.AUDIO]={startPTS:m,endPTS:C,startDTS:E,endDTS:v}),l.setElementaryStreamInfo(Tt.AUDIO,m,C,E,v),this.bufferFragmentData(p,l,c,o)}if(g&&d!=null&&(e=d.samples)!=null&&e.length){const m={id:i,frag:l,details:g,samples:d.samples};s.trigger(I.FRAG_PARSING_METADATA,m)}if(g&&u){const m={id:i,frag:l,details:g,samples:u.samples};s.trigger(I.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(t,e,i,s){if(this.state!==N.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:o,audiovideo:a}=e;if(r){let l=t.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}`)),t.audioCodec&&t.audioCodec!==l&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${t.audioCodec||""}/${r.codec}]`)}o&&(o.levelCodec=t.videoCodec,o.id="main",this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${t.videoCodec||""}/${o.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(I.BUFFER_CODECS,e),Object.keys(e).forEach(l=>{const h=e[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,et.MAIN)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=N.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(Rt.isBuffered(t,i)?e=this.getAppendedFrag(i):Rt.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const s=this.fragPlaying,r=e.level;(!s||e.sn!==s.sn||s.level!==r)&&(this.fragPlaying=e,this.hls.trigger(I.FRAG_CHANGED,{frag:e}),(!s||s.level!==r)&&this.hls.trigger(I.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&j(e)&&j(i.programDateTime)){const s=i.programDateTime+(e-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class ni{static get version(){return"1.5.18"}static isMSESupported(){return rl()}static isSupported(){return tf()}static getMediaSource(){return ai()}static get Events(){return I}static get ErrorTypes(){return ot}static get ErrorDetails(){return M}static get DefaultConfig(){return ni.defaultConfig?ni.defaultConfig:jd}static set DefaultConfig(t){ni.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new el,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,YB(t.debug||!1,"Hls instance");const e=this.config=b_(ni.DefaultConfig,t);this.userConfig=t,e.progressive&&F_(e);const{abrController:i,bufferController:s,capLevelController:r,errorController:o,fpsController:a}=e,l=new o(this),c=this.abrController=new i(this),h=this.bufferController=new s(this),A=this.capLevelController=new r(this),u=new a(this),d=new kv(this),f=new Nv(this),g=e.contentSteeringController,p=g?new g(this):null,m=this.levelController=new M_(this,p),C=new fS(this),E=new P_(this.config),v=this.streamController=new H_(this,C,E);A.setStreamController(v),u.setStreamController(v);const y=[d,m,v];p&&y.splice(1,0,p),this.networkControllers=y;const S=[c,h,A,u,f,C];this.audioTrackController=this.createController(e.audioTrackController,y);const T=e.audioStreamController;T&&y.push(new T(this,C,E)),this.subtitleTrackController=this.createController(e.subtitleTrackController,y);const x=e.subtitleStreamController;x&&y.push(new x(this,C,E)),this.createController(e.timelineController,S),E.emeController=this.emeController=this.createController(e.emeController,S),this.cmcdController=this.createController(e.cmcdController,S),this.latencyController=this.createController(Hv,S),this.coreComponents=S,y.push(l);const F=l.onErrorOut;typeof F=="function"&&this.on(I.ERROR,F,l)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(i){if(R.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=t===I.ERROR;this.trigger(I.ERROR,{type:ot.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:s,event:t,error:i}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){R.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){R.log("attachMedia"),this._media=t,this.trigger(I.MEDIA_ATTACHING,{media:t})}detachMedia(){R.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,s=this.url=Ka.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,R.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(I.MANIFEST_LOADING,{url:t})}startLoad(t=-1){R.log(`startLoad(${t})`),this.started=!0,this.resumeBuffering();for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].startLoad(t),!(!this.started||!this.networkControllers));e++);}stopLoad(){R.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}resumeBuffering(){R.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()})}pauseBuffering(){R.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()})}swapAudioCodec(){R.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){R.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){R.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){R.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){R.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){R.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){R.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(R.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Kv(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(e===-1&&t!=null&&t.length?s=t.length-1:s=e,i)for(let r=s;r--;){const o=t[r].attrs["HDCP-LEVEL"];if(o&&o<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return(e=this.audioTrackController)==null?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return(e=this.subtitleTrackController)==null||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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}}ni.defaultConfig=void 0;const K_=Object.freeze(Object.defineProperty({__proto__:null,AbrController:ad,AttrList:bt,AudioStreamController:xd,AudioTrackController:Dd,BasePlaylistController:Ir,BaseSegment:Va,BaseStreamController:Br,BufferController:Ld,CMCDController:$d,CapLevelController:vr,ChunkMetadata:yr,ContentSteeringController:qd,DateRange:Ya,EMEController:Ii,ErrorActionFlags:ce,ErrorController:rd,ErrorDetails:M,ErrorTypes:ot,Events:I,FPSController:Hd,Fragment:Dn,Hls:ni,HlsSkip:Ps,HlsUrlParameters:Zo,KeySystemFormats:Wt,KeySystems:xt,Level:Bi,LevelDetails:Ou,LevelKey:Wi,LoadStats:Ws,MetadataSchema:ue,NetworkErrorAction:Ht,Part:Qu,PlaylistLevelType:et,SubtitleStreamController:Rd,SubtitleTrackController:wd,TimelineController:Ud,default:ni,getMediaSource:ai,isMSESupported:rl,isSupported:tf},Symbol.toStringTag,{value:"Module"}));var Yh,Vh;const Y_=typeof window<"u"&&typeof((Yh=window.document)==null?void 0:Yh.createElement)=="function"&&typeof((Vh=window.navigator)==null?void 0:Vh.userAgent)=="string";let Bo=null;async function V_(...n){var t;(t=Bo)!==null&&t!==void 0||(Bo=await vE(()=>Promise.resolve().then(()=>K_),void 0));const e=Bo.default;return e.isSupported()?new e(...n):null}function ef(n,{unsuspend:t="loadedmetadata",start:e=!0,hls:i={},crossOrigin:s="anonymous",muted:r=!0,loop:o=!0,playsInline:a=!0,onVideoFrame:l,...c}={}){const h=$(f=>f.gl),A=B.useRef(null),u=es(()=>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:s,loop:o,muted:r,playsInline:a,...c});if(g&&Y_&&g.endsWith(".m3u8")){const E=A.current=await V_(i);E&&(E.on(I.MEDIA_ATTACHED,()=>void E.loadSource(g)),E.attachMedia(m))}const C=new Xf(m);"colorSpace"in C?C.colorSpace=h.outputColorSpace:C.encoding=h.outputEncoding,m.addEventListener(t,()=>f(C))}),[n]),d=u.source.data;return J_(d,l),B.useEffect(()=>(e&&u.image.play(),()=>{A.current&&(A.current.destroy(),A.current=null)}),[u,e]),u}const Sr=B.forwardRef(({children:n,src:t,...e},i)=>{const s=ef(t,e);return B.useEffect(()=>()=>void s.dispose(),[s]),B.useImperativeHandle(i,()=>s,[s]),B.createElement(B.Fragment,null,n==null?void 0:n(s))}),J_=(n,t)=>{B.useEffect(()=>{if(!t||!n.requestVideoFrameCallback)return;let e;const i=(...s)=>{t(...s),e=n.requestVideoFrameCallback(i)};return n.requestVideoFrameCallback(i),()=>n.cancelVideoFrameCallback(e)},[n,t])};var sf={exports:{}};(function(n,t){(function(e,i){n.exports=i()})(yE,function(){var e=function(){function i(d){return o.appendChild(d.dom),d}function s(d){for(var f=0;f<o.children.length;f++)o.children[f].style.display=f===d?"block":"none";r=d}var r=0,o=document.createElement("div");o.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o.addEventListener("click",function(d){d.preventDefault(),s(++r%o.children.length)},!1);var a=(performance||Date).now(),l=a,c=0,h=i(new e.Panel("FPS","#0ff","#002")),A=i(new e.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var u=i(new e.Panel("MB","#f08","#201"));return s(0),{REVISION:16,dom:o,addPanel:i,showPanel:s,begin:function(){a=(performance||Date).now()},end:function(){c++;var d=(performance||Date).now();if(A.update(d-a,200),d>l+1e3&&(h.update(1e3*c/(d-l),100),l=d,c=0,u)){var f=performance.memory;u.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:o,setMode:s}};return e.Panel=function(i,s,r){var o=1/0,a=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,A=48*c,u=3*c,d=2*c,f=3*c,g=15*c,p=74*c,m=30*c,C=document.createElement("canvas");C.width=h,C.height=A,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,A),E.fillStyle=s,E.fillText(i,u,d),E.fillRect(f,g,p,m),E.fillStyle=r,E.globalAlpha=.9,E.fillRect(f,g,p,m),{dom:C,update:function(v,y){o=Math.min(o,v),a=Math.max(a,v),E.fillStyle=r,E.globalAlpha=1,E.fillRect(0,0,h,g),E.fillStyle=s,E.fillText(l(v)+" "+i+" ("+l(o)+"-"+l(a)+")",u,d),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-v/y)*m))}}},e})})(sf);var z_=sf.exports;const $_=BE(z_);function q_(n,t=[],e){const[i,s]=B.useState();return B.useLayoutEffect(()=>{const r=n();return s(r),()=>void 0},t),i}function X_({showPanel:n=0,className:t,parent:e}){const i=q_(()=>new $_,[]);return B.useEffect(()=>{if(i){const s=e&&e.current||document.body;i.showPanel(n),s==null||s.appendChild(i.dom);const r=(t??"").split(" ").filter(l=>l);r.length&&i.dom.classList.add(...r);const o=ha(()=>i.begin()),a=aA(()=>i.end());return()=>{r.length&&i.dom.classList.remove(...r),s==null||s.removeChild(i.dom),o(),a()}}},[e,i,t,n]),null}class W_{constructor(t,e,i){this.name=t,this.fg=e,this.bg=i,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 t=this.context.createLinearGradient(0,this.GRAPH_Y,0,this.GRAPH_Y+this.GRAPH_HEIGHT);let e;const i=this.fg;switch(this.fg.toLowerCase()){case"#0ff":e="#006666";break;case"#0f0":e="#006600";break;case"#ff0":e="#666600";break;case"#e1e1e1":e="#666666";break;default:e=this.bg;break}return t.addColorStop(0,e),t.addColorStop(1,i),t}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(t,e,i,s,r=0){if(!this.context||!this.gradient)return;const o=Math.min(1/0,t),a=Math.max(i,t);s=Math.max(s,e),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(`${t.toFixed(r)} ${this.name} (${o.toFixed(r)}-${parseFloat(a.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-e/s)*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 Ui{constructor({trackGPU:t=!1,logsPerSecond:e=30,samplesLog:i=60,samplesGraph:s=10,precision:r=2,minimal:o=!1,horizontal:a=!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=a,this.minimal=o,this.trackGPU=t,this.samplesLog=i,this.samplesGraph=s,this.precision=r,this.logsPerSecond=e,this.dom=document.createElement("div"),this.initializeDOM(),this.beginTime=performance.now(),this.prevTime=this.beginTime,this.prevCpuTime=this.beginTime,this.fpsPanel=this.addPanel(new Ui.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new Ui.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(t){if(!t){console.error('Stats: The "canvas" parameter is undefined.');return}this.handleThreeRenderer(t)||await this.handleWebGPURenderer(t)||this.initializeWebGL(t)}handleThreeRenderer(t){return t.isWebGLRenderer&&!this.threeRendererPatched?(this.patchThreeRenderer(t),this.gl=t.getContext(),this.trackGPU&&this.initializeGPUTracking(),!0):!1}async handleWebGPURenderer(t){return t.isWebGPURenderer?(this.trackGPU&&(t.backend.trackTimestamp=!0,await t.hasFeatureAsync("timestamp-query")&&this.initializeWebGPUPanels()),this.info=t.info,!0):!1}initializeWebGPUPanels(){this.gpuPanel=this.addPanel(new Ui.Panel("GPU","#ff0","#220"),2),this.gpuPanelCompute=this.addPanel(new Ui.Panel("CPT","#e1e1e1","#212121"),3)}initializeWebGL(t){if(t instanceof WebGL2RenderingContext)this.gl=t;else if(t instanceof HTMLCanvasElement||t instanceof OffscreenCanvas){if(this.gl=t.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 Ui.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(t,e){t.canvas.style.position="absolute",this.minimal?t.canvas.style.display="none":(t.canvas.style.display="block",this.horizontal?(t.canvas.style.top="0px",t.canvas.style.left=e*t.WIDTH/t.PR+"px"):(t.canvas.style.left="0px",t.canvas.style.top=e*t.HEIGHT/t.PR+"px"))}addPanel(t,e){return t.canvas&&(this.dom.appendChild(t.canvas),this.resizePanel(t,e)),t}showPanel(t){for(let e=0;e<this.dom.children.length;e++){const i=this.dom.children[e];i.style.display=e===t?"block":"none"}this.mode=t}processGpuQueries(){!this.gl||!this.ext||(this.totalGpuDuration=0,this.gpuQueries.forEach((t,e)=>{if(this.gl){const i=this.gl.getQueryParameter(t.query,this.gl.QUERY_RESULT_AVAILABLE),s=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT);if(i&&!s){const o=this.gl.getQueryParameter(t.query,this.gl.QUERY_RESULT)*1e-6;this.totalGpuDuration+=o,this.gl.deleteQuery(t.query),this.gpuQueries.splice(e,1)}}}))}endInternal(){this.frames++;const t=(performance||Date).now(),e=t-this.prevTime;if(t>=this.prevCpuTime+1e3/this.logsPerSecond){const i=Math.round(this.frames*1e3/e);this.addToAverage(i,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=t,this.prevTime=t}return t}addToAverage(t,e){e.logs.push(t),e.logs.length>this.samplesLog&&e.logs.shift(),e.graph.push(t),e.graph.length>this.samplesGraph&&e.graph.shift()}beginProfiling(t){window.performance&&(window.performance.mark(t),this.isRunningCPUProfiling=!0)}endProfiling(t,e,i){if(window.performance&&e&&this.isRunningCPUProfiling){window.performance.mark(e);const s=performance.measure(i,t,e);this.totalCpuDuration+=s.duration,this.isRunningCPUProfiling=!1}}updatePanel(t,e,i=2){if(e.logs.length>0){let s=0,r=.01;for(let l=0;l<e.logs.length;l++)s+=e.logs[l],e.logs[l]>r&&(r=e.logs[l]);let o=0,a=.01;for(let l=0;l<e.graph.length;l++)o+=e.graph[l],e.graph[l]>a&&(a=e.graph[l]);t&&t.update(s/Math.min(e.logs.length,this.samplesLog),o/Math.min(e.graph.length,this.samplesGraph),r,a,i)}}get domElement(){return this.dom}patchThreeRenderer(t){const e=t.render,i=this;t.render=function(s,r){i.begin(),e.call(this,s,r),i.end()},this.threeRendererPatched=!0}};nf.Panel=W_;let j_=nf;const rf=B.forwardRef(({className:n,parent:t,id:e,clearStatsGlStyle:i,...s},r)=>{const o=$(l=>l.gl),a=B.useMemo(()=>{const l=new j_({...s});return l.init(o),l},[o]);return B.useImperativeHandle(r,()=>a.domElement,[a]),B.useEffect(()=>{if(a){const l=t&&t.current||document.body;l==null||l.appendChild(a.domElement),a.domElement.querySelectorAll("canvas").forEach(A=>{A.style.removeProperty("position")}),e&&(a.domElement.id=e),i&&a.domElement.removeAttribute("style"),a.domElement.removeAttribute("style");const c=(n??"").split(" ").filter(A=>A);c.length&&a.domElement.classList.add(...c);const h=aA(()=>a.update());return()=>{c.length&&a.domElement.classList.remove(...c),l==null||l.removeChild(a.domElement),h()}}},[t,a,n,e,i]),null});rf.displayName="StatsGl";function Z_({size:n=256,frames:t=1/0}={}){const e=$(h=>h.viewport.dpr),{width:i,height:s}=$(h=>h.size),r=n||i*e,o=n||s*e,a=B.useMemo(()=>{const h=new lA(r,o);return h.format=cA,h.type=hA,{depthTexture:h}},[r,o]);let l=0;const c=AA(r,o,a);return Ot(h=>{(t===1/0||l<t)&&(h.gl.setRenderTarget(c),h.gl.render(h.scene,h.camera),h.gl.setRenderTarget(null),l++)}),c.depthTexture}function tx(n,t,e=1){const i=$(o=>o.viewport),s=t*(i.aspect>n/t?i.width/n:i.height/t);return[n*(i.aspect>n/t?i.width/n:i.height/t)*e,s*e,1]}function ex(n,t){const e=$(s=>s.pointer),[i]=B.useState(()=>{const s=new or;return t&&Aa(s,t,{}),function(r,o){s.setFromCamera(e,n instanceof Wf?n:n.current);const a=this.constructor.prototype.raycast.bind(this);a&&a(s,o)}});return i}function vo(n,t,e,i){return new(e||(e=Promise))(function(s,r){function o(c){try{l(i.next(c))}catch(h){r(h)}}function a(c){try{l(i.throw(c))}catch(h){r(h)}}function l(c){var h;c.done?s(c.value):(h=c.value,h instanceof e?h:new e(function(A){A(h)})).then(o,a)}l((i=i.apply(n,[])).next())})}const ix=["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 Jh(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 of=typeof window>"u",Le=(()=>{if(of)return;const{userAgent:n,platform:t,maxTouchPoints:e}=window.navigator,i=/(iphone|ipod|ipad)/i.test(n),s=t==="iPad"||t==="MacIntel"&&e>0&&!window.MSStream;return{isIpad:s,isMobile:/android/i.test(n)||i||s,isSafari12:/Version\/12.+Safari/.test(n),isFirefox:/Firefox/.test(n)}})();function sx(n,t,e){if(!e)return[t];const i=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
+ `,A=`
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
+ `,u=c.createShader(35633),d=c.createShader(35632),f=c.createProgram();if(!(d&&u&&f))return;c.shaderSource(u,h),c.shaderSource(d,A),c.compileShader(u),c.compileShader(d),c.attachShader(f,u),c.attachShader(f,d),c.linkProgram(f),c.detachShader(f,u),c.detachShader(f,d),c.deleteShader(u),c.deleteShader(d),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),s="801621810",r="8016218135",o="80162181161",a=Le!=null&&Le.isIpad?[["a7",o,12],["a8",r,15],["a8x",r,15],["a9",r,15],["a9x",r,15],["a10",r,15],["a10x",r,15],["a12",s,15],["a12x",s,15],["a12z",s,15],["a14",s,15],["a15",s,15],["m1",s,15],["m2",s,15]]:[["a7",o,12],["a8",r,12],["a9",r,15],["a10",r,15],["a11",s,15],["a12",s,15],["a13",s,15],["a14",s,15],["a15",s,15],["a16",s,15],["a17",s,15]];let l;return i==="80162181255"?l=a.filter(([,,c])=>c>=14):(l=a.filter(([,c])=>c===i),l.length||(l=a)),l.map(([c])=>`apple ${c} gpu`)}class zh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}const So=[],$h=[];function nx(n,t){if(n===t)return 0;const e=n;n.length>t.length&&(n=t,t=e);let i=n.length,s=t.length;for(;i>0&&n.charCodeAt(~-i)===t.charCodeAt(~-s);)i--,s--;let r,o=0;for(;o<i&&n.charCodeAt(o)===t.charCodeAt(o);)o++;if(i-=o,s-=o,i===0)return s;let a,l,c=0,h=0,A=0;for(;h<i;)$h[h]=n.charCodeAt(o+h),So[h]=++h;for(;A<s;)for(r=t.charCodeAt(o+A),a=A++,c=A,h=0;h<i;h++)l=r===$h[h]?a:a+1,a=So[h],c=So[h]=a>c?l>c?c+1:l:l>a?a+1:l;return c}function rx(n){return n!=null}const ox=({mobileTiers:n=[0,15,30,60],desktopTiers:t=[0,15,30,60],override:e={},glContext:i,failIfMajorPerformanceCaveat:s=!1,benchmarksURL:r="https://unpkg.com/detect-gpu@5.0.63/dist/benchmarks"}={})=>vo(void 0,void 0,void 0,function*(){const o={};if(of)return{tier:0,type:"SSR"};const{isIpad:a=!!(Le!=null&&Le.isIpad),isMobile:l=!!(Le!=null&&Le.isMobile),screenSize:c=window.screen,loadBenchmarks:h=y=>vo(void 0,void 0,void 0,function*(){const S=yield fetch(`${r}/${y}`).then(T=>T.json());if(parseInt(S.shift().split(".")[0],10)<4)throw new zh("Detect GPU benchmark data is out of date. Please update to version 4x");return S})}=e;let{renderer:A}=e;const u=(y,S,T,x,F)=>({device:F,fps:x,gpu:T,isMobile:l,tier:y,type:S});let d,f="";if(A)A=Jh(A),d=[A];else{const y=i||function(T,x=!1){const F={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:x,powerPreference:"high-performance",stencil:!1};T&&delete F.powerPreference;const _=window.document.createElement("canvas"),w=_.getContext("webgl",F)||_.getContext("experimental-webgl",F);return w??void 0}(Le==null?void 0:Le.isSafari12,s);if(!y)return u(0,"WEBGL_UNSUPPORTED");const S=Le!=null&&Le.isFirefox?null:y.getExtension("WEBGL_debug_renderer_info");if(A=S?y.getParameter(S.UNMASKED_RENDERER_WEBGL):y.getParameter(y.RENDERER),!A)return u(1,"FALLBACK");f=A,A=Jh(A),d=function(T,x,F){return x==="apple gpu"?sx(T,x,F):[x]}(y,A,l)}const g=(yield Promise.all(d.map(function(y){var S;return vo(this,void 0,void 0,function*(){const T=(Y=>{const D=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const it of D)if(Y.includes(it))return it})(y);if(!T)return;const x=`${l?"m":"d"}-${T}${a?"-ipad":""}.json`,F=o[x]=(S=o[x])!==null&&S!==void 0?S:h(x);let _;try{_=yield F}catch(Y){if(Y instanceof zh)throw Y;return}const w=function(Y){var D;const it=(Y=Y.replace(/\([^)]+\)/,"")).match(/\d+/)||Y.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(D=it==null?void 0:it.join("").replace(/\W|amd/g,""))!==null&&D!==void 0?D:""}(y);let U=_.filter(([,Y])=>Y===w);U.length||(U=_.filter(([Y])=>Y.includes(y)));const O=U.length;if(O===0)return;const W=y.split(/[.,()\[\]/\s]/g).sort().filter((Y,D,it)=>D===0||Y!==it[D-1]).join(" ");let K,[q,,,,Z]=O>1?U.map(Y=>[Y,nx(W,Y[2])]).sort(([,Y],[,D])=>Y-D)[0][0]:U[0],rt=Number.MAX_VALUE;const{devicePixelRatio:V}=window,G=c.width*V*c.height*V;for(const Y of Z){const[D,it]=Y,at=D*it,ht=Math.abs(G-at);ht<rt&&(rt=ht,K=Y)}if(!K)return;const[,,H,X]=K;return[rt,H,q,X]})}))).filter(rx).sort(([y=Number.MAX_VALUE,S],[T=Number.MAX_VALUE,x])=>y===T?S-x:y-T);if(!g.length){const y=ix.find(S=>A.includes(S));return y?u(0,"BLOCKLISTED",y):u(1,"FALLBACK",`${A} (${f})`)}const[,p,m,C]=g[0];if(p===-1)return u(0,"BLOCKLISTED",m,p,C);const E=l?n:t;let v=0;for(let y=0;y<E.length;y++)p>=E[y]&&(v=y);return u(v,"BENCHMARK",m,p,C)}),af=n=>es(()=>ox(n),["useDetectGPU"]);function ax({children:n,...t}){const e=af(t);return B.createElement(B.Fragment,null,n==null?void 0:n(e))}function lx(...n){const t=B.useRef([]);return t.current=n.map(e=>B.useContext(e)),B.useMemo(()=>({children:e})=>n.reduceRight((i,s,r)=>B.createElement(s.Provider,{value:t.current[r],children:i}),e),[])}function cx(n,t){const e=B.useRef(),[i]=B.useState(()=>t?t instanceof jt?{current:t}:t:e),[s]=B.useState(()=>new jf(void 0));B.useLayoutEffect(()=>{t&&(i.current=t instanceof jt?t:t.current),s._root=i.current});const r=B.useRef({}),o=B.useMemo(()=>{const a={};return n.forEach(l=>Object.defineProperty(a,l.name,{enumerable:!0,get(){if(i.current)return r.current[l.name]||(r.current[l.name]=s.clipAction(l,i.current))},configurable:!0})),{ref:i,clips:n,actions:a,names:n.map(l=>l.name),mixer:s}},[n]);return Ot((a,l)=>s.update(l)),B.useEffect(()=>{const a=i.current;return()=>{r.current={},s.stopAllAction(),Object.values(o.actions).forEach(l=>{a&&s.uncacheAction(l,a)})}},[n]),o}const hx=`
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
+ `,Ax=`
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
+ `,ux=`
86
+ #ifdef BOX_PROJECTED_ENV_MAP
87
+ worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition );
88
+ #endif
89
+ `,dx=`
90
+ #ifdef BOX_PROJECTED_ENV_MAP
91
+ reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition );
92
+ #endif
93
+ `;function fx(n,t,e){n.defines.BOX_PROJECTED_ENV_MAP=!0,n.uniforms.envMapPosition={value:t},n.uniforms.envMapSize={value:e},n.vertexShader=`
94
+ varying vec3 vWorldPosition;
95
+ ${n.vertexShader.replace("#include <worldpos_vertex>",hx)}`,n.fragmentShader=`
96
+ ${Ax}
97
+ ${n.fragmentShader.replace("#include <envmap_physical_pars_fragment>",Zf.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );",`vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
98
+ ${ux}
99
+ `).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );",`reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
100
+ ${dx}
101
+ `)}`}function gx(n=new k,t=new k){const[e]=B.useState(()=>({position:new k,size:new k}));Aa(e,{position:n,size:t});const i=B.useRef(null),s=B.useMemo(()=>({ref:i,onBeforeCompile:r=>fx(r,e.position,e.size),customProgramCacheKey:()=>JSON.stringify(e.position.toArray())+JSON.stringify(e.size.toArray())}),[...e.position.toArray(),...e.size.toArray()]);return B.useLayoutEffect(()=>void(i.current.needsUpdate=!0),[e]),s}function mx(n,t,e=.9){return t*e+n*(1-e)}const px=n=>Math.sqrt(1-Math.pow(n-1,2));class Ex{constructor({size:t=256,maxAge:e=750,radius:i=.3,intensity:s=.2,interpolate:r=0,smoothing:o=0,minForce:a=.3,blend:l="screen",ease:c=px}={}){this.size=t,this.maxAge=e,this.radius=i,this.intensity=s,this.ease=c,this.interpolate=r,this.smoothing=o,this.minForce=a,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 t=this.canvas.getContext("2d");if(t===null)throw new Error("2D not available");this.ctx=t,this.ctx.fillStyle="black",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.texture=new Qn(this.canvas),this.canvas.id="touchTexture",this.canvas.style.width=this.canvas.style.height=`${this.canvas.width}px`}update(t){this.clear(),this.trail.forEach((e,i)=>{e.age+=t*1e3,e.age>this.maxAge&&this.trail.splice(i,1)}),this.trail.length||(this.force=0),this.trail.forEach(e=>{this.drawTouch(e)}),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(t){const e=this.trail[this.trail.length-1];if(e){const i=e.x-t.x,s=e.y-t.y,r=i*i+s*s,o=Math.max(this.minForce,Math.min(r*1e4,1));if(this.force=mx(o,this.force,this.smoothing),this.interpolate){const a=Math.ceil(r/Math.pow(this.radius*.5/this.interpolate,2));if(a>1)for(let l=1;l<a;l++)this.trail.push({x:e.x-i/a*l,y:e.y-s/a*l,age:0,force:o})}}this.trail.push({x:t.x,y:t.y,age:0,force:this.force})}drawTouch(t){const e={x:t.x*this.size,y:(1-t.y)*this.size};let i=1;t.age<this.maxAge*.3?i=this.ease(t.age/(this.maxAge*.3)):i=this.ease(1-(t.age-this.maxAge*.3)/(this.maxAge*.7)),i*=t.force,this.ctx.globalCompositeOperation=this.blend;const s=this.size*this.radius*i,r=this.ctx.createRadialGradient(e.x,e.y,Math.max(0,s*.25),e.x,e.y,Math.max(0,s));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(e.x,e.y,Math.max(0,s),0,Math.PI*2),this.ctx.fill()}}function lf(n={}){const{size:t,maxAge:e,radius:i,intensity:s,interpolate:r,smoothing:o,minForce:a,blend:l,ease:c}=n,h=B.useMemo(()=>new Ex(n),[t,e,i,s,r,o,a,l,c]);Ot((u,d)=>void h.update(d));const A=B.useCallback(u=>h.addTouch(u.uv),[h]);return[h.texture,A]}const Cx=({children:n,...t})=>{const e=lf(t);return B.createElement(B.Fragment,null,n==null?void 0:n(e))},Ix=B.forwardRef(({font:n,color:t="#cbcbcb",bevelSize:e=.04,debug:i=!1,children:s,...r},o)=>{const[a,l]=B.useState(0),c=B.useCallback((u=1)=>l(a+u),[a]),h=B.useCallback((u=1)=>l(a-u),[a]),A=B.useMemo(()=>({incr:c,decr:h}),[c,h]);return B.useImperativeHandle(o,()=>A,[A]),B.createElement("group",r,B.createElement(B.Suspense,{fallback:null},B.createElement(uA,{top:!0,cacheKey:JSON.stringify({counter:a,font:n})},B.createElement(dA,{bevelEnabled:!0,bevelSize:e,font:n},i?B.createElement("meshNormalMaterial",{wireframe:!0}):B.createElement("meshStandardMaterial",{color:t}),a))),s)});function yx(n){const t=B.useRef(null);return B.useLayoutEffect(()=>{var e;const i=(e=t.current)==null?void 0:e.parent,s=i==null?void 0:i.geometry;if(s){const r=i.material;i.material=t.current.__r3f.objects;const o=[...s.groups];return s.clearGroups(),i.material.forEach((a,l)=>{l<i.material.length-1&&(a.depthWrite=!1),s.addGroup(0,1/0,l)}),()=>{i.material=r,s.groups=o}}}),B.createElement("group",wt({ref:t},n))}const Bx=B.forwardRef(({mixBlur:n=0,mixStrength:t=.5,resolution:e=256,blur:i=[0,0],args:s=[1,1],minDepthThreshold:r=.9,maxDepthThreshold:o=1,depthScale:a=0,depthToBlurRatioBias:l=.25,mirror:c=0,children:h,debug:A=0,distortion:u=1,mixContrast:d=1,distortionMap:f,...g},p)=>{pa({MeshReflectorMaterial:tg}),B.useEffect(()=>{console.warn("Reflector has been deprecated and will be removed next major. Replace it with <MeshReflectorMaterial />!")},[]);const m=$(({gl:Y})=>Y),C=$(({camera:Y})=>Y),E=$(({scene:Y})=>Y);i=Array.isArray(i)?i:[i,i];const v=i[0]+i[1]>0,y=B.useRef(null);B.useImperativeHandle(p,()=>y.current,[]);const[S]=B.useState(()=>new tA),[T]=B.useState(()=>new k),[x]=B.useState(()=>new k),[F]=B.useState(()=>new k),[_]=B.useState(()=>new dt),[w]=B.useState(()=>new k(0,0,-1)),[U]=B.useState(()=>new Te),[O]=B.useState(()=>new k),[W]=B.useState(()=>new k),[K]=B.useState(()=>new Te),[q]=B.useState(()=>new dt),[Z]=B.useState(()=>new Pt),rt=B.useCallback(()=>{if(x.setFromMatrixPosition(y.current.matrixWorld),F.setFromMatrixPosition(C.matrixWorld),_.extractRotation(y.current.matrixWorld),T.set(0,0,1),T.applyMatrix4(_),O.subVectors(x,F),O.dot(T)>0)return;O.reflect(T).negate(),O.add(x),_.extractRotation(C.matrixWorld),w.set(0,0,-1),w.applyMatrix4(_),w.add(F),W.subVectors(x,w),W.reflect(T).negate(),W.add(x),Z.position.copy(O),Z.up.set(0,1,0),Z.up.applyMatrix4(_),Z.up.reflect(T),Z.lookAt(W),Z.far=C.far,Z.updateMatrixWorld(),Z.projectionMatrix.copy(C.projectionMatrix),q.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),q.multiply(Z.projectionMatrix),q.multiply(Z.matrixWorldInverse),q.multiply(y.current.matrixWorld),S.setFromNormalAndCoplanarPoint(T,x),S.applyMatrix4(Z.matrixWorldInverse),U.set(S.normal.x,S.normal.y,S.normal.z,S.constant);const Y=Z.projectionMatrix;K.x=(Math.sign(U.x)+Y.elements[8])/Y.elements[0],K.y=(Math.sign(U.y)+Y.elements[9])/Y.elements[5],K.z=-1,K.w=(1+Y.elements[10])/Y.elements[14],U.multiplyScalar(2/U.dot(K)),Y.elements[2]=U.x,Y.elements[6]=U.y,Y.elements[10]=U.z+1,Y.elements[14]=U.w},[]),[V,G,H,X]=B.useMemo(()=>{const Y={type:Rs,minFilter:Gn,magFilter:Gn},D=new Al(e,e,Y);D.depthBuffer=!0,D.depthTexture=new lA(e,e),D.depthTexture.format=cA,D.depthTexture.type=hA;const it=new Al(e,e,Y),at=new eg({gl:m,resolution:e,width:i[0],height:i[1],minDepthThreshold:r,maxDepthThreshold:o,depthScale:a,depthToBlurRatioBias:l}),ht={mirror:c,textureMatrix:q,mixBlur:n,tDiffuse:D.texture,tDepth:D.depthTexture,tDiffuseBlur:it.texture,hasBlur:v,mixStrength:t,minDepthThreshold:r,maxDepthThreshold:o,depthScale:a,depthToBlurRatioBias:l,transparent:!0,debug:A,distortion:u,distortionMap:f,mixContrast:d,"defines-USE_BLUR":v?"":void 0,"defines-USE_DEPTH":a>0?"":void 0,"defines-USE_DISTORTION":f?"":void 0};return[D,it,at,ht]},[m,i,q,e,c,v,n,t,r,o,a,l,A,u,f,d]);return Ot(()=>{if(!(y!=null&&y.current))return;y.current.visible=!1;const Y=m.xr.enabled,D=m.shadowMap.autoUpdate;rt(),m.xr.enabled=!1,m.shadowMap.autoUpdate=!1,m.setRenderTarget(V),m.state.buffers.depth.setMask(!0),m.autoClear||m.clear(),m.render(E,Z),v&&H.render(m,V,G),m.xr.enabled=Y,m.shadowMap.autoUpdate=D,y.current.visible=!0,m.setRenderTarget(null)}),B.createElement("mesh",wt({ref:y},g),B.createElement("planeGeometry",{args:s}),h?h("meshReflectorMaterial",X):B.createElement("meshReflectorMaterial",X))});function vx(n){switch(n){case 64:return"-64px";case 128:return"-128px";case 256:return"-256px";case 512:return"-512px";default:return""}}const Sx="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json",Tx="https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d";function cf(n=0,t=1024,e){const i=es(()=>fetch(Sx).then(h=>h.json()),["matcapList"]),s=i[0],r=B.useMemo(()=>Object.keys(i).length,[]),a=`${B.useMemo(()=>typeof n=="string"?n:typeof n=="number"?i[n]:null,[n])||s}${vx(t)}.png`,l=`${Tx}/${t}/${a}`;return[Ea(l,e),l,r]}const _x=({children:n,id:t,format:e,onLoad:i})=>{const s=cf(t,e,i);return B.createElement(B.Fragment,null,n==null?void 0:n(s))},xx="https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb",Dx="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json";function hf(n=0,t={},e){const{repeat:i=[1,1],anisotropy:s=1,offset:r=[0,0]}=t,o=es(()=>fetch(Dx).then(u=>u.json()),["normalsList"]),a=B.useMemo(()=>Object.keys(o).length,[]),l=o[0],c=o[n]||l,h=`${xx}/normals/${c}`,A=Ea(h,e);return B.useLayoutEffect(()=>{A&&(A.wrapS=A.wrapT=Do,A.repeat=new Kt(i[0],i[1]),A.offset=new Kt(r[0],r[1]),A.anisotropy=s)},[A,s,i,r]),[A,h,a]}const Rx=({children:n,id:t,onLoad:e,...i})=>{const s=hf(t,i,e);return B.createElement(B.Fragment,null,n==null?void 0:n(s))},oi={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 kt("#ff0000"),backfaceStroke:new kt("#0000ff"),fill:new kt("#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
+ `},wx=fA(oi.uniforms,oi.vertex+`
197
+ void main() {
198
+ initWireframe();
199
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
200
+ }
201
+ `,oi.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 Lx(n,t){n.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...t},e.vertexShader=e.vertexShader.replace("void main() {",`
218
+ ${oi.vertex}
219
+ void main() {
220
+ initWireframe();
221
+ `),e.fragmentShader=e.fragmentShader.replace("void main() {",`
222
+ ${oi.fragment}
223
+ void main() {
224
+ `),e.fragmentShader=e.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=Vs,n.transparent=!0}function bx(n,t){B.useEffect(()=>{var e;return void(n.fillOpacity.value=(e=t.fillOpacity)!==null&&e!==void 0?e:n.fillOpacity.value)},[t.fillOpacity]),B.useEffect(()=>{var e;return void(n.fillMix.value=(e=t.fillMix)!==null&&e!==void 0?e:n.fillMix.value)},[t.fillMix]),B.useEffect(()=>{var e;return void(n.strokeOpacity.value=(e=t.strokeOpacity)!==null&&e!==void 0?e:n.strokeOpacity.value)},[t.strokeOpacity]),B.useEffect(()=>{var e;return void(n.thickness.value=(e=t.thickness)!==null&&e!==void 0?e:n.thickness.value)},[t.thickness]),B.useEffect(()=>void(n.colorBackfaces.value=!!t.colorBackfaces),[t.colorBackfaces]),B.useEffect(()=>void(n.dash.value=!!t.dash),[t.dash]),B.useEffect(()=>void(n.dashInvert.value=!!t.dashInvert),[t.dashInvert]),B.useEffect(()=>{var e;return void(n.dashRepeats.value=(e=t.dashRepeats)!==null&&e!==void 0?e:n.dashRepeats.value)},[t.dashRepeats]),B.useEffect(()=>{var e;return void(n.dashLength.value=(e=t.dashLength)!==null&&e!==void 0?e:n.dashLength.value)},[t.dashLength]),B.useEffect(()=>void(n.squeeze.value=!!t.squeeze),[t.squeeze]),B.useEffect(()=>{var e;return void(n.squeezeMin.value=(e=t.squeezeMin)!==null&&e!==void 0?e:n.squeezeMin.value)},[t.squeezeMin]),B.useEffect(()=>{var e;return void(n.squeezeMax.value=(e=t.squeezeMax)!==null&&e!==void 0?e:n.squeezeMax.value)},[t.squeezeMax]),B.useEffect(()=>void(n.stroke.value=t.stroke?new kt(t.stroke):n.stroke.value),[t.stroke]),B.useEffect(()=>void(n.fill.value=t.fill?new kt(t.fill):n.fill.value),[t.fill]),B.useEffect(()=>void(n.backfaceStroke.value=t.backfaceStroke?new kt(t.backfaceStroke):n.backfaceStroke.value),[t.backfaceStroke])}function Fx(n){return!!(n!=null&&n.geometry)}function Mx(n){return!!(n!=null&&n.isBufferGeometry)}function Px(n){return!!(n!=null&&n.current)}function qh(n){return(n==null?void 0:n.current)!==void 0}function Xh(n){return n.type==="WireframeGeometry"}function kx(){const n={};for(const t in oi.uniforms)n[t]={value:oi.uniforms[t]};return n}function Qx(n,t){const i=n.getAttribute("position").count,s=[];for(let r=0;r<i;r++){const o=r%2===0,a=t?1:0;o?s.push(0,0,1,0,1,0,1,0,a):s.push(0,1,0,0,0,1,1,0,a)}return new Ro(Float32Array.from(s),3)}function Af(n){const t=Px(n)?n.current:n;if(Mx(t))return t;{if(Xh(t))throw new Error("Wireframe: WireframeGeometry is not supported.");const e=t.parent;if(Fx(e)){if(Xh(e.geometry))throw new Error("Wireframe: WireframeGeometry is not supported.");return e.geometry}}}function uf(n,t){if(n.index){console.warn("Wireframe: Requires non-indexed geometry, converting to non-indexed geometry.");const i=n.toNonIndexed();n.copy(i),n.setIndex(null)}const e=Qx(n,t);n.setAttribute("barycentric",e)}function Ox({geometry:n,simplify:t=!1,...e}){pa({MeshWireframeMaterial:wx});const[i,s]=B.useState(null);B.useLayoutEffect(()=>{const o=Af(n);if(!o)throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry.");uf(o,t),qh(n)&&s(o)},[t,n]);const r=qh(n)?i:n;return B.createElement(B.Fragment,null,r&&B.createElement("mesh",{geometry:r},B.createElement("meshWireframeMaterial",wt({attach:"material",transparent:!0,side:Vs,polygonOffset:!0,polygonOffsetFactor:-4},e,{extensions:{derivatives:!0,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1}}))))}function Gx({simplify:n=!1,...t}){const e=B.useRef(null),i=B.useMemo(()=>kx(),[oi.uniforms]);return bx(i,t),B.useLayoutEffect(()=>{const s=Af(e);if(!s)throw new Error("Wireframe: Must be a child of a Mesh, Line or Points object or specify a geometry prop.");const r=s.clone();return uf(s,n),()=>{s.copy(r),r.dispose()}},[n]),B.useLayoutEffect(()=>{const s=e.current.parent,r=s.material.clone();return Lx(s.material,i),()=>{s.material.dispose(),s.material=r}},[]),B.createElement("object3D",{ref:e})}function Ux({geometry:n,...t}){return n?B.createElement(Ox,wt({geometry:n},t)):B.createElement(Gx,t)}function Nx({opacity:n,alphaMap:t}){const e=B.useRef(null),i=B.useRef(null),s=B.useRef({value:1}),r=B.useRef({value:null}),o=B.useRef({value:!1});return B.useLayoutEffect(()=>{e.current.onBeforeCompile=i.current.onBeforeCompile=a=>{const l=a.fragmentShader.indexOf("void main");let c="",h,A=l;for(;h!==`
237
+ `&&A<l+100;)h=a.fragmentShader.charAt(A),c+=h,A++;c=c.trim(),a.vertexShader=a.vertexShader.replace("void main() {",`
238
+ varying vec2 custom_vUv;
239
+
240
+ void main() {
241
+ custom_vUv = uv;
242
+
243
+ `),a.fragmentShader=a.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
+ `),a.uniforms.uShadowOpacity=s.current,a.uniforms.uAlphaMap=r.current,a.uniforms.uHasAlphaMap=o.current}},[]),Ot(()=>{var a;const l=(a=e.current.__r3f)==null?void 0:a.parent;if(l){const c=l.material;c&&(s.current.value=n??c.opacity,t===!1?(r.current.value=null,o.current.value=!1):(r.current.value=t||c.alphaMap,o.current.value=!!r.current.value))}}),B.createElement(B.Fragment,null,B.createElement("meshDepthMaterial",{ref:e,attach:"customDepthMaterial",depthPacking:ig}),B.createElement("meshDistanceMaterial",{ref:i,attach:"customDistanceMaterial"}))}const Wh=new dt,jh=new sg,To=new da,_o=new k;function Hx(n,t){const e=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(e.boundingSphere===null&&e.computeBoundingSphere(),To.copy(e.boundingSphere),To.applyMatrix4(s),n.ray.intersectsSphere(To)!==!1&&(Wh.copy(s).invert(),jh.copy(n.ray).applyMatrix4(Wh),!(e.boundingBox!==null&&jh.intersectBox(e.boundingBox,_o)===null)&&t.push({distance:_o.distanceTo(n.ray.origin),point:_o.clone(),object:this})))}const Kx=B.forwardRef(({options:n={video:!0},...t},e)=>{const i=es(()=>navigator.mediaDevices.getDisplayMedia(n),[]);return B.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),gA([])},[i]),B.createElement(Sr,wt({ref:e},t,{src:i}))}),df=B.forwardRef(({constraints:n={audio:!1,video:{facingMode:"user"}},...t},e)=>{const i=es(()=>navigator.mediaDevices.getUserMedia(n),[]);return B.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),gA([])},[i]),B.createElement(Sr,wt({ref:e},t,{src:i}))});function Zh(n,t){return n.clone().add(t).multiplyScalar(.5)}function Gi(n,t,e){const i=n.localToWorld(t);return e.worldToLocal(i)}const ff=B.createContext({}),Yx=B.forwardRef(({camera:n,videoTexture:t={start:!0},manualDetect:e=!1,faceLandmarkerResult:i,manualUpdate:s=!1,makeDefault:r,smoothTime:o=.25,offset:a=!0,offsetScalar:l=80,eyes:c=!1,eyesAsOrigin:h=!0,depth:A=.15,debug:u=!1,facemesh:d},f)=>{var g,p;const m=$(at=>at.scene),C=$(at=>at.camera),E=$(at=>at.set),v=$(at=>at.get),y=n||C,S=B.useRef(null),[T]=B.useState(()=>new jt),[x]=B.useState(()=>new k),[F]=B.useState(()=>new k),[_]=B.useState(()=>new k),[w]=B.useState(()=>new k),U=B.useCallback(()=>{T.parent=y.parent;const at=S.current;if(at){const{outerRef:ht,eyeRightRef:Vt,eyeLeftRef:ne}=at;if(Vt.current&&ne.current){const{irisDirRef:is}=Vt.current,{irisDirRef:Tr}=ne.current;is.current&&Tr.current&&ht.current&&(x.copy(Gi(is.current,new k(0,0,0),ht.current)),F.copy(Gi(Tr.current,new k(0,0,0),ht.current)),T.position.copy(Gi(ht.current,Zh(x,F),y.parent||m)),_.copy(Gi(is.current,new k(0,0,1),ht.current)),w.copy(Gi(Tr.current,new k(0,0,1),ht.current)),T.lookAt(ht.current.localToWorld(Zh(_,w))))}else ht.current&&(T.position.copy(Gi(ht.current,new k(0,0,0),y.parent||m)),T.lookAt(ht.current.localToWorld(new k(0,0,1))))}return T},[y,F,w,x,_,m,T]),[O]=B.useState(()=>new jt),W=B.useCallback(function(at,ht){if(y){var Vt;(Vt=ht)!==null&&Vt!==void 0||(ht=U()),o>0?($i.damp3(O.position,ht.position,o,at,void 0,void 0,1e-9),$i.dampE(O.rotation,ht.rotation,o,at,void 0,void 0,1e-9)):(O.position.copy(ht.position),O.rotation.copy(ht.rotation)),y.position.copy(O.position),y.rotation.copy(O.rotation)}},[y,U,o,O.position,O.rotation]);Ot((at,ht)=>{s||W(ht)});const K=B.useRef(null),[q,Z]=B.useState(),rt=mA(),V=B.useCallback((at,ht)=>{const Vt=K.current;if(!Vt)return;const ne=Vt.source.data,is=rt==null?void 0:rt.detectForVideo(ne,at);Z(is)},[rt]),G=B.useMemo(()=>Object.assign(Object.create(ng.prototype),{computeTarget:U,update:W,facemeshApiRef:S}),[U,W]);B.useImperativeHandle(f,()=>G,[G]),B.useEffect(()=>{if(r){const at=v().controls;return E({controls:G}),()=>E({controls:at})}},[r,G,v,E]);const H=i??q,X=H==null?void 0:H.faceLandmarks[0],Y=H==null||(g=H.facialTransformationMatrixes)==null?void 0:g[0],D=H==null||(p=H.faceBlendshapes)==null?void 0:p[0],it={onVideoFrame:V,...t};return B.createElement(ff.Provider,{value:G},!e&&B.createElement(B.Suspense,{fallback:null},"src"in it?B.createElement(Sr,wt({ref:K},it)):B.createElement(df,wt({ref:K},it))),B.createElement(pA,wt({ref:S,children:B.createElement("meshNormalMaterial",{side:Vs})},d,{points:X,depth:A,facialTransformationMatrix:Y,faceBlendshapes:D,eyes:c,eyesAsOrigin:h,offset:a,offsetScalar:l,debug:u,"rotation-z":Math.PI,visible:u})))}),Vx=()=>B.useContext(ff),gD=Object.freeze(Object.defineProperty({__proto__:null,AccumulativeShadows:rg,AdaptiveDpr:og,AdaptiveEvents:ag,ArcballControls:BB,AsciiRenderer:lg,BBAnchor:cg,Backdrop:hg,BakeShadows:Ag,Billboard:ug,Bounds:dg,Box:fg,Bvh:gg,CameraControls:RB,CameraShake:mg,Capsule:pg,CatmullRomLine:Eg,Caustics:Cg,Center:uA,Circle:Ig,Clone:ma,Cloud:yg,CloudInstance:Bg,Clouds:vg,ComputedAttribute:Sg,Cone:Tg,ContactShadows:_g,CubeCamera:xg,CubeTexture:FB,CubicBezierLine:Dg,CurveModifier:Rg,CycleRaycast:wg,Cylinder:Lg,Decal:bg,Detailed:Fg,DetectGPU:ax,DeviceOrientationControls:EB,Dodecahedron:Mg,DragControls:LE,Edges:Pg,Effects:kg,Environment:Qg,EnvironmentCube:Og,EnvironmentMap:Gg,EnvironmentPortal:Ug,Example:Ix,Extrude:Ng,FaceControls:Yx,FaceLandmarker:Hg,FaceLandmarkerDefaults:Kg,Facemesh:pA,FacemeshDatas:Yg,FacemeshEye:Vg,FacemeshEyeDefaults:Jg,Fbo:zg,Fbx:MB,FirstPersonControls:TB,Fisheye:$g,Float:qg,FlyControls:CB,GizmoHelper:Xg,GizmoViewcube:Wg,GizmoViewport:jg,Gltf:pB,GradientTexture:Zg,GradientType:tm,Grid:em,Helper:im,Html:sm,Hud:nm,Icosahedron:rm,Image:om,Instance:am,InstancedAttribute:lm,Instances:cm,IsObject:wo,KeyboardControls:jI,Ktx2:PB,Lathe:hm,Lightformer:Am,Line:um,Loader:wE,MapControls:IB,MarchingCube:dm,MarchingCubes:fm,MarchingPlane:gm,Mask:mm,MatcapTexture:_x,Merged:pm,MeshDiscardMaterial:Em,MeshDistortMaterial:Cm,MeshPortalMaterial:Im,MeshReflectorMaterial:ym,MeshRefractionMaterial:Bm,MeshTransmissionMaterial:vm,MeshWobbleMaterial:Sm,MotionPathControls:bB,MultiMaterial:yx,NormalTexture:Rx,Octahedron:Tm,OrbitControls:_m,OrthographicCamera:xm,Outlines:Dm,PerformanceMonitor:Rm,PerspectiveCamera:wm,PivotControls:Lm,Plane:bm,Point:Fm,PointMaterial:Mm,PointMaterialImpl:Pm,PointerLockControls:SB,Points:km,PointsBuffer:Qm,Polyhedron:Om,PositionMesh:Gm,PositionPoint:Um,PositionalAudio:Nm,Preload:Hm,PresentationControls:qI,Progress:DE,QuadraticBezierLine:Km,RandomizedLight:Ym,Reflector:Bx,RenderCubeTexture:Vm,RenderTexture:Jm,Resize:zm,Ring:$m,RoundedBox:qm,Sampler:Xm,ScreenQuad:Wm,ScreenSizer:mB,ScreenSpace:jm,ScreenVideoTexture:Kx,Scroll:bC,ScrollControls:RC,Segment:Zm,SegmentObject:tp,Segments:ep,Select:ip,Shadow:sp,ShadowAlpha:Nx,Shape:np,Sky:rp,SoftShadows:op,Sparkles:ap,Sphere:lp,Splat:cp,SpotLight:hp,SpotLightShadow:Ap,SpriteAnimator:up,Stage:dp,Stars:fp,Stats:X_,StatsGl:rf,Svg:gp,Tetrahedron:mp,Text:pp,Text3D:dA,Texture:Ep,Torus:Cp,TorusKnot:Ip,TrackballControls:yB,Trail:yp,TrailTexture:Cx,TransformControls:vB,Tube:Bp,VideoTexture:Sr,View:vp,WebcamVideoTexture:df,Wireframe:Ux,accumulativeContext:Sp,calcPosFromAngles:Tp,calculateScaleFactor:rA,checkIfFrameIsEmpty:_p,createInstances:xp,getFirstFrame:Dp,isWebGL2Available:Rp,meshBounds:Hx,shaderMaterial:fA,useAnimations:cx,useAspect:tx,useBVH:wp,useBounds:Lp,useBoxProjectedEnv:gx,useCamera:ex,useContextBridge:lx,useCubeCamera:bp,useCubeTexture:Ha,useCursor:SE,useDepthBuffer:Z_,useDetectGPU:af,useEnvironment:Fp,useFBO:AA,useFBX:pr,useFaceControls:Vx,useFaceLandmarker:mA,useFont:Mp,useGLTF:Xs,useGizmoContext:Pp,useHelper:kp,useIntersect:Qp,useKTX2:Er,useKeyboardControls:ZI,useMask:Op,useMatcapTexture:cf,useMotion:Mu,useNormalTexture:hf,usePerformanceMonitor:Gp,useProgress:Ba,useScroll:Sa,useSelect:Up,useSpriteAnimator:Np,useSpriteLoader:Hp,useSurfaceSampler:Kp,useTexture:Ea,useTrail:Yp,useTrailTexture:lf,useVideoTexture:ef},Symbol.toStringTag,{value:"Module"}));function gf(n,t,e,i){const s=$(r=>r.camera);Ot(()=>{n.current!=null&&t(Vp(s,n.current,e,i))})}function Jx({children:n,direction:t,angle:e=Math.PI/2}){const i=B.useRef(null);return gf(i,s=>{i.current!=null&&(i.current.visible=s)},t,e),Xe.jsx("group",{ref:i,children:n})}function zx({children:n,direction:t,angle:e=Math.PI/2}){const i=B.useRef(null),[s,r]=B.useState(!1);return gf(i,r,t,e),s?Xe.jsx(Xe.Fragment,{children:n}):null}function $x({children:n,mode:t}){const e=Ca(t);return Xe.jsx("group",{visible:e,children:n})}function qx({children:n,mode:t}){return Ca(t)?Xe.jsx(Xe.Fragment,{children:n}):null}function Xx({children:n}){const t=Ia();return Xe.jsx("group",{visible:t==null||t==="visible",children:n})}function Wx({children:n}){const t=Ia();return t!="visible"&&t!=null?null:Xe.jsx(Xe.Fragment,{children:n})}function jx(){const n=lr();return B.useMemo(()=>ya.bind(null,n),[n])}function Zx(){const[n,t]=B.useState(void 0),e=B.useRef(()=>{}),i=lr(),s=B.useCallback(async r=>{var l;(l=e.current)==null||l.call(e),e.current=void 0;let o=!1;e.current=()=>o=!0;const a=await ya(i,r);if(o){a==null||a.delete();return}return e.current=()=>a==null?void 0:a.delete(),t(a),a},[i]);return B.useEffect(()=>()=>{var r;return void((r=e.current)==null?void 0:r.call(e))},[]),[n,s]}function tD(n,t={},e={},i="left"){const s=lr(),r=B.useMemo(()=>Jp(),[]);Ot((o,a,l)=>r(typeof n=="function"?n:n.current,s,o.camera,a,t,e,i,a,o,l))}function eD({batchEvents:n,clickThesholdMs:t,contextMenuButton:e,customSort:i,dblClickThresholdMs:s,filter:r,forwardPointerCapture:o,intersectEveryFrame:a,pointerTypePrefix:l}){const c=$(d=>d.gl.domElement),h=$(d=>d.frameloop==="always"),A=$(d=>d.camera),u=$(d=>d.scene);return B.useEffect(()=>{const{destroy:d,update:f}=zp(c,()=>A,u,{batchEvents:n??h,clickThesholdMs:t,contextMenuButton:e,customSort:i,dblClickThresholdMs:s,filter:r,forwardPointerCapture:o,intersectEveryFrame:a,pointerTypePrefix:l}),g=ha(f);return()=>{g(),d()}},[c,A,u,h,n,t,e,i,s,r,o,a,l]),null}const iD=()=>({enabled:!1,priority:0}),mD=Object.freeze(Object.defineProperty({__proto__:null,ARButton:$p,CombinedPointer:qp,DefaultXRController:Xp,DefaultXRControllerGrabPointer:Wp,DefaultXRGaze:jp,DefaultXRHand:Zp,DefaultXRHandGrabPointer:t0,DefaultXRHandTouchPointer:e0,DefaultXRInputSourceRayPointer:i0,DefaultXRInputSourceTeleportPointer:s0,DefaultXRScreenInput:n0,DefaultXRTransientPointer:r0,FallbackXRLayerImplementation:o0,IfFacingCamera:zx,IfInSessionMode:a0,IfSessionModeSupported:qx,IfSessionVisible:Wx,Interactive:l0,PointerCursorModel:c0,PointerEvents:eD,PointerRayModel:h0,RayGrab:A0,RootCombinedPointer:u0,ShowIfFacingCamera:Jx,ShowIfInSessionMode:d0,ShowIfSessionModeSupported:$x,ShowIfSessionVisible:Xx,TeleportPointerRayModel:f0,TeleportTarget:g0,VRButton:m0,XR:p0,XRButton:E0,XRControllerComponent:C0,XRControllerModel:I0,XRDomOverlay:y0,XRHandJoint:B0,XRHandModel:v0,XRHitTest:S0,XRLayer:T0,XRLayerImplementation:_0,XRMeshModel:x0,XROrigin:D0,XRPlaneModel:R0,XRSpace:w0,createXRHitTestSource:L0,createXRStore:b0,defaultGrabPointerOpacity:F0,defaultRayPointerOpacity:M0,defaultTouchPointerOpacity:P0,isXRInputSourceState:k0,noEvents:iD,privateKeys:Q0,requestXRAnchor:ya,requestXRHitTest:O0,useApplyXRSpaceMatrix:G0,useGetXRSpaceMatrix:U0,useGrabPointer:N0,useHover:H0,useInitRoomCapture:K0,useInteraction:Y0,useLayerStore:V0,useLinesPointer:J0,useLoadXRControllerLayout:z0,useLoadXRControllerModel:$0,usePointerXRInputSourceEvents:q0,useRayPointer:X0,useRequestXRAnchor:jx,useSessionFeatureEnabled:W0,useSessionModeSupported:Ca,useTouchPointer:j0,useXR:Z0,useXRAnchor:Zx,useXRControllerButtonEvent:tE,useXRControllerLocomotion:tD,useXRControllerState:eE,useXREvent:iE,useXRGazeState:sE,useXRHandState:nE,useXRHitTest:rE,useXRHitTestSource:oE,useXRInputSourceEvent:aE,useXRInputSourceState:lE,useXRInputSourceStateContext:cE,useXRInputSourceStates:hE,useXRMeshGeometry:AE,useXRMeshes:uE,useXRPlaneGeometry:dE,useXRPlanes:fE,useXRReferenceSpace:gE,useXRRequestHitTest:mE,useXRScreenInputState:pE,useXRSessionVisibilityState:Ia,useXRSpace:EE,useXRStore:lr,useXRTransientPointerState:CE},Symbol.toStringTag,{value:"Module"}));export{gD as D,mD as X};
269
+ //# sourceMappingURL=chunk-DTi-TijR.js.map