vuer 0.0.42rc2__py3-none-any.whl → 0.0.42rc3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of vuer might be problematic. Click here for more details.
- vuer/client_build/404.html +4 -4
- vuer/client_build/assets/chunks/chunk-CGz9UiJu.js +3 -0
- vuer/client_build/assets/chunks/chunk-CGz9UiJu.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-CKKRRzH3.js +102 -0
- vuer/client_build/assets/chunks/chunk-CKKRRzH3.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-DD1m5zNV.js +4660 -0
- vuer/client_build/assets/chunks/chunk-DD1m5zNV.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-UihyksJm.js +269 -0
- vuer/client_build/assets/chunks/chunk-UihyksJm.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-ee-6dmlg.js +7728 -0
- vuer/client_build/assets/chunks/chunk-ee-6dmlg.js.map +1 -0
- vuer/client_build/assets/entries/entry-client-routing.DU90SOG0.js +5 -0
- vuer/client_build/assets/entries/entry-client-routing.DU90SOG0.js.map +1 -0
- vuer/client_build/assets/entries/pages_editor.Dp3xRhx4.js +2 -0
- vuer/client_build/assets/entries/pages_editor.Dp3xRhx4.js.map +1 -0
- vuer/client_build/assets/entries/pages_index.BHEhIviG.js +2 -0
- vuer/client_build/assets/entries/pages_index.BHEhIviG.js.map +1 -0
- vuer/client_build/assets/entries/pages_simple.DWLSCp--.js +2 -0
- vuer/client_build/assets/entries/pages_simple.DWLSCp--.js.map +1 -0
- vuer/client_build/editor/index.html +6 -6
- vuer/client_build/index.html +6 -6
- vuer/client_build/simple/index.html +5 -5
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/METADATA +2 -2
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/RECORD +28 -10
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/LICENSE +0 -0
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/WHEEL +0 -0
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/entry_points.txt +0 -0
- {vuer-0.0.42rc2.dist-info → vuer-0.0.42rc3.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import{f as qs,u as q,g as qh,i as It,j as k,k as dt,l as wt,m as Kt,o as Xh,p as Ts,C as kt,s as _e,E as qe,S as oo,t as Ot,v as al,T as df,w as lo,x as co,y as ct,B as Zi,G as jt,J as ar,K as ho,U as Hs,X as _s,Y as me,a0 as li,a1 as Se,a2 as $e,a3 as nt,a4 as Et,a5 as ci,a6 as gi,a7 as Xs,a8 as Wh,a9 as _r,aa as xa,ab as jh,ac as uo,ad as vr,ae as Pt,af as se,ag as ff,ah as gf,ai as Ao,aj as mf,ak as Hi,al as pf,am as Da,an as kn,ao as Qn,ap as xr,aq as Ef,ar as Cf,as as ol,at as On,au as ll,av as If,aw as yf,ax as Bf,ay as Sf,az as Tf,aA as _f,aB as vf,aC as xf,aD as Df,aE as Rf,aF as wf,aG as Zh,aH as Lf,aI as cl,aJ as or,aK as bf,aL as Ui,aM as Ff,aN as Mf,aO as Pf,aP as kf,aQ as Qf,aR as Of,aS as Gf,aT as Uf,aU as Nf,aV as ye,aW as Gn,aX as Hf,aY as _n,aZ as vs,a_ as Kf,a$ as ys,b0 as Bs,b1 as hl,b2 as Ra,b3 as tu,b4 as xe,b5 as fo,b6 as go,b7 as Yf,b8 as mo,b9 as Vf,ba as Jf,bb as eu,bc as wa,bd as ts,be as zf,bf as iu,bg as su,bh as nu,bi as ru,bj as au,bk as $f,bl as qf,bm as Xf,bn as ou,bo as lu,bp as Wf,bq as ul,br as jf,bs as po,bt as cu,bu as Zf,bv as tg,bw as hu,bx as uu,by as eg,bz as Au,bA as ig,bB as sg,bC as ng,bD as rg,bE as ag,bF as og,bG as lg,bH as cg,bI as hg,bJ as ug,bK as Ag,bL as dg,bM as fg,bN as gg,bO as mg,bP as pg,bQ as Eg,bR as Cg,bS as Ig,bT as yg,bU as Bg,bV as Sg,bW as Tg,bX as _g,bY as vg,bZ as xg,b_ as Dg,b$ as Rg,c0 as wg,c1 as Lg,c2 as bg,c3 as Fg,c4 as Mg,c5 as Pg,c6 as kg,c7 as Qg,c8 as Og,c9 as Gg,ca as Ug,cb as Ng,cc as Hg,cd as Kg,ce as Yg,cf as Vg,cg as Jg,ch as zg,ci as $g,cj as qg,ck as Xg,cl as Wg,cm as jg,cn as Zg,co as tm,cp as em,cq as im,cr as sm,cs as nm,ct as rm,cu as am,cv as om,cw as lm,cx as cm,cy as hm,cz as um,cA as Am,cB as dm,cC as fm,cD as gm,cE as mm,cF as pm,cG as Em,cH as Cm,cI as Im,cJ as ym,cK as Bm,cL as Sm,cM as Tm,cN as _m,cO as vm,cP as xm,cQ as Dm,cR as Rm,cS as wm,cT as Lm,cU as bm,cV as Fm,cW as Mm,cX as Pm,cY as km,cZ as Qm,c_ as Om,c$ as Gm,d0 as Um,d1 as Nm,d2 as Hm,d3 as Km,d4 as Ym,d5 as Vm,d6 as Jm,d7 as zm,d8 as $m,d9 as qm,da as Xm,db as Wm,dc as jm,dd as Zm,de as tp,df as ep,dg as ip,dh as sp,di as np,dj as rp,dk as ap,dl as op,dm as lp,dn as cp,dp as hp,dq as up,dr as Ap,ds as dp,dt as fp,du as gp,dv as mp,dw as pp,dx as Ep,dy as Cp,dz as Ip,dA as yp,dB as Bp,dC as Sp,dD as Tp,dE as _p,dF as vp,dG as xp,dH as Dp,dI as Rp,dJ as wp,dK as Lp,dL as bp,dM as Fp,dN as Mp,dO as Pp,dP as kp,dQ as Qp,dR as Op,dS as Gp,dT as Up,dU as Np,dV as Hp,dW as Eo,dX as Co,dY as lr,dZ as Io,d_ as Kp,d$ as Yp,e0 as Vp,e1 as Jp,e2 as zp,e3 as $p,e4 as qp,e5 as Xp,e6 as Wp,e7 as jp,e8 as Zp,e9 as t0,ea as e0,eb as i0,ec as s0,ed as n0,ee as r0,ef as a0,eg as o0,eh as l0,ei as c0,ej as h0,ek as u0,el as A0,em as d0,en as f0,eo as g0,ep as m0,eq as p0,er as E0,es as C0,et as I0,eu as y0,ev as B0,ew as S0,ex as T0,ey as _0,ez as v0,eA as x0,eB as D0,eC as R0,eD as w0,eE as L0,eF as b0,eG as F0,eH as M0,eI as P0,eJ as k0,eK as Q0,eL as O0,eM as G0,eN as U0,eO as N0,eP as H0,eQ as K0,eR as Y0,eS as V0,eT as J0,eU as z0,eV as $0,eW as q0,eX as X0,eY as W0,eZ as j0,e_ as Z0,e$ as tE,f0 as eE,f1 as iE,f2 as sE,f3 as nE,f4 as rE,f5 as aE,f6 as oE,f7 as lE,f8 as cE,f9 as hE,fa as uE,fb as AE,fc as dE,fd as fE,fe as gE,ff as mE}from"./chunk-ee-6dmlg.js";import{r as B,o as Al,e as pE,f as EE,g as CE,j as Xe}from"./chunk-11bBwnOQ.js";import{_ as IE}from"./chunk-D7HrI6pR.js";function yE(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 u=typeof c=="function"?c(t):c;if(!Object.is(u,t)){const A=t;t=h??(typeof u!="object"||u===null)?u:Object.assign({},t,u),e.forEach(d=>d(t,A))}},s=()=>t,o={setState:i,getState:s,getInitialState:()=>l,subscribe:c=>(e.add(c),()=>e.delete(c))},l=t=n(i,s,o);return o},BE=n=>n?dl(n):dl,SE=n=>n;function TE(n,t=SE){const e=Al.useSyncExternalStore(n.subscribe,()=>t(n.getState()),()=>t(n.getInitialState()));return Al.useDebugValue(e),e}const fl=n=>{const t=BE(n),e=i=>TE(t,i);return Object.assign(e,t),e},du=n=>n?fl(n):fl;let is=0;const yo=du(n=>(qs.onStart=(t,e,i)=>{n({active:!0,item:t,loaded:e,total:i,progress:(e-is)/(i-is)*100})},qs.onLoad=()=>{n({active:!1})},qs.onError=t=>n(e=>({errors:[...e.errors,t]})),qs.onProgress=(t,e,i)=>{e===i&&(is=i),n({active:!0,item:t,loaded:e,total:i,progress:(e-is)/(i-is)*100||100})},{errors:[],active:!1,progress:0,item:"",loaded:0,total:0}));function _E({children:n}){const t=yo();return B.createElement(B.Fragment,null,n==null?void 0:n(t))}const vE=n=>`Loading ${n.toFixed(2)}%`;function xE({containerStyles:n,innerStyles:t,barStyles:e,dataStyles:i,dataInterpolation:s=vE,initialState:r=a=>a}){const{active:a,progress:o}=yo(),l=B.useRef(0),c=B.useRef(0),h=B.useRef(null),[u,A]=B.useState(r(a));B.useEffect(()=>{let f;return a!==u&&(f=setTimeout(()=>A(a),300)),()=>clearTimeout(f)},[u,a]);const d=B.useCallback(()=>{h.current&&(l.current+=(o-l.current)/2,(l.current>.95*o||o===100)&&(l.current=o),h.current.innerText=s(l.current),l.current<o&&(c.current=requestAnimationFrame(d)))},[s,o]);return B.useEffect(()=>(d(),()=>cancelAnimationFrame(c.current)),[d]),u?B.createElement("div",{style:{...Ws.container,opacity:a?1:0,...n}},B.createElement("div",null,B.createElement("div",{style:{...Ws.inner,...t}},B.createElement("div",{style:{...Ws.bar,transform:`scaleX(${o/100})`,...e}}),B.createElement("span",{ref:h,style:{...Ws.data,...i}})))):null}const Ws={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"}},Dr=new k,gl=new Kt,hi=new k,js=new k,ss=new k,ml=new Xh,DE=B.forwardRef(({autoTransform:n=!0,matrix:t,axisLock:e,dragLimits:i,onHover:s,onDragStart:r,onDrag:a,onDragEnd:o,children:l,dragConfig:c,...h},u)=>{const A=q(E=>E.controls),{camera:d,size:f,raycaster:g,invalidate:p}=q(),m=B.useRef(null),C=qh({onHover:({hovering:E})=>s&&s(E??!1),onDragStart:({event:E})=>{A&&(A.enabled=!1);const{point:S}=E;m.current.matrix.decompose(Dr,new It,new k),hi.copy(S),js.copy(hi).sub(Dr),r&&r(Dr),p()},onDrag:({xy:[E,S],intentional:y})=>{if(!y)return;const _=(E-f.left)/f.width*2-1,T=-((S-f.top)/f.height)*2+1;if(gl.set(_,T),g.setFromCamera(gl,d),!e)d.getWorldDirection(ss).negate();else switch(e){case"x":ss.set(1,0,0);break;case"y":ss.set(0,1,0);break;case"z":ss.set(0,0,1);break}ml.setFromNormalAndCoplanarPoint(ss,hi),g.ray.intersectPlane(ml,hi);const v=m.current.matrix.clone(),F=m.current.matrixWorld.clone(),x=new k(hi.x-js.x,hi.y-js.y,hi.z-js.z);if(i&&(x.x=i[0]?Math.max(Math.min(x.x,i[0][1]),i[0][0]):x.x,x.y=i[1]?Math.max(Math.min(x.y,i[1][1]),i[1][0]):x.y,x.z=i[2]?Math.max(Math.min(x.z,i[2][1]),i[2][0]):x.z),n){m.current.matrix.setPosition(x);const w=m.current.matrix.clone().multiply(v.invert()),U=m.current.matrix.clone().multiply(F.invert());a&&a(m.current.matrix,w,m.current.matrixWorld,U)}else{const w=new dt().copy(m.current.matrix);w.setPosition(x);const U=w.clone().multiply(v.invert()),O=w.clone().multiply(F.invert());a&&a(w,U,m.current.matrixWorld,O)}p()},onDragEnd:()=>{A&&(A.enabled=!0),o&&o(),p()}},{drag:{filterTaps:!0,threshold:1,...typeof c=="object"?c:{}}});return B.useImperativeHandle(u,()=>m.current,[]),B.useLayoutEffect(()=>{t&&(m.current.matrix=t)},[t]),B.createElement("group",wt({ref:m},C(),{matrix:t,matrixAutoUpdate:!1},h),l)});function xs(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function La(n,t){return La=Object.setPrototypeOf||function(i,s){return i.__proto__=s,i},La(n,t)}function RE(){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 wE(){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],a=t[3],o=t[4],l=t[5],c=t[6],h=t[7],u=t[8];return i*o*u+s*l*c+r*a*h-r*o*c-s*a*u-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 Ts().fromArray(e)}function LE(n){if(Array.isArray(n))return n}function bE(n,t){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var i=[],s=!0,r=!1,a,o;try{for(e=e.call(n);!(s=(a=e.next()).done)&&(i.push(a.value),!(t&&i.length===t));s=!0);}catch(l){r=!0,o=l}finally{try{!s&&e.return!=null&&e.return()}finally{if(r)throw o}}return i}}function ba(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 fu(n,t){if(n){if(typeof n=="string")return ba(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 ba(n,t)}}function FE(){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 LE(n)||bE(n,t)||fu(n,t)||FE()}function ME(n){if(Array.isArray(n))return ba(n)}function PE(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function kE(){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 ME(n)||PE(n)||fu(n)||kE()}function vn(n,t,e){return RE()?vn=Reflect.construct:vn=function(s,r,a){var o=[null];o.push.apply(o,r);var l=Function.bind.apply(s,o),c=new l;return a&&La(c,a.prototype),c},vn.apply(null,arguments)}function QE(n){var t=Oe(n[0],2),e=t[0],i=t[1],s=Oe(n[1],2),r=s[0],a=s[1],o=Oe(n[2],2),l=o[0],c=o[1];return wE(e,i,1,r,a,1,l,c,1)}function OE(n){return QE(n)===0}var GE=new Kt,UE=new Kt;function El(n){var t=n.map(function(c){return Array.isArray(c)?vn(Kt,Un(c)):c}),e=Oe(t,3),i=e[0],s=e[1],r=e[2];if(OE(n))return!1;var a=GE.subVectors(s,i),o=UE.subVectors(r,i),l=o.cross(a);return l>0}function gu(n,t,e){return Math.max(t,Math.min(e,n))}function mu(n,t){return gu(n-Math.floor(n/t)*t,0,t)}function pu(n,t){var e=mu(t-n,Math.PI*2);return e>Math.PI&&(e-=Math.PI*2),e}function NE(n){return n/180*Math.PI}function HE(n){return n*180/Math.PI}function KE(n,t){for(var e=t.radius,i=e===void 0?1:e,s=n.length/3,r=2/s,a=Math.PI*(3-2.2360679775),o=0;o<n.length;o+=3){var l=o*r-1+r/2,c=Math.sqrt(1-Math.pow(l,2)),h=o%s*a,u=Math.cos(h)*c,A=Math.sin(h)*c;n[o]=u*i,n[o+1]=l*i,n[o+2]=A*i}}function YE(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 Eu(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 VE(n){for(var t=n.sort(Eu),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 a=[].concat(e,s);return a}function JE(n,t,e){var i=Oe(t,2),s=i[0],r=i[1],a=Oe(e,2),o=a[0],l=a[1];return o+(n-s)*(l-o)/(r-s)}function zE(n){return n*n*n*(n*(n*6-15)+10)}function $E(n,t,e){return n*(1-e)+t*e}function Cu(n,t,e){return(e-n)/(t-n)}function qE(n,t,e){var i=Math.sqrt(n*n+t*t+e*e);return[n/i,t/i,e/i]}function XE(n,t,e){var i=n*n,s=t*t,r=e*e,a=n*Math.sqrt(1-(s+r)/2+s*r/3),o=t*Math.sqrt(1-(r+i)/2+r*i/3),l=e*Math.sqrt(1-(i+s)/2+i*s/3);return[a,o,l]}function Iu(n,t){var e=new k().crossVectors(n,t),i=n.dot(t),s=new Ts().identity(),r=new Ts().set(0,-e.z,e.y,e.z,0,-e.x,-e.y,e.x,0),a=new Ts().multiplyMatrices(r,r).multiplyScalar(1/(1+i)),o=pl(pl(s,r),a);return o}function WE(n,t,e){var i=Math.asin(t),s=Math.atan2(n,-e);return[i,s]}function jE(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 ZE(n,t){var e=Oe(t,2),i=e[0],s=e[1],r=Iu(n.normal,new k(0,1,0)),a=Cu(i.clone().applyMatrix3(r).y,s.clone().applyMatrix3(r).y,0);return new k().lerpVectors(i,s,a)}function tC(n,t){var e=t.normal.dot(n);return e}function eC(n,t){var e=Oe(n,3),i=e[0],s=e[1],r=e[2],a=Oe(t,2),o=a[0],l=a[1];return r*o*l+s*o+i}function iC(n,t){var e=Oe(t,2),i=e[0],s=e[1],r=i*s,a=n/r,o=n-r*a,l=o/i,c=o%i;return[c,l,a]}function sC(n,t){return n[0]+t[0]*n[1]}function nC(n,t){var e=n%t,i=Math.floor(n/t);return[e,i]}var Rr=Object.freeze({__proto__:null,clamp:gu,repeat:mu,deltaAngle:pu,degToRad:NE,radToDeg:HE,fibonacciOnSphere:KE,vectorEquals:YE,lexicographic:Eu,convexHull:VE,remap:JE,fade:zE,lerp:$E,inverseLerp:Cu,normalize:qE,pointOnCubeToPointOnSphere:XE,rotateVectorOnVector:Iu,pointToCoordinate:WE,coordinateToPoint:jE,planeSegmentIntersection:ZE,pointToPlaneDistance:tC,getIndexFrom3D:eC,get3DFromIndex:iC,getIndexFrom2D:sC,get2DFromIndex:nC});function yu(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;yu(this,n),xs(this,"dot2",function(r,a){return s.x*r+s.y*a}),xs(this,"dot3",function(r,a,o){return s.x*r+s.y*a+s.z*o}),this.x=t,this.y=e,this.z=i},rC=[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),aC=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]=rC[i%12]}};aC(0);function oC(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=oC(n);return function(){var e=t*48271%2147483647;return t=e,e/2147483647}}var lC=function n(t){var e=this;yu(this,n),xs(this,"seed",0),xs(this,"init",function(i){e.seed=i,e.value=Bl(i)}),xs(this,"value",Bl(this.seed)),this.init(t)};new lC(Math.random());var cC=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)},Bu=function(t){return 1/(1+t+.48*t*t+.235*t*t*t)},hC=function(t){return t},uC={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}},AC={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}},dC={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}},fC={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}},gC={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}},mC={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,a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Bu,o=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)<=o)return n[t]=e,!1;i=Math.max(1e-4,i);var c=2/i,h=a(c*s),u=n[t]-e,A=e,d=r*i;u=Math.min(Math.max(u,-d),d),e=n[t]-u;var f=(n.__damp[l]+c*u)*s;n.__damp[l]=(n.__damp[l]-c*f)*h;var g=e+(u+f)*h;return A-n[t]>0==g>A&&(g=A,n.__damp[l]=(g-A)/s),n[t]=g,!0}var pC=function(t){return t&&t.isCamera},EC=function(t){return t&&t.isLight},ns=new k,Sl=new It,Tl=new It,rs=new dt,wr=new k;function CC(n,t,e,i,s,r,a){typeof t=="number"?ns.setScalar(t):Array.isArray(t)?ns.set(t[0],t[1],t[2]):ns.copy(t);var o=n.parent;n.updateWorldMatrix(!0,!1),wr.setFromMatrixPosition(n.matrixWorld),pC(n)||EC(n)?rs.lookAt(wr,ns,n.up):rs.lookAt(ns,wr,n.up),Nn(n.quaternion,Tl.setFromRotationMatrix(rs),e,i,s,r,a),o&&(rs.extractRotation(o.matrixWorld),Sl.setFromRotationMatrix(rs),Nn(n.quaternion,Tl.copy(n.quaternion).premultiply(Sl.invert()),e,i,s,r,a))}function Ki(n,t,e,i,s,r,a,o){return Yt(n,t,n[t]+pu(n[t],e),i,s,r,a,o)}var as=new Kt,_l,vl;function IC(n,t,e,i,s,r,a){return typeof t=="number"?as.setScalar(t):Array.isArray(t)?as.set(t[0],t[1]):as.copy(t),_l=Yt(n,"x",as.x,e,i,s,r,a),vl=Yt(n,"y",as.y,e,i,s,r,a),_l||vl}var Si=new k,xl,Dl,Rl;function Fa(n,t,e,i,s,r,a){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,a),Dl=Yt(n,"y",Si.y,e,i,s,r,a),Rl=Yt(n,"z",Si.z,e,i,s,r,a),xl||Dl||Rl}var ui=new _e,wl,Ll,bl,Fl;function yC(n,t,e,i,s,r,a){return typeof t=="number"?ui.setScalar(t):Array.isArray(t)?ui.set(t[0],t[1],t[2],t[3]):ui.copy(t),wl=Yt(n,"x",ui.x,e,i,s,r,a),Ll=Yt(n,"y",ui.y,e,i,s,r,a),bl=Yt(n,"z",ui.z,e,i,s,r,a),Fl=Yt(n,"w",ui.w,e,i,s,r,a),wl||Ll||bl||Fl}var os=new qe,Ml,Pl,kl;function BC(n,t,e,i,s,r,a){return Array.isArray(t)?os.set(t[0],t[1],t[2],t[3]):os.copy(t),Ml=Ki(n,"x",os.x,e,i,s,r,a),Pl=Ki(n,"y",os.y,e,i,s,r,a),kl=Ki(n,"z",os.z,e,i,s,r,a),Ml||Pl||kl}var Ti=new kt,Ql,Ol,Gl;function SC(n,t,e,i,s,r,a){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,a),Ol=Yt(n,"g",Ti.g,e,i,s,r,a),Gl=Yt(n,"b",Ti.b,e,i,s,r,a),Ql||Ol||Gl}var pe=new It,Ne=new _e,Ul=new _e,ls=new _e,Nl,Hl,Kl,Yl;function Nn(n,t,e,i,s,r,a){var o=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,a),Hl=Yt(n,"y",pe.y,e,i,s,r,a),Kl=Yt(n,"z",pe.z,e,i,s,r,a),Yl=Yt(n,"w",pe.w,e,i,s,r,a),Ne.set(n.x,n.y,n.z,n.w).normalize(),Ul.set(o.__damp.velocity_x,o.__damp.velocity_y,o.__damp.velocity_z,o.__damp.velocity_w),ls.copy(Ne).multiplyScalar(Ul.dot(Ne)/Ne.dot(Ne)),o.__damp.velocity_x-=ls.x,o.__damp.velocity_y-=ls.y,o.__damp.velocity_z-=ls.z,o.__damp.velocity_w-=ls.w,n.set(Ne.x,Ne.y,Ne.z,Ne.w),Nl||Hl||Kl||Yl}var cs=new oo,Vl,Jl,zl;function TC(n,t,e,i,s,r,a){return Array.isArray(t)?cs.set(t[0],t[1],t[2]):cs.copy(t),Vl=Yt(n,"radius",cs.radius,e,i,s,r,a),Jl=Ki(n,"phi",cs.phi,e,i,s,r,a),zl=Ki(n,"theta",cs.theta,e,i,s,r,a),Vl||Jl||zl}var Zs=new dt,$l=new k,ql=new It,Xl=new k,Wl,jl,Zl;function _C(n,t,e,i,s,r,a){var o=n;return o.__damp===void 0&&(o.__damp={position:new k,rotation:new It,scale:new k},n.decompose(o.__damp.position,o.__damp.rotation,o.__damp.scale)),Array.isArray(t)?Zs.set.apply(Zs,Un(t)):Zs.copy(t),Zs.decompose($l,ql,Xl),Wl=Fa(o.__damp.position,$l,e,i,s,r,a),jl=Nn(o.__damp.rotation,ql,e,i,s,r,a),Zl=Fa(o.__damp.scale,Xl,e,i,s,r,a),n.compose(o.__damp.position,o.__damp.rotation,o.__damp.scale),Wl||jl||Zl}var zi=Object.freeze({__proto__:null,rsqw:cC,exp:Bu,linear:hC,sine:uC,cubic:AC,quint:dC,circ:fC,quart:gC,expo:mC,damp:Yt,dampLookAt:CC,dampAngle:Ki,damp2:IC,damp3:Fa,damp4:yC,dampE:BC,dampC:SC,dampQ:Nn,dampS:TC,dampM:_C});const Bo=B.createContext(null);function So(){return B.useContext(Bo)}function vC({eps:n=1e-5,enabled:t=!0,infinite:e,horizontal:i,pages:s=1,distance:r=1,damping:a=.25,maxSpeed:o=1/0,prepend:l=!1,style:c={},children:h}){const{get:u,setEvents:A,gl:d,size:f,invalidate:g,events:p}=q(),[m]=B.useState(()=>document.createElement("div")),[C]=B.useState(()=>document.createElement("div")),[E]=B.useState(()=>document.createElement("div")),S=d.domElement.parentNode,y=B.useRef(0),_=B.useMemo(()=>({el:m,eps:n,fill:C,fixed:E,horizontal:i,damping:a,offset:0,delta:0,scroll:y,pages:s,range(F,x,w=0){const U=F-w,O=U+x+w*2;return this.offset<U?0:this.offset>O?1:(this.offset-U)/(O-U)},curve(F,x,w=0){return Math.sin(this.range(F,x,w)*Math.PI)},visible(F,x,w=0){const U=F-w,O=U+x+w*2;return this.offset>=U&&this.offset<=O}}),[n,a,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 x in c)m.style[x]=c[x];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?S.prepend(m):S.appendChild(m),m[i?"scrollLeft":"scrollTop"]=1;const v=p.connected||d.domElement;requestAnimationFrame(()=>p.connect==null?void 0:p.connect(m));const F=u().events.compute;return A({compute(x,w){const{left:U,top:O}=S.getBoundingClientRect(),W=x.clientX-U,Y=x.clientY-O;w.pointer.set(W/w.size.width*2-1,-(Y/w.size.height)*2+1),w.raycaster.setFromCamera(w.pointer,w.camera)}}),()=>{S.removeChild(m),A({compute:F}),p.connect==null||p.connect(v)}},[s,r,i,m,C,E,S]),B.useEffect(()=>{if(p.connected===m){const v=f[i?"width":"height"],F=m[i?"scrollWidth":"scrollHeight"],x=F-v;let w=0,U=!0,O=!0;const W=()=>{if(!(!t||O)&&(g(),w=m[i?"scrollLeft":"scrollTop"],y.current=w/x,e)){if(!U){if(w>=x){const X=1-_.offset;m[i?"scrollLeft":"scrollTop"]=1,y.current=_.offset=-X,U=!0}else if(w<=0){const X=1+_.offset;m[i?"scrollLeft":"scrollTop"]=F,y.current=_.offset=X,U=!0}}U&&setTimeout(()=>U=!1,40)}};m.addEventListener("scroll",W,{passive:!0}),requestAnimationFrame(()=>O=!1);const Y=X=>m.scrollLeft+=X.deltaY/2;return i&&m.addEventListener("wheel",Y,{passive:!0}),()=>{m.removeEventListener("scroll",W),i&&m.removeEventListener("wheel",Y)}}},[m,p,f,e,_,g,i,t]);let T=0;return Ot((v,F)=>{T=_.offset,zi.damp(_,"offset",y.current,a,F,o,void 0,n),zi.damp(_,"delta",Math.abs(T-_.offset),a,F,o,void 0,n),_.delta>n&&g()}),B.createElement(Bo.Provider,{value:_},h)}const xC=B.forwardRef(({children:n},t)=>{const e=B.useRef(null);B.useImperativeHandle(t,()=>e.current,[]);const i=So(),{width:s,height:r}=q(a=>a.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)}),DC=B.forwardRef(({children:n,style:t,...e},i)=>{const s=So(),r=B.useRef(null);B.useImperativeHandle(i,()=>r.current,[]);const{width:a,height:o}=q(h=>h.size),l=B.useContext(al),c=B.useMemo(()=>pE(s.fixed),[s.fixed]);return Ot(()=>{s.delta>s.eps&&(r.current.style.transform=`translate3d(${s.horizontal?-a*(s.pages-1)*s.offset:0}px,${s.horizontal?0:o*(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(Bo.Provider,{value:s},B.createElement(al.Provider,{value:l},n)))),null}),RC=B.forwardRef(({html:n,...t},e)=>{const i=n?DC:xC;return B.createElement(i,wt({ref:e},t))});var To=Ys(),At=n=>Ks(n,To),_o=Ys();At.write=n=>Ks(n,_o);var cr=Ys();At.onStart=n=>Ks(n,cr);var vo=Ys();At.onFrame=n=>Ks(n,vo);var xo=Ys();At.onFinish=n=>Ks(n,xo);var Yi=[];At.setTimeout=(n,t)=>{const e=At.now()+t,i=()=>{const r=Yi.findIndex(a=>a.cancel==i);~r&&Yi.splice(r,1),si-=~r?1:0},s={time:e,handler:n,cancel:i};return Yi.splice(Su(e),0,s),si+=1,Tu(),s};var Su=n=>~(~Yi.findIndex(t=>t.time>n)||~Yi.length);At.cancel=n=>{cr.delete(n),vo.delete(n),xo.delete(n),To.delete(n),_o.delete(n)};At.sync=n=>{Ma=!0,At.batchedUpdates(n),Ma=!1};At.throttle=n=>{let t;function e(){try{n(...t)}finally{t=null}}function i(...s){t=s,At.onStart(e)}return i.handler=n,i.cancel=()=>{cr.delete(e),t=null},i};var Do=typeof window<"u"?window.requestAnimationFrame:()=>{};At.use=n=>Do=n;At.now=typeof performance<"u"?()=>performance.now():Date.now;At.batchedUpdates=n=>n();At.catch=console.error;At.frameLoop="always";At.advance=()=>{At.frameLoop!=="demand"?console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"):vu()};var ii=-1,si=0,Ma=!1;function Ks(n,t){Ma?(t.delete(n),n(0)):(t.add(n),Tu())}function Tu(){ii<0&&(ii=0,At.frameLoop!=="demand"&&Do(_u))}function wC(){ii=-1}function _u(){~ii&&(Do(_u),At.batchedUpdates(vu))}function vu(){const n=ii;ii=At.now();const t=Su(ii);if(t&&(xu(Yi.splice(0,t),e=>e.handler()),si-=t),!si){wC();return}cr.flush(),To.flush(n?Math.min(64,ii-n):16.667),vo.flush(),_o.flush(),xo.flush()}function Ys(){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,xu(t,i=>i(e)&&n.add(i)),si+=n.size,t=n)}}}function xu(n,t){n.forEach(e=>{try{t(e)}catch(i){At.catch(i)}})}var LC=Object.defineProperty,bC=(n,t)=>{for(var e in t)LC(n,e,{get:t[e],enumerable:!0})},ve={};bC(ve,{assign:()=>MC,colors:()=>ri,createStringInterpolator:()=>wo,skipAnimation:()=>Ru,to:()=>Du,willAdvance:()=>Lo});function Pa(){}var FC=(n,t,e)=>Object.defineProperty(n,t,{value:e,writable:!0,configurable:!0}),$={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($.arr(n)){if(!$.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 Tt=(n,t)=>n.forEach(t);function We(n,t,e){if($.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=>$.und(n)?[]:$.arr(n)?n:[n];function Ds(n,t){if(n.size){const e=Array.from(n);n.clear(),Tt(e,t)}}var Ss=(n,...t)=>Ds(n,e=>e(...t)),Ro=()=>typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),wo,Du,ri=null,Ru=!1,Lo=Pa,MC=n=>{n.to&&(Du=n.to),n.now&&(At.now=n.now),n.colors!==void 0&&(ri=n.colors),n.skipAnimation!=null&&(Ru=n.skipAnimation),n.createStringInterpolator&&(wo=n.createStringInterpolator),n.requestAnimationFrame&&At.use(n.requestAnimationFrame),n.batchedUpdates&&(At.batchedUpdates=n.batchedUpdates),n.willAdvance&&(Lo=n.willAdvance),n.frameLoop&&(At.frameLoop=n.frameLoop)},Rs=new Set,de=[],Lr=[],Hn=0,hr={get idle(){return!Rs.size&&!de.length},start(n){Hn>n.priority?(Rs.add(n),At.onStart(PC)):(wu(n),At(ka))},advance:ka,sort(n){if(Hn)At.onFrame(()=>hr.sort(n));else{const t=de.indexOf(n);~t&&(de.splice(t,1),Lu(n))}},clear(){de=[],Rs.clear()}};function PC(){Rs.forEach(wu),Rs.clear(),At(ka)}function wu(n){de.includes(n)||Lu(n)}function Lu(n){de.splice(kC(de,t=>t.priority>n.priority),0,n)}function ka(n){const t=Lr;for(let e=0;e<de.length;e++){const i=de[e];Hn=i.priority,i.idle||(Lo(i),i.advance(n),i.idle||t.push(i))}return Hn=0,Lr=de,Lr.length=0,de=t,de.length>0}function kC(n,t){const e=n.findIndex(t);return e<0?n.length:e}var QC=(n,t,e)=>Math.min(Math.max(e,n),t),OC={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},Te="[-+]?\\d*\\.?\\d+",Kn=Te+"%";function ur(...n){return"\\(\\s*("+n.join(")\\s*,\\s*(")+")\\s*\\)"}var GC=new RegExp("rgb"+ur(Te,Te,Te)),UC=new RegExp("rgba"+ur(Te,Te,Te,Te)),NC=new RegExp("hsl"+ur(Te,Kn,Kn)),HC=new RegExp("hsla"+ur(Te,Kn,Kn,Te)),KC=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,YC=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,VC=/^#([0-9a-fA-F]{6})$/,JC=/^#([0-9a-fA-F]{8})$/;function zC(n){let t;return typeof n=="number"?n>>>0===n&&n>=0&&n<=4294967295?n:null:(t=VC.exec(n))?parseInt(t[1]+"ff",16)>>>0:ri&&ri[n]!==void 0?ri[n]:(t=GC.exec(n))?(_i(t[1])<<24|_i(t[2])<<16|_i(t[3])<<8|255)>>>0:(t=UC.exec(n))?(_i(t[1])<<24|_i(t[2])<<16|_i(t[3])<<8|ic(t[4]))>>>0:(t=KC.exec(n))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+"ff",16)>>>0:(t=JC.exec(n))?parseInt(t[1],16)>>>0:(t=YC.exec(n))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+t[4]+t[4],16)>>>0:(t=NC.exec(n))?(tc(ec(t[1]),tn(t[2]),tn(t[3]))|255)>>>0:(t=HC.exec(n))?(tc(ec(t[1]),tn(t[2]),tn(t[3]))|ic(t[4]))>>>0:null}function br(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=br(s,i,n+1/3),a=br(s,i,n),o=br(s,i,n-1/3);return Math.round(r*255)<<24|Math.round(a*255)<<16|Math.round(o*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 tn(n){const t=parseFloat(n);return t<0?0:t>100?1:t/100}function sc(n){let t=zC(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 Fs=(n,t,e)=>{if($.fun(n))return n;if($.arr(n))return Fs({range:n,output:t,extrapolate:e});if($.str(n.output[0]))return wo(n);const i=n,s=i.output,r=i.range||[0,1],a=i.extrapolateLeft||i.extrapolate||"extend",o=i.extrapolateRight||i.extrapolate||"extend",l=i.easing||(c=>c);return c=>{const h=qC(c,r);return $C(c,r[h],r[h+1],s[h],s[h+1],l,a,o,i.map)}};function $C(n,t,e,i,s,r,a,o,l){let c=l?l(n):n;if(c<t){if(a==="identity")return c;a==="clamp"&&(c=t)}if(c>e){if(o==="identity")return c;o==="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 qC(n,t){for(var e=1;e<t.length-1&&!(t[e]>=n);++e);return e-1}var XC=(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 QC(0,1,s/n)},Yn=1.70158,en=Yn*1.525,nc=Yn+1,rc=2*Math.PI/3,ac=2*Math.PI/4.5,sn=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,WC={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)*((en+1)*2*n-en)/2:(Math.pow(2*n-2,2)*((en+1)*(n*2-2)+en)+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)*ac))/2:Math.pow(2,-20*n+10)*Math.sin((20*n-11.125)*ac)/2+1,easeInBounce:n=>1-sn(1-n),easeOutBounce:sn,easeInOutBounce:n=>n<.5?(1-sn(1-2*n))/2:(1+sn(2*n-1))/2,steps:XC},Ms=Symbol.for("FluidValue.get"),$i=Symbol.for("FluidValue.observers"),Me=n=>!!(n&&n[Ms]),ue=n=>n&&n[Ms]?n[Ms]():n,oc=n=>n[$i]||null;function jC(n,t){n.eventObserved?n.eventObserved(t):n(t)}function Vn(n,t){const e=n[$i];e&&e.forEach(i=>{jC(i,t)})}var ZC=class{constructor(n){if(!n&&!(n=this.get))throw Error("Unknown getter");tI(this,n)}},tI=(n,t)=>bu(n,Ms,t);function Vs(n,t){if(n[Ms]){let e=n[$i];e||bu(n,$i,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[$i];if(e&&e.has(t)){const i=e.size-1;i?e.delete(t):n[$i]=null,n.observerRemoved&&n.observerRemoved(i,t)}}var bu=(n,t,e)=>Object.defineProperty(n,t,{value:e,writable:!0,configurable:!0}),xn=/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,eI=/(#(?:[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"),iI=/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi,Ar=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/,Fu=n=>{const[t,e]=sI(n);if(!t||Ro())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&&Ar.test(e))return Fu(e);if(e)return e}return n},sI=n=>{const t=Ar.exec(n);if(!t)return[,];const[,e,i]=t;return[e,i]},Fr,nI=(n,t,e,i,s)=>`rgba(${Math.round(t)}, ${Math.round(e)}, ${Math.round(i)}, ${s})`,Mu=n=>{Fr||(Fr=ri?new RegExp(`(${Object.keys(ri).join("|")})(?!\\w)`,"g"):/^\b$/);const t=n.output.map(r=>ue(r).replace(Ar,Fu).replace(eI,sc).replace(Fr,sc)),e=t.map(r=>r.match(xn).map(Number)),s=e[0].map((r,a)=>e.map(o=>{if(!(a in o))throw Error('The arity of each "output" value must be equal');return o[a]})).map(r=>Fs({...n,output:r}));return r=>{var l;const a=!lc.test(t[0])&&((l=t.find(c=>lc.test(c)))==null?void 0:l.replace(xn,""));let o=0;return t[0].replace(xn,()=>`${s[o++](r)}${a||""}`).replace(iI,nI)}},bo="react-spring: ",Pu=n=>{const t=n;let e=!1;if(typeof t!="function")throw new TypeError(`${bo}once requires a function parameter`);return(...i)=>{e||(t(...i),e=!0)}},rI=Pu(console.warn);function aI(){rI(`${bo}The "interpolate" function is deprecated in v9 (use "to" instead)`)}var oI=Pu(console.warn);function lI(){oI(`${bo}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 $.str(n)&&(n[0]=="#"||/\d/.test(n)||!Ro()&&Ar.test(n)||n in(ri||{}))}var Fo=Ro()?B.useEffect:B.useLayoutEffect,cI=()=>{const n=B.useRef(!1);return Fo(()=>(n.current=!0,()=>{n.current=!1}),[]),n};function ku(){const n=B.useState()[1],t=cI();return()=>{t.current&&n(Math.random())}}function hI(n,t){const[e]=B.useState(()=>({inputs:t,result:n()})),i=B.useRef(),s=i.current;let r=s;return r?r.inputs&&uI(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 uI(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 Qu=n=>B.useEffect(n,AI),AI=[];function cc(n){const t=B.useRef();return B.useEffect(()=>{t.current=n}),t.current}var Ps=Symbol.for("Animated:node"),dI=n=>!!n&&n[Ps]===n,be=n=>n&&n[Ps],Mo=(n,t)=>FC(n,Ps,t),fr=n=>n&&n[Ps]&&n[Ps].getPayload(),Ou=class{constructor(){Mo(this,this)}getPayload(){return this.payload||[]}},Js=class extends Ou{constructor(n){super(),this._value=n,this.done=!0,this.durationProgress=0,$.num(this._value)&&(this.lastPosition=this._value)}static create(n){return new Js(n)}getPayload(){return[this]}getValue(){return this._value}setValue(n,t){return $.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,$.num(this._value)&&(this.elapsedTime=0,this.durationProgress=0,this.lastPosition=this._value,n&&(this.lastVelocity=null),this.v0=null)}},ks=class extends Js{constructor(n){super(0),this._string=null,this._toString=Fs({output:[n,n]})}static create(n){return new ks(n)}getValue(){const n=this._string;return n??(this._string=this._toString(this._value))}setValue(n){if($.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=Fs({output:[this.getValue(),n]})),this._value=0,super.reset()}},zn={dependencies:null},Po=class extends Ou{constructor(n){super(),this.source=n,this.setValue(n)}getValue(n){const t={};return We(this.source,(e,i)=>{dI(e)?t[i]=e.getValue(n):Me(e)?t[i]=ue(e):n||(t[i]=e)}),t}setValue(n){this.source=n,this.payload=this._makePayload(n)}reset(){this.payload&&Tt(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&&Tt(t,e=>this.add(e))}},Gu=class extends Po{constructor(n){super(n)}static create(n){return new Gu(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(fI)),!0)}};function fI(n){return(dr(n)?ks:Js).create(n)}function Qa(n){const t=be(n);return t?t.constructor:$.arr(n)?Gu:dr(n)?ks:Js}var hc=(n,t)=>{const e=!$.fun(n)||n.prototype&&n.prototype.isReactComponent;return B.forwardRef((i,s)=>{const r=B.useRef(null),a=e&&B.useCallback(f=>{r.current=pI(s,f)},[s]),[o,l]=mI(i,t),c=ku(),h=()=>{const f=r.current;if(e&&!f)return;(f?t.applyAnimatedValues(f,o.getValue(!0)):!1)===!1&&c()},u=new gI(h,l),A=B.useRef();Fo(()=>(A.current=u,Tt(l,f=>Vs(f,u)),()=>{A.current&&(Tt(A.current.deps,f=>Jn(f,A.current)),At.cancel(A.current.update))})),B.useEffect(h,[]),Qu(()=>()=>{const f=A.current;Tt(f.deps,g=>Jn(g,f))});const d=t.getComponentProps(o.getValue());return B.createElement(n,{...d,ref:a})})},gI=class{constructor(n,t){this.update=n,this.deps=t}eventObserved(n){n.type=="change"&&At.write(this.update)}};function mI(n,t){const e=new Set;return zn.dependencies=e,n.style&&(n={...n,style:t.createAnimatedStyle(n.style)}),n=new Po(n),zn.dependencies=null,[n,e]}function pI(n,t){return n&&($.fun(n)?n(t):n.current=t),t}var uc=Symbol.for("AnimatedComponent"),EI=(n,{applyAnimatedValues:t=()=>!1,createAnimatedStyle:e=s=>new Po(s),getComponentProps:i=s=>s}={})=>{const s={applyAnimatedValues:t,createAnimatedStyle:e,getComponentProps:i},r=a=>{const o=Ac(a)||"Anonymous";return $.str(a)?a=r[a]||(r[a]=hc(a,s)):a=a[uc]||(a[uc]=hc(a,s)),a.displayName=`Animated(${o})`,a};return We(n,(a,o)=>{$.arr(n)&&(o=Ac(a)),r[o]=r(a)}),{animated:r}},Ac=n=>$.str(n)?n:n&&$.str(n.displayName)?n.displayName:$.fun(n)&&n.name||null;function pi(n,...t){return $.fun(n)?n(...t):n}var ws=(n,t)=>n===!0||!!(t&&n&&($.fun(n)?n(t):fe(n).includes(t))),Uu=(n,t)=>$.obj(n)?t&&n[t]:n,Nu=(n,t)=>n.default===!0?n[t]:n.default?n.default[t]:void 0,CI=n=>n,ko=(n,t=CI)=>{let e=II;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);$.und(r)||(i[s]=r)}return i},II=["config","onProps","onStart","onChange","onPause","onResume","onRest"],yI={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 BI(n){const t={};let e=0;if(We(n,(i,s)=>{yI[s]||(t[s]=i,e++)}),e)return t}function Hu(n){const t=BI(n);if(t){const e={to:t};return We(n,(i,s)=>s in t||(e[s]=i)),e}return{...n}}function Qs(n){return n=ue(n),$.arr(n)?n.map(Qs):dr(n)?ve.createStringInterpolator({range:[0,1],output:[n,n]})(1):n}function SI(n){for(const t in n)return!0;return!1}function Oa(n){return $.fun(n)||$.arr(n)&&$.obj(n[0])}function TI(n,t){var e;(e=n.ref)==null||e.delete(n),t==null||t.delete(n)}function _I(n,t){var e;t&&n.ref!==t&&((e=n.ref)==null||e.delete(n),t.add(n),n.ref=t)}var vI={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}},Ga={...vI.default,mass:1,damping:1,easing:WC.linear,clamp:!1},xI=class{constructor(){this.velocity=0,Object.assign(this,Ga)}};function DI(n,t,e){e&&(e={...e},dc(e,t),t={...e,...t}),dc(n,t),Object.assign(n,t);for(const a in Ga)n[a]==null&&(n[a]=Ga[a]);let{frequency:i,damping:s}=n;const{mass:r}=n;return $.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(!$.und(t.decay))n.duration=void 0;else{const e=!$.und(t.tension)||!$.und(t.friction);(e||!$.und(t.frequency)||!$.und(t.damping)||!$.und(t.mass))&&(n.duration=void 0,n.decay=void 0),e&&(n.frequency=void 0)}}var fc=[],RI=class{constructor(){this.changed=!1,this.values=fc,this.toValues=null,this.fromValues=fc,this.config=new xI,this.immediate=!1}};function Ku(n,{key:t,props:e,defaultProps:i,state:s,actions:r}){return new Promise((a,o)=>{let l,c,h=ws(e.cancel??(i==null?void 0:i.cancel),t);if(h)d();else{$.und(e.pause)||(s.paused=ws(e.pause,t));let f=i==null?void 0:i.pause;f!==!0&&(f=s.paused||ws(f,t)),l=pi(e.delay||0,t),f?(s.resumeQueue.add(A),r.pause()):(r.resume(),A())}function u(){s.resumeQueue.add(A),s.timeouts.delete(c),c.cancel(),l=c.time-At.now()}function A(){l>0&&!ve.skipAnimation?(s.delayed=!0,c=At.setTimeout(d,l),s.pauseQueue.add(u),s.timeouts.add(c)):d()}function d(){s.delayed&&(s.delayed=!1),s.pauseQueue.delete(u),s.timeouts.delete(c),n<=(s.cancelId||0)&&(h=!0);try{r.start({...e,callId:n,cancel:h},a)}catch(f){o(f)}}})}var Qo=(n,t)=>t.length==1?t[0]:t.some(e=>e.cancelled)?Vi(n.get()):t.every(e=>e.noop)?Yu(n.get()):Be(n.get(),t.every(e=>e.finished)),Yu=n=>({value:n,noop:!0,finished:!0,cancelled:!1}),Be=(n,t,e=!1)=>({value:n,finished:t,cancelled:e}),Vi=n=>({value:n,cancelled:!0,finished:!1});function Vu(n,t,e,i){const{callId:s,parentId:r,onRest:a}=t,{asyncTo:o,promise:l}=e;return!r&&n===o&&!t.reset?l:e.promise=(async()=>{e.asyncId=s,e.asyncTo=n;const c=ko(t,(p,m)=>m==="onRest"?void 0:p);let h,u;const A=new Promise((p,m)=>(h=p,u=m)),d=p=>{const m=s<=(e.cancelId||0)&&Vi(i)||s!==e.asyncId&&Be(i,!1);if(m)throw p.result=m,u(p),p},f=(p,m)=>{const C=new gc,E=new mc;return(async()=>{if(ve.skipAnimation)throw Os(e),E.result=Be(i,!1),u(E),E;d(C);const S=$.obj(p)?{...p}:{...m,to:p};S.parentId=s,We(c,(_,T)=>{$.und(S[T])&&(S[T]=_)});const y=await i.start(S);return d(C),e.paused&&await new Promise(_=>{e.resumeQueue.add(_)}),y})()};let g;if(ve.skipAnimation)return Os(e),Be(i,!1);try{let p;$.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),A]),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?o:void 0,e.promise=r?l:void 0)}return $.fun(a)&&At.batchedUpdates(()=>{a(g,i,i.item)}),g})()}function Os(n,t){Ds(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")}},Ua=n=>n instanceof Oo,wI=1,Oo=class extends ZC{constructor(){super(...arguments),this.id=wI++,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 ve.to(this,n)}interpolate(...n){return aI(),ve.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"),Ju=1,zu=2,$u=4,Mr=n=>(n[yi]&Ju)>0,je=n=>(n[yi]&zu)>0,hs=n=>(n[yi]&$u)>0,pc=(n,t)=>t?n[yi]|=zu|Ju:n[yi]&=-3,Ec=(n,t)=>t?n[yi]|=$u:n[yi]&=-5,LI=class extends Oo{constructor(n,t){if(super(),this.animation=new RI,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,!$.und(n)||!$.und(t)){const e=$.obj(n)?{...n}:{...t,from:n};$.und(e.default)&&(e.default=!0),this.start(e)}}get idle(){return!(je(this)||this._state.asyncTo)||hs(this)}get goal(){return ue(this.animation.to)}get velocity(){const n=be(this);return n instanceof Js?n.lastVelocity||0:n.getPayload().map(t=>t.lastVelocity||0)}get hasAnimated(){return Mr(this)}get isAnimating(){return je(this)}get isPaused(){return hs(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,a=fr(i.to);!a&&Me(i.to)&&(s=fe(ue(i.to))),i.values.forEach((c,h)=>{if(c.done)return;const u=c.constructor==ks?1:a?a[h].lastPosition:s[h];let A=i.immediate,d=u;if(!A){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=$.arr(r.velocity)?r.velocity[h]:r.velocity;let m;const C=r.precision||(g==u?.005:Math.min(1,Math.abs(u-g)*.001));if($.und(r.duration))if(r.decay){const E=r.decay===!0?.998:r.decay,S=Math.exp(-(1-E)*f);d=g+p/(1-E)*(1-S),A=Math.abs(c.lastPosition-d)<=C,m=p*S}else{m=c.lastVelocity==null?p:c.lastVelocity;const E=r.restVelocity||C/10,S=r.clamp?0:r.bounce,y=!$.und(S),_=g==u?c.v0>0:g<u;let T,v=!1;const F=1,x=Math.ceil(n/F);for(let w=0;w<x&&(T=Math.abs(m)>E,!(!T&&(A=Math.abs(u-d)<=C,A)));++w){y&&(v=d==u||d>u==_,v&&(m=-m*S,d=u));const U=-r.tension*1e-6*(d-u),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)*(u-g),m=(d-c.lastPosition)/n,A=E==1}c.lastVelocity=m,Number.isNaN(d)&&(console.warn("Got NaN while animating:",this),A=!0)}a&&!a[h].done&&(A=!1),A?c.done=!0:t=!1,c.setValue(d,r.round)&&(e=!0)});const o=be(this),l=o.getValue();if(t){const c=ue(i.to);(l!==c||e)&&!r.decay?(o.setValue(c),this._onChange(c)):e&&r.decay&&this._onChange(l),this._stop()}else e&&this._onChange(l)}set(n){return At.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;At.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 $.und(n)?(e=this.queue||[],this.queue=[]):e=[$.obj(n)?n:{...t,to:n}],Promise.all(e.map(i=>this._update(i))).then(i=>Qo(this,i))}stop(n){const{to:t}=this.animation;return this._focus(this.get()),Os(this._state,n&&this._lastCallId),At.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=$.obj(e)?e[t]:e,(e==null||Oa(e))&&(e=void 0),i=$.obj(i)?i[t]:i,i==null&&(i=void 0);const s={to:e,from:i};return Mr(this)||(n.reverse&&([e,i]=[i,e]),i=ue(i),$.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,ko(n,(a,o)=>/^on/.test(o)?Uu(a,e):a)),Ic(this,n,"onProps"),As(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 Ku(++this._lastCallId,{key:e,props:n,defaultProps:i,state:r,actions:{pause:()=>{hs(this)||(Ec(this,!0),Ss(r.pauseQueue),As(this,"onPause",Be(this,us(this,this.animation.to)),this))},resume:()=>{hs(this)&&(Ec(this,!1),je(this)&&this._resume(),Ss(r.resumeQueue),As(this,"onResume",Be(this,us(this,this.animation.to)),this))},start:this._merge.bind(this,s)}}).then(a=>{if(n.loop&&a.finished&&!(t&&a.noop)){const o=qu(n);if(o)return this._update(o,!0)}return a})}_merge(n,t,e){if(t.cancel)return this.stop(!0),e(Vi(this));const i=!$.und(n.to),s=!$.und(n.from);if(i||s)if(t.callId>this._lastToId)this._lastToId=t.callId;else return e(Vi(this));const{key:r,defaultProps:a,animation:o}=this,{to:l,from:c}=o;let{to:h=l,from:u=c}=n;s&&!i&&(!t.default||$.und(h))&&(h=u),t.reverse&&([h,u]=[u,h]);const A=!Ve(u,c);A&&(o.from=u),u=ue(u);const d=!Ve(h,l);d&&this._focus(h);const f=Oa(t.to),{config:g}=o,{decay:p,velocity:m}=g;(i||s)&&(g.velocity=0),t.config&&!f&&DI(g,pi(t.config,r),t.config!==a.config?pi(a.config,r):void 0);let C=be(this);if(!C||$.und(h))return e(Be(this,!0));const E=$.und(t.reset)?s&&!t.default:!$.und(u)&&ws(t.reset,r),S=E?u:this.get(),y=Qs(h),_=$.num(y)||$.arr(y)||dr(y),T=!f&&(!_||ws(a.immediate||t.immediate,r));if(d){const w=Qa(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 v=C.constructor;let F=Me(h),x=!1;if(!F){const w=E||!Mr(this)&&A;(d||w)&&(x=Ve(Qs(S),y),F=!x),(!Ve(o.immediate,T)&&!T||!Ve(g.decay,p)||!Ve(g.velocity,m))&&(F=!0)}if(x&&je(this)&&(o.changed&&!E?F=!0:F||this._stop(l)),!f&&((F||Me(l))&&(o.values=C.getPayload(),o.toValues=Me(h)?null:v==ks?[1]:fe(y)),o.immediate!=T&&(o.immediate=T,!T&&!E&&this._set(l)),F)){const{onRest:w}=o;Tt(FI,O=>Ic(this,t,O));const U=Be(this,us(this,l));Ss(this._pendingCalls,U),this._pendingCalls.add(e),o.changed&&At.batchedUpdates(()=>{var O;o.changed=!E,w==null||w(U,this),E?pi(a.onRest,U):(O=o.onStart)==null||O.call(o,U,this)})}E&&this._set(S),f?e(Vu(t.to,t,this._state,this)):F?this._start():je(this)&&!d?this._pendingCalls.add(e):e(Yu(S))}_focus(n){const t=this.animation;n!==t.to&&(oc(this)&&this._detach(),t.to=n,oc(this)&&this._attach())}_attach(){let n=0;const{to:t}=this.animation;Me(t)&&(Vs(t,this),Ua(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=ue(n);if(!$.und(e)){const i=be(this);if(!i||!Ve(e,i.getValue())){const s=Qa(e);!i||i.constructor!=s?Mo(this,s.create(e)):i.setValue(e),i&&At.batchedUpdates(()=>{this._onChange(e,t)})}}return be(this)}_onStart(){const n=this.animation;n.changed||(n.changed=!0,As(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(ue(n.to)),n.immediate||(n.fromValues=n.values.map(t=>t.lastPosition)),je(this)||(pc(this,!0),hs(this)||this._resume())}_resume(){ve.skipAnimation?this.finish():hr.start(this)}_stop(n,t){if(je(this)){pc(this,!1);const e=this.animation;Tt(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?Vi(this.get()):Be(this.get(),us(this,n??e.to));Ss(this._pendingCalls,i),e.changed&&(e.changed=!1,As(this,"onRest",i,this))}}};function us(n,t){const e=Qs(t),i=Qs(n.get());return Ve(i,e)}function qu(n,t=n.loop,e=n.to){const i=pi(t);if(i){const s=i!==!0&&Hu(i),r=(s||n).reverse,a=!s||s.reset;return Gs({...n,loop:t,default:!1,pause:void 0,to:!r||Oa(e)?e:void 0,from:a?n.from:void 0,reset:a,...s})}}function Gs(n){const{to:t,from:e}=n=Hu(n),i=new Set;return $.obj(t)&&Cc(t,i),$.obj(e)&&Cc(e,i),n.keys=i.size?Array.from(i):null,n}function bI(n){const t=Gs(n);return $.und(t.default)&&(t.default=ko(t)),t}function Cc(n,t){We(n,(e,i)=>e!=null&&t.add(i))}var FI=["onStart","onRest","onChange","onPause","onResume"];function Ic(n,t,e){n.animation[e]=t[e]!==Nu(t,e)?Uu(t[e],n.key):void 0}function As(n,t,...e){var i,s,r,a;(s=(i=n.animation)[t])==null||s.call(i,...e),(a=(r=n.defaultProps)[t])==null||a.call(r,...e)}var MI=["onStart","onChange","onRest"],PI=1,kI=class{constructor(n,t){this.id=PI++,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];$.und(e)||this.springs[t].set(e)}}update(n){return n&&this.queue.push(Gs(n)),this}start(n){let{queue:t}=this;return n?t=fe(n).map(Gs):this.queue=[],this._flush?this._flush(this,t):(tA(this,t),Na(this,t))}stop(n,t){if(n!==!!n&&(t=n),t){const e=this.springs;Tt(fe(t),i=>e[i].stop(!!n))}else Os(this._state,this._lastAsyncId),this.each(e=>e.stop(!!n));return this}pause(n){if($.und(n))this.start({pause:!0});else{const t=this.springs;Tt(fe(n),e=>t[e].pause())}return this}resume(n){if($.und(n))this.start({pause:!1});else{const t=this.springs;Tt(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,Ds(n,([o,l])=>{l.value=this.get(),o(l,this,this._item)}));const r=!i&&this._started,a=s||r&&e.size?this.get():null;s&&t.size&&Ds(t,([o,l])=>{l.value=a,o(l,this,this._item)}),r&&(this._started=!1,Ds(e,([o,l])=>{l.value=a,o(l,this,this._item)}))}eventObserved(n){if(n.type=="change")this._changed.add(n.parent),n.idle||this._active.add(n.parent);else if(n.type=="idle")this._active.delete(n.parent);else return;At.onFrame(this._onFrame)}};function Na(n,t){return Promise.all(t.map(e=>Xu(n,e))).then(e=>Qo(n,e))}async function Xu(n,t,e){const{keys:i,to:s,from:r,loop:a,onRest:o,onResolve:l}=t,c=$.obj(t.default)&&t.default;a&&(t.loop=!1),s===!1&&(t.to=null),r===!1&&(t.from=null);const h=$.arr(s)||$.fun(s)?s:void 0;h?(t.to=void 0,t.onRest=void 0,c&&(c.onRest=void 0)):Tt(MI,g=>{const p=t[g];if($.fun(p)){const m=n._events[g];t[g]=({finished:C,cancelled:E})=>{const S=m.get(p);S?(C||(S.finished=!1),E&&(S.cancelled=!0)):m.set(p,{value:null,finished:C||!1,cancelled:E||!1})},c&&(c[g]=t[g])}});const u=n._state;t.pause===!u.paused?(u.paused=t.pause,Ss(t.pause?u.pauseQueue:u.resumeQueue)):u.paused&&(t.pause=!0);const A=(i||Object.keys(n.springs)).map(g=>n.springs[g].start(t)),d=t.cancel===!0||Nu(t,"cancel")===!0;(h||d&&u.asyncId)&&A.push(Ku(++n._lastAsyncId,{props:t,state:u,actions:{pause:Pa,resume:Pa,start(g,p){d?(Os(u,n._lastAsyncId),p(Vi(n))):(g.onRest=o,p(Vu(h,g,u,n)))}}})),u.paused&&await new Promise(g=>{u.resumeQueue.add(g)});const f=Qo(n,await Promise.all(A));if(a&&f.finished&&!(e&&f.noop)){const g=qu(t,a,s);if(g)return tA(n,[g]),Xu(n,g,!0)}return l&&At.batchedUpdates(()=>l(f,n,n.item)),f}function yc(n,t){const e={...n.springs};return t&&Tt(fe(t),i=>{$.und(i.keys)&&(i=Gs(i)),$.obj(i.to)||(i={...i,to:void 0}),Zu(e,i,s=>ju(s))}),Wu(n,e),e}function Wu(n,t){We(t,(e,i)=>{n.springs[i]||(n.springs[i]=e,Vs(e,n))})}function ju(n,t){const e=new LI;return e.key=n,t&&Vs(e,t),e}function Zu(n,t,e){t.keys&&Tt(t.keys,i=>{(n[i]||(n[i]=e(i)))._prepareNode(t)})}function tA(n,t){Tt(t,e=>{Zu(n.springs,e,i=>ju(i,n))})}var gr=({children:n,...t})=>{const e=B.useContext($n),i=t.pause||!!e.pause,s=t.immediate||!!e.immediate;t=hI(()=>({pause:i,immediate:s}),[i,s]);const{Provider:r}=$n;return B.createElement(r,{value:t},n)},$n=QI(gr,{});gr.Provider=$n.Provider;gr.Consumer=$n.Consumer;function QI(n,t){return Object.assign(n,B.createContext(t)),n.Provider._context=n,n.Consumer._context=n,n}var OI=()=>{const n=[],t=function(i){lI();const s=[];return Tt(n,(r,a)=>{if($.und(i))s.push(r.start());else{const o=e(i,r,a);o&&s.push(r.start(o))}}),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 Tt(n,i=>i.pause(...arguments)),this},t.resume=function(){return Tt(n,i=>i.resume(...arguments)),this},t.set=function(i){Tt(n,(s,r)=>{const a=$.fun(i)?i(r,s):i;a&&s.set(a)})},t.start=function(i){const s=[];return Tt(n,(r,a)=>{if($.und(i))s.push(r.start());else{const o=this._getProps(i,r,a);o&&s.push(r.start(o))}}),s},t.stop=function(){return Tt(n,i=>i.stop(...arguments)),this},t.update=function(i){return Tt(n,(s,r)=>s.update(this._getProps(i,s,r))),this};const e=function(i,s,r){return $.fun(i)?i(r,s):i};return t._getProps=e,t};function GI(n,t,e){const i=$.fun(t)&&t;i&&!e&&(e=[]);const s=B.useMemo(()=>i||arguments.length==3?OI():void 0,[]),r=B.useRef(0),a=ku(),o=B.useMemo(()=>({ctrls:[],queue:[],flush(m,C){const E=yc(m,C);return r.current>0&&!o.queue.length&&!Object.keys(E).some(y=>!m.springs[y])?Na(m,C):new Promise(y=>{Wu(m,E),o.queue.push(()=>{y(Na(m,C))}),a()})}}),[]),l=B.useRef([...o.ctrls]),c=[],h=cc(n)||0;B.useMemo(()=>{Tt(l.current.slice(n,h),m=>{TI(m,s),m.stop(!0)}),l.current.length=n,u(h,n)},[n]),B.useMemo(()=>{u(0,Math.min(h,n))},e);function u(m,C){for(let E=m;E<C;E++){const S=l.current[E]||(l.current[E]=new kI(null,o.flush)),y=i?i(E,S):t[E];y&&(c[E]=bI(y))}}const A=l.current.map((m,C)=>yc(m,c[C])),d=B.useContext(gr),f=cc(d),g=d!==f&&SI(d);Fo(()=>{r.current++,o.ctrls=l.current;const{queue:m}=o;m.length&&(o.queue=[],Tt(m,C=>C())),Tt(l.current,(C,E)=>{s==null||s.add(C),g&&C.start({default:d});const S=c[E];S&&(_I(C,S.ref),C.ref?C.queue.push(S):C.start(S))})}),Qu(()=>()=>{Tt(o.ctrls,m=>m.stop(!0))});const p=A.map(m=>({...m}));return s?[p,s]:p}function UI(n,t){const e=$.fun(n),[[i],s]=GI(1,e?n:[n],e?[]:t);return e||arguments.length==2?[i,s]:i}var NI=class extends Oo{constructor(n,t){super(),this.source=n,this.idle=!0,this._active=new Set,this.calc=Fs(...t);const e=this._get(),i=Qa(e);Mo(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)&&Pr(this)}_get(){const n=$.arr(this.source)?this.source.map(ue):fe(ue(this.source));return this.calc(...n)}_start(){this.idle&&!Bc(this._active)&&(this.idle=!1,Tt(fr(this),n=>{n.done=!1}),ve.skipAnimation?(At.batchedUpdates(()=>this.advance()),Pr(this)):hr.start(this))}_attach(){let n=1;Tt(fe(this.source),t=>{Me(t)&&Vs(t,this),Ua(t)&&(t.idle||this._active.add(t),n=Math.max(n,t.priority+1))}),this.priority=n,this._start()}_detach(){Tt(fe(this.source),n=>{Me(n)&&Jn(n,this)}),this._active.clear(),Pr(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,(Ua(e)?e.priority:0)+1),0))}};function HI(n){return n.idle!==!1}function Bc(n){return!n.size||Array.from(n).every(HI)}function Pr(n){n.idle||(n.idle=!0,Tt(fr(n),t=>{t.done=!0}),Vn(n,{type:"idle",parent:n}))}ve.assign({createStringInterpolator:Mu,to:(n,t)=>new NI(n,t)});var KI=["primitive"].concat(Object.keys(df).filter(n=>/^[A-Z]/.test(n)).map(n=>n[0].toLowerCase()+n.slice(1)));ve.assign({createStringInterpolator:Mu,colors:OC,frameLoop:"demand"});lo(()=>{At.advance()});var YI=EI(KI,{applyAnimatedValues:co}),VI=YI.animated;function JI({enabled:n=!0,snap:t,global:e,domElement:i,cursor:s=!0,children:r,speed:a=1,rotation:o=[0,0,0],zoom:l=1,polar:c=[0,Math.PI/2],azimuth:h=[-1/0,1/0],config:u={mass:1,tension:170,friction:26}}){const A=q(_=>_.events),d=q(_=>_.gl),f=i||A.connected||d.domElement,{size:g}=q(),p=B.useMemo(()=>[o[0]+c[0],o[0]+c[1]],[o[0],c[0],c[1]]),m=B.useMemo(()=>[o[1]+h[0],o[1]+h[1]],[o[1],h[0],h[1]]),C=B.useMemo(()=>[ct.clamp(o[0],...p),ct.clamp(o[1],...m),o[2]],[o[0],o[1],o[2],p,m]),[E,S]=UI(()=>({scale:1,rotation:C,config:u}));B.useEffect(()=>void S.start({scale:1,rotation:C,config:u}),[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=qh({onHover:({last:_})=>{s&&!e&&n&&(f.style.cursor=_?"auto":"grab")},onDrag:({down:_,delta:[T,v],memo:[F,x]=E.rotation.animation.to||C})=>{if(!n)return[v,T];s&&(f.style.cursor=_?"grabbing":"grab"),T=ct.clamp(x+T/g.width*Math.PI*a,...m),v=ct.clamp(F+v/g.height*Math.PI*a,...p);const w=t&&!_&&typeof t!="boolean"?t:u;return S.start({scale:_&&v>p[1]/2?l:1,rotation:t&&!_?C:[v,T,0],config:U=>U==="scale"?{...w,friction:w.friction*3}:w}),[v,T]}},{target:e?f:void 0});return B.createElement(VI.group,wt({},y==null?void 0:y(),E),r)}const zI=n=>(t,e,i)=>{const s=i.subscribe;return i.subscribe=(a,o,l)=>{let c=a;if(o){const h=(l==null?void 0:l.equalityFn)||Object.is;let u=a(i.getState());c=A=>{const d=a(A);if(!h(u,d)){const f=u;o(u=d,f)}},l!=null&&l.fireImmediately&&o(u,u)}return s(c)},n(t,e,i)},$I=zI,eA=B.createContext(null);function qI({map:n,children:t,onChange:e,domElement:i}){const s=n.map(l=>l.name+l.keys).join("-"),r=B.useMemo(()=>du($I(()=>n.reduce((l,c)=>({...l,[c.name]:!1}),{}))),[s]),a=B.useMemo(()=>[r.subscribe,r.getState,r],[s]),o=r.setState;return B.useEffect(()=>{const c=n.map(({name:d,keys:f,up:g})=>({keys:f,up:g,fn:p=>{o({[d]:p}),e&&e(d,p,a[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)},u=({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)},A=i||window;return A.addEventListener("keydown",h,{passive:!0}),A.addEventListener("keyup",u,{passive:!0}),()=>{A.removeEventListener("keydown",h),A.removeEventListener("keyup",u)}},[i,s]),B.createElement(eA.Provider,{value:a,children:t})}function XI(n){const[t,e,i]=B.useContext(eA);return n?i(n):[t,e]}var WI=Object.defineProperty,jI=(n,t,e)=>t in n?WI(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,ut=(n,t,e)=>(jI(n,typeof t!="symbol"?t+"":t,e),e);const Sc=new k;let ZI=class extends Zi{constructor(t,e){super(),ut(this,"object"),ut(this,"domElement"),ut(this,"enabled",!0),ut(this,"movementSpeed",1),ut(this,"lookSpeed",.005),ut(this,"lookVertical",!0),ut(this,"autoForward",!1),ut(this,"activeLook",!0),ut(this,"heightSpeed",!1),ut(this,"heightCoef",1),ut(this,"heightMin",0),ut(this,"heightMax",1),ut(this,"constrainVertical",!1),ut(this,"verticalMin",0),ut(this,"verticalMax",Math.PI),ut(this,"mouseDragOn",!1),ut(this,"autoSpeedFactor",0),ut(this,"mouseX",0),ut(this,"mouseY",0),ut(this,"moveForward",!1),ut(this,"moveBackward",!1),ut(this,"moveLeft",!1),ut(this,"moveRight",!1),ut(this,"moveUp",!1),ut(this,"moveDown",!1),ut(this,"viewHalfX",0),ut(this,"viewHalfY",0),ut(this,"lat",0),ut(this,"lon",0),ut(this,"lookDirection",new k),ut(this,"spherical",new oo),ut(this,"target",new k),ut(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()}),ut(this,"dispose",()=>{var i,s,r,a;(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),(a=this.domElement)==null||a.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}),ut(this,"handleResize",()=>{this.domElement&&(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}),ut(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}),ut(this,"onMouseUp",i=>{if(this.activeLook)switch(i.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}),ut(this,"onMouseMove",i=>{this.domElement&&(this.mouseX=i.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=i.pageY-this.domElement.offsetTop-this.viewHalfY)}),ut(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}}),ut(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}}),ut(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)),ut(this,"update",i=>{if(!this.enabled)return;if(this.heightSpeed){const u=ct.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=i*(u*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 a=1;this.constrainVertical&&(a=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.mouseX*r,this.lookVertical&&(this.lat-=this.mouseY*r*a),this.lat=Math.max(-85,Math.min(85,this.lat));let o=ct.degToRad(90-this.lat);const l=ct.degToRad(this.lon);this.constrainVertical&&(o=ct.mapLinear(o,0,Math.PI,this.verticalMin,this.verticalMax));const c=this.object.position;Sc.setFromSphericalCoords(1,o,l).add(c),this.object.lookAt(Sc)}),ut(this,"contextmenu",i=>i.preventDefault()),ut(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 ty=Object.defineProperty,ey=(n,t,e)=>t in n?ty(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,P=(n,t,e)=>(ey(n,typeof t!="symbol"?t+"":t,e),e);let iy=class extends jt{constructor(t,e){super(),P(this,"isTransformControls",!0),P(this,"visible",!1),P(this,"domElement"),P(this,"raycaster",new ar),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,a)=>{const o=r.intersectObject(s,!0);for(let l=0;l<o.length;l++)if(o[l].object.visible||a)return o[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 a=this.space;if(this.mode==="scale"?a="local":(this.axis==="E"||this.axis==="XYZE"||this.axis==="XYZ")&&(a="world"),a==="local"&&this.mode==="rotate"){const o=this.rotationSnap;this.axis==="X"&&o&&(this.object.rotation.x=Math.round(this.object.rotation.x/o)*o),this.axis==="Y"&&o&&(this.object.rotation.y=Math.round(this.object.rotation.y/o)*o),this.axis==="Z"&&o&&(this.object.rotation.z=Math.round(this.object.rotation.z/o)*o)}this.object.updateMatrixWorld(),this.object.parent&&this.object.parent.updateMatrixWorld(),this.positionStart.copy(this.object.position),this.quaternionStart.copy(this.object.quaternion),this.scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this.worldScaleStart),this.pointStart.copy(r.point).sub(this.worldPositionStart)}this.dragging=!0,this.mouseDownEvent.mode=this.mode,this.dispatchEvent(this.mouseDownEvent)}}),P(this,"pointerMove",s=>{const r=this.axis,a=this.mode,o=this.object;let l=this.space;if(a==="scale"?l="local":(r==="E"||r==="XYZE"||r==="XYZ")&&(l="world"),o===void 0||r===null||this.dragging===!1||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),a==="translate")this.offset.copy(this.pointEnd).sub(this.pointStart),l==="local"&&r!=="XYZ"&&this.offset.applyQuaternion(this.worldQuaternionInv),r.indexOf("X")===-1&&(this.offset.x=0),r.indexOf("Y")===-1&&(this.offset.y=0),r.indexOf("Z")===-1&&(this.offset.z=0),l==="local"&&r!=="XYZ"?this.offset.applyQuaternion(this.quaternionStart).divide(this.parentScale):this.offset.applyQuaternion(this.parentQuaternionInv).divide(this.parentScale),o.position.copy(this.offset).add(this.positionStart),this.translationSnap&&(l==="local"&&(o.position.applyQuaternion(this.tempQuaternion.copy(this.quaternionStart).invert()),r.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(o.position.z=Math.round(o.position.z/this.translationSnap)*this.translationSnap),o.position.applyQuaternion(this.quaternionStart)),l==="world"&&(o.parent&&o.position.add(this.tempVector.setFromMatrixPosition(o.parent.matrixWorld)),r.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),r.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),r.search("Z")!==-1&&(o.position.z=Math.round(o.position.z/this.translationSnap)*this.translationSnap),o.parent&&o.position.sub(this.tempVector.setFromMatrixPosition(o.parent.matrixWorld))));else if(a==="scale"){if(r.search("XYZ")!==-1){let h=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(h*=-1),this.tempVector2.set(h,h,h)}else this.tempVector.copy(this.pointStart),this.tempVector2.copy(this.pointEnd),this.tempVector.applyQuaternion(this.worldQuaternionInv),this.tempVector2.applyQuaternion(this.worldQuaternionInv),this.tempVector2.divide(this.tempVector),r.search("X")===-1&&(this.tempVector2.x=1),r.search("Y")===-1&&(this.tempVector2.y=1),r.search("Z")===-1&&(this.tempVector2.z=1);o.scale.copy(this.scaleStart).multiply(this.tempVector2),this.scaleSnap&&this.object&&(r.search("X")!==-1&&(this.object.scale.x=Math.round(o.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Y")!==-1&&(o.scale.y=Math.round(o.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),r.search("Z")!==-1&&(o.scale.z=Math.round(o.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(a==="rotate"){this.offset.copy(this.pointEnd).sub(this.pointStart);const h=20/this.worldPosition.distanceTo(this.tempVector.setFromMatrixPosition(this.camera.matrixWorld));r==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this.startNorm.copy(this.pointStart).normalize(),this.endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this.endNorm.cross(this.startNorm).dot(this.eye)<0?1:-1):r==="XYZE"?(this.rotationAxis.copy(this.offset).cross(this.eye).normalize(),this.rotationAngle=this.offset.dot(this.tempVector.copy(this.rotationAxis).cross(this.eye))*h):(r==="X"||r==="Y"||r==="Z")&&(this.rotationAxis.copy(this.unit[r]),this.tempVector.copy(this.unit[r]),l==="local"&&this.tempVector.applyQuaternion(this.worldQuaternion),this.rotationAngle=this.offset.dot(this.tempVector.cross(this.eye).normalize())*h),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),l==="local"&&r!=="E"&&r!=="XYZE"?(o.quaternion.copy(this.quaternionStart),o.quaternion.multiply(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this.parentQuaternionInv),o.quaternion.copy(this.tempQuaternion.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),o.quaternion.multiply(this.quaternionStart).normalize())}this.dispatchEvent(this.changeEvent),this.dispatchEvent(this.objectChangeEvent)}}),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 a=s.changedTouches?s.changedTouches[0]:s,o=this.domElement.getBoundingClientRect();return{x:(a.clientX-o.left)/o.width*2-1,y:-(a.clientY-o.top)/o.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,a,o,l,c;(s=this.domElement)==null||s.removeEventListener("pointerdown",this.onPointerDown),(r=this.domElement)==null||r.removeEventListener("pointermove",this.onPointerHover),(o=(a=this.domElement)==null?void 0:a.ownerDocument)==null||o.removeEventListener("pointermove",this.onPointerMove),(c=(l=this.domElement)==null?void 0:l.ownerDocument)==null||c.removeEventListener("pointerup",this.onPointerUp),this.traverse(h=>{const u=h;u.geometry&&u.geometry.dispose(),u.material&&u.material.dispose()})}),this.domElement=e,this.camera=t,this.gizmo=new sy,this.add(this.gizmo),this.plane=new ny,this.add(this.plane);const i=(s,r)=>{let a=r;Object.defineProperty(this,s,{get:function(){return a!==void 0?a:r},set:function(o){a!==o&&(a=o,this.plane[s]=o,this.gizmo[s]=o,this.dispatchEvent({type:s+"-changed",value:o}),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 sy 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 J=[];J=J.concat(this.picker[this.mode].children),J=J.concat(this.gizmo[this.mode].children),J=J.concat(this.helper[this.mode].children);for(let K=0;K<J.length;K++){const D=J[K];D.visible=!0,D.rotation.set(0,0,0),D.position.copy(this.worldPosition);let et;if(this.camera.isOrthographicCamera?et=(this.camera.top-this.camera.bottom)/this.camera.zoom:et=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(et*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(ot){return D.name===ot})?(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 ho({depthTest:!1,depthWrite:!1,transparent:!0,side:Hs,fog:!1,toneMapped:!1}),e=new _s({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 a=t.clone();a.color.set(65280);const o=t.clone();o.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 u=l.clone();u.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 S=C.clone();S.opacity=.25;const y=new me(0,.05,.2,12,1,!1),_=new li(.125,.125,.125),T=new Se;T.setAttribute("position",new $e([0,0,0,1,0,0],3));const v=(G,H)=>{const J=new Se,K=[];for(let D=0;D<=64*H;++D)K.push(0,Math.cos(D/32*Math.PI)*G,Math.sin(D/32*Math.PI)*G);return J.setAttribute("position",new $e(K,3)),J},F=()=>{const G=new Se;return G.setAttribute("position",new $e([0,0,0,1,1,1],3)),G},x={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,a),[0,1,0],null,null,"fwd"],[new nt(y,a),[0,1,0],[Math.PI,0,0],null,"bwd"],[new Et(T,f),null,[0,0,Math.PI/2]]],Z:[[new nt(y,o),[0,0,1],[Math.PI/2,0,0],null,"fwd"],[new nt(y,o),[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),u.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(v(1,.5),d)],[new nt(new ci(.04,0),r),[0,0,.99],null,[1,3,1]]],Y:[[new Et(v(1,.5),f),null,[0,0,-Math.PI/2]],[new nt(new ci(.04,0),a),[0,0,.99],null,[3,1,1]]],Z:[[new Et(v(1,.5),g),null,[0,Math.PI/2,0]],[new nt(new ci(.04,0),o),[.99,0,0],null,[1,3,1]]],E:[[new Et(v(1.25,1),S),null,[0,Math.PI/2,0]],[new nt(new me(.03,0,.15,4,1,!1),S),[1.17,0,0],[0,0,-Math.PI/2],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),S),[-1.17,0,0],[0,0,Math.PI/2],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),S),[0,-1.17,0],[Math.PI,0,0],[1,1,.001]],[new nt(new me(.03,0,.15,4,1,!1),S),[0,1.17,0],[0,0,0],[1,1,.001]]],XYZE:[[new Et(v(1,1),E),null,[0,Math.PI/2,0]]]},W={AXIS:[[new Et(T,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},Y={X:[[new nt(new Xs(1,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new nt(new Xs(1,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new nt(new Xs(1,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new nt(new Xs(1.25,.1,2,24),i)]],XYZE:[[new nt(new Wh(.7,10,8),i)]]},X={X:[[new nt(_,r),[.8,0,0],[0,0,-Math.PI/2]],[new Et(T,d),null,null,[.8,1,1]]],Y:[[new nt(_,a),[0,.8,0]],[new Et(T,f),null,[0,0,Math.PI/2],[.8,1,1]]],Z:[[new nt(_,o),[0,0,.8],[Math.PI/2,0,0]],[new Et(T,g),null,[0,-Math.PI/2,0],[.8,1,1]]],XY:[[new nt(_,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(_,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(_,u),[.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(_,i),[.85,.85,0],null,[3,3,.2]]],YZ:[[new nt(_,i),[0,.85,.85],null,[.2,3,3]]],XZ:[[new nt(_,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]]]},at={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 J in G)for(let K=G[J].length;K--;){const D=G[J][K][0].clone(),et=G[J][K][1],ot=G[J][K][2],ht=G[J][K][3],Vt=G[J][K][4];D.name=J,D.tag=Vt,et&&D.position.set(et[0],et[1],et[2]),ot&&D.rotation.set(ot[0],ot[1],ot[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(x)),this.add(this.gizmo.rotate=V(O)),this.add(this.gizmo.scale=V(X)),this.add(this.picker.translate=V(w)),this.add(this.picker.rotate=V(Y)),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(at)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}}class ny extends nt{constructor(){super(new gi(1e5,1e5,2,2),new ho({visible:!1,wireframe:!0,side:Hs,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 ry=Object.defineProperty,ay=(n,t,e)=>t in n?ry(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,Gt=(n,t,e)=>(ay(n,typeof t!="symbol"?t+"":t,e),e);const vi=new qe(0,0,0,"YXZ"),xi=new k,oy={type:"change"},ly={type:"lock"},cy={type:"unlock"},Tc=Math.PI/2;let hy=class extends Zi{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||(vi.setFromQuaternion(this.camera.quaternion),vi.y-=i.movementX*.002*this.pointerSpeed,vi.x-=i.movementY*.002*this.pointerSpeed,vi.x=Math.max(Tc-this.maxPolarAngle,Math.min(Tc-this.minPolarAngle,vi.x)),this.camera.quaternion.setFromEuler(vi),this.dispatchEvent(oy))}),Gt(this,"onPointerlockChange",()=>{this.domElement&&(this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(ly),this.isLocked=!0):(this.dispatchEvent(cy),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=>{xi.setFromMatrixColumn(this.camera.matrix,0),xi.crossVectors(this.camera.up,xi),this.camera.position.addScaledVector(xi,i)}),Gt(this,"moveRight",i=>{xi.setFromMatrixColumn(this.camera.matrix,0),this.camera.position.addScaledVector(xi,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 uy=Object.defineProperty,Ay=(n,t,e)=>t in n?uy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,Ut=(n,t,e)=>(Ay(n,typeof t!="symbol"?t+"":t,e),e);let dy=class extends Zi{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,a)=>{this.euler.set(s,i,-r,"YXZ"),e.setFromEuler(this.euler),e.multiply(this.q1),e.multiply(this.q0.setFromAxisAngle(this.zee,-a))}),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,a=this.screenOrientation?ct.degToRad(this.screenOrientation):0;this.setObjectQuaternion(this.object.quaternion,i,s,r,a),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 fy=Object.defineProperty,gy=(n,t,e)=>t in n?fy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,z=(n,t,e)=>(gy(n,typeof t!="symbol"?t+"":t,e),e);let my=class extends Zi{constructor(t,e){super(),z(this,"enabled",!0),z(this,"screen",{left:0,top:0,width:0,height:0}),z(this,"rotateSpeed",1),z(this,"zoomSpeed",1.2),z(this,"panSpeed",.3),z(this,"noRotate",!1),z(this,"noZoom",!1),z(this,"noPan",!1),z(this,"staticMoving",!1),z(this,"dynamicDampingFactor",.2),z(this,"minDistance",0),z(this,"maxDistance",1/0),z(this,"keys",["KeyA","KeyS","KeyD"]),z(this,"mouseButtons",{LEFT:_r.ROTATE,MIDDLE:_r.DOLLY,RIGHT:_r.PAN}),z(this,"object"),z(this,"domElement"),z(this,"cursorZoom",!1),z(this,"target",new k),z(this,"mousePosition",new Kt),z(this,"STATE",{NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4}),z(this,"EPS",1e-6),z(this,"lastZoom",1),z(this,"lastPosition",new k),z(this,"cursorVector",new k),z(this,"targetVector",new k),z(this,"_state",this.STATE.NONE),z(this,"_keyState",this.STATE.NONE),z(this,"_eye",new k),z(this,"_movePrev",new Kt),z(this,"_moveCurr",new Kt),z(this,"_lastAxis",new k),z(this,"_lastAngle",0),z(this,"_zoomStart",new Kt),z(this,"_zoomEnd",new Kt),z(this,"_touchZoomDistanceStart",0),z(this,"_touchZoomDistanceEnd",0),z(this,"_panStart",new Kt),z(this,"_panEnd",new Kt),z(this,"target0"),z(this,"position0"),z(this,"up0"),z(this,"zoom0"),z(this,"changeEvent",{type:"change"}),z(this,"startEvent",{type:"start"}),z(this,"endEvent",{type:"end"}),z(this,"onScreenVector",new Kt),z(this,"getMouseOnScreen",(i,s)=>(this.onScreenVector.set((i-this.screen.left)/this.screen.width,(s-this.screen.top)/this.screen.height),this.onScreenVector)),z(this,"onCircleVector",new Kt),z(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)),z(this,"axis",new k),z(this,"quaternion",new It),z(this,"eyeDirection",new k),z(this,"objectUpDirection",new k),z(this,"objectSidewaysDirection",new k),z(this,"moveDirection",new k),z(this,"angle",0),z(this,"rotateCamera",()=>{this.moveDirection.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0),this.angle=this.moveDirection.length(),this.angle?(this._eye.copy(this.object.position).sub(this.target),this.eyeDirection.copy(this._eye).normalize(),this.objectUpDirection.copy(this.object.up).normalize(),this.objectSidewaysDirection.crossVectors(this.objectUpDirection,this.eyeDirection).normalize(),this.objectUpDirection.setLength(this._moveCurr.y-this._movePrev.y),this.objectSidewaysDirection.setLength(this._moveCurr.x-this._movePrev.x),this.moveDirection.copy(this.objectUpDirection.add(this.objectSidewaysDirection)),this.axis.crossVectors(this.moveDirection,this._eye).normalize(),this.angle*=this.rotateSpeed,this.quaternion.setFromAxisAngle(this.axis,this.angle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion),this._lastAxis.copy(this.axis),this._lastAngle=this.angle):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),this.quaternion.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion)),this._movePrev.copy(this._moveCurr)}),z(this,"zoomCamera",()=>{let 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()}}),z(this,"mouseChange",new Kt),z(this,"objectUp",new k),z(this,"pan",new k),z(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))}}),z(this,"checkDistances",()=>{(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}),z(this,"handleResize",()=>{if(!this.domElement)return;const 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}),z(this,"update",()=>{this._eye.subVectors(this.object.position,this.target),this.noRotate||this.rotateCamera(),this.noZoom||this.zoomCamera(),this.noPan||this.panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this.checkDistances(),this.object.lookAt(this.target),this.lastPosition.distanceToSquared(this.object.position)>this.EPS&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this.lastPosition.distanceToSquared(this.object.position)>this.EPS||this.lastZoom!==this.object.zoom)&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type")}),z(this,"reset",()=>{this._state=this.STATE.NONE,this._keyState=this.STATE.NONE,this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.up.copy(this.up0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom}),z(this,"keydown",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)))}),z(this,"onPointerDown",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseDown(i);break}}),z(this,"onPointerMove",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseMove(i);break}}),z(this,"onPointerUp",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseUp();break}}),z(this,"keyup",()=>{this.enabled!==!1&&(this._keyState=this.STATE.NONE,window.addEventListener("keydown",this.keydown))}),z(this,"onMouseDown",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)}),z(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))}),z(this,"onMouseUp",()=>{this.domElement&&this.enabled!==!1&&(this._state=this.STATE.NONE,this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.endEvent))}),z(this,"mousewheel",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)}}),z(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 a=(i.touches[0].pageX+i.touches[1].pageX)/2,o=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panStart.copy(this.getMouseOnScreen(a,o)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(this.startEvent)}}),z(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 a=(i.touches[0].pageX+i.touches[1].pageX)/2,o=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panEnd.copy(this.getMouseOnScreen(a,o));break}}),z(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)}}),z(this,"contextmenu",i=>{this.enabled!==!1&&i.preventDefault()}),z(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()}),z(this,"dispose",()=>{this.domElement&&(this.domElement.removeEventListener("contextmenu",this.contextmenu),this.domElement.removeEventListener("pointerdown",this.onPointerDown),this.domElement.removeEventListener("wheel",this.mousewheel),this.domElement.removeEventListener("touchstart",this.touchstart),this.domElement.removeEventListener("touchend",this.touchend),this.domElement.removeEventListener("touchmove",this.touchmove),this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.keydown),window.removeEventListener("keyup",this.keyup))}),this.object=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 py=Object.defineProperty,Ey=(n,t,e)=>t in n?py(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,b=(n,t,e)=>(Ey(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()},_t={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"},ae={type:"end"};let Cy=class extends Zi{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,o=new vr(0,0,r,r).getPoints(this._curvePts),l=new Se().setFromPoints(o);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=_t.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!=_t.CURSOR)switch(this._touchStart.push(s),this._touchCurrent.push(s),this._input){case _t.NONE:this._input=_t.ONE_FINGER,this.onSinglePanStart(s,"ROTATE"),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp);break;case _t.ONE_FINGER:case _t.ONE_FINGER_SWITCHED:this._input=_t.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case _t.TWO_FINGER:this._input=_t.MULT_FINGER,this.onTriplePanStart();break}else if(s.pointerType!="touch"&&this._input==_t.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=_t.CURSOR,this._button=s.button,this.onSinglePanStart(s,this._mouseOp))}}),b(this,"onPointerMove",s=>{if(s.pointerType=="touch"&&this._input!=_t.CURSOR)switch(this._input){case _t.ONE_FINGER:this.updateTouchEvent(s),this.onSinglePanMove(s,tt.ROTATE);break;case _t.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],s)*this._devPxRatio>=this._switchSensibility){this._input=_t.ONE_FINGER,this.updateTouchEvent(s),this.onSinglePanStart(s,"ROTATE");break}break;case _t.TWO_FINGER:this.updateTouchEvent(s),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case _t.MULT_FINGER:this.updateTouchEvent(s),this.onTriplePanMove();break}else if(s.pointerType!="touch"&&this._input==_t.CURSOR){let r=null;s.ctrlKey||s.metaKey?r="CTRL":s.shiftKey&&(r="SHIFT");const a=this.getOpStateFromAction(this._button,r);a&&this.onSinglePanMove(s,a)}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!=_t.CURSOR){const r=this._touchCurrent.length;for(let a=0;a<r;a++)if(this._touchCurrent[a].pointerId==s.pointerId){this._touchCurrent.splice(a,1),this._touchStart.splice(a,1);break}switch(this._input){case _t.ONE_FINGER:case _t.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=_t.NONE,this.onSinglePanEnd();break;case _t.TWO_FINGER:this.onDoublePanEnd(),this.onPinchEnd(),this.onRotateEnd(),this._input=_t.ONE_FINGER_SWITCHED;break;case _t.MULT_FINGER:this._touchCurrent.length==0&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=_t.NONE,this.onTriplePanEnd());break}}else s.pointerType!="touch"&&this._input==_t.CURSOR&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=_t.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 a=s.timeStamp-this._clickStart,o=this.calculatePointersDistance(this._downEvents[1],this._downEvents[0])*this._devPxRatio;a<=this._maxInterval&&o<=this._posThreshold?(this._nclicks=0,this._downEvents.splice(0,this._downEvents.length),this.onDoubleTap(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,a;if(this.enabled&&this.enableZoom&&this.domElement){let o=null;s.ctrlKey||s.metaKey?o="CTRL":s.shiftKey&&(o="SHIFT");const l=this.getOpFromAction("WHEEL",o);if(l){s.preventDefault(),this.dispatchEvent(Ee);const c=125;let h=s.deltaY/c,u=1;switch(h>0?u=1/this.scaleFactor:h<0&&(u=this.scaleFactor),l){case"ZOOM":if(this.updateTbState(tt.SCALE,!0),h>0?u=1/Math.pow(this.scaleFactor,h):h<0&&(u=Math.pow(this.scaleFactor,-h)),this.cursorZoom&&this.enablePan){let A;this.camera instanceof se&&(A=(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&&(A=(a=this.unprojectOnTbPlane(this.camera,s.clientX,s.clientY,this.domElement))==null?void 0:a.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)),A!==void 0&&this.applyTransformMatrix(this.applyScale(u,A))}else this.applyTransformMatrix(this.applyScale(u,this._gizmos.position));this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt),this.dispatchEvent(ae);break;case"FOV":if(this.camera instanceof Pt){this.updateTbState(tt.FOV,!0),s.deltaX!=0&&(h=s.deltaX/c,u=1,h>0?u=1/Math.pow(this.scaleFactor,h):h<0&&(u=Math.pow(this.scaleFactor,-h))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const A=this._v3_1.distanceTo(this._gizmos.position);let d=A/u;d=ct.clamp(d,this.minDistance,this.maxDistance);const f=A*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));u=A/p,this.setFov(g),this.applyTransformMatrix(this.applyScale(u,this._gizmos.position,!1))}this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(tt.IDLE,!1),this.dispatchEvent(Lt),this.dispatchEvent(ae);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 a=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement);a!==void 0&&this._startCursorPosition.copy(a),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 a=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);a!==void 0&&this._startCursorPosition.copy(a),this.activateGizmos(!0),this.enableAnimations&&(this._timePrev=this._timeCurrent=performance.now(),this._angleCurrent=this._anglePrev=0,this._cursorPosPrev.copy(this._startCursorPosition),this._cursorPosCurr.copy(this._cursorPosPrev),this._wCurr=0,this._wPrev=this._wCurr)}this.dispatchEvent(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 a=r!=this._state;switch(this.setCenter(s.clientX,s.clientY),r){case tt.PAN:if(this.enablePan&&this.camera)if(a){this.dispatchEvent(ae),this.dispatchEvent(Ee),this.updateTbState(r,!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.activateGizmos(!1)}else{const o=this.unprojectOnTbPlane(this.camera,gt.x,gt.y,this.domElement);o!==void 0&&this._currentCursorPosition.copy(o),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition))}break;case tt.ROTATE:if(this.enableRotate&&this.camera)if(a){this.dispatchEvent(ae),this.dispatchEvent(Ee),this.updateTbState(r,!0);const o=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);o!==void 0&&this._startCursorPosition.copy(o),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!0)}else{const o=this.unprojectOnTbSurface(this.camera,gt.x,gt.y,this.domElement,this._tbRadius);o!==void 0&&this._currentCursorPosition.copy(o);const l=this._startCursorPosition.distanceTo(this._currentCursorPosition),c=this._startCursorPosition.angleTo(this._currentCursorPosition),h=Math.max(l/this._tbRadius,c);this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition,this._currentCursorPosition),h)),this.enableAnimations&&(this._timePrev=this._timeCurrent,this._timeCurrent=performance.now(),this._anglePrev=this._angleCurrent,this._angleCurrent=h,this._cursorPosPrev.copy(this._cursorPosCurr),this._cursorPosCurr.copy(this._currentCursorPosition),this._wPrev=this._wCurr,this._wCurr=this.calculateAngularSpeed(this._anglePrev,this._angleCurrent,this._timePrev,this._timeCurrent))}break;case tt.SCALE:if(this.enableZoom)if(a)this.dispatchEvent(ae),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(a)this.dispatchEvent(ae),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 u=h/c;u=ct.clamp(u,this.minDistance,this.maxDistance);const A=h*Math.tan(ct.DEG2RAD*this._fovState*.5);let d=ct.RAD2DEG*(Math.atan(A/u)*2);d=ct.clamp(d,this.minFov,this.maxFov);const f=A/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),a=this;this._animationId=window.requestAnimationFrame(function(o){a.updateTbState(tt.ANIMATION_ROTATE,!0);const l=a.calculateRotationAxis(a._cursorPosPrev,a._cursorPosCurr);a.onRotationAnim(o,l,Math.min(r,a.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(ae)}),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 a=this;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),this._timeStart=-1,this._animationId=window.requestAnimationFrame(function(o){a.updateTbState(tt.ANIMATION_FOCUS,!0),a.onFocusAnim(o,r,a._cameraMatrixState,a._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(ae)}),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(ae)}),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 a=ct.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);r!==void 0&&this.applyTransformMatrix(this.zRotate(r,a)),this.dispatchEvent(Lt)}}),b(this,"onRotateEnd",()=>{this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(ae)}),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 a=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]),a*this._devPxRatio);const o=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(o,l)),this.dispatchEvent(Lt)}}),b(this,"onPinchEnd",()=>{this.updateTbState(tt.IDLE,!1),this.dispatchEvent(ae)}),b(this,"onTriplePanStart",()=>{if(this.enabled&&this.enableZoom&&this.domElement){this.dispatchEvent(Ee),this.updateTbState(tt.SCALE,!0);let s=0,r=0;const a=this._touchCurrent.length;for(let o=0;o<a;o++)s+=this._touchCurrent[o].clientX,r+=this._touchCurrent[o].clientY;this.setCenter(s/a,r/a),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 a=this._touchCurrent.length;for(let p=0;p<a;p++)s+=this._touchCurrent[p].clientX,r+=this._touchCurrent[p].clientY;this.setCenter(s/a,r/a);const o=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*o):l>0&&(c=Math.pow(this.scaleFactor,l*o)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const h=this._v3_1.distanceTo(this._gizmos.position);let u=h/c;u=ct.clamp(u,this.minDistance,this.maxDistance);const A=h*Math.tan(ct.DEG2RAD*this._fovState*.5);let d=ct.RAD2DEG*(Math.atan(A/u)*2);d=ct.clamp(d,this.minFov,this.maxFov);const f=A/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(ae)}),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,a=null)=>{const o=["PAN","ROTATE","ZOOM","FOV"],l=[0,1,2,"WHEEL"],c=["CTRL","SHIFT",null];let h;if(!o.includes(s)||!l.includes(r)||!c.includes(a)||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 u={operation:s,mouse:r,key:a,state:h};for(let A=0;A<this.mouseActions.length;A++)if(this.mouseActions[A].mouse==u.mouse&&this.mouseActions[A].key==u.key)return this.mouseActions.splice(A,1,u),!0;return this.mouseActions.push(u),!0}),b(this,"getOpFromAction",(s,r)=>{let a;for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==s&&a.key==r)return a.operation;if(r){for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==s&&a.key==null)return a.operation}return null}),b(this,"getOpStateFromAction",(s,r)=>{let a;for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==s&&a.key==r)return a.state;if(r){for(let o=0;o<this.mouseActions.length;o++)if(a=this.mouseActions[o],a.mouse==s&&a.key==null)return a.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,a,o)=>{const l=r-s,c=(o-a)/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 a=s.position.distanceTo(this._gizmos.position);if(s instanceof Pt){const o=ct.DEG2RAD*s.fov*.5,l=Math.atan(s.aspect*Math.tan(o));return Math.tan(Math.min(o,l))*a*.67}else if(s instanceof se)return Math.min(s.top,s.right)*.67}),b(this,"focus",(s,r,a=1)=>{if(this.camera){const o=s.clone();o.sub(this._gizmos.position).multiplyScalar(a),this._translationMatrix.makeTranslation(o.x,o.y,o.z);const l=this._gizmoMatrixState.clone();this._gizmoMatrixState.premultiply(this._translationMatrix),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale);const c=this._cameraMatrixState.clone();this._cameraMatrixState.premultiply(this._translationMatrix),this._cameraMatrixState.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.enableZoom&&this.applyTransformMatrix(this.applyScale(r,this._gizmos.position)),this._gizmoMatrixState.copy(l),this._cameraMatrixState.copy(c)}}),b(this,"drawGrid",()=>{if(this.scene){let a,o,l,c;if(this.camera instanceof se){const h=this.camera.right-this.camera.left,u=this.camera.bottom-this.camera.top;l=Math.max(h,u),c=l/20,a=l/this.camera.zoom*3,o=a/c*this.camera.zoom}else if(this.camera instanceof Pt){const h=this.camera.position.distanceTo(this._gizmos.position),u=ct.DEG2RAD*this.camera.fov*.5,A=Math.atan(this.camera.aspect*Math.tan(u));l=Math.tan(Math.max(u,A))*h*2,c=l/20,a=l*3,o=a/c}this._grid==null&&this.camera&&(this._grid=new ff(a,o,8947848,8947848),this._grid.position.copy(this._gizmos.position),this._gridPosition.copy(this._grid.position),this._grid.quaternion.copy(this.camera.quaternion),this._grid.rotateX(Math.PI*.5),this.scene.add(this._grid))}}),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,a,o,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),(a=this.domElement)==null||a.removeEventListener("wheel",this.onWheel),(o=this.domElement)==null||o.removeEventListener("contextmenu",this.onContextMenu),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("resize",this.onWindowResize),(l=this.scene)==null||l.remove(this._gizmos),this.disposeGrid()}),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,a)=>{const o=a.getBoundingClientRect();return this._v2_1.setX((s-o.left)/o.width*2-1),this._v2_1.setY((o.bottom-r)/o.height*2-1),this._v2_1.clone()}),b(this,"getCursorPosition",(s,r,a)=>(this._v2_1.copy(this.getCursorNDC(s,r,a)),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 o=new vr(0,0,r,r).getPoints(this._curvePts),l=new Se().setFromPoints(o),c=new _s({color:16744576,fog:!1,transparent:!0,opacity:.6}),h=new _s({color:8454016,fog:!1,transparent:!0,opacity:.6}),u=new _s({color:8421631,fog:!1,transparent:!0,opacity:.6}),A=new Et(l,c),d=new Et(l,h),f=new Et(l,u),g=Math.PI*.5;if(A.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(A),this._gizmos.add(d),this._gizmos.add(f)}),b(this,"onFocusAnim",(s,r,a,o)=>{if(this._timeStart==-1&&(this._timeStart=s),this._state==tt.ANIMATION_FOCUS){const c=(s-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(o),c>=1)this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,this.scaleFactor),this._timeStart=-1,this.updateTbState(tt.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Lt);else{const h=this.easeOutCubic(c),u=1-h+this.scaleFactor*h;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(r,u,h),this.dispatchEvent(Lt);const A=this;this._animationId=window.requestAnimationFrame(function(d){A.onFocusAnim(d,r,a,o.clone())})}}else this._animationId=-1,this._timeStart=-1}),b(this,"onRotationAnim",(s,r,a)=>{if(this._timeStart==-1&&(this._anglePrev=0,this._angleCurrent=0,this._timeStart=s),this._state==tt.ANIMATION_ROTATE){const o=(s-this._timeStart)/1e3;if(a+-this.dampingFactor*o>0){this._angleCurrent=.5*-this.dampingFactor*Math.pow(o,2)+a*o+0,this.applyTransformMatrix(this.rotate(r,this._angleCurrent)),this.dispatchEvent(Lt);const c=this;this._animationId=window.requestAnimationFrame(function(h){c.onRotationAnim(h,r,a)})}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,a=!1)=>{if(this.camera){const o=s.clone().sub(r);if(this.camera instanceof se&&o.multiplyScalar(1/this.camera.zoom),this.camera instanceof Pt&&a){this._v3_1.setFromMatrixPosition(this._cameraMatrixState0),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0);const l=this._v3_1.distanceTo(this._v3_2)/this.camera.position.distanceTo(this._gizmos.position);o.multiplyScalar(1/l)}this._v3_1.set(o.x,o.y,0).applyQuaternion(this.camera.quaternion),this._m4_1.makeTranslation(this._v3_1.x,this._v3_1.y,this._v3_1.z),this.setTransformationMatrices(this._m4_1,this._m4_1)}return 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 a=this._gizmos.position;return this._translationMatrix.makeTranslation(-a.x,-a.y,-a.z),this._rotationMatrix.makeRotationAxis(s,-r),this._m4_1.makeTranslation(a.x,a.y,a.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1),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(a){s.setStateFromJSON(a)})}),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,a=!0)=>{if(!this.camera)return;const o=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),o.sub(this._v3_1);const c=o.clone().multiplyScalar(l);return o.sub(c),this._m4_1.makeTranslation(o.x,o.y,o.z),this._m4_2.premultiply(this._m4_1),this.setTransformationMatrices(this._m4_1,this._m4_2),ie}if(this.camera instanceof Pt){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let c=this._v3_1.distanceTo(o),h=c-c*l;const u=c-h;u<this.minDistance?(l=this.minDistance/c,h=c-c*l):u>this.maxDistance&&(l=this.maxDistance/c,h=c-c*l);let A=o.clone().sub(this._v3_1).normalize().multiplyScalar(h);if(this._m4_1.makeTranslation(A.x,A.y,A.z),a){const d=this._v3_2;c=d.distanceTo(o),h=c-c*l,A=o.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(A.x,A.y,A.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,a)=>{if(this.camera){this.target.set(s,r,a),this._gizmos.position.set(s,r,a);const o=this.calculateTbRadius(this.camera);o!==void 0&&(this._tbRadius=o),this.makeGizmos(this.target,this._tbRadius),this.camera.lookAt(this.target)}}),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 a=new ar;a.near=r.near,a.far=r.far,a.setFromCamera(s,r);const o=a.intersectObjects(this.scene.children,!0);for(let l=0;l<o.length;l++)if(o[l].object.uuid!=this._gizmos.uuid&&o[l].face)return o[l].point.clone();return null}),b(this,"unprojectOnTbSurface",(s,r,a,o,l)=>{if(s instanceof se){this._v2_1.copy(this.getCursorPosition(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0);const c=Math.pow(this._v2_1.x,2),h=Math.pow(this._v2_1.y,2),u=Math.pow(this._tbRadius,2);return c+h<=u*.5?this._v3_1.setZ(Math.sqrt(u-(c+h))):this._v3_1.setZ(u*.5/Math.sqrt(c+h)),this._v3_1}if(s instanceof Pt){this._v2_1.copy(this.getCursorNDC(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=s.position.distanceTo(this._gizmos.position),u=Math.pow(l,2),A=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=A/d,g=h;let p=Math.pow(f,2)+1,m=2*f*g,C=Math.pow(g,2)-u,E=Math.pow(m,2)-4*p*C;if(E>=0&&(this._v2_1.setX((-m-Math.sqrt(E))/(2*p)),this._v2_1.setY(f*this._v2_1.x+g),ct.RAD2DEG*this._v2_1.angle()>=45)){const _=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(h-this._v2_1.y,2));return c.multiplyScalar(_),c.z+=h,c}p=f,m=g,C=-u*.5,E=Math.pow(m,2)-4*p*C,this._v2_1.setX((-m-Math.sqrt(E))/(2*p)),this._v2_1.setY(f*this._v2_1.x+g);const 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}}),b(this,"unprojectOnTbPlane",(s,r,a,o,l=!1)=>{if(s instanceof se)return this._v2_1.copy(this.getCursorPosition(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0),this._v3_1.clone();if(s instanceof Pt){this._v2_1.copy(this.getCursorNDC(r,a,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const c=this._v3_1.clone().normalize(),h=this._v3_1.z,u=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let A;if(l?A=this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):A=s.position.distanceTo(this._gizmos.position),u==0)return c.set(0,0,0),c;const d=h/u,f=A,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 a=this._tbRadius,o=this.calculateTbRadius(this.camera);if(o!==void 0&&(this._tbRadius=o),a<this._tbRadius-1e-6||a>this._tbRadius+1e-6){const l=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,c=this._tbRadius/l,u=new vr(0,0,c,c).getPoints(this._curvePts),A=new Se().setFromPoints(u);for(const d in this._gizmos.children){const f=this._gizmos.children[d];f.geometry=A}}}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 a=this.calculateTbRadius(this.camera);a!==void 0&&(this._tbRadius=a);const o=new dt().copy(this._gizmoMatrixState0);this.makeGizmos(this._gizmos.position,this._tbRadius),this._gizmoMatrixState0.copy(o),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=_t.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 xa,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 jh;s.setFromObject(this._gizmos);const r=new uo;s.getBoundingSphere(r);const a=Math.max(this._nearPos0,r.radius+r.center.length()),o=i-this._initialNear,l=Math.min(a,o);this.camera.near=i-l;const c=Math.min(this._farPos0,-r.radius+r.center.length()),h=i-this._initialFar,u=Math.min(c,h);this.camera.far=i-u,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 Iy=Object.defineProperty,yy=(n,t,e)=>t in n?Iy(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,xt=(n,t,e)=>(yy(n,typeof t!="symbol"?t+"":t,e),e);function _c(n){n.preventDefault()}let By=class extends Zi{constructor(t,e){super(),xt(this,"object"),xt(this,"domElement",null),xt(this,"movementSpeed",1),xt(this,"rollSpeed",.005),xt(this,"dragToLook",!1),xt(this,"autoForward",!1),xt(this,"changeEvent",{type:"change"}),xt(this,"EPS",1e-6),xt(this,"tmpQuaternion",new It),xt(this,"mouseStatus",0),xt(this,"movementSpeedMultiplier",1),xt(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}),xt(this,"moveVector",new k(0,0,0)),xt(this,"rotationVector",new k(0,0,0)),xt(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()}}),xt(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()}),xt(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()}}),xt(this,"pointermove",i=>{if(!this.dragToLook||this.mouseStatus>0){const s=this.getContainerDimensions(),r=s.size[0]/2,a=s.size[1]/2;this.moveState.yawLeft=-(i.pageX-s.offset[0]-r)/r,this.moveState.pitchDown=(i.pageY-s.offset[1]-a)/a,this.updateRotationVector()}}),xt(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()}),xt(this,"lastQuaternion",new It),xt(this,"lastPosition",new k),xt(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))}),xt(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}),xt(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}),xt(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]}),xt(this,"connect",i=>{this.domElement=i,i instanceof Document||i.setAttribute("tabindex",-1),this.domElement.addEventListener("contextmenu",_c),this.domElement.addEventListener("pointermove",this.pointermove),this.domElement.addEventListener("pointerdown",this.pointerdown),this.domElement.addEventListener("pointerup",this.pointerup),window.addEventListener("keydown",this.keydown),window.addEventListener("keyup",this.keyup)}),xt(this,"dispose",()=>{this.domElement.removeEventListener("contextmenu",_c),this.domElement.removeEventListener("pointermove",this.pointermove),this.domElement.removeEventListener("pointerdown",this.pointerdown),this.domElement.removeEventListener("pointerup",this.pointerup),window.removeEventListener("keydown",this.keydown),window.removeEventListener("keyup",this.keyup)}),this.object=t,e!==void 0&&this.connect(e),this.updateMovementVector(),this.updateRotationVector()}};function iA(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,a=Math.floor((s+r)/2);for(;t<e[a]||t>=e[a+1];)t<e[a]?r=a:s=a,a=Math.floor((s+r)/2);return a}function Sy(n,t,e,i){const s=[],r=[],a=[];s[0]=1;for(let o=1;o<=e;++o){r[o]=t-i[n+1-o],a[o]=i[n+o]-t;let l=0;for(let c=0;c<o;++c){const h=a[c+1],u=r[o-c],A=s[c]/(h+u);s[c]=l+h*A,l=u*A}s[o]=l}return s}function Ty(n,t,e,i){const s=iA(n,i,t),r=Sy(s,i,n,t),a=new _e(0,0,0,0);for(let o=0;o<=n;++o){const l=e[s-n+o],c=r[o],h=l.w*c;a.x+=l.x*h,a.y+=l.y*h,a.z+=l.z*h,a.w+=l.w*c}return a}function _y(n,t,e,i,s){const r=[];for(let u=0;u<=e;++u)r[u]=0;const a=[];for(let u=0;u<=i;++u)a[u]=r.slice(0);const o=[];for(let u=0;u<=e;++u)o[u]=r.slice(0);o[0][0]=1;const l=r.slice(0),c=r.slice(0);for(let u=1;u<=e;++u){l[u]=t-s[n+1-u],c[u]=s[n+u]-t;let A=0;for(let d=0;d<u;++d){const f=c[d+1],g=l[u-d];o[u][d]=f+g;const p=o[d][u-1]/o[u][d];o[d][u]=A+f*p,A=g*p}o[u][u]=A}for(let u=0;u<=e;++u)a[0][u]=o[u][e];for(let u=0;u<=e;++u){let A=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=u-g,C=e-g;u>=g&&(f[d][0]=f[A][0]/o[C+1][m],p=f[d][0]*o[m][C]);const E=m>=-1?1:-m,S=u-1<=C?g-1:e-u;for(let _=E;_<=S;++_)f[d][_]=(f[A][_]-f[A][_-1])/o[C+1][m+_],p+=f[d][_]*o[m+_][C];u<=C&&(f[d][g]=-f[A][g-1]/o[C+1][u],p+=f[d][g]*o[u][C]),a[g][u]=p;const y=A;A=d,d=y}}let h=e;for(let u=1;u<=i;++u){for(let A=0;A<=e;++A)a[u][A]*=h;h*=e-u}return a}function vy(n,t,e,i,s){const r=s<n?s:n,a=[],o=iA(n,i,t),l=_y(o,i,n,r,t),c=[];for(let h=0;h<e.length;++h){const u=e[h].clone(),A=u.w;u.x*=A,u.y*=A,u.z*=A,c[h]=u}for(let h=0;h<=r;++h){const u=c[o-n].clone().multiplyScalar(l[h][0]);for(let A=1;A<=n;++A)u.add(c[o-n+A].clone().multiplyScalar(l[h][A]));a[h]=u}for(let h=r+1;h<=s+1;++h)a[h]=new _e(0,0,0);return a}function xy(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 Dy(n){const t=n.length,e=[],i=[];for(let r=0;r<t;++r){const a=n[r];e[r]=new k(a.x,a.y,a.z),i[r]=a.w}const s=[];for(let r=0;r<t;++r){const a=e[r].clone();for(let o=1;o<=r;++o)a.sub(s[r-o].clone().multiplyScalar(xy(r,o)*i[o]));s[r]=a.divideScalar(i[0])}return s}function Ry(n,t,e,i,s){const r=vy(n,t,e,i,s);return Dy(r)}class vc extends gf{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 a=0;a<i.length;++a){const o=i[a];this.controlPoints[a]=new _e(o.x,o.y,o.z,o.w)}}getPoint(t,e){const i=e||new k,s=this.knots[this.startKnot]+t*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=Ty(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=Ry(this.degree,this.knots,this.controlPoints,s,1);return i.copy(r[1]).normalize(),i}}let pt,Mt,ee;class Go extends Ao{constructor(t){super(t)}load(t,e,i,s){const r=this,a=r.path===""?mf.extractUrlBase(t):r.path,o=new Hi(this.manager);o.setPath(r.path),o.setResponseType("arraybuffer"),o.setRequestHeader(r.requestHeader),o.setWithCredentials(r.withCredentials),o.load(t,function(l){try{e(r.parse(l,a))}catch(c){s?s(c):console.error(c),r.manager.itemError(t)}},i,s)}parse(t,e){if(Py(t))pt=new My().parse(t);else{const s=aA(t);if(!ky(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 Fy().parse(s)}const i=new pf(this.manager).setPath(this.resourcePath||e).setCrossOrigin(this.crossOrigin);return new wy(i,this.manager).parse(pt)}}class wy{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 Ly().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],a=i[2];t.has(s)||t.set(s,{parents:[],children:[]});const o={ID:r,relationship:a};t.get(s).parents.push(o),t.has(r)||t.set(r,{parents:[],children:[]});const l={ID:s,relationship:a};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],a=parseInt(s);if(t[a]=r.RelativeFilename||r.Filename,"Content"in r){const o=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,l=typeof r.Content=="string"&&r.Content!=="";if(o||l){const c=this.parseImage(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 a=new Uint8Array(e);return window.URL.createObjectURL(new Blob([a],{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,a=s!==void 0?s.value:0,o=r!==void 0?r.value:0;if(i.wrapS=a===0?Da:kn,i.wrapT=o===0?Da: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 a;const o=t.FileName.slice(-3).toLowerCase();if(o==="tga"){const l=this.manager.getHandler(".tga");l===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",t.RelativeFilename),a=new Qn):(l.setPath(this.textureLoader.path),a=l.load(i))}else o==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",t.RelativeFilename),a=new Qn):a=this.textureLoader.load(i);return this.textureLoader.setPath(s),a}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 a=this.parseParameters(t,e,i);let o;switch(r.toLowerCase()){case"phong":o=new xr;break;case"lambert":o=new Ef;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),o=new xr;break}return o.setValues(a),o.name=s,o}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(a){const o=a.relationship;switch(o){case"Bump":s.bumpMap=r.getTexture(e,a.ID);break;case"Maya|TEX_ao_map":s.aoMap=r.getTexture(e,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=r.getTexture(e,a.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,a.ID);break;case"EmissiveColor":s.emissiveMap=r.getTexture(e,a.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,a.ID);break;case"ReflectionColor":s.envMap=r.getTexture(e,a.ID),s.envMap!==void 0&&(s.envMap.mapping=Cf,"colorSpace"in s.envMap?s.envMap.colorSpace="srgb":s.envMap.encoding=3001);break;case"SpecularColor":s.specularMap=r.getTexture(e,a.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,a.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.",o);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],a=Mt.get(parseInt(s));if(r.attrType==="Skin"){const o=this.parseSkeleton(a,i);o.ID=s,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,t[s]=o}else if(r.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(a,i),o.id=s,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),e[s]=o}}}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 a={ID:s.ID,indices:[],weights:[],transformLink:new dt().fromArray(r.TransformLink.a)};"Indexes"in r&&(a.indices=r.Indexes.a,a.weights=r.Weights.a),i.push(a)}),{rawBones:i,bones:[]}}parseMorphTargets(t,e){const i=[];for(let s=0;s<t.children.length;s++){const r=t.children[s],a=e[r.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=Mt.get(parseInt(r.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,i.push(o)}return i}parseScene(t,e,i){ee=new xa;const s=this.parseModels(t.skeletons,e,i),r=pt.Objects.Model,a=this;s.forEach(function(l){const c=r[l.ID];a.setLookAtProperties(l,c),Mt.get(l.ID).parents.forEach(function(u){const A=s.get(u.ID);A!==void 0&&A.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=nA(l.userData.transformData);l.applyMatrix4(c),l.updateWorldMatrix()}});const o=new by().parse();ee.children.length===1&&ee.children[0].isGroup&&(ee.children[0].animations=o,ee=ee.children[0]),ee.animations=o}parseModels(t,e,i){const s=new Map,r=pt.Objects.Model;for(const a in r){const o=parseInt(a),l=r[a],c=Mt.get(o);let h=this.buildSkeleton(c,t,o,l.attrName);if(!h){switch(l.attrType){case"Camera":h=this.createCamera(c);break;case"Light":h=this.createLight(c);break;case"Mesh":h=this.createMesh(c,e,i);break;case"NurbsCurve":h=this.createCurve(c,e);break;case"LimbNode":case"Root":h=new ol;break;case"Null":default:h=new xa;break}h.name=l.attrName?On.sanitizeNodeName(l.attrName):"",h.ID=o}this.getTransformData(h,l),s.set(o,h)}return s}buildSkeleton(t,e,i,s){let r=null;return t.parents.forEach(function(a){for(const o in e){const l=e[o];l.rawBones.forEach(function(c,h){if(c.ID===a.ID){const u=r;r=new ol,r.matrixWorld.copy(c.transformLink),r.name=s?On.sanitizeNodeName(s):"",r.ID=i,l.bones[h]=r,u!==null&&r.add(u)}})}}),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 a=1e3;i.FarPlane!==void 0&&(a=i.FarPlane.value/1e3);let o=window.innerWidth,l=window.innerHeight;i.AspectWidth!==void 0&&i.AspectHeight!==void 0&&(o=i.AspectWidth.value,l=i.AspectHeight.value);const c=o/l;let h=45;i.FieldOfView!==void 0&&(h=i.FieldOfView.value);const u=i.FocalLength?i.FocalLength.value:null;switch(s){case 0:e=new Pt(h,c,r,a),u!==null&&e.setFocalLength(u);break;case 1:e=new se(-o/2,o/2,l/2,-l/2,r,a);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 a=i.Intensity===void 0?1:i.Intensity.value/100;i.CastLightOnObject!==void 0&&i.CastLightOnObject.value===0&&(a=0);let o=0;i.FarAttenuationEnd!==void 0&&(i.EnableFarAttenuation!==void 0&&i.EnableFarAttenuation.value===0?o=0:o=i.FarAttenuationEnd.value);const l=1;switch(s){case 0:e=new ll(r,a,o,l);break;case 1:e=new yf(r,a);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 If(r,a,o,c,h,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),e=new ll(r,a);break}i.CastShadows!==void 0&&i.CastShadows.value===1&&(e.castShadow=!0)}return e}createMesh(t,e,i){let s,r=null,a=null;const o=[];return t.children.forEach(function(l){e.has(l.ID)&&(r=e.get(l.ID)),i.has(l.ID)&&o.push(i.get(l.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new xr({color:13421772}),o.push(a)),"color"in r.attributes&&o.forEach(function(l){l.vertexColors=!0}),r.FBX_Deformer?(s=new Bf(r,a),s.normalizeSkinWeights()):s=new nt(r,a),s}createCurve(t,e){const i=t.children.reduce(function(r,a){return e.has(a.ID)&&(r=e.get(a.ID)),r},null),s=new _s({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=rA(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 a=r.Lcl_Translation.value;t.target!==void 0?(t.target.position.fromArray(a),ee.add(t.target)):t.lookAt(new k().fromArray(a))}}})}bindSkeleton(t,e,i){const s=this.parsePoseNodes();for(const r in t){const a=t[r];Mt.get(parseInt(a.ID)).parents.forEach(function(l){if(e.has(l.ID)){const c=l.ID;Mt.get(c).parents.forEach(function(u){i.has(u.ID)&&i.get(u.ID).bind(new Sf(a.bones),s[u.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 Tf(r,1))}}}}class Ly{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)),a=this.parseGeometry(r,i[s],t);e.set(parseInt(s),a)}}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=[],a=t.parents.map(function(u){return pt.Objects.Model[u.ID]});if(a.length===0)return;const o=t.children.reduce(function(u,A){return s[A.ID]!==void 0&&(u=s[A.ID]),u},null);t.children.forEach(function(u){i.morphTargets[u.ID]!==void 0&&r.push(i.morphTargets[u.ID])});const l=a[0],c={};"RotationOrder"in l&&(c.eulerOrder=rA(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=nA(c);return this.genGeometry(e,o,r,h)}genGeometry(t,e,i,s){const r=new Se;t.attrName&&(r.name=t.attrName);const a=this.parseGeoNode(t,e),o=this.genBuffers(a),l=new $e(o.vertex,3);if(l.applyMatrix4(s),r.setAttribute("position",l),o.colors.length>0&&r.setAttribute("color",new $e(o.colors,3)),e&&(r.setAttribute("skinIndex",new _f(o.weightsIndices,4)),r.setAttribute("skinWeight",new $e(o.vertexWeights,4)),r.FBX_Deformer=e),o.normal.length>0){const c=new Ts().getNormalMatrix(s),h=new $e(o.normal,3);h.applyNormalMatrix(c),r.setAttribute("normal",h)}if(o.uvs.forEach(function(c,h){Lf==="uv2"&&h++;const u=h===0?"uv":`uv${h}`;r.setAttribute(u,new $e(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let c=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,A){u!==c&&(r.addGroup(h,A-h,c),c=u,h=A)}),r.groups.length>0){const u=r.groups[r.groups.length-1],A=u.start+u.count;A!==o.materialIndex.length&&r.addGroup(A,o.materialIndex.length-A,c)}r.groups.length===0&&r.addGroup(0,o.materialIndex.length,o.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(a,o){i.weightTable[a]===void 0&&(i.weightTable[a]=[]),i.weightTable[a].push({id:r,weight:s.weights[o]})})})),i}genBuffers(t){const e={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,r=!1,a=[],o=[],l=[],c=[],h=[],u=[];const A=this;return t.vertexIndices.forEach(function(d,f){let g,p=!1;d<0&&(d=d^-1,p=!0);let m=[],C=[];if(a.push(d*3,d*3+1,d*3+2),t.color){const E=nn(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],S=[0,0,0,0];C.forEach(function(y,_){let T=y,v=m[_];S.forEach(function(F,x,w){if(T>F){w[x]=T,T=F;const U=E[x];E[x]=v,v=U}})}),m=E,C=S}for(;C.length<4;)C.push(0),m.push(0);for(let E=0;E<4;++E)h.push(C[E]),u.push(m[E])}if(t.normal){const E=nn(f,i,d,t.normal);o.push(E[0],E[1],E[2])}t.material&&t.material.mappingType!=="AllSame"&&(g=nn(f,i,d,t.material)[0]),t.uv&&t.uv.forEach(function(E,S){const y=nn(f,i,d,E);c[S]===void 0&&(c[S]=[]),c[S].push(y[0]),c[S].push(y[1])}),s++,p&&(A.genFace(e,t,a,g,o,l,c,h,u,s),i++,s=0,a=[],o=[],l=[],c=[],h=[],u=[])}),e}genFace(t,e,i,s,r,a,o,l,c,h){for(let u=2;u<h;u++)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[(u-1)*3]]),t.vertex.push(e.vertexPositions[i[(u-1)*3+1]]),t.vertex.push(e.vertexPositions[i[(u-1)*3+2]]),t.vertex.push(e.vertexPositions[i[u*3]]),t.vertex.push(e.vertexPositions[i[u*3+1]]),t.vertex.push(e.vertexPositions[i[u*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[(u-1)*4]),t.vertexWeights.push(l[(u-1)*4+1]),t.vertexWeights.push(l[(u-1)*4+2]),t.vertexWeights.push(l[(u-1)*4+3]),t.vertexWeights.push(l[u*4]),t.vertexWeights.push(l[u*4+1]),t.vertexWeights.push(l[u*4+2]),t.vertexWeights.push(l[u*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[(u-1)*4]),t.weightsIndices.push(c[(u-1)*4+1]),t.weightsIndices.push(c[(u-1)*4+2]),t.weightsIndices.push(c[(u-1)*4+3]),t.weightsIndices.push(c[u*4]),t.weightsIndices.push(c[u*4+1]),t.weightsIndices.push(c[u*4+2]),t.weightsIndices.push(c[u*4+3])),e.color&&(t.colors.push(a[0]),t.colors.push(a[1]),t.colors.push(a[2]),t.colors.push(a[(u-1)*3]),t.colors.push(a[(u-1)*3+1]),t.colors.push(a[(u-1)*3+2]),t.colors.push(a[u*3]),t.colors.push(a[u*3+1]),t.colors.push(a[u*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[(u-1)*3]),t.normal.push(r[(u-1)*3+1]),t.normal.push(r[(u-1)*3+2]),t.normal.push(r[u*3]),t.normal.push(r[u*3+1]),t.normal.push(r[u*3+2])),e.uv&&e.uv.forEach(function(A,d){t.uvs[d]===void 0&&(t.uvs[d]=[]),t.uvs[d].push(o[d][0]),t.uvs[d].push(o[d][1]),t.uvs[d].push(o[d][(u-1)*2]),t.uvs[d].push(o[d][(u-1)*2+1]),t.uvs[d].push(o[d][u*2]),t.uvs[d].push(o[d][u*2+1])})}addMorphTargets(t,e,i,s){if(i.length===0)return;t.morphTargetsRelative=!0,t.morphAttributes.position=[];const r=this;i.forEach(function(a){a.rawTargets.forEach(function(o){const l=pt.Objects.Geometry[o.geoID];l!==void 0&&r.genMorphGeometry(t,e,l,s,o.name)})})}genMorphGeometry(t,e,i,s,r){const a=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],o=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]=o[f*3],h[g+1]=o[f*3+1],h[g+2]=o[f*3+2]}const u={vertexIndices:a,vertexPositions:h},A=this.genBuffers(u),d=new $e(A.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 a=0;a<s.length;++a)r.push(a);return{dataSize:1,buffer:s,indices:r,mappingType:e,referenceType:i}}parseNurbsGeometry(t){if(vc===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 Se;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 Se;const i=e-1,s=t.KnotVector.a,r=[],a=t.Points.a;for(let u=0,A=a.length;u<A;u+=4)r.push(new _e().fromArray(a,u));let o,l;if(t.Form==="Closed")r.push(r[0]);else if(t.Form==="Periodic"){o=i,l=s.length-1-o;for(let u=0;u<i;++u)r.push(r[u])}const h=new vc(i,s,r,o,l).getPoints(r.length*12);return new Se().setFromPoints(h)}}class by{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(Qy),values:e[i].KeyValueFloat.a},r=Mt.get(s.id);if(r!==void 0){const a=r.parents[0].ID,o=r.parents[0].relationship;o.match(/X/)?t.get(a).curves.x=s:o.match(/Y/)?t.get(a).curves.y=s:o.match(/Z/)?t.get(a).curves.z=s:o.match(/d|DeformPercent/)&&t.has(a)&&(t.get(a).curves.morph=s)}}}parseAnimationLayers(t){const e=pt.Objects.AnimationLayer,i=new Map;for(const s in e){const r=[],a=Mt.get(parseInt(s));a!==void 0&&(a.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 u=Mt.get(l.ID).parents.filter(function(A){return A.relationship!==void 0})[0].ID;if(u!==void 0){const A=pt.Objects.Model[u.toString()];if(A===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const d={modelName:A.attrName?On.sanitizeNodeName(A.attrName):"",ID:A.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ee.traverse(function(f){f.ID===A.id&&(d.transform=f.matrix,f.userData.transformData&&(d.eulerOrder=f.userData.transformData.eulerOrder))}),d.transform||(d.transform=new dt),"PreRotation"in A&&(d.preRotation=A.PreRotation.value),"PostRotation"in A&&(d.postRotation=A.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 u=Mt.get(l.ID).parents.filter(function(m){return m.relationship!==void 0})[0].ID,A=Mt.get(u).parents[0].ID,d=Mt.get(A).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[u].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 a=t.get(r[0].ID);i[s]={name:e[s].attrName,layer:a}}return i}addClip(t){let e=[];const i=this;return t.layer.forEach(function(s){e=e.concat(i.generateTracks(s))}),new vf(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 a=this.generateVectorTrack(t.modelName,t.T.curves,i,"position");a!==void 0&&e.push(a)}if(t.R!==void 0&&Object.keys(t.R.curves).length>0){const a=this.generateRotationTrack(t.modelName,t.R.curves,s,t.preRotation,t.postRotation,t.eulerOrder);a!==void 0&&e.push(a)}if(t.S!==void 0&&Object.keys(t.S.curves).length>0){const a=this.generateVectorTrack(t.modelName,t.S.curves,r,"scale");a!==void 0&&e.push(a)}if(t.DeformPercent!==void 0){const a=this.generateMorphTrack(t);a!==void 0&&e.push(a)}return e}generateVectorTrack(t,e,i,s){const r=this.getTimesForAllAxes(e),a=this.getKeyframeTrackValues(r,e,i);return new xf(t+"."+s,r,a)}generateRotationTrack(t,e,i,s,r,a){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 o=this.getTimesForAllAxes(e),l=this.getKeyframeTrackValues(o,e,i);s!==void 0&&(s=s.map(ct.degToRad),s.push(a),s=new qe().fromArray(s),s=new It().setFromEuler(s)),r!==void 0&&(r=r.map(ct.degToRad),r.push(a),r=new qe().fromArray(r),r=new It().setFromEuler(r).invert());const c=new It,h=new qe,u=[];for(let A=0;A<l.length;A+=3)h.set(l[A],l[A+1],l[A+2],a),c.setFromEuler(h),s!==void 0&&c.premultiply(s),r!==void 0&&c.multiply(r),c.toArray(u,A/3*4);return new Df(t+".quaternion",o,u)}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 Rf(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 a=e[r];a!==s&&(e[i]=a,s=a,i++)}e=e.slice(0,i)}return e}getKeyframeTrackValues(t,e,i){const s=i,r=[];let a=-1,o=-1,l=-1;return t.forEach(function(c){if(e.x&&(a=e.x.times.indexOf(c)),e.y&&(o=e.y.times.indexOf(c)),e.z&&(l=e.z.times.indexOf(c)),a!==-1){const h=e.x.values[a];r.push(h),s[0]=h}else r.push(s[0]);if(o!==-1){const h=e.y.values[o];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 a=r/180,o=s/a;let l=i+o;const c=t.times[e-1],u=(t.times[e]-c)/a;let A=c+u;const d=[],f=[];for(;A<t.times[e];)d.push(A),A+=u,f.push(l),l+=o;t.times=Rc(t.times,e,d),t.values=Rc(t.values,e,f)}}}}class Fy{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 sA,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const e=this,i=t.split(/[\r\n]+/);return i.forEach(function(s,r){const a=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(a||o)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},a=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,r):i in o?(i==="PoseNode"?o.PoseNode.push(r):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),a.id!==""&&(o[i][a.id]=r)):typeof a.id=="number"?(o[i]={},o[i][a.id]=r):i!=="Properties70"&&(i==="PoseNode"?o[i]=[r]:o[i]=r),typeof a.id=="number"&&(r.id=a.id),a.name!==""&&(r.attrName=a.name),a.type!==""&&(r.attrType=a.type),this.pushStack(r)}parseNodeAttr(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 a=this.getCurrentNode();if(a.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 u=r.split(",").slice(3);u=u.map(function(A){return A.trim().replace(/^"/,"")}),s="connections",r=[c,h],Gy(r,u),a[s]===void 0&&(a[s]=[])}s==="Node"&&(a.id=r),s in a&&Array.isArray(a[s])?a[s].push(r):s!=="a"?a[s]=r:a.a=r,this.setCurrentProp(a,s),s==="a"&&r.slice(-1)!==","&&(a.a=Qr(r))}parseNodePropertyContinued(t){const e=this.getCurrentNode();e.a+=t,t.slice(-1)!==","&&(e.a=Qr(e.a))}parseNodeSpecialProperty(t,e,i){const s=i.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=s[0],a=s[1],o=s[2],l=s[3];let c=s[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=Qr(c);break}this.getPrevNode()[r]={type:a,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),r)}}class My{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 sA;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 a=t.getUint8(),o=t.getString(a);if(s===0)return null;const l=[];for(let A=0;A<r;A++)l.push(this.parseProperty(t));const c=l.length>0?l[0]:"",h=l.length>1?l[1]:"",u=l.length>2?l[2]:"";for(i.singleProperty=r===1&&t.getOffset()===s;s>t.getOffset();){const A=this.parseNode(t,e);A!==null&&this.parseSubNode(o,i,A)}return i.propertyList=l,typeof c=="number"&&(i.id=c),h!==""&&(i.attrName=h),u!==""&&(i.attrType=u),o!==""&&(i.name=o),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,a){a!==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 a=i.propertyList[2],o=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:a,flag:o,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(),a=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 o=wf(new Uint8Array(t.getArrayBuffer(a))),l=new xc(o.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)),Zh(new Uint8Array(e))}}class sA{add(t,e){this[t]=e}}function Py(n){const t="Kaydara FBX Binary \0";return n.byteLength>=t.length&&t===aA(n,0,t.length)}function ky(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 Qy(n){return n/46186158e3}const Oy=[];function nn(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,a=r+i.dataSize;return Uy(Oy,i.buffer,r,a)}const kr=new qe,Di=new k;function nA(n){const t=new dt,e=new dt,i=new dt,s=new dt,r=new dt,a=new dt,o=new dt,l=new dt,c=new dt,h=new dt,u=new dt,A=new dt,d=n.inheritType?n.inheritType:0;if(n.translation&&t.setPosition(Di.fromArray(n.translation)),n.preRotation){const x=n.preRotation.map(ct.degToRad);x.push(n.eulerOrder),e.makeRotationFromEuler(kr.fromArray(x))}if(n.rotation){const x=n.rotation.map(ct.degToRad);x.push(n.eulerOrder),i.makeRotationFromEuler(kr.fromArray(x))}if(n.postRotation){const x=n.postRotation.map(ct.degToRad);x.push(n.eulerOrder),s.makeRotationFromEuler(kr.fromArray(x)),s.invert()}n.scale&&r.scale(Di.fromArray(n.scale)),n.scalingOffset&&o.setPosition(Di.fromArray(n.scalingOffset)),n.scalingPivot&&a.setPosition(Di.fromArray(n.scalingPivot)),n.rotationOffset&&l.setPosition(Di.fromArray(n.rotationOffset)),n.rotationPivot&&c.setPosition(Di.fromArray(n.rotationPivot)),n.parentMatrixWorld&&(u.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,S=new dt;if(d===0)S.copy(g).multiply(f).multiply(C).multiply(E);else if(d===1)S.copy(g).multiply(C).multiply(f).multiply(E);else{const w=new dt().scale(new k().setFromMatrixScale(u)).clone().invert(),U=C.clone().multiply(w);S.copy(g).multiply(f).multiply(U).multiply(E)}const y=c.clone().invert(),_=a.clone().invert();let T=t.clone().multiply(l).multiply(c).multiply(e).multiply(i).multiply(s).multiply(y).multiply(o).multiply(a).multiply(r).multiply(_);const v=new dt().copyPosition(T),F=h.clone().multiply(v);return A.copyPosition(F),T=A.clone().multiply(S),T.premultiply(h.invert()),T}function rA(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 Qr(n){return n.split(",").map(function(e){return parseFloat(e)})}function aA(n,t,e){return t===void 0&&(t=0),e===void 0&&(e=n.byteLength),Zh(new Uint8Array(n,t,e))}function Gy(n,t){for(let e=0,i=n.length,s=t.length;e<s;e++,i++)n[i]=t[e]}function Uy(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 Ny 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 Hy{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:a}=this.queue.shift();this.workersResolve[t]=s,this.workers[t].postMessage(r,a)}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 oA=0,wc=2,Ky=0,Yy=0,Vy=2,Jy=0,zy=0,$y=1,Ha=2,qy=0,lA=1,Xy=10,Wy=64,cA=0,hA=9,uA=15,AA=16,dA=22,fA=37,gA=43,mA=76,pA=83,EA=97,CA=100,IA=103,yA=109,BA=165,SA=166;class jy{constructor(){this.vkFormat=cA,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=oA,this.levels=[],this.dataFormatDescriptor=[{vendorId:Yy,descriptorType:Ky,descriptorBlockSize:0,versionNumber:Vy,colorModel:Jy,colorPrimaries:lA,transferFunction:Ha,flags:zy,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class ds{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 Zy(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 jy,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new ds(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 a=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),c=s._nextUint32(),h=s._nextUint64(),u=s._nextUint64(),A=r*3*8,d=new ds(n,Xt.length+i,A,!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 ds(n,a,o,!0),g={vendorId:f._skip(4)._nextUint16(),descriptorType:f._nextUint16(),versionNumber:f._nextUint16(),descriptorBlockSize:f._nextUint16(),colorModel:f._nextUint8(),colorPrimaries:f._nextUint8(),transferFunction:f._nextUint8(),flags:f._nextUint8(),texelBlockDimension:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],bytesPlane:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],samples:[]},C=(g.descriptorBlockSize/4-6)/4;for(let G=0;G<C;G++){const H={bitOffset:f._nextUint16(),bitLength:f._nextUint8(),channelType:f._nextUint8(),samplePosition:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};H.channelType&Wy?(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 ds(n,l,c,!0);for(;E._offset<c;){const G=E._nextUint32(),H=E._scan(G),J=Lc(H);if(e.keyValue[J]=E._nextUint8Array(G-H.byteLength-1),J.match(/^ktx/i)){const D=Lc(e.keyValue[J]);e.keyValue[J]=D.substring(0,D.lastIndexOf("\0"))}const K=G%4?4-G%4:0;E._skip(K)}if(u<=0)return e;const S=new ds(n,h,u,!0),y=S._nextUint16(),_=S._nextUint16(),T=S._nextUint32(),v=S._nextUint32(),F=S._nextUint32(),x=S._nextUint32(),w=[];for(let G=0;G<r;G++)w.push({imageFlags:S._nextUint32(),rgbSliceByteOffset:S._nextUint32(),rgbSliceByteLength:S._nextUint32(),alphaSliceByteOffset:S._nextUint32(),alphaSliceByteLength:S._nextUint32()});const U=h+S._offset,O=U+T,W=O+v,Y=W+F,X=new Uint8Array(n.buffer,n.byteOffset+U,T),Z=new Uint8Array(n.buffer,n.byteOffset+O,v),at=new Uint8Array(n.buffer,n.byteOffset+W,F),V=new Uint8Array(n.buffer,n.byteOffset+Y,x);return e.globalData={endpointCount:y,selectorCount:_,imageDescs:w,endpointsData:X,selectorsData:Z,tablesData:at,extendedData:V},e}let fs,Ye,Ka;const Or={env:{emscripten_notify_memory_growth:function(n){Ka=new Uint8Array(Ye.exports.memory.buffer)}}};class tB{init(){return fs||(typeof fetch<"u"?fs=fetch("data:application/wasm;base64,"+bc).then(t=>t.arrayBuffer()).then(t=>WebAssembly.instantiate(t,Or)).then(this._init):fs=WebAssembly.instantiate(Buffer.from(bc,"base64"),Or).then(this._init),fs)}_init(t){Ye=t.instance,Or.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);Ka.set(t,s),e=e||Number(Ye.exports.ZSTD_findDecompressedSize(s,i));const r=Ye.exports.malloc(e),a=Ye.exports.ZSTD_decompress(r,e,s,i),o=Ka.slice(r,r+a);return Ye.exports.free(s),Ye.exports.free(r),o}}const bc="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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQh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ASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigC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C0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdB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IAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY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wOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEE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";class eB extends or{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,bf),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class iB extends or{constructor(t,e,i,s,r,a){super(t,e,i,r,a),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=kn}}var sB=Object.defineProperty,nB=(n,t,e)=>t in n?sB(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,rn=(n,t,e)=>(nB(n,typeof t!="symbol"?t+"":t,e),e);const TA=3e3,_A=3001,Fc="",rB="display-p3",aB="display-p3-linear",oB="srgb-linear",Uo="srgb",Gr=new WeakMap;let Ur=0,Nr;const No=(()=>{const n=class extends Ao{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new Hy,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(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}detectSupport(e){return this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},e.capabilities.isWebGL2&&(this.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){const e=new Hi(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const i=e.loadAsync("basis_transcoder.js"),s=new Hi(this.manager);s.setPath(this.transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const r=s.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([i,r]).then(([a,o])=>{const l=n.BasisWorker.toString(),c=["/* constants */","let _EngineFormat = "+JSON.stringify(n.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(n.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(n.BasisFormat),"/* basis_transcoder.js */",a,"/* worker */",l.substring(l.indexOf("{")+1,l.lastIndexOf("}"))].join(`
|
|
4
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([c])),this.transcoderBinary=o,this.workerPool.setWorkerCreator(()=>{const h=new Worker(this.workerSourceURL),u=this.transcoderBinary.slice(0);return h.postMessage({type:"init",config:this.workerConfig,transcoderBinary:u},[u]),h})}),Ur>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),Ur++}return this.transcoderPending}load(e,i,s,r){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const a=new Hi(this.manager);a.setResponseType("arraybuffer"),a.setWithCredentials(this.withCredentials),a.load(e,o=>{if(Gr.has(o))return Gr.get(o).promise.then(i).catch(r);this._createTexture(o).then(l=>i?i(l):null).catch(r)},s,r)}_createTextureFrom(e,i){const{faces:s,width:r,height:a,format:o,type:l,error:c,dfdFlags:h}=e;if(l==="error")return Promise.reject(c);let u;if(i.faceCount===6)u=new eB(s,o,ye);else{const d=s[0].mipmaps;u=i.layerCount>1?new iB(d,r,a,i.layerCount,o,ye):new or(d,r,a,o,ye)}u.minFilter=s[0].mipmaps.length===1?Gn:Hf,u.magFilter=Gn,u.generateMipmaps=!1,u.needsUpdate=!0;const A=vA(i);return"colorSpace"in u?u.colorSpace=A:u.encoding=A===Uo?_A:TA,u.premultiplyAlpha=!!(h&$y),u}async _createTexture(e,i={}){const s=Zy(new Uint8Array(e));if(s.vkFormat!==cA)return cB(s);const r=i,a=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:r},[e])).then(o=>this._createTextureFrom(o.data,s));return Gr.set(e,{promise:a}),a}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),Ur--,this}};let t=n;return rn(t,"BasisFormat",{ETC1S:0,UASTC_4x4:1}),rn(t,"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}),rn(t,"EngineFormat",{RGBAFormat:Ui,RGBA_ASTC_4x4_Format:Ff,RGBA_BPTC_Format:Mf,RGBA_ETC2_EAC_Format:Pf,RGBA_PVRTC_4BPPV1_Format:kf,RGBA_S3TC_DXT5_Format:Qf,RGB_ETC1_Format:Of,RGB_ETC2_Format:Gf,RGB_PVRTC_4BPPV1_Format:Uf,RGB_S3TC_DXT1_Format:Nf}),rn(t,"BasisWorker",function(){let e,i,s;const r=_EngineFormat,a=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",function(p){const m=p.data;switch(m.type){case"init":e=m.config,l(m.transcoderBinary);break;case"transcode":i.then(()=>{try{const{faces:C,buffers:E,width:S,height:y,hasAlpha:_,format:T,dfdFlags:v}=c(m.buffer);self.postMessage({type:"transcode",id:m.id,faces:C,width:S,height:y,hasAlpha:_,format:T,dfdFlags:v},E)}catch(C){console.error(C),self.postMessage({type:"error",id:m.id,error:C.message})}});break}});function l(p){i=new Promise(m=>{s={wasmBinary:p,onRuntimeInitialized:m},BASIS(s)}).then(()=>{s.initializeBasis(),s.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function c(p){const m=new s.KTX2File(new Uint8Array(p));function C(){m.close(),m.delete()}if(!m.isValid())throw C(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");const E=m.isUASTC()?o.UASTC_4x4:o.ETC1S,S=m.getWidth(),y=m.getHeight(),_=m.getLayers()||1,T=m.getLevels(),v=m.getFaces(),F=m.getHasAlpha(),x=m.getDFDFlags(),{transcoderFormat:w,engineFormat:U}=d(E,S,y,F);if(!S||!y||!T)throw C(),new Error("THREE.KTX2Loader: Invalid texture");if(!m.startTranscoding())throw C(),new Error("THREE.KTX2Loader: .startTranscoding failed");const O=[],W=[];for(let Y=0;Y<v;Y++){const X=[];for(let Z=0;Z<T;Z++){const at=[];let V,G;for(let J=0;J<_;J++){const K=m.getImageLevelInfo(Z,J,Y);Y===0&&Z===0&&J===0&&(K.origWidth%4!==0||K.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),T>1?(V=K.origWidth,G=K.origHeight):(V=K.width,G=K.height);const D=new Uint8Array(m.getImageTranscodedSizeInBytes(Z,J,0,w));if(!m.transcodeImage(D,Z,J,Y,w,0,-1,-1))throw C(),new Error("THREE.KTX2Loader: .transcodeImage failed.");at.push(D)}const H=g(at);X.push({data:H,width:V,height:G}),W.push(H.buffer)}O.push({mipmaps:X,width:S,height:y,format:U})}return C(),{faces:O,buffers:W,width:S,height:y,hasAlpha:F,format:U,dfdFlags:x}}const h=[{if:"astcSupported",basisFormat:[o.UASTC_4x4],transcoderFormat:[a.ASTC_4x4,a.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.BC7_M5,a.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.BC1,a.BC3],engineFormat:[r.RGB_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.ETC1,a.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.ETC1],engineFormat:[r.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[a.PVRTC1_4_RGB,a.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],u=h.sort(function(p,m){return p.priorityETC1S-m.priorityETC1S}),A=h.sort(function(p,m){return p.priorityUASTC-m.priorityUASTC});function d(p,m,C,E){let S,y;const _=p===o.ETC1S?u:A;for(let T=0;T<_.length;T++){const v=_[T];if(e[v.if]&&v.basisFormat.includes(p)&&!(E&&v.transcoderFormat.length<2)&&!(v.needsPowerOfTwo&&!(f(m)&&f(C))))return S=v.transcoderFormat[E?1:0],y=v.engineFormat[E?1:0],{transcoderFormat:S,engineFormat:y}}return console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."),S=a.RGBA32,y=r.RGBAFormat,{transcoderFormat:S,engineFormat:y}}function f(p){return p<=2?!0:(p&p-1)===0&&p!==0}function g(p){if(p.length===1)return p[0];let m=0;for(let S=0;S<p.length;S++){const y=p[S];m+=y.byteLength}const C=new Uint8Array(m);let E=0;for(let S=0;S<p.length;S++){const y=p[S];C.set(y,E),E+=y.byteLength}return C}}),t})(),lB=new Set([Ui,ys,Bs]),Hr={[yA]:Ui,[EA]:Ui,[fA]:Ui,[gA]:Ui,[IA]:ys,[pA]:ys,[AA]:ys,[dA]:ys,[CA]:Bs,[mA]:Bs,[uA]:Bs,[hA]:Bs,[SA]:hl,[BA]:hl},Kr={[yA]:_n,[EA]:vs,[fA]:ye,[gA]:ye,[IA]:_n,[pA]:vs,[AA]:ye,[dA]:ye,[CA]:_n,[mA]:vs,[uA]:ye,[hA]:ye,[SA]:ye,[BA]:ye};async function cB(n){const{vkFormat:t}=n;if(Hr[t]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let e;n.supercompressionScheme===wc&&(Nr||(Nr=new Promise(async a=>{const o=new tB;await o.init(),a(o)})),e=await Nr);const i=[];for(let a=0;a<n.levels.length;a++){const o=Math.max(1,n.pixelWidth>>a),l=Math.max(1,n.pixelHeight>>a),c=n.pixelDepth?Math.max(1,n.pixelDepth>>a):0,h=n.levels[a];let u;if(n.supercompressionScheme===oA)u=h.levelData;else if(n.supercompressionScheme===wc)u=e.decode(h.levelData,h.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let A;Kr[t]===_n?A=new Float32Array(u.buffer,u.byteOffset,u.byteLength/Float32Array.BYTES_PER_ELEMENT):Kr[t]===vs?A=new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT):A=u,i.push({data:A,width:o,height:l,depth:c})}let s;if(lB.has(Hr[t]))s=n.pixelDepth===0?new Kf(i[0].data,n.pixelWidth,n.pixelHeight):new Ny(i[0].data,n.pixelWidth,n.pixelHeight,n.pixelDepth);else{if(n.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");s=new or(i,n.pixelWidth,n.pixelHeight)}s.mipmaps=i,s.type=Kr[t],s.format=Hr[t],s.needsUpdate=!0;const r=vA(n);return"colorSpace"in s?s.colorSpace=r:s.encoding=r===Uo?_A:TA,Promise.resolve(s)}function vA(n){const t=n.dataFormatDescriptor[0];return t.colorPrimaries===lA?t.transferFunction===Ha?Uo:oB:t.colorPrimaries===Xy?t.transferFunction===Ha?rB:aB:(t.colorPrimaries===qy||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),Fc)}const Yr=new WeakMap;class hB extends Ao{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 Hi(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(t,a=>{const o={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(a,o).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(Yr.has(t)){const l=Yr.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++,a=t.byteLength,o=this._getWorker(r,a).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 o.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),Yr.set(t,{key:i,promise:o}),o}_createGeometry(t){const e=new Se;t.index&&e.setIndex(new Ra(t.index.array,1));for(let i=0;i<t.attributes.length;i++){const s=t.attributes[i],r=s.name,a=s.array,o=s.itemSize;e.setAttribute(r,new Ra(a,o))}return e}_loadLibrary(t,e){const i=new Hi(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=uB.toString(),a=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
|
|
5
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),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 a=r.data;switch(a.type){case"decode":s._callbacks[a.id].resolve(a);break;case"error":s._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.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 uB(){let n,t;onmessage=function(a){const o=a.data;switch(o.type){case"init":n=o.decoderConfig,t=new Promise(function(h){n.onModuleLoaded=function(u){h({draco:u})},DracoDecoderModule(n)});break;case"decode":const l=o.buffer,c=o.taskConfig;t.then(h=>{const u=h.draco,A=new u.Decoder,d=new u.DecoderBuffer;d.Init(new Int8Array(l),l.byteLength);try{const f=e(u,A,d,c),g=f.attributes.map(p=>p.array.buffer);f.index&&g.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},g)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{u.destroy(d),u.destroy(A)}});break}};function e(a,o,l,c){const h=c.attributeIDs,u=c.attributeTypes;let A,d;const f=o.GetEncodedGeometryType(l);if(f===a.TRIANGULAR_MESH)A=new a.Mesh,d=o.DecodeBufferToMesh(l,A);else if(f===a.POINT_CLOUD)A=new a.PointCloud,d=o.DecodeBufferToPointCloud(l,A);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!d.ok()||A.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[u[p]];let C,E;if(c.useUniqueIDs)E=h[p],C=o.GetAttributeByUniqueId(A,E);else{if(E=o.GetAttributeId(A,a[h[p]]),E===-1)continue;C=o.GetAttribute(A,E)}g.attributes.push(s(a,o,A,p,m,C))}return f===a.TRIANGULAR_MESH&&(g.index=i(a,o,A)),a.destroy(A),g}function i(a,o,l){const h=l.num_faces()*3,u=h*4,A=a._malloc(u);o.GetTrianglesUInt32Array(l,u,A);const d=new Uint32Array(a.HEAPF32.buffer,A,h).slice();return a._free(A),{array:d,itemSize:1}}function s(a,o,l,c,h,u){const A=u.num_components(),f=l.num_points()*A,g=f*h.BYTES_PER_ELEMENT,p=r(a,h),m=a._malloc(g);o.GetAttributeDataArrayForAllPoints(l,u,p,g,m);const C=new h(a.HEAPF32.buffer,m,f).slice();return a._free(m),{name:c,array:C,itemSize:A}}function r(a,o){switch(o){case Float32Array:return a.DT_FLOAT32;case Int8Array:return a.DT_INT8;case Int16Array:return a.DT_INT16;case Int32Array:return a.DT_INT32;case Uint8Array:return a.DT_UINT8;case Uint16Array:return a.DT_UINT16;case Uint32Array:return a.DT_UINT32}}}let an;const Vr=()=>{if(an)return an;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 a=WebAssembly.instantiate(o(s),{}).then(u=>{r=u.instance,r.exports.__wasm_call_ctors()});function o(u){const A=new Uint8Array(u.length);for(let f=0;f<u.length;++f){const g=u.charCodeAt(f);A[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<u.length;++f)A[d++]=A[f]<60?i[A[f]]:(A[f]-60)*64+A[++f];return A.buffer.slice(0,d)}function l(u,A,d,f,g,p){const m=r.exports.sbrk,C=d+3&-4,E=m(C*f),S=m(g.length),y=new Uint8Array(r.exports.memory.buffer);y.set(g,S);const _=u(E,d,f,S,g.length);if(_===0&&p&&p(E,C,f),A.set(y.subarray(E,E+d*f)),m(E-m(0)),_!==0)throw new Error(`Malformed buffer data: ${_}`)}const c={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},h={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return an={ready:a,supported:!0,decodeVertexBuffer(u,A,d,f,g){l(r.exports.meshopt_decodeVertexBuffer,u,A,d,f,r.exports[c[g]])},decodeIndexBuffer(u,A,d,f){l(r.exports.meshopt_decodeIndexBuffer,u,A,d,f)},decodeIndexSequence(u,A,d,f){l(r.exports.meshopt_decodeIndexSequence,u,A,d,f)},decodeGltfBuffer(u,A,d,f,g,p){l(r.exports[h[g]],u,A,d,f,r.exports[c[p]])}},an},AB=new k,dB=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 a=tu(r.getWorldPosition(AB),n,s.camera,s.size);r.scale.setScalar(a*n)}),B.createElement("object3D",wt({ref:i},t))});let on=null,xA="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function DA(n=!0,t=!0,e){return i=>{e&&e(i),n&&(on||(on=new hB),on.setDecoderPath(typeof n=="string"?n:xA),i.setDRACOLoader(on)),t&&i.setMeshoptDecoder(typeof Vr=="function"?Vr():Vr)}}const zs=(n,t,e,i)=>xe(fo,n,DA(t,e,i));zs.preload=(n,t,e,i)=>xe.preload(fo,n,DA(t,e,i));zs.clear=n=>xe.clear(fo,n);zs.setDecoderPath=n=>{xA=n};const fB=B.forwardRef(({src:n,useDraco:t,useMeshOpt:e,extendLoader:i,...s},r)=>{const{scene:a}=zs(n,t,e,i);return B.createElement(go,wt({ref:r},s,{object:a}))}),gB=B.forwardRef((n,t)=>{const{camera:e,onChange:i,makeDefault:s,...r}=n,a=q(A=>A.camera),o=q(A=>A.invalidate),l=q(A=>A.get),c=q(A=>A.set),h=e||a,u=B.useMemo(()=>new dy(h),[h]);return B.useEffect(()=>{const A=d=>{o(),i&&i(d)};return u==null||u.addEventListener==null||u.addEventListener("change",A),()=>u==null||u.removeEventListener==null?void 0:u.removeEventListener("change",A)},[i,u,o]),Ot(()=>u==null?void 0:u.update(),-1),B.useEffect(()=>{const A=u;return A==null||A.connect(),()=>A==null?void 0:A.dispose()},[u]),B.useEffect(()=>{if(s){const A=l().controls;return c({controls:u}),()=>c({controls:A})}},[s,u]),u?B.createElement("primitive",wt({ref:t,object:u},r)):null}),mB=B.forwardRef(({domElement:n,...t},e)=>{const{onChange:i,makeDefault:s,...r}=t,a=q(f=>f.invalidate),o=q(f=>f.camera),l=q(f=>f.gl),c=q(f=>f.events),h=q(f=>f.get),u=q(f=>f.set),A=n||c.connected||l.domElement,d=B.useMemo(()=>new By(o),[o]);return B.useEffect(()=>(d.connect(A),()=>void d.dispose()),[A,d,a]),B.useEffect(()=>{const f=g=>{a(),i&&i(g)};return d.addEventListener==null||d.addEventListener("change",f),()=>d.removeEventListener==null?void 0:d.removeEventListener("change",f)},[i,a]),B.useEffect(()=>{if(s){const f=h().controls;return u({controls:d}),()=>u({controls:f})}},[s,d]),Ot((f,g)=>d.update(g)),B.createElement("primitive",wt({ref:e,object:d,args:[o,A]},r))}),pB=B.forwardRef((n={enableDamping:!0},t)=>{const{domElement:e,camera:i,makeDefault:s,onChange:r,onStart:a,onEnd:o,...l}=n,c=q(C=>C.invalidate),h=q(C=>C.camera),u=q(C=>C.gl),A=q(C=>C.events),d=q(C=>C.set),f=q(C=>C.get),g=e||A.connected||u.domElement,p=i||h,m=B.useMemo(()=>new Yf(p),[p]);return B.useEffect(()=>{m.connect(g);const C=E=>{c(),r&&r(E)};return m.addEventListener("change",C),a&&m.addEventListener("start",a),o&&m.addEventListener("end",o),()=>{m.dispose(),m.removeEventListener("change",C),a&&m.removeEventListener("start",a),o&&m.removeEventListener("end",o)}},[r,a,o,m,c,g]),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))}),EB=B.forwardRef(({makeDefault:n,camera:t,domElement:e,regress:i,onChange:s,onStart:r,onEnd:a,...o},l)=>{const{invalidate:c,camera:h,gl:u,events:A,set:d,get:f,performance:g,viewport:p}=q(),m=t||h,C=e||A.connected||u.domElement,E=B.useMemo(()=>new my(m),[m]);return Ot(()=>{E.enabled&&E.update()},-1),B.useEffect(()=>(E.connect(C),()=>void E.dispose()),[C,i,E,c]),B.useEffect(()=>{const S=y=>{c(),i&&g.regress(),s&&s(y)};return E.addEventListener("change",S),r&&E.addEventListener("start",r),a&&E.addEventListener("end",a),()=>{r&&E.removeEventListener("start",r),a&&E.removeEventListener("end",a),E.removeEventListener("change",S)}},[s,r,a,E,c]),B.useEffect(()=>{E.handleResize()},[p]),B.useEffect(()=>{if(n){const S=f().controls;return d({controls:E}),()=>d({controls:S})}},[n,E]),B.createElement("primitive",wt({ref:l,object:E},o))}),CB=B.forwardRef(({camera:n,makeDefault:t,regress:e,domElement:i,onChange:s,onStart:r,onEnd:a,...o},l)=>{const c=q(E=>E.invalidate),h=q(E=>E.camera),u=q(E=>E.gl),A=q(E=>E.events),d=q(E=>E.set),f=q(E=>E.get),g=q(E=>E.performance),p=n||h,m=i||A.connected||u.domElement,C=B.useMemo(()=>new Cy(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=S=>{c(),e&&g.regress(),s&&s(S)};return C.addEventListener("change",E),r&&C.addEventListener("start",r),a&&C.addEventListener("end",a),()=>{C.removeEventListener("change",E),r&&C.removeEventListener("start",r),a&&C.removeEventListener("end",a)}},[s,r,a]),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},o))}),IB=B.forwardRef(({children:n,domElement:t,onChange:e,onMouseDown:i,onMouseUp:s,onObjectChange:r,object:a,makeDefault:o,camera:l,enabled:c,axis:h,mode:u,translationSnap:A,rotationSnap:d,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E,...S},y)=>{const _=q(H=>H.controls),T=q(H=>H.gl),v=q(H=>H.events),F=q(H=>H.camera),x=q(H=>H.invalidate),w=q(H=>H.get),U=q(H=>H.set),O=l||F,W=t||v.connected||T.domElement,Y=B.useMemo(()=>new iy(O,W),[O,W]),X=B.useRef(null);B.useLayoutEffect(()=>(a?Y.attach(a instanceof jt?a:a.current):X.current instanceof jt&&Y.attach(X.current),()=>void Y.detach()),[a,n,Y]),B.useEffect(()=>{if(_){const H=J=>_.enabled=!J.value;return Y.addEventListener("dragging-changed",H),()=>Y.removeEventListener("dragging-changed",H)}},[Y,_]);const Z=B.useRef(),at=B.useRef(),V=B.useRef(),G=B.useRef();return B.useLayoutEffect(()=>void(Z.current=e),[e]),B.useLayoutEffect(()=>void(at.current=i),[i]),B.useLayoutEffect(()=>void(V.current=s),[s]),B.useLayoutEffect(()=>void(G.current=r),[r]),B.useEffect(()=>{const H=et=>{x(),Z.current==null||Z.current(et)},J=et=>at.current==null?void 0:at.current(et),K=et=>V.current==null?void 0:V.current(et),D=et=>G.current==null?void 0:G.current(et);return Y.addEventListener("change",H),Y.addEventListener("mouseDown",J),Y.addEventListener("mouseUp",K),Y.addEventListener("objectChange",D),()=>{Y.removeEventListener("change",H),Y.removeEventListener("mouseDown",J),Y.removeEventListener("mouseUp",K),Y.removeEventListener("objectChange",D)}},[x,Y]),B.useEffect(()=>{if(o){const H=w().controls;return U({controls:Y}),()=>U({controls:H})}},[o,Y]),B.createElement(B.Fragment,null,B.createElement("primitive",{ref:y,object:Y,enabled:c,axis:h,mode:u,translationSnap:A,rotationSnap:d,scaleSnap:f,space:g,size:p,showX:m,showY:C,showZ:E}),B.createElement("group",wt({ref:X},S),n))}),yB=B.forwardRef(({domElement:n,selector:t,onChange:e,onLock:i,onUnlock:s,enabled:r=!0,makeDefault:a,...o},l)=>{const{camera:c,...h}=o,u=q(y=>y.setEvents),A=q(y=>y.gl),d=q(y=>y.camera),f=q(y=>y.invalidate),g=q(y=>y.events),p=q(y=>y.get),m=q(y=>y.set),C=c||d,E=n||g.connected||A.domElement,S=B.useMemo(()=>new hy(C),[C]);return B.useEffect(()=>{if(r){S.connect(E);const y=p().events.compute;return u({compute(_,T){const v=T.size.width/2,F=T.size.height/2;T.pointer.set(v/T.size.width*2-1,-(F/T.size.height)*2+1),T.raycaster.setFromCamera(T.pointer,T.camera)}}),()=>{S.disconnect(),u({compute:y})}}},[r,S]),B.useEffect(()=>{const y=v=>{f(),e&&e(v)};S.addEventListener("change",y),i&&S.addEventListener("lock",i),s&&S.addEventListener("unlock",s);const _=()=>S.lock(),T=t?Array.from(document.querySelectorAll(t)):[document];return T.forEach(v=>v&&v.addEventListener("click",_)),()=>{S.removeEventListener("change",y),i&&S.removeEventListener("lock",i),s&&S.removeEventListener("unlock",s),T.forEach(v=>v?v.removeEventListener("click",_):void 0)}},[e,i,s,t,S,f]),B.useEffect(()=>{if(a){const y=p().controls;return m({controls:S}),()=>m({controls:y})}},[a,S]),B.createElement("primitive",wt({ref:l,object:S},h))}),BB=B.forwardRef(({domElement:n,makeDefault:t,...e},i)=>{const s=q(u=>u.camera),r=q(u=>u.gl),a=q(u=>u.events),o=q(u=>u.get),l=q(u=>u.set),c=n||a.connected||r.domElement,[h]=B.useState(()=>new ZI(s,c));return B.useEffect(()=>{if(t){const u=o().controls;return l({controls:h}),()=>l({controls:u})}},[t,h]),Ot((u,A)=>{h.update(A)},-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}),Ri={NONE:0,IN:1,OUT:-1};function Ai(n){return n.isPerspectiveCamera}function ti(n){return n.isOrthographicCamera}const wi=Math.PI*2,Mc=Math.PI/2,RA=1e-5,gs=Math.PI/180;function Ce(n,t,e){return Math.max(t,Math.min(e,n))}function Dt(n,t=RA){return Math.abs(n)<t}function St(n,t,e=RA){return Dt(n-t,e)}function Pc(n,t){return Math.round(n/t)*t}function ms(n){return isFinite(n)?n:n<0?-Number.MAX_VALUE:Number.MAX_VALUE}function ps(n){return Math.abs(n)<Number.MAX_VALUE?n:n*(1/0)}function ln(n,t,e,i,s=1/0,r){i=Math.max(1e-4,i);const a=2/i,o=a*r,l=1/(1+o+.48*o*o+.235*o*o*o);let c=n-t;const h=t,u=s*i;c=Ce(c,-u,u),t=n-c;const A=(e.value+a*c)*r;e.value=(e.value-a*A)*l;let d=t+(c+A)*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,a){i=Math.max(1e-4,i);const o=2/i,l=o*r,c=1/(1+l+.48*l*l+.235*l*l*l);let h=t.x,u=t.y,A=t.z,d=n.x-h,f=n.y-u,g=n.z-A;const p=h,m=u,C=A,E=s*i,S=E*E,y=d*d+f*f+g*g;if(y>S){const Y=Math.sqrt(y);d=d/Y*E,f=f/Y*E,g=g/Y*E}h=n.x-d,u=n.y-f,A=n.z-g;const _=(e.x+o*d)*r,T=(e.y+o*f)*r,v=(e.z+o*g)*r;e.x=(e.x-o*_)*c,e.y=(e.y-o*T)*c,e.z=(e.z-o*v)*c,a.x=h+(d+_)*c,a.y=u+(f+T)*c,a.z=A+(g+v)*c;const F=p-n.x,x=m-n.y,w=C-n.z,U=a.x-p,O=a.y-m,W=a.z-C;return F*U+x*O+w*W>0&&(a.x=p,a.y=m,a.z=C,e.x=(a.x-p)/r,e.y=(a.y-m)/r,e.z=(a.z-C)/r),a}function Jr(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 zr(n,t){return ti(n)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}class SB{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,a=s.length;r<a;r++)s[r].call(this,t)}}}var $r;const TB="2.9.0",cn=1/8,_B=/Mac/.test(($r=globalThis==null?void 0:globalThis.navigator)===null||$r===void 0?void 0:$r.platform);let lt,Qc,hn,qr,Zt,mt,yt,Li,Es,De,Re,di,Oc,Gc,oe,Cs,bi,Uc,Xr,Nc,Wr,jr,un,Zr=class Ya extends SB{static install(t){lt=t.THREE,Qc=Object.freeze(new lt.Vector3(0,0,0)),hn=Object.freeze(new lt.Vector3(0,1,0)),qr=Object.freeze(new lt.Vector3(0,0,1)),Zt=new lt.Vector2,mt=new lt.Vector3,yt=new lt.Vector3,Li=new lt.Vector3,Es=new lt.Vector3,De=new lt.Vector3,Re=new lt.Vector3,di=new lt.Vector3,Oc=new lt.Vector3,Gc=new lt.Vector3,oe=new lt.Spherical,Cs=new lt.Spherical,bi=new lt.Box3,Uc=new lt.Box3,Xr=new lt.Sphere,Nc=new lt.Quaternion,Wr=new lt.Quaternion,jr=new lt.Matrix4,un=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=Ri.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 S,y;if(Ai(this._camera)){const _=mt.copy(this._camera.position).sub(this._target),T=this._camera.getEffectiveFOV()*gs,v=_.length()*Math.tan(T*.5);S=this.truckSpeed*m*v/this._elementRect.height,y=this.truckSpeed*C*v/this._elementRect.height}else if(ti(this._camera)){const _=this._camera;S=m*(_.right-_.left)/_.zoom/this._elementRect.width,y=C*(_.top-_.bottom)/_.zoom/this._elementRect.height}else return;this.verticalDragToForward?(E?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-y,!0)):E?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+y,this._focalOffsetEnd.z,!0):this.truck(S,y,!0)},this._rotateInternal=(m,C)=>{const E=wi*this.azimuthRotateSpeed*m/this._elementRect.height,S=wi*this.polarRotateSpeed*C/this._elementRect.height;this.rotate(E,S,!0)},this._dollyInternal=(m,C,E)=>{const S=Math.pow(.95,-m*this.dollySpeed),y=this._sphericalEnd.radius,_=this._sphericalEnd.radius*S,T=Ce(_,this.minDistance,this.maxDistance),v=T-_;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(_,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(v,!0),this._dollyToNoClamp(T,!0)):this._dollyToNoClamp(T,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?_:T)-y,this._dollyControlCoord.set(C,E)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,C,E)=>{const S=Math.pow(.95,m*this.dollySpeed),y=this._zoom,_=this._zoom*S;this.zoomTo(_,!0),this.dollyToCursor&&(this._changedZoom+=_-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,hn),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:Ai(this._camera)?Q.DOLLY:ti(this._camera)?Q.ZOOM:Q.NONE},this.touches={one:Q.TOUCH_ROTATE,two:Ai(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,a=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const S=this._domElement.getBoundingClientRect(),y=m.clientX/S.width,_=m.clientY/S.height;if(y<this._interactiveArea.left||y>this._interactiveArea.right||_<this._interactiveArea.top||_>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 S=this._findPointerByMouseButton(C);S&&this._disposePointer(S)}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",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,A(m)},o=m=>{m.cancelable&&m.preventDefault();const C=m.pointerId,E=this._lockedPointer||this._findPointerById(C);if(E){if(E.clientX=m.clientX,E.clientY=m.clientY,E.deltaX=m.movementX,E.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&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 _=this._domElement.getBoundingClientRect(),T=m.clientX/_.width,v=m.clientY/_.height;if(T<this._interactiveArea.left||T>this._interactiveArea.right||v<this._interactiveArea.top||v>this._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===Q.ROTATE||this.mouseButtons.wheel===Q.TRUCK){const _=performance.now();c-_<1e3&&this._getClientRect(this._elementRect),c=_}const C=_B?-1:-3,E=m.deltaMode===1?m.deltaY/C:m.deltaY/(C*10),S=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,S,y),this._isUserControllingDolly=!0;break}case Q.ZOOM:{this._zoomInternal(-E,S,y),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Ya.ACTION.NONE){const C=m instanceof PointerEvent?m.pointerId:0,E=this._findPointerById(C);E&&this._disposePointer(E),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},A=m=>{if(!this._enabled)return;if(Jr(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,S=Zt.y-this._activePointers[1].clientY,y=Math.sqrt(E*E+S*S);r.set(0,y);const _=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,T=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(_,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,Jr(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,S=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,S),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,_=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*S*cn,y,_),this._isUserControllingDolly=!0):(this._zoomInternal(T*S*cn,y,_),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,_=Zt.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+_*_),v=r.y-T;r.set(0,T);const F=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=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(v*cn,F,x),this._isUserControllingDolly=!0):(this._zoomInternal(v*cn,F,x),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,S,!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,S,!0),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{Jr(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",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",p),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),A())},this.unlockPointer=()=>{var m,C,E;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(C=this._domElement)===null||C===void 0||C.ownerDocument.removeEventListener("pointerlockchange",g),(E=this._domElement)===null||E===void 0||E.ownerDocument.removeEventListener("pointerlockerror",p),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},p=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",a),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",a),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",p))},this.cancel=()=>{this._state!==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 a=!i||St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(t,e=!1){return this.dollyTo(this._sphericalEnd.radius-t,e)}dollyTo(t,e=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Ri.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 a=this._collisionTest(),o=St(a,this._spherical.radius);if(!(i>t)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(t,a)}else this._sphericalEnd.radius=t;this._needsUpdate=!0,e||(this._spherical.radius=this._sphericalEnd.radius);const r=!e||St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(Es).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(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||St(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 a=!s||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(t,e,i,s=!1){const o=mt.set(t,e,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(t,e,{cover:i=!1,paddingLeft:s=0,paddingRight:r=0,paddingBottom:a=0,paddingTop:o=0}={}){const l=[],c=t.isBox3?bi.copy(t):bi.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),u=Pc(this._sphericalEnd.phi,Mc);l.push(this.rotateTo(h,u,e));const A=mt.setFromSpherical(this._sphericalEnd).normalize(),d=Nc.setFromUnitVectors(A,qr),f=St(Math.abs(A.y),1);f&&d.multiply(Wr.setFromAxisAngle(hn,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-=a,g.max.x+=r,g.max.y+=o,d.setFromUnitVectors(qr,A),f&&d.premultiply(Wr.invert()),d.premultiply(this._yAxisUpSpace);const p=g.getSize(mt),m=g.getCenter(yt).applyQuaternion(d);if(Ai(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,S=C.top-C.bottom,y=i?Math.max(E/p.x,S/p.y):Math.min(E/p.x,S/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?Ya.createBoundingSphere(t,Xr):Xr.copy(t);if(i.push(this.moveTo(r.center.x,r.center.y,r.center.z,e)),Ai(this._camera)){const a=this.getDistanceToFitSphere(r.radius);i.push(this.dollyTo(a,e))}else if(ti(this._camera)){const a=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*r.radius,c=Math.min(a/l,o/l);i.push(this.zoomTo(c,e))}return i.push(this.setFocalOffset(0,0,0,e)),Promise.all(i)}setLookAt(t,e,i,s,r,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ri.NONE,this._changedDolly=0;const l=yt.set(s,r,a),c=mt.set(t,e,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!o||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold)&&St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(t,e,i,s,r,a,o,l,c,h,u,A,d,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ri.NONE,this._changedDolly=0;const g=mt.set(s,r,a),p=yt.set(t,e,i);oe.setFromVector3(p.sub(g).applyQuaternion(this._yAxisUpSpace));const m=Li.set(h,u,A),C=yt.set(o,l,c);Cs.setFromVector3(C.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,d));const E=Cs.theta-oe.theta,S=Cs.phi-oe.phi,y=Cs.radius-oe.radius;this._sphericalEnd.set(oe.radius+y*d,oe.phi+S*d,oe.theta+E*d),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const _=!f||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold)&&St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(_)}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),a=this.setLookAt(r.x,r.y,r.z,t,e,i,s);return this._sphericalEnd.phi=Ce(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}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||St(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&St(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&St(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),a=s.sub(this._camera.position);De.multiplyScalar(a.x),Re.multiplyScalar(a.y),di.multiplyScalar(a.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(zr(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const r=t/e,a=this._camera.getEffectiveFOV()*gs,o=this._camera.aspect;return((s?r>o:r<o)?e:t/o)*.5/Math.tan(a*.5)+i*.5}getDistanceToFitSphere(t){if(zr(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*gs,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%wi,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=wi),this._spherical.theta+=wi*Math.round((this._sphericalEnd.theta-this._spherical.theta)/wi)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!St(this._camera.up.x,this._cameraUp0.x)||!St(this._camera.up.y,this._cameraUp0.y)||!St(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,hn),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),a=Gc.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Dt(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=ln(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,t),this._needsUpdate=!0}if(Dt(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=ln(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,t),this._needsUpdate=!0}if(Dt(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=ln(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,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 u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;kc(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(Dt(a.x)&&Dt(a.y)&&Dt(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;kc(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(Dt(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=ln(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,t)}if(this.dollyToCursor){if(Ai(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,A=this._camera,d=this._getCameraDirection(Es),f=mt.copy(d).cross(A.up).normalize();f.lengthSq()===0&&(f.x=1);const g=yt.crossVectors(f,d),p=this._sphericalEnd.radius*Math.tan(A.getEffectiveFOV()*gs*.5),C=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,E=Li.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*p*A.aspect)).add(g.multiplyScalar(this._dollyControlCoord.y*p)),S=mt.copy(this._targetEnd).lerp(E,C),y=this._lastDollyDirection===Ri.IN&&this._spherical.radius<=this.minDistance,_=this._lastDollyDirection===Ri.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(y||_)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const v=yt.copy(d).multiplyScalar(-u);S.add(v)}this._boundary.clampPoint(S,S);const T=yt.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(T),this._changedDolly-=u,Dt(this._changedDolly)&&(this._changedDolly=0)}else if(ti(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,A=this._camera,d=mt.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(A.near+A.far)/(A.near-A.far)).unproject(A),f=yt.set(0,0,-1).applyQuaternion(A.quaternion),g=Li.copy(d).add(f.multiplyScalar(-d.dot(A.up))),m=-(this._zoom-u-this._zoom)/this._zoom,C=this._getCameraDirection(Es),E=this._targetEnd.dot(C),S=mt.copy(this._targetEnd).lerp(g,m),y=S.dot(C),_=C.multiplyScalar(y-E);S.sub(_),this._boundary.clampPoint(S,S);const T=yt.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(T),this._changedZoom-=u,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(a.x,this.restThreshold)&&Dt(a.y,this.restThreshold)&&Dt(a.z,this.restThreshold)&&Dt(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!h&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=h,this._needsUpdate=!1,h}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:ms(this.maxDistance),minZoom:this.minZoom,maxZoom:ms(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:ms(this.maxPolarAngle),minAzimuthAngle:ms(this.minAzimuthAngle),maxAzimuthAngle:ms(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=ps(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=ps(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=ps(i.maxPolarAngle),this.minAzimuthAngle=ps(i.minAzimuthAngle),this.maxAzimuthAngle=ps(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),oe.setFromVector3(mt.fromArray(i.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(oe.theta,oe.phi,e),this.dollyTo(oe.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",TB),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),o=this._boundary.clampPoint(r,Li).sub(r),l=o.lengthSq();if(l===0)return t.add(e);if(l===s)return t;if(i===0)return t.add(e).add(o);{const c=1+i*l/e.dot(o);return t.add(yt.copy(e).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(Ai(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*gs,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,a=t.bottom*e;this._nearPlaneCorners[0].set(i,r,0),this._nearPlaneCorners[1].set(s,r,0),this._nearPlaneCorners[2].set(s,a,0),this._nearPlaneCorners[3].set(i,a,0)}}_collisionTest(){let t=1/0;if(!(this.colliderMeshes.length>=1)||zr(this._camera,"_collisionTest"))return t;const i=this._getTargetDirection(Es);jr.lookAt(Qc,i,this._camera.up);for(let s=0;s<4;s++){const r=yt.copy(this._nearPlaneCorners[s]);r.applyMatrix4(jr);const a=Li.addVectors(this._target,r);un.set(a,i),un.far=this._spherical.radius+1;const o=un.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance<t&&(t=o[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;bi.makeEmpty(),t.traverseVisible(a=>{a.isMesh&&bi.expandByObject(a)}),bi.getCenter(s);let r=0;return t.traverseVisible(a=>{if(!a.isMesh)return;const o=a,l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const h=l.attributes.position;for(let u=0,A=h.count;u<A;u++)mt.fromBufferAttribute(h,u),r=Math.max(r,s.distanceToSquared(mt))}),i.radius=Math.sqrt(r),i}};const vB=B.forwardRef((n,t)=>{B.useMemo(()=>{const y={Box3:jh,MathUtils:{clamp:ct.clamp},Matrix4:dt,Quaternion:It,Raycaster:ar,Sphere:uo,Spherical:oo,Vector2:Kt,Vector3:k,Vector4:_e};Zr.install({THREE:y}),mo({CameraControlsImpl:Zr})},[]);const{camera:e,domElement:i,makeDefault:s,onStart:r,onEnd:a,onChange:o,regress:l,...c}=n,h=q(y=>y.camera),u=q(y=>y.gl),A=q(y=>y.invalidate),d=q(y=>y.events),f=q(y=>y.setEvents),g=q(y=>y.set),p=q(y=>y.get),m=q(y=>y.performance),C=e||h,E=i||d.connected||u.domElement,S=B.useMemo(()=>new Zr(C),[C]);return Ot((y,_)=>{S.enabled&&S.update(_)},-1),B.useEffect(()=>(S.connect(E),()=>void S.disconnect()),[E,S]),B.useEffect(()=>{const y=v=>{A(),l&&m.regress(),o&&o(v)},_=v=>{r&&r(v)},T=v=>{a&&a(v)};return S.addEventListener("update",y),S.addEventListener("controlstart",_),S.addEventListener("controlend",T),S.addEventListener("control",y),S.addEventListener("transitionstart",y),S.addEventListener("wake",y),()=>{S.removeEventListener("update",y),S.removeEventListener("controlstart",_),S.removeEventListener("controlend",T),S.removeEventListener("control",y),S.removeEventListener("transitionstart",y),S.removeEventListener("wake",y)}},[S,r,a,A,f,l,o]),B.useEffect(()=>{if(s){const y=p().controls;return g({controls:S}),()=>g({controls:y})}},[s,S]),B.createElement("primitive",wt({ref:t,object:S},c))}),xB=n=>(n==null?void 0:n.current)instanceof jt,wA=B.createContext(null);function LA(){return B.useContext(wA)}function DB({points:n=50}){const{path:t}=LA(),[e,i]=B.useState([]),[s]=B.useState(()=>new ho({color:"black"})),[r]=B.useState(()=>new Wh(.025,16,16)),a=B.useRef([]);return B.useEffect(()=>{t.curves!==a.current&&(i(t.getPoints(n)),a.current=t.curves)}),B.createElement(B.Fragment,null,e.map((o,l)=>B.createElement("mesh",{key:l,material:s,geometry:r,position:[o.x,o.y,o.z]})))}const RB=B.forwardRef(({children:n,curves:t=[],object:e,debug:i=!1,smooth:s=!1,focus:r,offset:a=void 0,eps:o=1e-5,damping:l=.1,focusDamping:c=.1,maxSpeed:h=1/0,...u},A)=>{const{camera:d}=q(),f=B.useRef(),[g]=B.useState(()=>new Vf),p=B.useRef(a??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 S;g.curves=[];const y=t.length>0?t:(S=f.current)==null?void 0:S.__r3f.objects;for(var _=0;_<y.length;_++)g.add(y[_]);if(s){const T=g.getPoints(typeof s=="number"?s:1),v=new Jf(T);g.curves=[v]}g.updateArcLengths()}),B.useImperativeHandle(A,()=>f.current,[]),B.useLayoutEffect(()=>{p.current=Rr.repeat(p.current,1)},[a]);let C=0;const[E]=B.useState(()=>new k);return Ot((S,y)=>{if(C=m.offset,zi.damp(p,"current",a!==void 0?a:m.current,l,y,h,void 0,o),m.offset=Rr.repeat(p.current,1),g.getCurveLengths().length>0){g.getPointAt(m.offset,m.point),g.getTangentAt(m.offset,m.tangent).normalize(),g.getPointAt(Rr.repeat(p.current-(C-m.offset),1),m.next);const _=(e==null?void 0:e.current)instanceof jt?e.current:d;_.position.copy(m.point),r&&zi.dampLookAt(_,xB(r)?r.current.getWorldPosition(E):r,c,y,h,void 0,o)}}),B.createElement("group",wt({ref:f},u),B.createElement(wA.Provider,{value:m},n,i&&B.createElement(DB,null)))});function Ho(n,{path:t}){const[e]=xe(eu,[n],i=>i.setPath(t));return e}Ho.preload=(n,{path:t})=>xe.preload(eu,[n],e=>e.setPath(t));function wB({children:n,files:t,...e}){const i=Ho(t,{...e});return B.createElement(B.Fragment,null,n==null?void 0:n(i))}function mr(n){return xe(Go,n)}mr.preload=n=>xe.preload(Go,n);mr.clear=n=>xe.clear(Go,n);function LB({path:n,...t}){const i=mr(n).children[0];return B.createElement(go,wt({},t,{object:i}))}const bA="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master";function pr(n,t=`${bA}/basis/`){const e=q(s=>s.gl),i=xe(No,wa(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]),wa(n)){const s=Object.keys(n),r={};return s.forEach(a=>Object.assign(r,{[a]:i[s.indexOf(a)]})),r}else return i}pr.preload=(n,t=`${bA}/basis/`)=>xe.preload(No,n,e=>{e.setTranscoderPath(t)});pr.clear=n=>xe.clear(No,n);const bB=({children:n,input:t,basisPath:e})=>{const i=pr(t,e);return B.createElement(B.Fragment,null,n==null?void 0:n(i))};function FB(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var FA={exports:{}};(function(n,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var A=o.parseURL(c);if(!A)throw new Error("Error trying to parse relative URL.");if(A.scheme)return h.alwaysNormalize?(A.path=o.normalizePath(A.path),o.buildURLFromParts(A)):c;var d=o.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:A.netLoc,path:null,params:A.params,query:A.query,fragment:A.fragment};if(!A.netLoc&&(g.netLoc=d.netLoc,A.path[0]!=="/"))if(!A.path)g.path=d.path,A.params||(g.params=d.params,A.query||(g.query=d.query));else{var p=d.path,m=p.substring(0,p.lastIndexOf("/")+1)+A.path;g.path=o.normalizePath(m)}return g.path===null&&(g.path=h.alwaysNormalize?o.normalizePath(A.path):A.path),o.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(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(FA);var Ko=FA.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){kB(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 MB(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 PB(n){var t=MB(n,"string");return typeof t=="symbol"?t:String(t)}function kB(n,t,e){return t=PB(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)},QB=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=OB},OB=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}({}),rt=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(){},Va={trace:mi,debug:mi,log:mi,warn:mi,info:mi,error:mi};let Ls=Va;function GB(n){const t=self.console[n];return t?t.bind(self.console,`[${n}] >`):mi}function UB(n,...t){t.forEach(function(e){Ls[e]=n[e]?n[e].bind(n):GB(e)})}function NB(n,t){if(typeof console=="object"&&n===!0||typeof n=="object"){UB(n,"debug","log","info","warn","error");try{Ls.log(`Debug logs enabled for "${t}" in hls.js version 1.5.19`)}catch{Ls=Va}}else Ls=Va}const R=Ls,HB=/^(\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=HB.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 a=e[1].trim();i[a]=r}return i}}function KB(n){return n!=="ID"&&n!=="CLASS"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function YB(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"}class Yo{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 $s{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 vt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Vo{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[vt.AUDIO]:null,[vt.VIDEO]:null,[vt.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=Ko.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Dn extends Vo{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 $s,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,a=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:a};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[vt.AUDIO]=null,t[vt.VIDEO]=null,t[vt.AUDIOVIDEO]=null}}class MA extends Vo{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 $s,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 a=t.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}const VB=10;class PA{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||VB}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 Jo(n){return Uint8Array.from(atob(n),t=>t.charCodeAt(0))}function JB(n){const t=Ja(n).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function zB(n){const t=function(i,s,r){const a=i[s];i[s]=i[r],i[r]=a};t(n,0,3),t(n,1,2),t(n,4,5),t(n,6,7)}function $B(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",a=s[1];r?(i.splice(-1,1),e=Jo(a)):e=JB(a)}}return e}function Ja(n){return Uint8Array.from(unescape(encodeURIComponent(n)),t=>t.charCodeAt(0))}const qi=typeof self<"u"?self:void 0;var Bt={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 ta(n){switch(n){case Wt.FAIRPLAY:return Bt.FAIRPLAY;case Wt.PLAYREADY:return Bt.PLAYREADY;case Wt.WIDEVINE:return Bt.WIDEVINE;case Wt.CLEARKEY:return Bt.CLEARKEY}}var An={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function ea(n){if(n===An.WIDEVINE)return Bt.WIDEVINE;if(n===An.PLAYREADY)return Bt.PLAYREADY;if(n===An.CENC||n===An.CLEARKEY)return Bt.CLEARKEY}function ia(n){switch(n){case Bt.FAIRPLAY:return Wt.FAIRPLAY;case Bt.PLAYREADY:return Wt.PLAYREADY;case Bt.WIDEVINE:return Wt.WIDEVINE;case Bt.CLEARKEY:return Wt.CLEARKEY}}function dn(n){const{drmSystems:t,widevineLicenseUrl:e}=n,i=t?[Bt.FAIRPLAY,Bt.WIDEVINE,Bt.PLAYREADY,Bt.CLEARKEY].filter(s=>!!t[s]):[];return!i[Bt.WIDEVINE]&&e&&i.push(Bt.WIDEVINE),i}const kA=function(n){return qi!=null&&(n=qi.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function qB(n,t,e,i){let s;switch(n){case Bt.FAIRPLAY:s=["cenc","sinf"];break;case Bt.WIDEVINE:case Bt.PLAYREADY:s=["cenc"];break;case Bt.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return XB(s,t,e,i)}function XB(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 QA(n){const t=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),e=String.fromCharCode.apply(null,Array.from(t)),i=e.substring(e.indexOf("<"),e.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=Jo(o).subarray(0,16);return zB(l),l}}return null}function Ci(n,t,e){return Uint8Array.prototype.slice?n.slice(t,e):new Uint8Array(Array.prototype.slice.call(n,t,e))}const zo=(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,OA=(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,Us=(n,t)=>{const e=t;let i=0;for(;zo(n,t);){i+=10;const s=Er(n,t+6);i+=s,OA(n,t+10)&&(i+=10),t+=i}if(i>0)return n.subarray(e,e+i)},Er=(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},WB=(n,t)=>zo(n,t)&&Er(n,t+6)+10<=n.length-t,$o=n=>{const t=UA(n);for(let e=0;e<t.length;e++){const i=t[e];if(GA(i))return sS(i)}},GA=n=>n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp",jB=n=>{const t=String.fromCharCode(n[0],n[1],n[2],n[3]),e=Er(n,4),i=10;return{type:t,size:e,data:n.subarray(i,i+e)}},UA=n=>{let t=0;const e=[];for(;zo(n,t);){const i=Er(n,t+6);t+=10;const s=t+i;for(;t+8<s;){const r=jB(n.subarray(t)),a=ZB(r);a&&e.push(a),t+=r.size+10}OA(n,t)&&(t+=10)}return e},ZB=n=>n.type==="PRIV"?tS(n):n.type[0]==="W"?iS(n):eS(n),tS=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}},eS=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}},iS=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}},sS=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=nS();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,a,o="",l=0;for(;l<i;){if(s=n[l++],s===0&&t)return o;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:o+=String.fromCharCode(s);break;case 12:case 13:r=n[l++],o+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=n[l++],a=n[l++],o+=String.fromCharCode((s&15)<<12|(r&63)<<6|(a&63)<<0);break}}return o};let sa;function nS(){if(!navigator.userAgent.includes("PlayStation 4"))return!sa&&typeof self.TextDecoder<"u"&&(sa=new self.TextDecoder("utf-8")),sa}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,rS=[].push,NA={video:1,audio:2,id3:3,text:4};function Nt(n){return String.fromCharCode.apply(null,n)}function HA(n,t){const e=n[t]<<8|n[t+1];return e<0?65536+e:e}function st(n,t){const e=KA(n,t);return e<0?4294967296+e:e}function Yc(n,t){let e=st(n,t);return e*=Math.pow(2,32),e+=st(n,t+4),e}function KA(n,t){return n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3]}function na(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 aS(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),a=Nt(n.subarray(s+4,s+8)),o=r>1?s+r:i;if(a===t[0])if(t.length===1)e.push(n.subarray(s+8,o));else{const l=ft(n.subarray(s+8,o),t.slice(1));l.length&&rS.apply(e,l)}s=o}return e}function oS(n){const t=[],e=n[0];let i=8;const s=st(n,i);i+=4;let r=0,a=0;e===0?(r=st(n,i),a=st(n,i+4),i+=8):(r=Yc(n,i),a=Yc(n,i+8),i+=16),i+=2;let o=n.length+a;const l=HA(n,i);i+=2;for(let c=0;c<l;c++){let h=i;const u=st(n,h);h+=4;const A=u&2147483647;if((u&2147483648)>>>31===1)return R.warn("SIDX has hierarchical references (not supported)"),null;const f=st(n,h);h+=4,t.push({referenceSize:A,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+A-1}}),o+=A,h+=4,i=h}return{earliestPresentationTime:r,timescale:s,version:e,referencesCount:l,references:t}}function YA(n){const t=[],e=ft(n,["moov","trak"]);for(let s=0;s<e.length;s++){const r=e[s],a=ft(r,["tkhd"])[0];if(a){let o=a[0];const l=st(a,o===0?12:20),c=ft(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=st(c,o===0?12:20),u=ft(r,["mdia","hdlr"])[0];if(u){const A=Nt(u.subarray(8,12)),d={soun:vt.AUDIO,vide:vt.VIDEO}[A];if(d){const f=ft(r,["mdia","minf","stbl","stsd"])[0],g=lS(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),a=t[r];a&&(a.default={duration:st(s,12),flags:st(s,20)})}),t}function lS(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 o=ft(t,[i])[0].subarray(i==="enca"?28:78);ft(o,["sinf"]).forEach(c=>{const h=ft(c,["schm"])[0];if(h){const u=Nt(h.subarray(4,8));if(u==="cbcs"||u==="cenc"){const A=ft(c,["frma"])[0];A&&(s=Nt(A))}}})}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const a=ft(e,["avcC"])[0];s+="."+fn(a[1])+fn(a[2])+fn(a[3]);break}case"mp4a":{const a=ft(t,[i])[0],o=ft(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=ra(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=ra(o,l);const h=o[l++];if(h===64)s+="."+fn(h);else break;if(l+=12,o[l++]!==5)break;l=ra(o,l);const u=o[l++];let A=(u&248)>>3;A===31&&(A+=1+((u&7)<<3)+((o[l]&224)>>5)),s+="."+A}break}case"hvc1":case"hev1":{const a=ft(e,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,h=st(a,2),u=(o&32)>>5?"H":"L",A=a[12],d=a.subarray(6,12);s+="."+l+c,s+="."+h.toString(16).toUpperCase(),s+="."+u+A;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 a=ft(e,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;s+="."+we(o)+"."+we(l);break}case"vp09":{const a=ft(e,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;s+="."+we(o)+"."+we(l)+"."+we(c);break}case"av01":{const a=ft(e,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",h=(a[2]&64)>>6,u=(a[2]&32)>>5,A=o===2&&h?u?12:10:h?10:8,d=(a[2]&16)>>4,f=(a[2]&8)>>3,g=(a[2]&4)>>2,p=a[2]&3;s+="."+o+"."+we(l)+c+"."+we(A)+"."+d+"."+f+g+p+"."+we(1)+"."+we(1)+"."+we(1)+"."+0;break}}return{codec:s,encrypted:r}}function ra(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 cS(n,t){if(!n||!t)return n;const e=t.keyId;return e&&t.isCommonEncryption&&ft(n,["moov","trak"]).forEach(s=>{const a=ft(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=ft(a,["enca"]);const l=o.length>0;l||(o=ft(a,["encv"])),o.forEach(c=>{const h=l?c.subarray(28):c.subarray(78);ft(h,["sinf"]).forEach(A=>{const d=VA(A);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 VA(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 hS(n,t){return ft(t,["moof","traf"]).reduce((e,i)=>{const s=ft(i,["tfdt"])[0],r=s[0],a=ft(i,["tfhd"]).reduce((o,l)=>{const c=st(l,4),h=n[c];if(h){let u=st(s,4);if(r===1){if(u===qn)return R.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;u*=qn+1,u+=st(s,8)}const A=h.timescale||9e4,d=u/A;if(j(d)&&(o===null||d<o))return d}return o},null);return a!==null&&j(a)&&(e===null||a<e)?a:e},null)}function uS(n,t){let e=0,i=0,s=0;const r=ft(n,["moof","traf"]);for(let a=0;a<r.length;a++){const o=r[a],l=ft(o,["tfhd"])[0],c=st(l,4),h=t[c];if(!h)continue;const u=h.default,A=st(l,0)|(u==null?void 0:u.flags);let d=u==null?void 0:u.duration;A&8&&(A&2?d=st(l,12):d=st(l,8));const f=h.timescale||9e4,g=ft(o,["trun"]);for(let p=0;p<g.length;p++){if(e=AS(g[p]),!e&&d){const m=st(g[p],4);e=d*m}h.type===vt.VIDEO?i+=e/f:h.type===vt.AUDIO&&(s+=e/f)}}if(i===0&&s===0){let a=1/0,o=0,l=0;const c=ft(n,["sidx"]);for(let h=0;h<c.length;h++){const u=oS(c[h]);if(u!=null&&u.references){a=Math.min(a,u.earliestPresentationTime/u.timescale);const A=u.references.reduce((d,f)=>d+f.info.duration||0,0);o=Math.max(o,A+u.earliestPresentationTime/u.timescale),l=o-a}}if(l&&j(l))return l}return i||s}function AS(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 a=st(n,e);i+=a,e+=4}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4)}return i}function dS(n,t,e){ft(t,["moof","traf"]).forEach(i=>{ft(i,["tfhd"]).forEach(s=>{const r=st(s,4),a=n[r];if(!a)return;const o=a.timescale||9e4;ft(i,["tfdt"]).forEach(l=>{const c=l[0],h=e*o;if(h){let u=st(l,4);if(c===0)u-=h,u=Math.max(u,0),na(l,4,u);else{u*=Math.pow(2,32),u+=st(l,8),u-=h,u=Math.max(u,0);const A=Math.floor(u/(qn+1)),d=Math.floor(u%(qn+1));na(l,4,A),na(l,8,d)}}})})})}function fS(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 Vc(n,t){const e=[],i=t.samples,s=t.timescale,r=t.id;let a=!1;return ft(i,["moof"]).map(l=>{const c=l.byteOffset-8;ft(l,["traf"]).map(u=>{const A=ft(u,["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 A!==void 0&&(n=A),ft(u,["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 S=(g&16)!==0;let y=0;const _=(g&32)!==0;let T=8;f===r&&(p&&(T+=8),m&&(T+=4),C&&(E=st(d,T),T+=4),S&&(y=st(d,T),T+=4),_&&(T+=4),t.type==="video"&&(a=gS(t.codec)),ft(u,["trun"]).map(v=>{const F=v[0],x=st(v,0)&16777215,w=(x&1)!==0;let U=0;const O=(x&4)!==0,W=(x&256)!==0;let Y=0;const X=(x&512)!==0;let Z=0;const at=(x&1024)!==0,V=(x&2048)!==0;let G=0;const H=st(v,4);let J=8;w&&(U=st(v,J),J+=4),O&&(J+=4);let K=U+c;for(let D=0;D<H;D++){if(W?(Y=st(v,J),J+=4):Y=E,X?(Z=st(v,J),J+=4):Z=y,at&&(J+=4),V&&(F===0?G=st(v,J):G=KA(v,J),J+=4),t.type===vt.VIDEO){let et=0;for(;et<Z;){const ot=st(i,K);if(K+=4,mS(a,i[K])){const ht=i.subarray(K,K+ot);JA(ht,a?2:1,n+G/s,e)}K+=ot,et+=ot+4}}n+=Y/s}}))})})}),e}function gS(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 mS(n,t){if(n){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function JA(n,t,e,i){const s=zA(n);let r=0;r+=t;let a=0,o=0,l=0;for(;r<s.length;){a=0;do{if(r>=s.length)break;l=s[r++],a+=l}while(l===255);o=0;do{if(r>=s.length)break;l=s[r++],o+=l}while(l===255);const c=s.length-r;let h=r;if(o<c)r+=o;else if(o>c){R.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(s[h++]===181){const A=HA(s,h);if(h+=2,A===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 S=1;S<C;S++)E[S]=s[h++]}i.push({type:f,payloadType:a,pts:e,bytes:E})}}}}}else if(a===5&&o>16){const u=[];for(let f=0;f<16;f++){const g=s[h++].toString(16);u.push(g.length==1?"0"+g:g),(f===3||f===5||f===7||f===9)&&u.push("-")}const A=o-16,d=new Uint8Array(A);for(let f=0;f<A;f++)d[f]=s[h++];i.push({payloadType:a,pts:e,uuid:u.join(""),userData:Ge(d),userDataBytes:d})}}}function zA(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 a=0;for(i=0;i<s;a++,i++)a===e[0]&&(a++,e.shift()),r[i]=n[a];return r}function pS(n){const t=n[0];let e="",i="",s=0,r=0,a=0,o=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),o=st(n,20),l=st(n,24),c=28}else if(t===1){c+=4,s=st(n,c),c+=4;const u=st(n,c);c+=4;const A=st(n,c);for(c+=4,a=2**32*u+A,QB(a)||(a=Number.MAX_SAFE_INTEGER,R.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=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:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function ES(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 CS(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 a=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(a.buffer).setUint32(0,e.byteLength,!1),ES([112,115,115,104],new Uint8Array([i,0,0,0]),n,r,s,a,e||new Uint8Array)}function IS(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=yS(s);t.push(r),i+=r.size}}return t}function yS(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 a=n.buffer,o=Fe.hexDump(new Uint8Array(a,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(a,e+32,l)}else if(r===1){if(!l||i<e+32+l*16+16)return{offset:e,size:t};c=[];for(let u=0;u<l;u++)c.push(new Uint8Array(a,e+32+u*16,16))}return{version:r,systemId:o,kids:c,data:h,offset:e,size:t}}let gn={};class Xi{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=BS(t);return new Xi(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=$B(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=CS(i,null,e),this.keyId=QA(e);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 BS(n){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=n>>8*(15-e)&255;return t}const $A=/\{\$([a-zA-Z0-9-_]+)\}/g;function Jc(n){return $A.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]=za(n,r))}}function za(n,t){if(n.variableList!==null||n.hasVariableRefs){const e=n.variableList;return t.replace($A,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 zc(n,t,e){let i=n.variableList;i||(n.variableList=i={});let s,r;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const a=new self.URL(e).searchParams;if(a.has(s))r=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${e}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.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 SS(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 oi(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function TS(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 _S(n,t){const e=Xn[t];return!!e&&!!e[n.slice(0,4)]}function aa(n,t,e=!0){return!n.split(",").some(i=>!qA(i,t,e))}function qA(n,t,e=!0){var i;const s=oi(e);return(i=s==null?void 0:s.isTypeSupported(Ns(n,t)))!=null?i:!1}function Ns(n,t){return`${t}/mp4;codecs="${n}"`}function $c(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 oa={};function vS(n,t=!0){if(oa[n])return oa[n];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[n];for(let i=0;i<e.length;i++)if(qA(e[i],"audio",t))return oa[n]=e[i],e[i];return n}const xS=/flac|opus/i;function jn(n,t=!0){return n.replace(xS,e=>vS(e.toLowerCase(),t))}function qc(n,t){return n&&n!=="mp4a"?n:t&&t.split(",")[0]}function DS(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 Xc=/#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,Wc=/#EXT-X-MEDIA:(.*)/g,RS=/^#EXT(?:INF|-X-TARGETDURATION):/m,jc=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"),wS=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 Ko.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return RS.test(t)}static parseMasterPlaylist(t,e){const i=Jc(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];Xc.lastIndex=0;let a;for(;(a=Xc.exec(t))!=null;)if(a[1]){var o;const c=new bt(a[1]);te(s,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=za(s,a[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:ke.resolve(h,e)},A=c.decimalResolution("RESOLUTION");A&&(u.width=A.width,u.height=A.height),LS(c.CODECS,u),(o=u.unknownCodecs)!=null&&o.length||r.push(u),s.levels.push(u)}else if(a[3]){const c=a[3],h=a[4];switch(c){case"SESSION-DATA":{const u=new bt(h);te(s,u,["DATA-ID","LANGUAGE","VALUE","URI"]);const A=u["DATA-ID"];A&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[A]=u);break}case"SESSION-KEY":{const u=Zc(h,e,s);u.encrypted&&u.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(u)):R.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new bt(h);te(s,u,["NAME","VALUE","QUERYPARAM"]),zc(s,u,e)}break}case"CONTENT-STEERING":{const u=new bt(h);te(s,u,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:ke.resolve(u["SERVER-URI"],e),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=th(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={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Wc.lastIndex=0;(s=Wc.exec(t))!==null;){const c=new bt(s[1]),h=c.TYPE;if(h){const u=o[h],A=r[h]||[];r[h]=A,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),u!=null&&u.length){const E=ke.findGroup(u,C.groupId)||u[0];eh(C,E,"audioCodec"),eh(C,E,"textCodec")}A.push(C)}}return r}static parseLevelPlaylist(t,e,i,s,r,a){const o=new PA(e),l=o.fragments;let c=null,h=0,u=0,A=0,d=0,f=null,g=new Dn(s,e),p,m,C,E=-1,S=!1,y=null;for(jc.lastIndex=0,o.m3u8=t,o.hasVariableRefs=Jc(t);(p=jc.exec(t))!==null;){S&&(S=!1,g=new Dn(s,e),g.start=A,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 x=(" "+p[2]).slice(1);g.title=x||null,g.tagList.push(x?["INF",F,x]:["INF",F])}else if(p[3]){if(j(g.duration)){g.start=A,C&&nh(g,C,o),g.sn=h,g.level=i,g.cc=d,l.push(g);const x=(" "+p[3]).slice(1);g.relurl=za(o,x),ih(g,f),f=g,A+=g.duration,h++,u=0,S=!0}}else if(p[4]){const x=(" "+p[4]).slice(1);f?g.setByteRange(x,f):g.setByteRange(x)}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(wS),!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 x=(" "+p[m]).slice(1),w=(" "+p[m+1]).slice(1),U=p[m+2]?(" "+p[m+2]).slice(1):"";switch(x){case"PLAYLIST-TYPE":o.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(w);break;case"SKIP":{const O=new bt(w);te(o,O,["RECENTLY-REMOVED-DATERANGES"]);const W=O.decimalInteger("SKIPPED-SEGMENTS");if(j(W)){o.skippedSegments=W;for(let X=W;X--;)l.unshift(null);h+=W}const Y=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");Y&&(o.recentlyRemovedDateranges=Y.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(w),1);break;case"VERSION":o.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.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([x]);break;case"BITRATE":g.tagList.push([x,w]);break;case"DATERANGE":{const O=new bt(w);te(o,O,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),te(o,O,O.clientAttrs);const W=new Yo(O,o.dateRanges[O.ID]);W.isValid||o.skippedSegments?o.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(o,O,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in O?SS(o,O,a):zc(o,O,e)}break}case"DISCONTINUITY-SEQUENCE":d=parseInt(w);break;case"KEY":{const O=Zc(w,e,o);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":o.startTimeOffset=th(w);break;case"MAP":{const O=new bt(w);if(te(o,O,["BYTERANGE","URI"]),g.duration){const W=new Dn(s,e);sh(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 Y=g.byteRangeStartOffset;y=`${W-Y}@${Y}`}else y=null;sh(g,O,i,C),c=g,S=!0}break}case"SERVER-CONTROL":{const O=new bt(w);o.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),o.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const O=new bt(w);o.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=o.partList;O||(O=o.partList=[]);const W=u>0?O[O.length-1]:void 0,Y=u++,X=new bt(w);te(o,X,["BYTERANGE","URI"]);const Z=new MA(X,g,e,Y,W);O.push(Z),g.duration+=Z.duration;break}case"PRELOAD-HINT":{const O=new bt(w);te(o,O,["URI"]),o.preloadHint=O;break}case"RENDITION-REPORT":{const O=new bt(w);te(o,O,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(O);break}default:R.warn(`line parsed but not handled: ${p}`);break}}}f&&!f.relurl?(l.pop(),A-=f.duration,o.partList&&(o.fragmentHint=f)):o.partList&&(ih(g,f),g.cc=d,o.fragmentHint=g,C&&nh(g,C,o));const _=l.length,T=l[0],v=l[_-1];if(A+=o.skippedSegments*o.targetduration,A>0&&_&&v){o.averagetargetduration=A/_;const F=v.sn;o.endSN=F!=="initSegment"?F:0,o.live||(v.endList=!0),T&&(o.startCC=T.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(A+=o.fragmentHint.duration),o.totalduration=A,o.endCC=d,E>0&&bS(l,E),o}}function Zc(n,t,e){var i,s;const r=new bt(n);te(e,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(s=r.KEYFORMAT)!=null?s:"identity";o&&r.IV&&!l&&R.error(`Invalid IV: ${r.IV}`);const u=o?ke.resolve(o,t):"",A=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Xi(a,u,h,A,l)}function th(n){const e=new bt(n).decimalFloatingPoint("TIME-OFFSET");return j(e)?e:null}function LS(n,t){let e=(n||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=e.filter(r=>_S(r,i));s.length&&(t[`${i}Codec`]=s.join(","),e=e.filter(r=>s.indexOf(r)===-1))}),t.unknownCodecs=e}function eh(n,t,e){const i=t[e];i&&(n[e]=i)}function bS(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 ih(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 sh(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 nh(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"},it={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function rh(n){const{type:t}=n;switch(t){case Ct.AUDIO_TRACK:return it.AUDIO;case Ct.SUBTITLE_TRACK:return it.SUBTITLE;default:return it.MAIN}}function la(n,t){let e=n.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class FS{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,a=new r(e);return this.loaders[t.type]=a,a}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:a,deliveryDirectives:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:Ct.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:Ct.AUDIO_TRACK,url:r,deliveryDirectives:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:Ct.SUBTITLE_TRACK,url:r,deliveryDirectives:a})}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,u=c.targetduration;if(h&&u){const A=Math.max(h*3,u*.8)*1e3;r=Qt({},r,{maxTimeToFirstByteMs:Math.min(A,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(A,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,A)=>{const d=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=c.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,u,new Error("no EXTM3U delimiter"),A||null,h);return}h.parsing.start=performance.now(),ke.isMediaPlaylist(f)?this.handleTrackOrLevelPlaylist(c,h,u,A||null,d):this.handleMasterPlaylist(c,h,u,A)},onError:(c,h,u,A)=>{this.handleNetworkError(h,u,!1,c,A)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};s.load(t,o,l)}handleMasterPlaylist(t,e,i,s){const r=this.hls,a=t.data,o=la(t,i),l=ke.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}const{contentSteering:c,levels:h,sessionData:u,sessionKeys:A,startTimeOffset:d,variableList:f}=l;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=ke.parseMasterPlaylistMedia(a,o,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:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:A,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,s,r){const a=this.hls,{id:o,level:l,type:c}=i,h=la(t,i),u=0,A=j(l)?l:j(o)?o:0,d=rh(i),f=ke.parseLevelPlaylist(t.data,h,A,d,u,this.variableList);if(c===Ct.MANIFEST){const g={attrs:new bt({}),bitrate:0,details:f,name:"",url:h};a.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:rt.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 a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===Ct.LEVEL?a+=`: ${t.level} id: ${t.id}`:(t.type===Ct.AUDIO_TRACK||t.type===Ct.SUBTITLE_TRACK)&&(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);R.warn(`[playlist-loader]: ${a}`);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 u={type:rt.NETWORK_ERROR,details:l,fatal:c,url:t.url,loader:h,context:t,error:o,networkDetails:e,stats:r};if(s){const A=(e==null?void 0:e.url)||t.url;u.response=$t({url:A,data:void 0},s)}this.hls.trigger(I.ERROR,u)}handlePlaylistLoaded(t,e,i,s,r,a){const o=this.hls,{type:l,level:c,id:h,groupId:u,deliveryDirectives:A}=s,d=la(e,s),f=rh(s),g=typeof s.level=="number"&&f===it.MAIN?c:void 0;if(!t.fragments.length){const m=new Error("No Segments found in Playlist");o.trigger(I.ERROR,{type:rt.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){o.trigger(I.ERROR,{type:rt.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&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case Ct.MANIFEST:case Ct.LEVEL:o.trigger(I.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:A});break;case Ct.AUDIO_TRACK:o.trigger(I.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:A});break;case Ct.SUBTITLE_TRACK:o.trigger(I.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:A});break}}}function XA(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 WA(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 Ni(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 $a(n,t,e,i){const s=n.mode;if(s==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=PS(n.cues,t,e);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&n.removeCue(r[a])}s==="disabled"&&(n.mode=s)}function MS(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 PS(n,t,e){const i=[],s=MS(n,t);if(s>-1)for(let r=s,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=t&&o.endTime<=e)i.push(o);else if(o.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 Ae={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const kS=.25;function qa(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ah(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=qa();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ca(n,t){return n.getTime()/1e3-t}function QS(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class OS{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&&(Ni(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 XA(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 a=qa();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===Ae.emsg&&!i||!s)continue;const c=UA(r[o].data);if(c){const h=r[o].pts;let u=h+r[o].duration;u>mn&&(u=mn),u-h<=0&&(u=h+kS);for(let d=0;d<c.length;d++){const f=c[d];if(!GA(f)){this.updateId3CueEnds(h,l);const g=ah(a,h,u,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 a=s[r];a.type===e&&a.startTime<t&&a.endTime===mn&&(a.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;s==="audio"?c=h=>h.type===Ae.audioId3&&l:s==="video"?c=h=>h.type===Ae.emsg&&o:c=h=>h.type===Ae.audioId3&&l||h.type===Ae.emsg&&o,$a(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,a=Object.keys(r);if(s){const h=Object.keys(i).filter(u=>!a.includes(u));for(let u=h.length;u--;){const A=h[u];Object.keys(i[A].cues).forEach(d=>{s.removeCue(i[A].cues[d])}),delete i[A]}}const o=e.fragments[e.fragments.length-1];if(a.length===0||!j(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=qa();for(let h=0;h<a.length;h++){const u=a[h],A=r[u],d=ca(A.startDate,l),f=i[u],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1,m=mn;const C=A.endDate;if(C)m=ca(C,l),p=!0;else if(A.endOnNext&&!p){const S=a.reduce((y,_)=>{if(_!==A.id){const T=r[_];if(T.class===A.class&&T.startDate>A.startDate&&(!y||A.startDate<y.startDate))return T}return y},null);S&&(m=ca(S.startDate,l),p=!0)}const E=Object.keys(A.attr);for(let S=0;S<E.length;S++){const y=E[S];if(!KB(y))continue;const _=g[y];if(_)p&&!f.durationKnown&&(_.endTime=m);else if(c){let T=A.attr[y];YB(y)&&(T=QS(T));const v=ah(c,d,m,{key:y,data:T},Ae.dateRange);v&&(v.id=u,this.id3Track.addCue(v),g[y]=v)}}i[u]={cues:g,dateRange:A,durationKnown:p}}}}class GS{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:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||e;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*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,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}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 a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+e.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(h,Math.max(1,u))}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 Xa=["NONE","TYPE-0","TYPE-1",null];function US(n){return Xa.indexOf(n)>-1}const Zn=["SDR","PQ","HLG"];function NS(n){return!!n&&Zn.indexOf(n)>-1}var bs={No:"",Yes:"YES",v2:"v2"};function oh(n){const{canSkipUntil:t,canSkipDateRanges:e,age:i}=n,s=i<t/2;return t&&s?e?bs.v2:bs.Yes:bs.No}class Wa{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 lh(this._audioGroups,t)}hasSubtitleGroup(t){return lh(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 lh(n,t){return!t||!n?!1:n.indexOf(t)!==-1}function ha(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 jA(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 o=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,o=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 u=e-t.start;t.start!==0&&(t.start=e),t.duration=i-t.start,t.startPTS=e,t.maxStartPTS=o,t.startDTS=s,t.endPTS=i,t.minEndPTS=l,t.endDTS=r;const A=t.sn;if(!n||A<n.startSN||A>n.endSN)return 0;let d;const f=A-n.startSN,g=n.fragments;for(g[f]=t,d=f;d>0;d--)ha(g[d],g[d-1]);for(d=f;d<g.length-1;d++)ha(g[d],g[d+1]);return n.fragmentHint&&ha(g[g.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,u}function HS(n,t){let e=null;const i=n.fragments;for(let o=i.length-1;o>=0;o--){const l=i[o].initSegment;if(l){e=l;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let s;VS(n,t,(o,l,c,h)=>{if(t.skippedSegments&&l.cc!==o.cc){const u=o.cc-l.cc;for(let A=c;A<h.length;A++)h[A].cc+=u}j(o.startPTS)&&j(o.endPTS)&&(l.start=l.startPTS=o.startPTS,l.startDTS=o.startDTS,l.maxStartPTS=o.maxStartPTS,l.endPTS=o.endPTS,l.endDTS=o.endDTS,l.minEndPTS=o.minEndPTS,l.duration=o.endPTS-o.startPTS,l.duration&&(s=l),t.PTSKnown=t.alignedSliding=!0),l.elementaryStreams=o.elementaryStreams,l.loader=o.loader,l.stats=o.stats,o.initSegment&&(l.initSegment=o.initSegment,e=o.initSegment)});const r=t.fragments;if(e&&(t.fragmentHint?r.concat(t.fragmentHint):r).forEach(l=>{var c;l&&(!l.initSegment||l.initSegment.relurl===((c=e)==null?void 0:c.relurl))&&(l.initSegment=e)}),t.skippedSegments){if(t.deltaUpdateFailed=r.some(o=>!o),t.deltaUpdateFailed){R.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let o=t.skippedSegments;o--;)r.shift();t.startSN=r[0].sn}else t.canSkipDateRanges&&(t.dateRanges=KS(n.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));t.startCC=t.fragments[0].cc,t.endCC=r[r.length-1].cc}YS(n.partList,t.partList,(o,l)=>{l.elementaryStreams=o.elementaryStreams,l.stats=o.stats}),s?jA(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):ZA(n,t),r.length&&(t.totalduration=t.edge-r[0].start),t.driftStartTime=n.driftStartTime,t.driftStart=n.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const o=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=o),t.driftEndTime=a,t.driftEnd=o}else t.driftEndTime=n.driftEndTime,t.driftEnd=n.driftEnd,t.advancedDateTime=n.advancedDateTime}function KS(n,t,e){const i=Qt({},n);return e&&e.forEach(s=>{delete i[s]}),Object.keys(t).forEach(s=>{const r=new Yo(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 YS(n,t,e){if(n&&t){let i=0;for(let s=0,r=n.length;s<=r;s++){const a=n[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?e(a,o):i--}}}function VS(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,a=t.startSN-n.startSN,o=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[a+c];let u=o[c];i&&!u&&c<i&&(u=t.fragments[c]=h),h&&u&&e(h,u,c,o)}}function ZA(n,t){const e=t.startSN+t.skippedSegments-n.startSN,i=n.fragments;e<0||e>=i.length||ja(t,i[e].start)}function ja(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 JS(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 zS(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 ch(n,t,e){var i;return n!=null&&n.details?td((i=n.details)==null?void 0:i.partList,t,e):null}function td(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 ed(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 hh(n,t){const e=tr(t);return n.default[`${e?"timeout":"error"}Retry`]}function qo(n,t){const e=n.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*n.retryDelayMs,n.maxRetryDelayMs)}function uh(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&&($S(s)||!!e);return n.shouldRetry?n.shouldRetry(n,t,e,i,r):r}function $S(n){return n===0&&navigator.onLine===!1||!!n&&(n<400||n>499)}const id={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 a=t(r);if(a>0)e=s+1;else if(a<0)i=s-1;else return r}return null}};function qS(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 a=n[r];if(WS(t,e,a))return a}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 o=n.endDTS-e;o>0&&o<15e-7&&(e+=15e-7)}else e===0&&t[0].start===0&&(r=t[0]);if(r&&((!n||n.level===r.level)&&Za(e,i,r)===0||XS(r,n,Math.min(s,i))))return r;const a=id.search(t,Za.bind(null,e,i));return a&&(a!==n||!r)?a:r}function XS(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 Za(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 WS(n,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>n}function jS(n,t){return id.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 sd{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)===it.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,a=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 o,l;const c=e.parent===it.MAIN?e.level:r.loadLevel;e.details===M.LEVEL_EMPTY_ERROR&&((o=e.context)!=null&&(l=o.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(a==null?void 0:a.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.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(a){const c=r.levels[r.loadLevel];if(c&&(a.type===Ct.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===Ct.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.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===rt.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=hh(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 o=this.getLevelSwitchAction(t,e);return s&&(o.retryConfig=s,o.retryCount=r),o}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=hh(t.details.startsWith("key")?a:r,t),l=e.levels.reduce((h,u)=>h+u.fragmentError,0);if(s&&(t.details!==M.FRAG_GAP&&s.fragmentError++,er(o,l,tr(t),t.response)))return{action:Ht.RetryRequest,flags:ce.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(t,i);return o&&(c.retryConfig=o,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,a;const c=t.details;s.loadError++,c===M.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:u,loadLevel:A,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(r=t.frag)==null?void 0:r.type,m=(g===it.AUDIO&&c===M.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(c===M.BUFFER_ADD_CODEC_ERROR||c===M.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:_})=>s.audioCodec!==_),E=t.sourceBufferName==="video"&&(c===M.BUFFER_ADD_CODEC_ERROR||c===M.BUFFER_APPEND_ERROR)&&u.some(({codecSet:_,audioCodec:T})=>s.codecSet!==_&&s.audioCodec===T),{type:S,groupId:y}=(a=t.context)!=null?a:{};for(let _=u.length;_--;){const T=(_+A)%u.length;if(T!==A&&T>=d&&T<=f&&u[T].loadError===0){var o,l;const v=u[T];if(c===M.FRAG_GAP&&g===it.MAIN&&t.frag){const F=u[T].details;if(F){const x=ir(t.frag,F.fragments,t.frag.start);if(x!=null&&x.gap)continue}}else{if(S===Ct.AUDIO_TRACK&&v.hasAudioGroup(y)||S===Ct.SUBTITLE_TRACK&&v.hasSubtitleGroup(y))continue;if(g===it.AUDIO&&(o=s.audioGroups)!=null&&o.some(F=>v.hasAudioGroup(F))||g===it.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(F=>v.hasSubtitleGroup(F))||m&&s.audioCodec===v.audioCodec||!m&&s.audioCodec!==v.audioCodec||E&&s.codecSet===v.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:a}=i;switch(s){case ce.None:this.switchLevel(t,a);break;case ce.MoveAllAlternatesMatchingHDCP:r&&(e.maxHdcpLevel=Xa[Xa.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(t,a)}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 Cr{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 a=0;a<s.length;a++){const o=s[a];let l;try{l=new self.URL(o.URI,e.url).href}catch(c){R.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===t){r=a;break}else l===t.substring(0,l.length)&&(r=a)}if(r!==-1){const a=s[r],o=parseInt(a["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let l=parseInt(a["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&&oh(i);return new Wa(o,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,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;if(s.advancedDateTime=Date.now()-o,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&&HS(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,S=E!==-1,y=m===C,_=p?0:E;S?(c=y?C+1:m,h=y?_:E+1):c=C+1;const T=s.age,v=T+s.ageHeader;let F=Math.min(v-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 x=Math.floor(F/s.targetduration);if(c+=x,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 ${x} 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 u=this.hls.mainForwardBufferInfo,A=u?u.end-u.len:0,d=(s.edge-A)*1e3,f=JS(s,d);s.updated&&a>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<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=f);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${t} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(t,e,i,s){let r=oh(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=bs.No),new Wa(i,s,r)}checkRetry(t){const e=t.details,i=tr(t),s=t.errorAction,{action:r,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(r===Ht.RetryRequest||!s.resolved&&r===Ht.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=t.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const h=qo(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" in ${h}ms`)}t.levelRetry=!0,s.resolved=!0}return l}}class Fi{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 ZS{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 Fi(t),this.fast_=new Fi(e),this.defaultTTFB_=s,this.ttfb_=new Fi(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new Fi(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Fi(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Fi(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 nd={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Ah={};function tT(n,t,e,i,s,r){const a=n.audioCodec?n.audioGroups:null,o=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,c=l?parseInt(l):o?1/0:2;let h=null;if(a!=null&&a.length)try{a.length===1&&a[0]?h=t.groups[a[0]].channels:h=a.reduce((u,A)=>{if(A){const d=t.groups[A];if(!d)throw new Error(`Audio track group ${A} not found`);Object.keys(d.channels).forEach(f=>{u[f]=(u[f]||0)+d.channels[f]})}return u},{2:0})}catch{return!0}return n.videoCodec!==void 0&&(n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(i,30)||n.videoRange!=="SDR"&&n.videoRange!==e||n.bitrate>Math.max(s,8e6))||!!h&&j(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function eT(n,t,e){const i=n.videoCodec,s=n.audioCodec;if(!i||!s||!e)return Promise.resolve(nd);const r={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)),framerate:n.frameRate||30},a=n.videoRange;a!=="SDR"&&(r.transferFunction=a.toLowerCase());const o=i.split(",").map(l=>({type:"media-source",video:$t($t({},r),{},{contentType:Ns(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 u=h.channels||"",A=parseFloat(u);j(A)&&A>2&&o.push.apply(o,s.split(",").map(d=>({type:"media-source",audio:{contentType:Ns(d,"audio"),channels:""+A}})))}}))}),Promise.all(o.map(l=>{const c=iT(l);return Ah[c]||(Ah[c]=e.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function iT(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 sT(){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 nT(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:sT(),e?i=i.filter(s=>s!=="SDR"):i=["SDR"]),{preferHDR:e,allowedVideoRanges:i}}function rT(n,t,e,i,s){const r=Object.keys(n),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2;let c=!0,h=!1,u=1/0,A=1/0,d=1/0,f=0,g=[];const{preferHDR:p,allowedVideoRanges:m}=nT(t,s);for(let y=r.length;y--;){const _=n[r[y]];c=_.channels[2]>0,u=Math.min(u,_.minHeight),A=Math.min(A,_.minFramerate),d=Math.min(d,_.minBitrate);const T=m.filter(v=>_.videoRanges[v]>0);T.length>0&&(h=!0,g=T)}u=j(u)?u:0,A=j(A)?A:0;const C=Math.max(1080,u),E=Math.max(30,A);return d=j(d)?d:e,e=Math.max(d,e),h||(t=void 0,g=[]),{codecSet:r.reduce((y,_)=>{const T=n[_];if(_===y)return y;if(T.minBitrate>e)return He(_,`min bitrate of ${T.minBitrate} > current estimate of ${e}`),y;if(!T.hasDefaultAudio)return He(_,"no renditions with default or auto-select sound found"),y;if(o&&_.indexOf(o.substring(0,4))%5!==0)return He(_,`audio codec preference "${o}" not found`),y;if(a&&!l){if(!T.channels[a])return He(_,`no renditions with ${a} channel sound found (channels options: ${Object.keys(T.channels)})`),y}else if((!o||l)&&c&&T.channels[2]===0)return He(_,"no renditions with stereo sound found"),y;return T.minHeight>C?(He(_,`min resolution of ${T.minHeight} > maximum of ${C}`),y):T.minFramerate>E?(He(_,`min framerate of ${T.minFramerate} > maximum of ${E}`),y):g.some(v=>T.videoRanges[v]>0)?T.maxScore<f?(He(_,`max score of ${T.maxScore} < selected max of ${f}`),y):y&&(Wn(_)>=Wn(y)||T.fragmentError>n[y].fragmentError)?y:(f=T.maxScore,_):(He(_,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),y)},void 0),videoRanges:g,preferHDR:p,minFramerate:A,minBitrate:d}}function He(n,t){R.log(`[abr] start candidates with "${n}" ignored because ${t}`)}function aT(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 oT(n,t,e,i){return n.slice(e,i+1).reduce((s,r)=>{if(!r.codecSet)return s;const a=r.audioGroups;let o=s[r.codecSet];o||(s[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,r.frameRate),o.maxScore=Math.max(o.maxScore,r.score),o.fragmentError+=r.fragmentError,o.videoRanges[r.videoRange]=(o.videoRanges[r.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const h=t.groups[c];h&&(o.hasDefaultAudio=o.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{o.channels[u]=(o.channels[u]||0)+h.channels[u]}))}),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(Ji(n,s,e))return i}return-1}function Ji(n,t,e){const{groupId:i,name:s,lang:r,assocLang:a,characteristics:o,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===a)&&(l===void 0||t.default===l)&&(c===void 0||t.forced===c)&&(o===void 0||lT(o,t.characteristics))&&(e===void 0||e(n,t))}function lT(n,t=""){const e=n.split(","),i=t.split(",");return e.length===i.length&&!e.some(s=>i.indexOf(s)===-1)}function Mi(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 cT(n,t,e,i,s){const r=t[i],o=t.reduce((A,d,f)=>{const g=d.uri;return(A[g]||(A[g]=[])).push(f),A},{})[r.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=dh(t,i,A=>{if(A.videoRange!==l||A.frameRate!==c||A.codecSet.substring(0,4)!==h)return!1;const d=A.audioGroups,f=e.filter(g=>!d||d.indexOf(g.groupId)!==-1);return Qe(n,f,s)>-1});return u>-1?u:dh(t,i,A=>{const d=A.audioGroups,f=e.filter(g=>!d||d.indexOf(g.groupId)!==-1);return Qe(n,f,s)>-1})}function dh(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 rd{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:a}=s;if(!e||!a)return;const o=performance.now(),l=i?i.stats:e.stats,c=i?i.duration:e.duration,h=o-l.loading.start,u=s.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||e.level<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||a.paused||!a.playbackRate||!a.readyState)return;const A=s.mainForwardBufferInfo;if(A===null)return;const d=this.bwEstimator.getEstimateTTFB(),f=Math.abs(a.playbackRate);if(h<=Math.max(d,1e3*(c/(f*2))))return;const g=A.len/f,p=l.loading.first?l.loading.first-l.loading.start:-1,m=l.loaded&&p>-1,C=this.getBwEstimate(),E=s.levels,S=E[e.level],y=l.total||Math.max(l.loaded,Math.round(c*S.averageBitrate/8));let _=m?h-p:h;_<1&&m&&(_=Math.min(h,l.loaded*8/C));const T=m?l.loaded*1e3/_:0,v=T?(y-l.loaded)/T:y*8/C+d/1e3;if(v<=g)return;const F=T?T*8:C;let x=Number.POSITIVE_INFINITY,w;for(w=e.level-1;w>u;w--){const O=E[w].maxBitrate;if(x=this.getTimeToLoadFrag(d/1e3,F,c*O,!E[w].details),x<g)break}if(x>=v||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: ${v.toFixed(3)} s
|
|
13
|
+
Estimated load time for down switch fragment: ${x.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 ZS(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 a=performance.now(),o=r?r.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,i,s){const r=t+i/e,a=s?this.lastLevelLoadSec:0;return r+a}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===it.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,a=this.hls.levels[e.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/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 a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==it.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 a=this.hls.firstLevel,o=Math.min(Math.max(a,e),t);return R.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const 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 a=this.hls.levels;if(a.length>Math.max(t,r)&&a[t].loadError<=a[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:a}=i,o=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const p=this.findBestLevel(l,a,s,c,0,h,u);if(p>=0)return p}let A=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const p=this.bitrateTestDelay;p&&(A=(o?Math.min(o,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*A)} ms`),h=u=1)}const d=this.findBestLevel(l,a,s,c,A,h,u);if(R.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`),d>-1)return d;const f=i.levels[a],g=i.levels[i.loadLevel];return(f==null?void 0:f.bitrate)<(g==null?void 0:g.bitrate)?a: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,a,o){var l;const c=s+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:A,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(f.length===1)return 0;const C=f[u],E=!!(C!=null&&(l=C.details)!=null&&l.live),S=p===-1||h===-1;let y,_="SDR",T=(C==null?void 0:C.frameRate)||0;const{audioPreference:v,videoPreference:F}=m,x=this.audioTracksByGroup||(this.audioTracksByGroup=aT(g));if(S){if(this.firstSelection!==-1)return this.firstSelection;const Y=this.codecTiers||(this.codecTiers=oT(f,x,e,i)),X=rT(Y,_,t,v,F),{codecSet:Z,videoRanges:at,minFramerate:V,minBitrate:G,preferHDR:H}=X;y=Z,_=H?at[at.length-1]:at[0],T=V,t=Math.max(t,G),R.log(`[abr] picked start tier ${JSON.stringify(X)}`)}else y=C==null?void 0:C.codecSet,_=C==null?void 0:C.videoRange;const w=d?d.duration:A?A.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let Y=i;Y>=e;Y--){var W;const X=f[Y],Z=Y>u;if(!X)continue;if(m.useMediaCapabilities&&!X.supportedResult&&!X.supportedPromise){const D=navigator.mediaCapabilities;typeof(D==null?void 0:D.decodingInfo)=="function"&&tT(X,x,_,T,t,v)?(X.supportedPromise=eT(X,x,D),X.supportedPromise.then(et=>{if(!this.hls)return;X.supportedResult=et;const ot=this.hls.levels,ht=ot.indexOf(X);et.error?R.warn(`[abr] MediaCapabilities decodingInfo error: "${et.error}" for level ${ht} ${JSON.stringify(et)}`):et.supported||(R.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${ht} ${JSON.stringify(et)}`),ht>-1&&ot.length>1&&(R.log(`[abr] Removing unsupported level ${ht}`),this.hls.removeLevel(ht)))})):X.supportedResult=nd}if(y&&X.codecSet!==y||_&&X.videoRange!==_||Z&&T>X.frameRate||!Z&&T>0&&T<X.frameRate||X.supportedResult&&!((W=X.supportedResult.decodingInfoResults)!=null&&W[0].smooth)){O.push(Y);continue}const at=X.details,V=(d?at==null?void 0:at.partTarget:at==null?void 0:at.averagetargetduration)||w;let G;Z?G=o*t:G=a*t;const H=w&&s>=w*2&&r===0?f[Y].averageBitrate:f[Y].maxBitrate,J=this.getTimeToLoadFrag(U,G,H*V,at===void 0);if(G>=H&&(Y===h||X.loadError===0&&X.fragmentError===0)&&(J<=U||!j(J)||E&&!this.bitrateTestDelay||J<c)){const D=this.forcedAutoLevel;return Y!==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}" ${_}`),R.info(`[abr] switch candidate:${u}->${Y} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-H)} ttfb:${U.toFixed(1)} avgDuration:${V.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${J.toFixed(1)} firstSelection:${S} codecSet:${y} videoRange:${_} hls.loadLevel:${p}`)),S&&(this.firstSelection=Y),Y}}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 hT{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 uT{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 a=r.end;if(r.start<=t&&a!==null&&t<=a)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 a=i[s[r]];if((a==null?void 0:a.body.type)===e&&a.buffered){const o=a.body;if(o.start<=t&&t<=o.end)return o}}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(a=>{const o=this.fragments[a];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[t];l&&l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,e);return h&&this.removeFragment(o.body),h})})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s}=t;if(!e||i.sn==="initSegment")return;const r=Pi(i),a=this.fragments[r];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const h=e[l],u=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,s,u,h)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),pn(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.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=Pi(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},a=t.start,o=t.end,l=t.minEndPTS||o,c=t.maxStartPTS||a;for(let h=0;h<s.length;h++){const u=s.start(h)-this.bufferPadding,A=s.end(h)+this.bufferPadding;if(c>=u&&l<=A){r.time.push({startPTS:Math.max(a,s.start(h)),endPTS:Math.min(o,s.end(h))});break}else if(a<A&&o>u){const d=Math.max(a,s.start(h)),f=Math.min(o,s.end(h));f>d&&(r.partial=!0,r.time.push({startPTS:d,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(t){let e=null,i,s,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&pn(h)&&(s=h.body.start-o,r=h.body.end+o,t>=s&&t<=r&&(i=Math.min(t-s,r-t),a<=i&&(e=h.body,a=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||pn(e))}getState(t){const e=Pi(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 a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,r=i.end(a)+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,a=Pi(i);this.fragments[a]={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 a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,a,s)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Pi(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(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<e&&l.end>t&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(t){const e=Pi(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 Pi(n){return`${n.type}_${n.level}_${n.sn}`}const AT={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 a;for(a=0;a<s.length;a++)r.push({start:s.start(a),end:s.end(a)});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 u=c.start-h.start;return u||h.end-c.end});let s=[];if(i)for(let c=0;c<t.length;c++){const h=s.length;if(h){const u=s[h-1].end;t[c].start-u<i?t[c].end>u&&(s[h-1].end=t[c].end):s.push(t[c])}else s.push(t[c])}else s=t;let r=0,a,o=e,l=e;for(let c=0;c<s.length;c++){const h=s[c].start,u=s[c].end;if(e+i>=h&&e<u)o=h,l=u,r=l-e;else if(e+i<h){a=h;break}}return{len:r,start:o||0,end:l||0,nextStart:a}}static getBuffered(t){try{return t.buffered}catch(e){return R.log("failed to get media.buffered",e),AT}}}class Ir{constructor(t,e,i,s=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=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=a}}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 dT(n,t,e){return!!(t&&(e.endCC>e.startCC||n&&n.cc<e.startCC))}function fT(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 fh(n,t){if(n){const e=n.start+t;n.start=n.startPTS=e,n.endPTS=e+n.duration}}function ad(n,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)fh(e[i],n);t.fragmentHint&&fh(t.fragmentHint,n),t.alignedSliding=!0}function gT(n,t,e){t&&(mT(n,e,t),!e.alignedSliding&&t&&sr(e,t),!e.alignedSliding&&t&&!e.skippedSegments&&ZA(t,e))}function mT(n,t,e){if(dT(n,e,t)){const i=fT(e,t);i&&j(i.start)&&(R.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),ad(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 a=Math.min(t.endCC,n.endCC);t.startCC<a&&n.startCC<a&&(s=wn(i,a),r=wn(e,a)),(!s||!r)&&(s=i[Math.floor(i.length/2)],r=wn(e,s.cc)||e[Math.floor(e.length/2)]);const o=s.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-s.start);ad(c,n)}const gh=Math.pow(2,17);class pT{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:rt.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,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(d=>d[0]==="GAP")){l(ph(t));return}else t.gap=!1;const c=this.loader=t.loader=r?new r(s):new a(s),h=mh(t),u=uh(s.fragLoadPolicy.default),A={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:gh};t.stats=c.stats,c.load(h,A,{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)),o({frag:t,part:null,payload:m,networkDetails:p})},onError:(d,f,g,p)=>{this.resetLoader(t,c),l(new Je({type:rt.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:rt.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:rt.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${A.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,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(ph(t,e));return}const c=this.loader=t.loader=r?new r(s):new a(s),h=mh(t,e),u=uh(s.fragLoadPolicy.default),A={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gh};e.stats=c.stats,c.load(h,A,{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),o(m)},onError:(d,f,g,p)=>{this.resetLoader(t,c),l(new Je({type:rt.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:rt.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:rt.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${A.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),u=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+u}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function mh(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 a;let o=s,l=r;if(n.sn==="initSegment"&&((a=n.decryptdata)==null?void 0:a.method)==="AES-128"){const c=r-s;c%16&&(l=r+(16-c%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function ph(n,t){const e=new Error(`GAP ${n.gap?"tag":"attribute"} found`),i={type:rt.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 ET{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 CT{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 IT(n){const t=n.byteLength,e=t&&new DataView(n.buffer).getUint8(t-1);return e?Ci(n,0,t-e):n}class yT{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],a=i[2],o=i[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],A=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],S=d[E];let y=d[m]*257^m*16843008;s[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,a[f]=y<<8|y>>>24,o[f]=y,y=S*16843009^E*65537^C*257^f*16843008,c[m]=y<<24|y>>>8,h[m]=y<<16|y>>>16,u[m]=y<<8|y>>>24,A[m]=y,f?(f=C^d[d[d[S^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 a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,A=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let C,E;for(o=0;o<a;o++){if(o<r){C=c[o]=e[o];continue}E=C,o%r===0?(E=E<<8|E>>>24,E=u[E>>>24]<<24|u[E>>>16&255]<<16|u[E>>>8&255]<<8|u[E&255],E^=A[o/r|0]<<24):r>6&&o%r===4&&(E=u[E>>>24]<<24|u[E>>>16&255]<<16|u[E>>>8&255]<<8|u[E&255]),c[o]=C=(c[o-r]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=c[o]:E=c[o-4],l<4||o<=4?h[l]=E:h[l]=f[u[E>>>24]]^g[u[E>>>16&255]]^p[u[E>>>8&255]]^m[u[E&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],A=this.uint8ArrayToUint32Array_(i);let d=A[0],f=A[1],g=A[2],p=A[3];const m=new Int32Array(t),C=new Int32Array(m.length);let E,S,y,_,T,v,F,x,w,U,O,W,Y,X;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],v=W^r[1],F=O^r[2],x=U^r[3],Y=4,X=1;X<s;X++)E=l[T>>>24]^c[v>>16&255]^h[F>>8&255]^u[x&255]^r[Y],S=l[v>>>24]^c[F>>16&255]^h[x>>8&255]^u[T&255]^r[Y+1],y=l[F>>>24]^c[x>>16&255]^h[T>>8&255]^u[v&255]^r[Y+2],_=l[x>>>24]^c[T>>16&255]^h[v>>8&255]^u[F&255]^r[Y+3],T=E,v=S,F=y,x=_,Y=Y+4;E=a[T>>>24]<<24^a[v>>16&255]<<16^a[F>>8&255]<<8^a[x&255]^r[Y],S=a[v>>>24]<<24^a[F>>16&255]<<16^a[x>>8&255]<<8^a[T&255]^r[Y+1],y=a[F>>>24]<<24^a[x>>16&255]<<16^a[T>>8&255]<<8^a[v&255]^r[Y+2],_=a[x>>>24]<<24^a[T>>16&255]<<16^a[v>>8&255]<<8^a[F&255]^r[Y+3],C[e]=Z(E^d),C[e+1]=Z(_^f),C[e+2]=Z(y^g),C[e+3]=Z(S^p),d=w,f=U,g=O,p=W,e=e+4}return C.buffer}}const BT=16;class Xo{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?IT(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 a=this.flush();a?s(a.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:a}=this;this.logOnce("JS AES decrypt"),a&&(t=ge(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new yT),l.expandKey(e);const c=r;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=Ci(o,-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 CT(this.subtle,e)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new ET(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%BT;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 ST={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 yr extends hT{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 pT(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Xo(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,a=i?i.currentTime:0,o=Rt.bufferInfo(s||i,a,t.maxBufferHole);if(this.log(`media seeking to ${j(a)?a.toFixed(3):a}, 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(!o.len||h<o.start||c>o.end){const u=a>h;(a<c||u)&&(u&&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(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(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 a=this.state;if(this.fragContextChanged(t)){(a===N.FRAG_LOADING||!this.fragCurrent&&a===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,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(t.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?t.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,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,a=t.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer).catch(l=>{throw s.trigger(I.ERROR,{type:rt.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:o,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,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===it.MAIN?"level":"track"} ${t.level} (frag:[${((i=t.startPTS)!=null?i:NaN).toFixed(3)}-${((s=t.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?ST.toString(Rt.getBuffered(o)):"(detached)"})`),t.sn!=="initSegment"){var l;if(t.type!==it.SUBTITLE){const h=t.elementaryStreams;if(!Object.keys(h).some(u=>!!h[u])){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,o&&(!this.loadedmetadata&&t.type==it.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,a=!r||r.length===0||r.some(l=>!l),o=new Ir(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);e.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var r;const a=e==null?void 0:e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(t.encrypted&&!((r=t.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${t.level}`),this.state=N.KEY_LOADING,this.fragCurrent=t,o=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&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(t,a.encryptedFragments),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){const h=a.partList;if(h&&s){i>t.end&&a.fragmentHint&&(t=a.fragmentHint);const u=this.getNextPart(h,t,i);if(u>-1){const A=h[u];this.log(`Loading part sn: ${t.sn} p: ${A.index} cc: ${t.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${u}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=A.start+A.duration,this.state=N.FRAG_LOADING;let d;return o?d=o.then(f=>!f||this.fragContextChanged(f.frag)?null:this.doFragPartsLoad(t,A,e,s)).catch(f=>this.handleFragLoadError(f)):d=this.doFragPartsLoad(t,A,e,s).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(I.FRAG_LOADING,{frag:t,part:A,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} ${a?"of ["+a.startSN+"-"+a.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&&o?c=o.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),o]).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,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(t,u,s).then(A=>{l[u.index]=A;const d=A.part;this.hls.trigger(I.FRAG_LOADED,A);const f=ch(i,t.sn,u.index+1)||td(c,t.sn,u.index+1);if(f)h(f);else return r({frag:t,part:d,partsLoaded:l})}).catch(a)};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:rt.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,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a),this.updateLevelTiming(i,s,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:a}=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 o=e[s],l=a>-1?ch(o,r,a):null,c=l?l.fragment:zS(o,r,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(t,e,i,s,r){var a;if(!t||this.state!==N.PARSING)return;const{data1:o,data2:l}=t;let c=o;if(o&&l&&(c=ge(o,l)),!((a=c)!=null&&a.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,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(t.start-a,s.end-a),i+a);t.start-o>a&&this.flushMainBuffer(o,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 a=this.fragmentTracker.getBufferedFrag(e,i);if(a&&r.nextStart<a.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=it.MAIN){const i=this.fragmentTracker.getAppendedFrag(t,it.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,a=i[0].start;let o;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<a)&&(o=this.getInitialLiveFragment(e,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:t)}else t<=a&&(o=i[0]);if(!o){const l=r.lowLatencyMode?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(o)}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 a=t.gap,o=this.getNextFragment(this.nextLoadPosition,e);if(o===null)return o;if(t=o,a&&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,a=!0;for(let o=0,l=t.length;o<l;o++){const c=t[o];if(a=a&&!c.independent,s>-1&&i<c.start)break;const h=c.loaded;h?s=-1:(r||c.independent||a)&&c.fragment===e&&(s=o),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=qS(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const a=e[r-t.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=jS(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:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=s,h=i.partList,u=!!(s.lowLatencyMode&&h!=null&&h.length&&l);u&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let A;if(t<e){const d=t>e-c?0:c;A=ir(r,a,t,d)}else A=a[a.length-1];if(A){const d=A.sn-i.startSN,f=this.fragmentTracker.getState(A);if((f===zt.OK||f===zt.PARTIAL&&A.gap)&&(r=A),r&&A.sn===r.sn&&(!u||h[0].fragment.sn>A.sn)&&r&&A.level===r.level){const p=a[d+1];A.sn<o&&this.fragmentTracker.getState(p)!==zt.OK?A=p:A=null}}return A}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=i.currentTime,a=t.fragments[0].start,o=t.edge,l=r>=a-e.maxFragLookUpTolerance&&r<=o;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<o-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: ${o}, 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,a=!e,o=t.alignedSliding&&j(r);if(a||!o&&!r){const{fragPrevious:l}=this;gT(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 a=e.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===Ht.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=qo(c,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),a.resolved=!0,this.retryDate=self.performance.now()+h,this.state=N.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(t),l<c.maxNumRetry)!r&&o!==Ht.RemoveAlternatePermanently&&(a.resolved=!0);else{R.warn(`${e.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.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 a=!r;return a&&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(),a}return!1}resetFragmentErrors(t){t===it.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 a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((l,c)=>{const h=t.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${t.sn} ${c} duration reliably (${u})`),l||!1;const A=s?0:jA(a,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:a,level:i,drift:A,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:rt.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 od{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=TT(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function TT(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 _T(){return typeof __HLS_WORKER_BUNDLE__=="function"}function vT(){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 xT(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 Wo{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=Us(t,0),s=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?$o(i):void 0,c=t.length;for((this.basePTS===null||this.frameIndex===0&&j(l))&&(this.basePTS=DT(l,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ae.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(t,s)){const h=this.appendFrame(a,t,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,r=s):s=c}else WB(t,s)?(i=Us(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ae.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:a,videoTrack:Pe(),id3Track:o,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 DT=(n,t,e)=>{if(j(n))return n*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};function RT(n,t,e,i){let s,r,a,o;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 u=(t[e+2]&60)>>>2;if(u>h.length-1){const A=new Error(`invalid ADTS sampling index:${u}`);n.emit(I.ERROR,I.ERROR,{type:rt.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!0,error:A,reason:A.message});return}return a=(t[e+2]&1)<<2,a|=(t[e+3]&192)>>>6,R.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),r=u-3):(s=2,o=new Array(2),r=u):l.indexOf("android")!==-1?(s=2,o=new Array(2),r=u):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&u>=6?r=u-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(u>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(s=2,o=new Array(2)),r=u)),o[0]=s<<3,o[0]|=(u&14)>>1,o[1]|=(u&1)<<7,o[1]|=a<<3,s===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c}}function ld(n,t){return n[t]===255&&(n[t+1]&246)===240}function cd(n,t){return n[t+1]&1?7:9}function jo(n,t){return(n[t+3]&3)<<11|n[t+4]<<3|(n[t+5]&224)>>>5}function wT(n,t){return t+5<n.length}function nr(n,t){return t+1<n.length&&ld(n,t)}function LT(n,t){return wT(n,t)&&ld(n,t)&&jo(n,t)<=n.length-t}function bT(n,t){if(nr(n,t)){const e=cd(n,t);if(t+e>=n.length)return!1;const i=jo(n,t);if(i<=e)return!1;const s=t+i;return s===n.length||nr(n,s)}return!1}function hd(n,t,e,i,s){if(!n.samplerate){const r=RT(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 ud(n){return 1024*9e4/n}function FT(n,t){const e=cd(n,t);if(t+e<=n.length){const i=jo(n,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function Ad(n,t,e,i,s){const r=ud(n.samplerate),a=i+s*r,o=FT(t,e);let l;if(o){const{frameLength:u,headerLength:A}=o,d=A+u,f=Math.max(0,e+d-t.length);f?(l=new Uint8Array(d-A),l.set(t.subarray(e+A,t.length),0)):l=t.subarray(e+A,e+d);const g={unit:l,pts:a};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:a},length:c,missing:-1}}let Cn=null;const MT=[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],PT=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],kT=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],QT=[0,1,1,4];function dd(n,t,e,i,s){if(e+24>t.length)return;const r=fd(t,e);if(r&&e+r.frameLength<=t.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+s*a,l={unit:t.subarray(e,e+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function fd(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 a=n[t+2]>>1&1,o=n[t+3]>>6,l=e===3?3-i:i===3?3:4,c=MT[l*14+s-1]*1e3,u=PT[(e===3?0:e===2?1:2)*3+r],A=o===3?1:2,d=kT[e][i],f=QT[i],g=d*8*f,p=Math.floor(d*c/u+a)*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&&o===0&&(n[t+3]=n[t+3]|128),{sampleRate:u,channelCount:A,frameLength:p,samplesPerFrame:g}}}function Zo(n,t){return n[t]===255&&(n[t+1]&224)===224&&(n[t+1]&6)!==0}function gd(n,t){return t+1<n.length&&Zo(n,t)}function OT(n,t){return Zo(n,t)&&4<=n.length-t}function md(n,t){if(t+1<n.length&&Zo(n,t)){const i=fd(n,t);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=t+s;return r===n.length||gd(n,r)}return!1}class GT extends Wo{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=Us(t,0);let i=(e==null?void 0:e.length)||0;if(md(t,i))return!1;for(let s=t.length;i<s;i++)if(bT(t,i))return R.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return LT(t,e)}appendFrame(t,e,i){hd(t,this.observer,e,i,t.manifestCodec);const s=Ad(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const UT=/\/emsg[-/]ID3/i;class NT{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),a=this.audioTrack=Pe("audio",1),o=this.txtTrack=Pe("text",1);if(this.id3Track=Pe("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=YA(t);if(l.video){const{id:c,timescale:h,codec:u}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=NA.text,r.sampleDuration=0,r.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return aS(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 o=fS(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,e);return r.samples=Vc(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,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=Vc(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 a=pS(r);if(UT.test(a.schemeIdUri)){const o=j(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Ae.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 pd=(n,t)=>{let e=0,i=5;t+=i;const s=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=n[t];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,s[0]=(a[0]&r[0])>>l,e=e?e<<o|s[0]:s[0],t+=1,i-=o}return e};class HT extends Wo{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=Ed(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=Us(t,0);if(!e)return!1;const i=e.length;return t[i]===11&&t[i+1]===119&&$o(e)!==void 0&&pd(t,i)<16}}function Ed(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 o=[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 u=t[e+6]>>5;let A=0;u===2?A+=2:(u&1&&u!==1&&(A+=2),u&4&&(A+=2));const d=(t[e+6]<<8|t[e+7])>>12-A&1,g=[2,1,2,3,3,4,4,5][u]+d,p=t[e+5]>>3,m=t[e+5]&7,C=new Uint8Array([r<<6|p<<1|m>>2,(m&3)<<6|u<<3|d<<2|l>>4,l<<4&224]),E=1536/o*9e4,S=i+s*E,y=t.subarray(e,e+h);return n.config=C,n.channelCount=g,n.samplerate=o,n.samples.push({unit:y,pts:S}),h}class KT{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 Eh{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,a,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),u=this.readBoolean.bind(this),A=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),A(3),l(),f(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const _=h();if(_===3&&A(1),f(),f(),A(1),u())for(a=_!==3?8:12,o=0;o<a;o++)u()&&(o<6?g(16):g(64))}f();const m=h();if(m===0)h();else if(m===1)for(A(1),d(),d(),r=h(),o=0;o<r;o++)d();f(),A(1);const C=h(),E=h(),S=c(1);S===0&&A(1),A(1),u()&&(t=h(),e=h(),i=h(),s=h());let y=[1,1];if(u()&&u())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-S)*(E+1)*16-(S?2:4)*(i+s),pixelRatio:y}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class YT extends KT{parseAVCPES(t,e,i,s,r){const a=this.parseAVCNALu(t,i.data);let o=this.VideoSample,l,c=!1;i.data=null,o&&a.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach(h=>{var u;switch(h.type){case 1:{let g=!1;l=!0;const p=h.data;if(c&&p.length>4){const m=new Eh(p).readSliceType();(m===2||m===4||m===7||m===9)&&(g=!0)}if(g){var A;(A=o)!=null&&A.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,JA(h.data,1,i.pts,e.samples);break}case 7:{var d,f;l=!0,c=!0;const g=h.data,m=new Eh(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 S=0;S<3;S++){let y=C[S].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,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+h.type+" ");break}o&&l&&o.units.push(h)}),s&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const i=e.byteLength;let s=t.naluState||0;const r=s,a=[];let o=0,l,c,h,u=-1,A=0;for(s===-1&&(u=0,A=e[0]&31,s=0,o=1);o<i;){if(l=e[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(c=o-s-1,u>=0){const d={data:e.subarray(u,c),type:A};a.push(d)}else{const d=this.getLastNalUnit(t.samples);d&&(r&&o<=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))}o<i?(h=e[o]&31,u=o,A=h,s=0):s=-1}else s=0}if(u>=0&&s>=0){const d={data:e.subarray(u,i),type:A,state:s};a.push(d)}if(a.length===0){const d=this.getLastNalUnit(t.samples);d&&(d.data=ge(d.data,e))}return t.naluState=s,a}}class VT{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Xo(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),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);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 a=zA(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,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 a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(t,e,i,s,a),!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 YT}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,a=-1,o=0;for(let l=s;l<e;l+=Jt)if(t[l]===71&&(e-l===Jt||t[l+Jt]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+Jt*99,t.length-Jt)+1)),r||(r=to(t,l)===0),r&&o>1&&(a===0&&o>2||l+Jt>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:NA[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 a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=a.pid,u=a.pesData,A=o.pid,d=l.pid,f=o.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:o,videoTrack:a,id3Track:l,textTrack:c};const S=Math.max(0,ei.syncOffset(t));E-=(E-S)%Jt,E<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));let y=0;for(let T=S;T<E;T+=Jt)if(t[T]===71){const v=!!(t[T+1]&64),F=to(t,T),x=(t[T+3]&48)>>4;let w;if(x>1){if(w=T+5+t[T+4],w===T+Jt)continue}else w=T+4;switch(F){case h:v&&(u&&(r=ki(u))&&this.videoParser.parseAVCPES(a,c,r,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(t.subarray(w,T+Jt)),u.size+=T+Jt-w);break;case A:if(v){if(f&&(r=ki(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(t.subarray(w,T+Jt)),f.size+=T+Jt-w);break;case d:v&&(g&&(r=ki(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:v&&(w+=t[w]+1),C=this._pmtId=JT(t,w);break;case C:{v&&(w+=t[w]+1);const U=zT(t,w,this.typeSupported,i,this.observer);h=U.videoPid,h>0&&(a.pid=h,a.segmentCodec=U.segmentVideoCodec),A=U.audioPid,A>0&&(o.pid=A,o.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 @${S} to parse all TS packets.`),p=null,T=S-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`)),a.pesData=u,o.pesData=f,l.pesData=g;const _={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return s&&this.extractRemainingSamples(_),_}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,a=i.pesData,o=e.pesData,l=s.pesData;let c;if(a&&(c=ki(a))?(this.videoParser.parseAVCPES(i,r,c,!0,this._duration),i.pesData=null):i.pesData=a,o&&(c=ki(o))){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 o!=null&&o.size&&R.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;l&&(c=ki(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 VT(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 u=s.missing,A=s.sample.unit.byteLength;if(u===-1)r=ge(s.sample.unit,r);else{const d=A-u;s.sample.unit.set(r.subarray(0,u),d),t.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=r.length;a<o-1&&!nr(r,a);a++);if(a!==i){let u;const A=a<o-1;if(A?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",rr(this.observer,new Error(u),A),!A)return}hd(t,this.observer,r,a,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(s){const u=ud(t.samplerate);l=s.sample.pts+u}else{R.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;a<o;)if(h=Ad(t,r,a,l,c),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;a<o-1&&!nr(r,a);a++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,a=0;const o=e.pts;if(o===void 0){R.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(gd(i,a)){const l=dd(t,i,a,o,r);if(l)a+=l.length,r++;else break}else a++}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 a=0,o=0,l;for(;o<r&&(l=Ed(t,i,o,s,a++))>0;)o+=l}}parseID3PES(t,e){if(e.pts===void 0){R.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Qt({},e,{type:this._videoTrack?Ae.emsg:Ae.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function to(n,t){return((n[t+1]&31)<<8)+n[t+2]}function JT(n,t){return(n[t+10]&31)<<8|n[t+11]}function zT(n,t,e,i,s){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(n[t+1]&15)<<8|n[t+2],o=t+3+a-4,l=(n[t+10]&15)<<8|n[t+11];for(t+=12+l;t<o;){const c=to(n,t),h=(n[t+3]&15)<<8|n[t+4];switch(n[t]){case 207:if(!i){ua("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){ua("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){ua("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 u=t+5,A=h;for(;A>2;){switch(n[u]){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[u+1]+2;u+=f,A-=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:rt.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:t,reason:t.message})}function ua(n){R.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function ki(n){let t=0,e,i,s,r,a;const o=n.data;if(!n||n.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=ge(o[0],o[1]),o.splice(1,1);if(e=o[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?(a=(e[14]&14)*536870912+(e[15]&255)*4194304+(e[16]&254)*16384+(e[17]&255)*128+(e[18]&254)/2,r-a>60*9e4&&(R.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),s=e[8];let h=s+9;if(n.size<=h)return null;n.size-=h;const u=new Uint8Array(n.size);for(let A=0,d=o.length;A<d;A++){e=o[A];let f=e.byteLength;if(h)if(h>f){h-=f;continue}else e=e.subarray(h),f-=h,h=0;u.set(e,t),t+=f}return i&&(i-=s+3),{data:u,pts:r,dts:a,len:i}}return null}class $T extends Wo{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=Us(t,0);let i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&$o(e)!==void 0&&pd(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(md(t,i))return R.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return OT(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return dd(t,e,i,this.basePTS,this.frameIndex)}}class Ch{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 a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,l,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(t,4),s=0,i=8;s<r;s++)a.set(e[s],i),i+=e[s].byteLength;return a}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,a;for(s=0;s<t.sps.length;s++)r=t.sps[s],a=r.byteLength,e.push(a>>>8&255),e.push(a&255),e=e.concat(Array.prototype.slice.call(r));for(s=0;s<t.pps.length;s++)r=t.pps[s],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=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],u=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]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(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,a=Math.floor(i/(Ze+1)),o=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,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,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)),a=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,a>>24,a>>16&255,a>>8&255,a&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,a=new Uint8Array(r);let o,l,c,h,u,A;for(e+=8+r,a.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),o=0;o<s;o++)l=i[o],c=l.duration,h=l.size,u=l.flags,A=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,A>>>24&255,A>>>16&255,A>>>8&255,A&255],12+16*o);return L.box(L.types.trun,a)}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 Cd=9e4;function tl(n,t,e=1,i=!1){const s=n*t*e;return i?Math.round(s):s}function qT(n,t,e=1,i=!1){return tl(n,t,1/e,i)}function Is(n,t=!1){return tl(n,1e3,1/Cd,t)}function XT(n,t=1){return tl(n,Cd,1/t)}const WT=10*1e3,Ih=1024,jT=1152,ZT=1536;let Qi=null,Aa=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,Qi===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qi=a?parseInt(a[1]):0}if(Aa===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Aa=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,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(e=!0,o=he(o,i),l=o-r),l>0?r:o},i);return e&&R.debug("PTS rollover detected"),s}remux(t,e,i,s,r,a,o,l){let c,h,u,A,d,f,g=r,p=r;const m=t.pid>-1,C=e.pid>-1,E=e.samples.length,S=t.samples.length>0,y=o&&E>0||E>1;if((!m||S)&&(!C||y)||this.ISGenerated||o){if(this.ISGenerated){var T,v,F,x;const W=this.videoTrackConfig;W&&(e.width!==W.width||e.height!==W.height||((T=e.pixelRatio)==null?void 0:T[0])!==((v=W.pixelRatio)==null?void 0:v[0])||((F=e.pixelRatio)==null?void 0:F[1])!==((x=W.pixelRatio)==null?void 0:x[1]))&&this.resetInitSegment()}else u=this.generateIS(t,e,r,a);const w=this.isVideoContiguous;let U=-1,O;if(y&&(U=t_(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(S&&y){const W=this.getVideoStartPts(e.samples),X=(he(t.samples[0].pts,W)-W)/e.inputTimeScale;g+=Math.max(0,X),p+=Math.max(0,-X)}if(S){if(t.samplerate||(R.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(t,e,r,a)),h=this.remuxAudio(t,g,this.isAudioContiguous,a,C||y||l===it.AUDIO?p:void 0),y){const W=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(R.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(t,e,r,a)),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=Id(i,r,this._initPTS,this._initDTS)),s.samples.length&&(A=yd(s,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:f,text:A,id3:d}}generateIS(t,e,i,s){const r=t.samples,a=e.samples,o=this.typeSupported,l={},c=this._initPTS;let h=!c||s,u="audio/mp4",A,d,f;if(h&&(A=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}l.audio={id:"audio",container:u,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(f=t.inputTimeScale,!c||f!==c.timescale?A=d=r[0].pts-Math.round(f*i):h=!1)}if(e.sps&&e.pps&&a.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(a),p=Math.round(f*i);d=Math.min(d,he(a[0].dts,g)-p),A=Math.min(A,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:A,timescale:f},this._initDTS={baseTime:d,timescale:f}):A=f=void 0,{tracks:l,initPTS:A,timescale:f}}remuxVideo(t,e,i,s){const r=t.inputTimeScale,a=t.samples,o=[],l=a.length,c=this._initPTS;let h=this.nextAvcDts,u=8,A=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!i||h===null){const V=e*r,G=a[0].pts-he(a[0].dts,a[0].pts);Qi&&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=a[V];G.pts=he(G.pts-C,h),G.dts=he(G.dts-C,h),G.dts<a[V>0?V-1:V].dts&&(m=!0)}m&&a.sort(function(V,G){const H=V.dts-G.dts,J=V.pts-G.pts;return H||J}),d=a[0].dts,f=a[a.length-1].dts;const E=f-d,S=E?Math.round(E/(l-1)):A||t.inputTimeScale/30;if(i){const V=d-h,G=V>S,H=V<-1;if((G||H)&&(G?R.warn(`AVC: ${Is(V,!0)} ms (${V}dts) hole between fragments detected at ${e.toFixed(3)}`):R.warn(`AVC: ${Is(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!H||h>=a[0].pts||Qi)){d=h;const J=a[0].pts-V;if(G)a[0].dts=d,a[0].pts=J;else for(let K=0;K<a.length&&!(a[K].dts>J);K++)a[K].dts-=V,a[K].pts-=V;R.log(`Video: Initial PTS/DTS adjusted: ${Is(J,!0)}/${Is(d,!0)}, delta: ${Is(V,!0)} ms`)}}d=Math.max(0,d);let y=0,_=0,T=d;for(let V=0;V<l;V++){const G=a[V],H=G.units,J=H.length;let K=0;for(let D=0;D<J;D++)K+=H[D].data.length;_+=K,y+=J,G.length=K,G.dts<T?(G.dts=T,T+=S/4|0||1):T=G.dts,g=Math.min(G.pts,g),p=Math.max(G.pts,p)}f=a[l-1].dts;const v=_+4*y+8;let F;try{F=new Uint8Array(v)}catch(V){this.observer.emit(I.ERROR,I.ERROR,{type:rt.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:v,reason:`fail allocating video mdat ${v}`});return}const x=new DataView(F.buffer);x.setUint32(0,v),F.set(L.types.mdat,4);let w=!1,U=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,W=Number.NEGATIVE_INFINITY,Y=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){const G=a[V],H=G.units;let J=0;for(let et=0,ot=H.length;et<ot;et++){const ht=H[et],Vt=ht.data,ne=ht.data.byteLength;x.setUint32(u,ne),u+=4,F.set(Vt,u),u+=ne,J+=4+ne}let K;if(V<l-1)A=a[V+1].dts-G.dts,K=a[V+1].pts-G.pts;else{const et=this.config,ot=V>0?G.dts-a[V-1].dts:S;if(K=V>0?G.pts-a[V-1].pts:S,et.stretchShortVideoTrack&&this.nextAudioPts!==null){const ht=Math.floor(et.maxBufferHole*r),Vt=(s?g+s*r:this.nextAudioPts)-G.pts;Vt>ht?(A=Vt-ot,A<0?A=ot:w=!0,R.log(`[mp4-remuxer]: It is approximately ${Vt/90} ms to the next segment; using duration ${A/90} ms for the last video frame.`)):A=ot}else A=ot}const D=Math.round(G.pts-G.dts);U=Math.min(U,A),W=Math.max(W,A),O=Math.min(O,K),Y=Math.max(Y,K),o.push(new yh(G.key,A,J,D))}if(o.length){if(Qi){if(Qi<70){const V=o[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(Aa&&Y-O<W-U&&S/W<.025&&o[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=o.length;G<H;G++){const J=V+o[G].duration,K=V+o[G].cts;if(G<H-1){const D=J+o[G+1].cts;o[G].duration=D-K}else o[G].duration=G?o[G-1].duration:S;o[G].cts=0,V=J}}}A=w||!A?S:A,this.nextAvcDts=h=f+A,this.videoSampleDuration=A,this.isVideoContiguous=!0;const at={data1:L.moof(t.sequenceNumber++,d,Qt({},t,{samples:o})),data2:F,startPTS:g/r,endPTS:(p+A)/r,startDTS:d/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,at}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return jT;case"ac3":return ZT;default:return Ih}}remuxAudio(t,e,i,s,r){const a=t.inputTimeScale,o=t.samplerate?t.samplerate:a,l=a/o,c=this.getSamplesPerFrame(t),h=c*l,u=this._initPTS,A=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=r!==void 0;let g=t.samples,p=A?0:8,m=this.nextAudioPts||-1;const C=e*a,E=u.baseTime*a/u.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(X){X.pts=he(X.pts-E,C)}),!i||m<0){if(g=g.filter(X=>X.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 X=this.config.maxAudioFramesDrift;for(let Z=0,at=m;Z<g.length;Z++){const V=g[Z],G=V.pts,H=G-at,J=Math.abs(1e3*H/a);if(H<=-X*h&&f)Z===0&&(R.warn(`Audio frame @ ${(G/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*H/a)} ms.`),this.nextAudioPts=m=at=G);else if(H>=X*h&&J<WT&&f){let K=Math.round(H/h);at=G-K*h,at<0&&(K--,at+=h),Z===0&&(this.nextAudioPts=m=at),R.warn(`[mp4-remuxer]: Injecting ${K} audio frame @ ${(at/a).toFixed(3)}s due to ${Math.round(1e3*H/a)} ms gap.`);for(let D=0;D<K;D++){const et=Math.max(at,0);let ot=Ch.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);ot||(R.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ot=V.unit.subarray()),g.splice(Z,0,{unit:ot,pts:et}),at+=h,Z++}}V.pts=at,at+=h}}let S=null,y=null,_,T=0,v=g.length;for(;v--;)T+=g[v].unit.byteLength;for(let X=0,Z=g.length;X<Z;X++){const at=g[X],V=at.unit;let G=at.pts;if(y!==null){const J=d[X-1];J.duration=Math.round((G-y)/l)}else if(i&&t.segmentCodec==="aac"&&(G=m),S=G,T>0){T+=p;try{_=new Uint8Array(T)}catch(J){this.observer.emit(I.ERROR,I.ERROR,{type:rt.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:J,bytes:T,reason:`fail allocating audio mdat ${T}`});return}A||(new DataView(_.buffer).setUint32(0,T),_.set(L.types.mdat,4))}else return;_.set(V,p);const H=V.byteLength;p+=H,d.push(new yh(!0,c,H,0)),y=G}const F=d.length;if(!F)return;const x=d[d.length-1];this.nextAudioPts=m=y+l*x.duration;const w=A?new Uint8Array(0):L.moof(t.sequenceNumber++,S/l,Qt({},t,{samples:d}));t.samples=[];const U=S/a,O=m/a,Y={data1:w,data2:_,startPTS:U,endPTS:O,startDTS:U,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,Y}remuxEmptyAudio(t,e,i,s){const r=t.inputTimeScale,a=t.samplerate?t.samplerate:r,o=r/a,l=this.nextAudioPts,c=this._initDTS,h=c.baseTime*9e4/c.timescale,u=(l!==null?l:s.startDTS*r)+h,A=s.endDTS*r+h,d=o*Ih,f=Math.ceil((A-u)/d),g=Ch.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=u+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 t_(n){for(let t=0;t<n.length;t++)if(n[t].key)return t;return-1}function Id(n,t,e,i){const s=n.samples.length;if(!s)return;const r=n.inputTimeScale;for(let o=0;o<s;o++){const l=n.samples[o];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 a=n.samples;return n.samples=[],{samples:a}}function yd(n,t,e){const i=n.samples.length;if(!i)return;const s=n.inputTimeScale;for(let a=0;a<i;a++){const o=n.samples[a];o.pts=he(o.pts-e.baseTime*s/e.timescale,t*s)/s}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class yh{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 e_{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(cS(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=YA(t);s.audio&&(e=Bh(s.audio,vt.AUDIO)),s.video&&(i=Bh(s.video,vt.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,a){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};j(h)||(h=this.lastEndTime=r||0);const A=e.samples;if(!(A!=null&&A.length))return u;const d={initPTS:void 0,timescale:1};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(A),f=this.initData),!((l=f)!=null&&l.length))return R.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=uS(A,f),p=hS(f,A),m=p===null?r:p;(i_(c,m,r,g)||d.timescale!==c.timescale&&a)&&(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;dS(f,A,c.baseTime/c.timescale),g>0?this.lastEndTime=E:(R.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!f.audio,y=!!f.video;let _="";S&&(_+="audio"),y&&(_+="video");const T={data1:A,startPTS:C,startDTS:C,endPTS:E,endDTS:E,type:_,hasAudio:S,hasVideo:y,nb:1,dropped:0};return u.audio=T.type==="audio"?T:void 0,u.video=T.type!=="audio"?T:void 0,u.initSegment=d,u.id3=Id(i,r,c,c),s.samples.length&&(u.text=yd(s,r,c)),u}}function i_(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 Bh(n,t){const e=n==null?void 0:n.codec;if(e&&e.length>4)return e;if(t===vt.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=qi==null?void 0:qi.Date.now}const bn=[{demux:NT,remux:e_},{demux:ei,remux:Ln},{demux:GT,remux:Ln},{demux:$T,remux:Ln}];bn.splice(2,0,{demux:HT,remux:Ln});class Sh{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 a=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:A,timeOffset:d,initSegmentChange:f}=s||o,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:C,initSegmentData:E}=l,S=s_(a,e);if(S&&S.method==="AES-128"){const v=this.getDecrypter();if(v.isSync()){let F=v.softwareDecrypt(a,S.key.buffer,S.iv.buffer);if(i.part>-1&&(F=v.flush()),!F)return r.executeEnd=ze(),da(i);a=new Uint8Array(F)}else return this.decryptionPromise=v.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer).then(F=>{const x=this.push(F,null,i);return this.decryptionPromise=null,x}),this.decryptionPromise}const y=this.needsProbing(h,u);if(y){const v=this.configureTransmuxer(a);if(v)return R.warn(`[transmuxer] ${v.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:rt.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:v,reason:v.message}),r.executeEnd=ze(),da(i)}(h||u||f||y)&&this.resetInitSegment(E,g,p,C,e),(h||f||y)&&this.resetInitialTimestamp(m),c||this.resetContiguity();const _=this.transmux(a,S,d,A,i),T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,r.executeEnd=ze(),_}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 a=[],{timeOffset:o}=s;if(i){const u=i.flush();u&&a.push(this.push(u,null,t))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return e.executeEnd=ze(),[da(t)];const h=l.flush(o);return Fn(h)?h.then(u=>(this.flushRemux(a,u,t),a)):(this.flushRemux(a,h,t),a)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:a,textTrack:o}=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,a,o,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:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(t,e,i,s),o.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 a;return e&&e.method==="SAMPLE-AES"?a=this.transmuxSampleAes(t,e,i,s,r):a=this.transmuxUnencrypted(t,i,s,r),a}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s,vendor:r}=this;let a;for(let A=0,d=bn.length;A<d;A++){var o;if((o=bn[A].demux)!=null&&o.probe(t)){a=bn[A];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=a.remux,u=a.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(i,e,s,r)),(!l||!(l instanceof u))&&(this.demuxer=new u(i,e,s),this.probe=u.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Xo(this.config)),t}}function s_(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 da=n=>({remuxResult:{},chunkMeta:n});function Fn(n){return"then"in n&&n.then instanceof Function}class n_{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 r_{constructor(t,e,i,s,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=a}}var Bd={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,u,A){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new s(h,u||l,A),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 a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)t.call(h,u)&&c.push(e?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=e?e+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var A=0,d=u.length,f=new Array(d);A<d;A++)f[A]=u[A].fn;return f},o.prototype.listenerCount=function(c){var h=e?e+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,A,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,u),!0;case 4:return p.fn.call(p.context,h,u,A),!0;case 5:return p.fn.call(p.context,h,u,A,d),!0;case 6:return p.fn.call(p.context,h,u,A,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 S=p.length,y;for(E=0;E<S;E++)switch(p[E].once&&this.removeListener(c,p[E].fn,void 0,!0),m){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,h);break;case 3:p[E].fn.call(p[E].context,h,u);break;case 4:p[E].fn.call(p[E].context,h,u,A);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},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,A){var d=e?e+c:c;if(!this._events[d])return this;if(!h)return a(this,d),this;var f=this._events[d];if(f.fn)f.fn===h&&(!A||f.once)&&(!u||f.context===u)&&a(this,d);else{for(var g=0,p=[],m=f.length;g<m;g++)(f[g].fn!==h||A&&!f[g].once||u&&f[g].context!==u)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:a(this,d)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=e?e+c:c,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,n.exports=o})(Bd);var a_=Bd.exports,el=FB(a_);class Sd{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 a=(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,a),this.observer.on(I.ERROR,a);const o=oi(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||_T())){try{r.workerPath?(R.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=xT(r.workerPath)):(R.log(`injecting Web Worker for "${e}"`),this.workerContext=vT()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=u=>{const A=new Error(`${u.message} (${u.filename}:${u.lineno})`);r.enableWorker=!1,R.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:rt.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:A})},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 Sh(this.observer,l,r,"",e)}return}this.transmuxer=new Sh(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,a,o,l,c,h){var u,A;c.transmuxing.start=self.performance.now();const{transmuxer:d}=this,f=a?a.start:r.start,g=r.decryptdata,p=this.frag,m=!(p&&r.cc===p.cc),C=!(p&&c.level===p.level),E=p?c.sn-p.sn:-1,S=this.part?c.part-this.part.index:-1,y=E===0&&c.id>1&&c.id===(p==null?void 0:p.stats.chunkCount),_=!C&&(E===1||E===0&&(S===1||y&&S<=0)),T=self.performance.now();(C||E||r.stats.parsing.start===0)&&(r.stats.parsing.start=T),a&&(S||!_)&&(a.stats.parsing.start=T);const v=!(p&&((u=r.initSegment)==null?void 0:u.url)===((A=p.initSegment)==null?void 0:A.url)),F=new r_(m,_,l,C,f,v);if(!_||m||v){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: ${_}
|
|
21
|
+
accurateTimeOffset: ${l}
|
|
22
|
+
timeOffset: ${f}
|
|
23
|
+
initSegmentChange: ${v}`);const x=new n_(i,s,e,o,h);this.configureTransmuxer(x)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:c,state:F},t instanceof ArrayBuffer?[t]:[]);else if(d){const x=d.push(t,g,c,F);Fn(x)?(d.async=!0,x.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,c,"transmuxer-interface push error")})):(d.async=!1,this.handleTransmuxComplete(x))}}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:rt.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 Td(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(!Wi(n[e].attrs,t[e].attrs))return!1;return!0}function Wi(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 eo(n,t){return t.label.toLowerCase()===n.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(n.lang||"").toLowerCase())}const Th=100;class _d extends yr{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",it.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 a=e.cc;this.initPTS[e.cc]={baseTime:s,timescale:r},this.log(`InitPTS for cc: ${a} found from main: ${s}`),this.videoTrackCC=a,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(Th),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:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((r==null?void 0:r[a])||null),this.state=N.IDLE}break}case N.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:r,cache:a,complete:o}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=N.FRAG_LOADING;const l=a.flush(),c={frag:s,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&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);Za(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 a=e[s],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=N.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,vt.AUDIO,it.AUDIO));const c=this.getFwdBufferInfo(l,it.AUDIO);if(c===null)return;const{bufferedTrack:h,switchingTrack:u}=this;if(!u&&this._streamEnded(c,o)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=N.ENDED;return}const A=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,it.MAIN),d=c.len,f=this.getMaxBufferLength(A==null?void 0:A.len),g=o.fragments,p=g[0].start;let m=this.flushing?this.getLoadPosition():c.end;if(u&&i){const y=this.getLoadPosition();h&&!Wi(u.attrs,h.attrs)&&(m=y),o.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&&!u&&m<g[g.length-1].start)return;let C=this.getNextFragment(m,o),E=!1;if(C&&this.isLoopLoading(C,m)&&(E=!!C.gap,C=this.getNextFragmentLoopLoading(C,o,c,it.MAIN,f)),!C){this.bufferFlushed=!0;return}const S=A&&C.start>A.end+o.targetduration;if(S||!(A!=null&&A.len)&&c.len){const y=this.getAppendedFrag(C.start,it.MAIN);if(y===null||(E||(E=!!y.gap||!!S&&A.len===0),S&&!E||E&&c.nextStart&&c.nextStart<y.end))return}this.loadFragment(C,a,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(Th):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:a}=e;if(!s){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=s[a];let l=0;if(r.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(r);const h=this.mainDetails;if(r.deltaUpdateFailed||!h)return;if(!o.details&&r.hasProgramDateTime&&h.hasProgramDateTime)sr(r,h),l=r.fragments[0].start;else{var c;l=this.alignPlaylists(r,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,l),this.state===N.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=N.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:r}=t,{config:a,trackId:o,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[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let A=this.transmuxer;A||(A=this.transmuxer=new Sd(this.hls,it.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 Ir(i.level,i.sn,i.stats.chunkCount,r.byteLength,p,m);A.push(r,f,u,"",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 ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new od,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!==it.AUDIO){if(!this.loadedmetadata&&i.type===it.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(it.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!==vt.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==vt.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,it.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:A,text:d,id3:f,initSegment:g}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=N.PARSING,this.switchingTrack&&A&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(h,g.tracks,p,a),s.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(A){const{startPTS:p,endPTS:m,startDTS:C,endDTS:E}=A;c&&(c.elementaryStreams[vt.AUDIO]={startPTS:p,endPTS:m,startDTS:C,endDTS:E}),l.setElementaryStreamInfo(vt.AUDIO,p,m,C,E),this.bufferFragmentData(A,l,c,a)}if(f!=null&&(e=f.samples)!=null&&e.length){const p=Qt({id:i,frag:l,details:u},f);s.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=Qt({id:i,frag:l,details:u},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 a=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(I.BUFFER_CODECS,e);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};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 a=this.mainDetails;a&&a.fragments[0].start!==e.details.fragments[0].start&&sr(e.details,a)}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 vd extends Cr{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,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=e.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}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(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(A=>!i||i.indexOf(A.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(A=>A.default)&&(this.selectDefaultTrack=!1),o.forEach((A,d)=>{A.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const A=Qe(l,o,Mi);if(A>-1)r=o[A];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:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const A=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(A.message),this.hls.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:A})}}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&&Ji(t,s,Mi))return s;const r=Qe(t,this.tracksInGroup,Mi);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(s){let a=e.loadLevel;a===-1&&(a=e.firstAutoLevel);const o=cT(t,e.levels,i,a,Mi);if(o===-1)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){const a=Qe(t,i);if(a>-1)return i[a]}}}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 a=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if(!(this.selectDefaultTrack&&!s.default)&&(!t||Ji(t,s,Mi)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l}=t;for(let c=0;c<e.length;c++){const h=e[c];if(Ji({name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,Mi))return c}for(let c=0;c<e.length;c++){const h=e[c];if(Wi(t.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<e.length;c++){const h=e[c];if(Wi(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(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}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 _h=500;class xd extends yr{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",it.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(_h),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 a;const o=i.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),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(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,r,it.SUBTITLE)}}onFragBuffered(t,e){if(!this.loadedmetadata&&e.frag.type===it.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)===it.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&&Td(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,it.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(_h)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:a,id:o}=e;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){const u=this.mainDetails;if(a.deltaUpdateFailed||!u)return;const A=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(sr(a,u),c=a.fragments[0].start):A&&(c=A.start,ja(a,c));else{var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&A&&(c=A.start,ja(a,c))}}l.details=a,this.levelLastLoaded=l,o===s&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===N.IDLE&&(ir(null,a.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 a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(o=>{throw r.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:e}),o}).then(o=>{const l=performance.now();r.trigger(I.FRAG_DECRYPTED,{frag:e,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=N.IDLE})}}doTick(){if(!this.media){this.state=N.IDLE;return}if(this.state===N.IDLE){const{currentTrackId: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(),a=Rt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,it.MAIN),h=i.details,u=this.getMaxBufferLength(c==null?void 0:c.len)+h.levelTargetDuration;if(l>u)return;const A=h.fragments,d=A.length,f=h.edge;let g=null;const p=this.fragPrevious;if(o<f){const m=s.maxFragLookUpTolerance,C=o>f-m?0:m;g=ir(p,A,Math.max(A[0].start,o),C),!g&&p&&p.start<A[0].start&&(g=A[0])}else g=A[d-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const m=g.sn-h.startSN,C=A[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,o)}}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 o_(this.tracksBuffered[this.currentTrackId]||[])}}class o_{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 Dd extends Cr{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=>{Ni(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,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=e.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}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(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Qe(o,a);if(h>-1)r=a[h];else{const u=Qe(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${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||Ji(r,t)))return s}if(t){for(let s=0;s<e.length;s++){const r=e[s];if(Wi(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(Wi(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(eo(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&&Ji(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(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}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=>eo(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:a,groupId:o="",name:l,type:c,url:h}=s;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:h});const u=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(u)}}class l_{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 vh=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class Rd{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=TS(oi(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 l_(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=oi(this.appendSource);if(i&&s){var r;const a=this.mediaSource=new s;this.log(`created media source: ${(r=a.constructor)==null?void 0:r.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,xh(i),c_(i,o),i.load()}catch{i.src=o}else i.src=o;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&&xh(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(a=>{if(i){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:h,levelCodec:u,container:A,metadata:d}=e[a],f=qc(l.codec,l.levelCodec),g=f==null?void 0:f.replace(vh,"$1");let p=qc(h,u);const m=(o=p)==null?void 0:o.replace(vh,"$1");if(p&&g!==m){a.slice(0,5)==="audio"&&(p=jn(p,this.appendSource));const C=`${A};codecs=${p}`;this.appendChangeType(a,C),this.log(`switching codec ${f} to ${p}`),this.tracks[a]={buffer:l.buffer,codec:h,container:A,levelCodec:u,metadata:d,id:c}}}}else this.pendingTracks[a]=e[a]}),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:a,type:o,frag:l,part:c,chunkMeta:h}=e,u=h.buffering[o],A=self.performance.now();u.start=A;const d=l.stats.buffering,f=c?c.stats.buffering:null;d.start===0&&(d.start=A),f&&f.start===0&&(f.start=A);const g=r.audio;let p=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const m=l.start,C={execute:()=>{if(u.executeStart=self.performance.now(),p){const E=this.sourceBuffer[o];if(E){const S=m-E.timestampOffset;Math.abs(S)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${m} (delta: ${S}) sn: ${l.sn})`),E.timestampOffset=m)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const E=self.performance.now();u.executeEnd=u.end=E,d.first===0&&(d.first=E),f&&f.first===0&&(f.first=E);const{sourceBuffer:S}=this,y={};for(const _ in S)y[_]=Rt.getBuffered(S[_]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:y})},onError:E=>{const S={type:rt.MEDIA_ERROR,parent:l.type,details:M.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:h,error:E,err:E,fatal:!1};if(E.code===DOMException.QUOTA_EXCEEDED_ERR)S.details=M.BUFFER_FULL_ERROR;else{const y=++this.appendErrors[o];S.details=M.BUFFER_APPEND_ERROR,this.warn(`Failed ${y}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),y>=i.config.appendErrorMaxRetry&&(S.fatal=!0)}i.trigger(I.ERROR,S)}};s.append(C,o,!!this.pendingTracks[o])}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:a=>{this.warn(`Failed to remove from ${r} SourceBuffer`,a)}});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=[],a=s?s.elementaryStreams:i.elementaryStreams;a[vt.AUDIOVIDEO]?r.push("audiovideo"):(a[vt.AUDIO]&&r.push("audio"),a[vt.VIDEO]&&r.push("video"));const o=()=>{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(o,r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((s,r)=>{const a=this.sourceBuffer[r];return a&&(!e.type||e.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} sourceBuffer now EOS`))),s&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const a=this.sourceBuffer[r];a&&(a.ending=!1)});const{mediaSource: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,a=i.currentTime,o=e.levelTargetDuration,l=e.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(j(l)&&l>0){const c=Math.max(l,o),h=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,h)}if(j(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(c,o),u=Math.floor(a/o)*o+h;this.flushFrontBuffer(a,o,u)}}flushBackBuffer(t,e,i){const{details:s,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];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 ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(t,e,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(a=>{const o=s[a];if(o){const l=Rt.getBuffered(o),c=l.length;if(c<2)return;const h=l.start(c-1),u=l.end(c-1);if(i>h||t>=h&&t<=u)return;if(o.ended&&t-u<2*e){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:a})}})}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,a=i.duration,o=j(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(t)):(r>o&&r>a||!j(a))&&(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),a=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${a}.`),e.setLiveSeekableRange(r,a)}}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(a=>{e.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.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 a=t[r];if(!a)throw Error(`source buffer exists for track ${r}, however track does not`);let o=((s=a.levelCodec)==null?void 0:s.indexOf(","))===-1?a.levelCodec:a.codec;o&&r.slice(0,5)==="audio"&&(o=jn(o,this.appendSource));const l=`${a.container};codecs=${o}`;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",(u,A)=>{const d=A.removedRanges;d!=null&&d.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(I.ERROR,{type:rt.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:rt.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:a,sourceBuffer:o}=this,l=o[t];if(!s||!r||!l){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(t);return}const c=j(s.duration)?s.duration:1/0,h=j(r.duration)?r.duration:1/0,u=Math.max(0,e),A=Math.min(i,c,h);A>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${A}] from the ${t} SourceBuffer`),l.remove(u,A)):a.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 a=this.sourceBuffer[r];a!=null&&a.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 xh(n){const t=n.querySelectorAll("source");[].slice.call(t).forEach(e=>{n.removeChild(e)})}function c_(n,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,n.appendChild(e)}const h_={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},wd=n=>String.fromCharCode(h_[n]||n),Ie=15,Ke=100,u_={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},A_={17:2,18:4,21:6,22:8,23:10,19:13,20:15},d_={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},f_={25:2,26:4,29:6,30:8,31:10,27:13,28:15},g_=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class m_{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 Ld{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 p_{constructor(){this.uchar=" ",this.penState=new Ld}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 E_{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Ld,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Ke;e++)this.chars.push(new p_);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=wd(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 fa{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 E_(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 o=0;o<Ie;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[e-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=e;const i=this.rows[this.currRow];if(t.indent!==null){const r=t.indent,a=Math.max(r-1,0);i.setCursor(t.indent),t.color=i.chars[a].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 a=this.rows[r].getTextString();a&&(s=r+1,t?e.push("Row "+s+": '"+a+"'"):e.push(a.trim()))}return e.length>0&&(t?i="["+e.join(" | ")+"]":i=e.join(`
|
|
24
|
+
`)),i}getTextAndFormat(){return this.rows}}class Dh{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 fa(i),this.nonDisplayedMemory=new fa(i),this.lastOutputScreen=new fa(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 Rh{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=I_(),this.logger=void 0;const s=this.logger=new m_;this.channels=[null,new Dh(t,e,s),new Dh(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 a=!1,o=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(C_(s,r,l)){In(null,null,l),this.logger.log(3,()=>"Repeated command ("+fi([s,r])+") is dropped");continue}In(s,r,this.cmdHistory),a=this.parseCmd(s,r),a||(a=this.parseMidrow(s,r)),a||(a=this.parsePAC(s,r)),a||(a=this.parseBackgroundAttributes(s,r))}else In(null,null,l);if(!a&&(o=this.parseChars(s,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+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,a=this.channels[r];return t===20||t===21||t===28||t===29?e===32?a.ccRCL():e===33?a.ccBS():e===34?a.ccAOF():e===35?a.ccAON():e===36?a.ccDER():e===37?a.ccRU(2):e===38?a.ccRU(3):e===39?a.ccRU(4):e===40?a.ccFON():e===41?a.ccRDC():e===42?a.ccTR():e===43?a.ccRTD():e===44?a.ccEDM():e===45?a.ccCR():e===46?a.ccENM():e===47&&a.ccEOC():a.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 a=t<=23?1:2;e>=64&&e<=95?i=a===1?u_[t]:d_[t]:i=a===1?A_[t]:f_[t];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,e)),this.currentChannel=a,!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 a;r===17?a=e+80:r===18?a=e+112:a=e+144,this.logger.log(2,()=>"Special char '"+wd(a)+"' in channel "+i),s=[a]}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 a={};t===16||t===24?(r=Math.floor((e-32)/2),a.background=g_[r],e%2===1&&(a.background=a.background+"_semi")):e===45?a.background="transparent":(a.foreground="black",e===47&&(a.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(a),!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 C_(n,t,e){return e.a===n&&e.b===t}function I_(){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(qi!=null&&qi.VTTCue)return self.VTTCue;const n=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return e(n,o)}function s(o){return e(t,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let A="",d=!1,f=o,g=l,p=c,m=null,C="",E=!0,S="auto",y="start",_=50,T="middle",v=50,F="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return A},set:function(x){A=""+x}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return d},set:function(x){d=!!x}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(x){if(typeof x!="number")throw new TypeError("Start time must be set to a number.");f=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return g},set:function(x){if(typeof x!="number")throw new TypeError("End time must be set to a number.");g=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return p},set:function(x){p=""+x,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return m},set:function(x){m=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return C},set:function(x){const w=i(x);if(w===!1)throw new SyntaxError("An invalid or illegal string was specified.");C=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return E},set:function(x){E=!!x,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return S},set:function(x){if(typeof x!="number"&&x!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return y},set:function(x){const w=s(x);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");y=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return _},set:function(x){if(x<0||x>100)throw new Error("Position must be between 0 and 100.");_=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return T},set:function(x){const w=s(x);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");T=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return v},set:function(x){if(x<0||x>100)throw new Error("Size must be between 0 and 100.");v=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return F},set:function(x){const w=s(x);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");F=w,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class y_{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function bd(n){function t(i,s,r,a){return(i|0)*3600+(s|0)*60+(r|0)+parseFloat(a||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 B_{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 Fd(n,t,e,i){const s=i?n.split(i):[n];for(const r in s){if(typeof s[r]!="string")continue;const a=s[r].split(e);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}const io=new il(0,0,""),Bn=io.align==="middle"?"middle":"center";function S_(n,t,e){const i=n;function s(){const o=bd(n);if(o===null)throw new Error("Malformed timestamp: "+i);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new B_;Fd(o,function(A,d){let f;switch(A){case"region":for(let g=e.length-1;g>=0;g--)if(e[g].id===d){c.set(A,e[g].region);break}break;case"vertical":c.alt(A,d,["rl","lr"]);break;case"line":f=d.split(","),c.integer(A,f[0]),c.percent(A,f[0])&&c.set("snapToLines",!1),c.alt(A,f[0],["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start",Bn,"end"]);break;case"position":f=d.split(","),c.percent(A,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start",Bn,"end","line-left","line-right","auto"]);break;case"size":c.percent(A,d);break;case"align":c.alt(A,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"&&io.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 u=c.get("position","auto");u==="auto"&&io.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);n=n.slice(3),a(),t.endTime=s(),a(),r(n,t)}function Md(n){return n.replace(/<br(?: \/)?>/gi,`
|
|
25
|
+
`)}class T_{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new y_,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,a=0;for(r=Md(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
26
|
+
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
27
|
+
`&&++a,e.buffer=r.slice(a),o}function s(r){Fd(r,function(a,o){},/:/)}try{let r="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;r=i();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let a=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!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{S_(r,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!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 __=/\r\n|\n\r|\n|\r/g,ga=function(t,e,i=0){return t.slice(i,i+e.length)===e},v_=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},ma=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 ma(n.toString())+ma(t.toString())+ma(e)}const x_=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(;(a=r)!=null&&a.new;){var a;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i};function D_(n,t,e,i,s,r,a){const o=new T_,l=Ge(new Uint8Array(n)).trim().replace(__,`
|
|
31
|
+
`).split(`
|
|
32
|
+
`),c=[],h=t?XT(t.baseTime,t.timescale):0;let u="00:00.000",A=0,d=0,f,g=!0;o.oncue=function(p){const m=e[i];let C=e.ccOffset;const E=(A-h)/9e4;if(m!=null&&m.new&&(d!==void 0?C=e.ccOffset=m.start:x_(e,i,E)),E){if(!t){f=new Error("Missing initPTS for VTT MPEGTS");return}C=E-e.presentationOffset}const S=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+S,0);const _=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(_)),p.id||(p.id=sl(p.startTime,p.endTime,_)),p.endTime>0&&c.push(p)},o.onparsingerror=function(p){f=p},o.onflush=function(){if(f){a(f);return}r(c)},l.forEach(p=>{if(g)if(ga(p,"X-TIMESTAMP-MAP=")){g=!1,p.slice(16).split(",").forEach(m=>{ga(m,"LOCAL:")?u=m.slice(6):ga(m,"MPEGTS:")&&(A=parseInt(m.slice(7)))});try{d=v_(u)/1e3}catch(m){f=m}return}else p===""&&(g=!1);o.parse(p+`
|
|
33
|
+
`)}),o.flush()}const pa="stpp.ttml.im1t",Pd=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,kd=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,R_={left:"start",center:"center",right:"end",start:"start",end:"end"};function wh(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(o=>Ge(o)),a=qT(t.baseTime,1,t.timescale);try{r.forEach(o=>e(w_(o,a)))}catch(o){i(o)}}function w_(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},a=Object.keys(r).reduce((u,A)=>(u[A]=s.getAttribute(`ttp:${A}`)||r[A],u),{}),o=s.getAttribute("xml:space")!=="preserve",l=Lh(Ea(s,"styling","style")),c=Lh(Ea(s,"layout","region")),h=Ea(s,"body","[begin]");return[].map.call(h,u=>{const A=Qd(u,o);if(!A||!u.hasAttribute("begin"))return null;const d=Ia(u.getAttribute("begin"),a),f=Ia(u.getAttribute("dur"),a);let g=Ia(u.getAttribute("end"),a);if(d===null)throw bh(u);if(g===null){if(f===null)throw bh(u);g=d+f}const p=new il(d-t,g-t,A);p.id=sl(p.startTime,p.endTime,p.text);const m=c[u.getAttribute("region")],C=l[u.getAttribute("style")],E=L_(m,C,l),{textAlign:S}=E;if(S){const y=R_[S];y&&(p.lineAlign=y),p.align=S}return Qt(p,E),p}).filter(u=>u!==null)}function Ea(n,t,e){const i=n.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function Lh(n){return n.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Qd(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?Qd(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function L_(n,t,e){const i="http://www.w3.org/ns/ttml#styling";let s=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&e.hasOwnProperty(a)&&(s=e[a]),r.reduce((o,l)=>{const c=Ca(t,i,l)||Ca(n,i,l)||Ca(s,i,l);return c&&(o[l]=c),o},{})}function Ca(n,t,e){return n&&n.hasAttributeNS(t,e)?n.getAttributeNS(t,e):null}function bh(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Ia(n,t){if(!n)return null;let e=bd(n);return e===null&&(Pd.test(n)?e=b_(n,t):kd.test(n)&&(e=F_(n,t))),e}function b_(n,t){const e=Pd.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 F_(n,t){const e=kd.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 Od{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=Mh(),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 Rh(1,t,e),this.cea608Parser2=new Rh(3,i,s)}}addCues(t,e,i,s,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=M_(l[0],l[1],e,i);if(c>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],i),a=!0,c/(i-e)>.5))return}if(a||r.push([e,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,e,i,s)}else{const o=this.Cues.newCue(null,e,i,s);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[e.cc]={baseTime:s,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(I.FRAG_LOADED,o)}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(Fh(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:a}=e[t],o=this.getExistingTrack(r,a);if(o)i[t]=o,Ni(i[t]),XA(i[t],s);else{const l=this.createTextTrack("captions",r,a);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=>{Ni(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Mh(),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++)Ni(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(r=>r.textCodec===pa);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Td(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Rn(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let A=0;A<o.length;A++)if(o[A]&&Fh(o[A],l)){u=o[A],o[A]=null;break}u&&(h=u)}if(h)Ni(h);else{const u=Gd(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&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 a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}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]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.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===it.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=e.frag,h=(i=(s=e.part)==null?void 0:s.index)!=null?i:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===it.SUBTITLE)if(s.byteLength){const r=i.decryptdata,a="stats"in e;if(r==null||!r.encrypted||a){const o=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),o&&o.textCodec===pa?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;wh(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:a}=this,o=r.length-1;if(!r[i.cc]&&o===-1){a.push(t);return}const l=this.hls,c=(e=i.initSegment)!=null&&e.data?ge(i.initSegment.data,new Uint8Array(s)):s;D_(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 u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(t):this._fallbackToIMSC1(i,s),R.log(`Failed to parse VTT cue: ${h}`),!(u&&o>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||wh(e,this.initPTS[t.cc],()=>{i.textCodec=pa,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=>WA(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===it.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:a}=e;if(!(r.type===it.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);i.addData(a[o].pts,c[0]),s.addData(a[o].pts,c[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>$a(o[l],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>$a(o[l],e,s))}}}extractCea608Data(t){const e=[[],[]],i=t[0]&31;let s=2;for(let r=0;r<i;r++){const a=t[s++],o=127&t[s++],l=127&t[s++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(e[h].push(o),e[h].push(l))}}return e}}function Gd(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Fh(n,t){return!!n&&n.kind===Gd(t)&&eo(t,n)}function M_(n,t,e,i){return Math.min(t,i)-Math.max(n,e)}function Mh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Br{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,Br.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=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=t.length-1;const a=Math.max(e,i);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=a||l.height>=a)&&s(l,t[o+1])){r=o;break}}return r}}class Ud{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,a=i-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(I.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){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 Sn="[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.debug=R.debug.bind(R,Sn),this.log=R.log.bind(R,Sn),this.warn=R.warn.bind(R,Sn),this.error=R.error.bind(R,Sn),this.onMediaEncrypted=e=>{const{initDataType:i,initData:s}=e,r=`"${e.type}" event: init data type: "${i}"`;if(this.debug(r),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=dn(this.config));const o=a.map(ia).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=ta(a);let l,c;if(i==="sinf"){if(o!==Bt.FAIRPLAY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const f=Nt(new Uint8Array(s));try{const g=Jo(JSON.parse(f).sinf),p=VA(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=p.subarray(8,24),c=Bt.FAIRPLAY}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}}else{if(o!==Bt.WIDEVINE&&o!==Bt.PLAYREADY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const f=IS(s),g=f.filter(m=>!!m.systemId&&ea(m.systemId)===o);g.length>1&&this.warn(`${r} Using first of ${g.length} pssh found for selected key-system ${o}`);const p=g[0];if(!p){f.length===0||f.some(m=>!m.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${f.map(m=>ea(m.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(c=ea(p.systemId),p.version===0&&p.data)if(c===Bt.WIDEVINE){const m=p.data.length-22;l=p.data.subarray(m,m+16)}else c===Bt.PLAYREADY&&(l=QA(p.data))}if(!c||!l){this.log(`Unable to handle ${r} with key-system ${o}`);return}const h=Fe.hexDump(l),{keyIdToKeySessionPromise:u,mediaKeySessions:A}=this;let d=u[h];for(let f=0;f<A.length;f++){const g=A[f],p=g.decryptdata;if(!p.keyId)continue;const m=Fe.hexDump(p.keyId);if(h===m||p.uri.replace(/-/g,"").indexOf(h)!==-1){if(d=u[m],p.pssh)break;delete u[m],p.pssh=new Uint8Array(s),p.keyId=l,d=u[h]=d.then(()=>this.generateRequestWithPreferredKeySession(g,i,s,"encrypted-event-key-match")),d.catch(C=>this.handleError(C));break}}if(!d){if(c!==o){this.log(`Ignoring "${r}" with ${c} init data for selected key-system ${o}`);return}d=u[h]=this.getKeySystemSelectionPromise([c]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const m=new Xi("ISO-23001-7",h,(p=ia(f))!=null?p:"");return m.pssh=new Uint8Array(s),m.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const C=this.createMediaKeySessionContext({decryptdata:m,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(C,i,s,"encrypted-event-no-match")})}),d.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},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.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=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===Bt.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(e===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return e}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=(a,o,l)=>!!a&&l.indexOf(a)===o,s=e.map(a=>a.audioCodec).filter(i),r=e.map(a=>a.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,s,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof le?o(u):o(new le({type:rt.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.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 kA===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=qB(t,e,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(t,s);const o=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),o.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${t}"`),c.then(u=>u?this.setMediaKeysServerCertificate(h,t,u):h))),o.mediaKeys.catch(h=>{this.error(`Failed to create media-keys for "${t}"}: ${h}`)}),o.mediaKeys})}return a.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=dn(this.config),r=t.map(ta).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=ia(a);o?e(o):i(new Error(`Unable to find format for key-system "${a}"`))}).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:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:e});return this.generateRequestWithPreferredKeySession(l,"cenc",e.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),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:rt.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=ta(t.keyFormat),r=s?[s]:dn(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=dn(this.config)),t.length===0)throw new le({type:rt.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)}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,a;const o=(r=this.config.drmSystems)==null||(a=r[t.keySystem])==null?void 0:a.generateRequest;if(o)try{const f=o.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,u=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===Bt.FAIRPLAY&&(this.updateKeySession(t,Ja("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${p}"`)},A=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",u),t.mediaKeysSession.addEventListener("keystatuseschange",A);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:rt.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new le({type:rt.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:rt.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((a,o)=>{const l={responseType:"arraybuffer",url:r},c=e.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(A,d,f,g)=>{a(A.data)},onError:(A,d,f,g)=>{o(new le({type:rt.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:$t({url:l.url,data:void 0},A)},`"${t}" certificate request failed (${r}). Status: ${A.code} (${A.text})`))},onTimeout:(A,d,f)=>{o(new le({type:rt.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:(A,d,f)=>{o(new Error("aborted"))}};s.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,r)=>{t.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${e}"`),s(t)}).catch(a=>{r(new le({type:rt.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.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:rt.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 u=0,A=r.length;u<A;u++){var a,o;h=r[u];const d=(a=h.querySelector("name"))==null?void 0:a.textContent,f=(o=h.querySelector("value"))==null?void 0:o.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 Ja(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(a=>{if(!i.decryptdata)throw a;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)}).then(a=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:a||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 a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,t)}catch(h){this.error(h)}s(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new le({type:rt.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,e).then(s,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,e).then(({xhr:l,licenseChallenge:c})=>{t.keySystem==Bt.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.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),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={},Xi.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 so;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(so||(so={}));var Ei;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(Ei||(Ei={}));const P_={[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 ji{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map(i=>i instanceof ji?i:new ji(i))),this.value=t,this.params=e}}class Nd{constructor(t){this.description=void 0,this.description=t}}const k_="Dict";function Q_(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 O_(n,t,e,i){return new Error(`failed to ${n} "${Q_(t)}" as ${e}`,{cause:i})}const Ph="Bare Item",G_="Boolean",U_="Byte Sequence",N_="Decimal",H_="Integer";function K_(n){return n<-999999999999999||999999999999999<n}const Y_=/[\x00-\x1f\x7f]+/,V_="Token",J_="Key";function Ue(n,t,e){return O_("serialize",n,t,e)}function z_(n){if(typeof n!="boolean")throw Ue(n,G_);return n?"?1":"?0"}function $_(n){return btoa(String.fromCharCode(...n))}function q_(n){if(ArrayBuffer.isView(n)===!1)throw Ue(n,U_);return`:${$_(n)}:`}function Hd(n){if(K_(n))throw Ue(n,H_);return n.toString()}function X_(n){return`@${Hd(n.getTime()/1e3)}`}function Kd(n,t){if(n<0)return-Kd(-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 W_(n){const t=Kd(n,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ue(n,N_);const e=t.toString();return e.includes(".")?e:`${e}.0`}const j_="String";function Z_(n){if(Y_.test(n))throw Ue(n,j_);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function tv(n){return n.description||n.toString().slice(7,-1)}function kh(n){const t=tv(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ue(t,V_);return t}function no(n){switch(typeof n){case"number":if(!j(n))throw Ue(n,Ph);return Number.isInteger(n)?Hd(n):W_(n);case"string":return Z_(n);case"symbol":return kh(n);case"boolean":return z_(n);case"object":if(n instanceof Date)return X_(n);if(n instanceof Uint8Array)return q_(n);if(n instanceof Nd)return kh(n);default:throw Ue(n,Ph)}}function ro(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Ue(n,J_);return n}function nl(n){return n==null?"":Object.entries(n).map(([t,e])=>e===!0?`;${ro(t)}`:`;${ro(t)}=${no(e)}`).join("")}function Yd(n){return n instanceof ji?`${no(n.value)}${nl(n.params)}`:no(n)}function ev(n){return`(${n.value.map(Yd).join(" ")})${nl(n.params)}`}function iv(n,t={whitespace:!0}){if(typeof n!="object")throw Ue(n,k_);const e=n instanceof Map?n.entries():Object.entries(n),i=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([s,r])=>{r instanceof ji||(r=new ji(r));let a=ro(s);return r.value===!0?a+=nl(r.params):(a+="=",Array.isArray(r.value)?a+=ev(r):a+=Yd(r)),a}).join(`,${i}`)}function sv(n,t){return iv(n,t)}const nv=n=>n==="ot"||n==="sf"||n==="st",rv=n=>typeof n=="number"?j(n):n!=null&&n!==""&&n!==!1;function av(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 ov(){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),lv=(n,t)=>(t!=null&&t.baseUrl&&(n=av(n,t.baseUrl)),encodeURIComponent(n)),Tn=n=>Mn(n/100)*100,cv={br:Mn,d:Mn,bl:Tn,dl:Tn,mtp:Tn,nor:lv,rtp:Tn,tb:Mn};function hv(n,t){const e={};if(n==null||typeof n!="object")return e;const i=Object.keys(n).sort(),s=Qt({},cv,t==null?void 0:t.formatters),r=t==null?void 0:t.filter;return i.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const l=s[a];l&&(o=l(o,t)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||rv(o)&&(nv(a)&&typeof o=="string"&&(o=new Nd(o)),e[a]=o))}),e}function Vd(n,t={}){return n?sv(hv(n,t),Qt({whitespace:!1},t)):""}function uv(n,t={}){if(!n)return{};const e=Object.entries(n),i=Object.entries(P_).concat(Object.entries((t==null?void 0:t.customHeaderMap)||{})),s=e.reduce((r,a)=>{var o,l;const[c,h]=a,u=((o=i.find(A=>A[1].includes(c)))==null?void 0:o[0])||Ei.REQUEST;return(l=r[u])!=null||(r[u]={}),r[u][c]=h,r},{});return Object.entries(s).reduce((r,[a,o])=>(r[a]=Vd(o,t),r),{})}function Av(n,t,e){return Qt(n,uv(t,e))}const dv="CMCD";function fv(n,t={}){if(!n)return"";const e=Vd(n,t);return`${dv}=${encodeURIComponent(e)}`}const Qh=/CMCD=[^&#]+/;function gv(n,t,e){const i=fv(t,e);if(!i)return n;if(Qh.test(n))return n.replace(Qh,i);const s=n.includes("?")?"&":"?";return`${n}${s}${i}`}class Jd{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,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===qt.VIDEO||o===qt.AUDIO||o==qt.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),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||ov(),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:so.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,a)=>(s.includes(a)&&(r[a]=e[a]),r),{})),this.useHeaders?(t.headers||(t.headers={}),Av(t.headers,e)):t.url=gv(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,a=r>-1?r+1:s.levels.length;i=s.levels.slice(0,a)}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,a,o){e(r),this.loader.load(r,a,o)}}}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,a,o){e(r),this.loader.load(r,a,o)}}}}const mv=3e5;class zd{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,a=this.pathwayId;if(e.context){const{groupId:o,pathwayId:l,type:c}=e.context;o&&s?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&s&&(r=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),i.resolved||R.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${a} 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]>mv&&delete i[r]});for(let r=0;r<t.length;r++){const a=t[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(a),e.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,ed(e),this.hls.trigger(I.LEVELS_UPDATED,{levels:e});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(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:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(e.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new bt(h.attrs);u["PATHWAY-ID"]=a;const A=u.AUDIO&&`${u.AUDIO}_clone_${a}`,d=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;A&&(i[u.AUDIO]=A,u.AUDIO=A),d&&(s[u.SUBTITLES]=d,u.SUBTITLES=d);const f=$d(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Bi({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)g.addGroupId("audio",`${h.audioGroups[p]}_clone_${a}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)g.addGroupId("text",`${h.subtitleGroups[p]}_clone_${a}`);return g});e.push(...c),Oh(this.audioTracks,i,l,a),Oh(this.subtitleTracks,s,l,a)})}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},a=e.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,A,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||A.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,u,A,d)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,A)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.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 Oh(n,t,e,i){n&&Object.keys(t).forEach(s=>{const r=n.filter(a=>a.groupId===s).map(a=>{const o=Qt({},a);return o.details=void 0,o.attrs=new bt(o.attrs),o.url=o.attrs.URI=$d(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=i,o});n.push(...r)})}function $d(n,t,e,i){const{HOST:s,PARAMS:r,[e]:a}=i;let o;t&&(o=a==null?void 0:a[t],o&&(n=o));const l=new self.URL(n);return s&&!o&&(l.host=s),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const pv=/^age:\s*[\d.]+\s*$/im;class qd{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 $s,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(a=>{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(a=>{this.callbacks.onError({code:i.status,text:a.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:a}=i.loadPolicy;if(s)for(const o in s)t.setRequestHeader(o,s[o]);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:a,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 a=e.status,o=e.responseType==="text"?e.responseText:null;if(a>=200&&a<300){const u=o??e.response;if(u!=null){i.loading.end=Math.max(self.performance.now(),i.loading.first);const A=e.responseType==="arraybuffer"?u.byteLength:u.length;if(i.loaded=i.total=A,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(i,t,u,e),!this.callbacks)return;const f={url:e.responseURL,data:u,code:a};this.callbacks.onSuccess(f,i,t,e);return}}const l=r.loadPolicy.errorRetry,c=i.retry,h={url:t.url,data:void 0,code:a};er(l,c,!1,h)?this.retry(l):(R.error(`${a} while loading ${t.url}`),this.callbacks.onError({code:a,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=qo(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&&pv.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 Ev(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Cv=/(\d+)-(\d+)\/(\d+)/;class Gh{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||Sv,this.controller=new self.AbortController,this.stats=new $s}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=Iv(t,this.controller.signal),a=i.onProgress,o=t.responseType==="arraybuffer",l=o?"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(u=>{this.response=this.loader=u;const A=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-(A-s.loading.start)),!u.ok){const{status:d,statusText:f}=u;throw new Tv(f||"fetch, bad network response",d,u)}return s.loading.first=A,s.total=Bv(u.headers)||s.total,a&&j(e.highWaterMark)?this.loadProgressively(u,s,t,e.highWaterMark,a):o?u.arrayBuffer():t.responseType==="json"?u.json():u.text()}).then(u=>{const A=this.response;if(!A)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const d=u[l];d&&(s.loaded=s.total=d);const f={url:A.url,data:u,code:A.status};a&&!j(e.highWaterMark)&&a(s,t,u,A),i.onSuccess(f,s,t,A)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const A=u&&u.code||0,d=u?u.message:null;i.onError({code:A,text:d},t,u?u.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 a=new od,o=t.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(e,i,a.flush(),t),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return e.loaded+=u,u<s||a.dataLength?(a.push(h),a.dataLength>=s&&r(e,i,a.flush(),t)):r(e,i,h,t),l()}).catch(()=>Promise.reject());return l()}}function Iv(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 yv(n){const t=Cv.exec(n);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Bv(n){const t=n.get("Content-Range");if(t){const i=yv(t);if(j(i))return i}const e=n.get("Content-Length");if(e)return parseInt(e)}function Sv(n,t){return new self.Request(n.url,t)}class Tv extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const _v=/\s/,vv={newCue(n,t,e,i){const s=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let A=0;A<i.rows.length;A++)if(r=i.rows[A],o=!0,l=0,c="",!r.isEmpty()){var u;for(let g=0;g<r.chars.length;g++)_v.test(r.chars[g].uchar)&&o?l++:(c+=r.chars[g].uchar,o=!1);r.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const d=Md(c.trim()),f=sl(t,e,d);n!=null&&(u=n.cues)!=null&&u.getCueById(f)||(a=new h(t,e,d),a.id=f,a.line=A+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return n&&s.length&&(s.sort((A,d)=>A.line==="auto"||d.line==="auto"?0:A.line>8&&d.line>8?d.line-A.line:A.line-d.line),s.forEach(A=>WA(n,A))),s}},xv={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Xd=$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:qd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:rd,bufferController:Rd,capLevelController:Br,errorController:sd,fpsController:Ud,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:kA,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:xv},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},Dv()),{},{subtitleStreamController:xd,subtitleTrackController:Dd,timelineController:Od,audioStreamController:_d,audioTrackController:vd,emeController:Ii,cmcdController:Jd,contentSteeringController:zd});function Dv(){return{cueHandler:vv,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 Rv(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=ao(n),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=t[a]===void 0,l=[];s.forEach(c=>{const h=`${r}Loading${c}`,u=t[h];if(u!==void 0&&o){l.push(h);const A=e[a].default;switch(t[a]={default:A},c){case"TimeOut":A.maxLoadTimeMs=u,A.maxTimeToFirstByteMs=u;break;case"MaxRetry":A.errorRetry.maxNumRetry=u,A.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":A.errorRetry.retryDelayMs=u,A.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":A.errorRetry.maxRetryDelayMs=u,A.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&R.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(t[a])}`)}),$t($t({},e),t)}function ao(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(ao):Object.keys(n).reduce((t,e)=>(t[e]=ao(n[e]),t),{}):n}function wv(n){const t=n.loader;t!==Gh&&t!==qd?(R.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):Ev()&&(n.loader=Gh,n.progressive=!0,n.enableSoftwareAES=!0,R.log("[config]: Progressive streaming enabled, using FetchLoader"))}let ya;class Lv extends Cr{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={},a={};let o=!1,l=!1,c=!1;e.levels.forEach(h=>{var u,A;const d=h.attrs;let{audioCodec:f,videoCodec:g}=h;((u=f)==null?void 0:u.indexOf("mp4a.40.34"))!==-1&&(ya||(ya=/chrome|firefox/i.test(navigator.userAgent)),ya&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=jn(f,i)),((A=g)==null?void 0:A.indexOf("avc1"))===0&&(g=h.videoCodec=DS(g));const{width:p,height:m,unknownCodecs:C}=h;if(o||(o=!!(p&&m)),l||(l=!!g),c||(c=!!f),C!=null&&C.length||f&&!aa(f,"audio",i)||g&&!aa(g,"video",i))return;const{CODECS:E,"FRAME-RATE":S,"HDCP-LEVEL":y,"PATHWAY-ID":_,RESOLUTION:T,"VIDEO-RANGE":v}=d,x=`${`${_||"."}-`}${h.bitrate}-${T}-${S}-${E}-${v}-${y}`;if(r[x])if(r[x].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const w=a[x]+=1;h.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const U=new Bi(h);r[x]=U,s.push(U)}else r[x].addGroupId("audio",d.AUDIO),r[x].addGroupId("text",d.SUBTITLES);else{const w=new Bi(h);r[x]=w,a[x]=1,s.push(w)}}),this.filterAndSortMediaOptions(s,e,o,l,c)}filterAndSortMediaOptions(t,e,i,s,r){let a=[],o=[],l=t;if((i||s)&&r&&(l=l.filter(({videoCodec:f,videoRange:g,width:p,height:m})=>(!!f||!!(p&&m))&&NS(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:rt.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;a=e.audioTracks.filter(g=>!g.audioCodec||aa(g.audioCodec,"audio",f)),Uh(a)}e.subtitles&&(o=e.subtitles,Uh(o));const c=l.slice(0);l.sort((f,g)=>{if(f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(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=$c(f.videoCodec),m=$c(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 u;this._firstLevel=f;const g=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const m=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);m>p&&p===Xd.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}const A=r&&!s,d={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:!A&&a.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"),u=t<0;if(this.hls.trigger(I.ERROR,{type:rt.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:t,fatal:u,error:h,reason:h.message}),u)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,a=e[t],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=a,i===t&&a.details&&s&&r===o)return;this.log(`Switching to level ${t} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:t,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.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===it.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,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,e,a.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(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}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(a=>a.level=-1)),!1));ed(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 Uh(n){const t={};n.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}class bv{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:rt.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 a=e[r];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?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 a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:t,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":return this.loadKeyHTTP(o,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((a,o)=>{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},u={onSuccess:(A,d,f,g)=>{const{frag:p,keyInfo:m,url:C}=f;if(!p.decryptdata||m!==this.keyUriToKeyInfo[C])return o(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(A.data),p.keyLoader=null,m.loader=null,a({frag:p,keyInfo:m})},onError:(A,d,f,g)=>{this.resetLoader(d),o(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${A.code} loading key ${A.text}`),f,$t({url:l.url,data:void 0},A)))},onTimeout:(A,d,f)=>{this.resetLoader(d),o(this.createKeyLoadError(e,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(A,d,f)=>{this.resetLoader(d),o(this.createKeyLoadError(e,M.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,u)})}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 Wd(){return self.SourceBuffer||self.WebKitSourceBuffer}function rl(){if(!oi())return!1;const t=Wd();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function jd(){if(!rl())return!1;const n=oi();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(Ns(t,"video")))||["mp4a.40.2","fLaC"].some(t=>n.isTypeSupported(Ns(t,"audio"))))}function Fv(){var n;const t=Wd();return typeof(t==null||(n=t.prototype)==null?void 0:n.changeType)=="function"}const Mv=250,Pn=2,Pv=.1,kv=.05;class Qv{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:a,seeking:o}=s,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==t){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const p=self.performance.now()-r;R.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!Rt.getBuffered(s).length){this.nudgeRetry=0;return}const h=Rt.bufferInfo(s,a,0),u=h.nextStart||0;if(o){const p=h.len>Pn,m=!u||e&&e.start<=a||u-a>Pn&&!this.fragmentTracker.getPartialFragment(a);if(p||m)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var A;if(!(h.len>0)&&!u)return;const m=Math.max(u,h.start||0)-a,C=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(C==null||(A=C.details)==null?void 0:A.live)?C.details.targetduration*2:Pn,y=this.fragmentTracker.getPartialFragment(a);if(m>0&&(m<=S||y)){s.paused||this._trySkipBufferHole(y);return}}const d=self.performance.now();if(r===null){this.stalled=d;return}const f=d-r;if(!o&&f>=Mv&&(this._reportStall(h),!this.media))return;const g=Rt.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:s,media:r}=this;if(r===null)return;const a=r.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-a<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:rt.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,a=Rt.bufferInfo(s,r,0),o=r<a.start?a.start:a.nextStart;if(o){const l=a.len<=e.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,h=o-r;if(h>0&&(l||c)){if(h>e.maxBufferHole){const{fragmentTracker:A}=this;let d=!1;if(r===0){const f=A.getAppendedFrag(0,it.MAIN);f&&o<f.end&&(d=!0)}if(!d){const f=t||A.getAppendedFrag(r,it.MAIN);if(f){let g=!1,p=f.end;for(;p<o;){const m=A.getPartialFragment(p);if(m)p+=m.duration;else{g=!0;break}}if(g)return 0}}}const u=Math.max(o+kv,r+Pv);if(R.warn(`skipping hole, adjusting currentTime from ${r} to ${u}`),this.moved=!0,this.stalled=null,s.currentTime=u,t&&!t.gap){const A=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${u}`);i.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:A,reason:A.message,frag:t})}return u}}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 a=r+(s+1)*t.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${a}`);R.warn(o.message),i.currentTime=a,e.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${r} after ${t.nudgeMaxRetry} nudges`);R.error(a.message),e.trigger(I.ERROR,{type:rt.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Ov=100;class Gv extends yr{constructor(t,e,i){super(t,e,i,"[stream-controller]",it.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(Ov),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,a=s==null?void 0:s[r];this.resetStartWhenNotLoaded(a||null),this.state=N.IDLE}}break}this.state===N.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls: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 a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(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=a.details;if(!c||this.state===N.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=r,this.state=N.WAITING_LEVEL;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const A=this.backtrackFragment?this.backtrackFragment.start:o.end;let d=this.getNextFragment(A,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&&o.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,A)){if(!d.gap){const p=this.audioOnly&&!this.altAudio?vt.AUDIO:vt.VIDEO,m=(p===vt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,p,it.MAIN)}d=this.getNextFragmentLoopLoading(d,c,o,it.MAIN,u)}d&&(d.initSegment&&!d.initSegment.data&&!this.bitrateTest&&(d=d.initSegment),this.loadFragment(d,a,A))}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,it.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 o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!e.paused&&t){const o=this.hls.nextLoadLevel,l=t[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(e.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,h=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const 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 Qv(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 a=r.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!Fv(),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,a=e.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=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(a.live||(i=l.details)!=null&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(I.LEVEL_UPDATED,{details:a,level:r}),this.state===N.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=N.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:r}=t,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.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=o.videoCodec,h=l.PTSKnown||!l.live,u=(e=i.initSegment)==null?void 0:e.data,A=this._getAudioCodec(o),d=this.transmuxer=this.transmuxer||new Sd(this.hls,it.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=f!==-1,p=new Ir(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[i.cc];d.push(r,u,A,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 a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;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,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,s=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&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!==it.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(it.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!==vt.AUDIO||this.audioOnly&&!this.altAudio){const i=(e===vt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,e,it.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),a=(s.length?s.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,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:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{video:u,text:A,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,a),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(u&&g&&l.sn!=="initSegment"){const m=g.fragments[l.sn-1-g.startSN],C=l.sn===g.startSN,E=!m||l.cc>m.cc;if(r.independent!==!1){const{startPTS:S,endPTS:y,startDTS:_,endDTS:T}=u;if(c)c.elementaryStreams[u.type]={startPTS:S,endPTS:y,startDTS:_,endDTS:T};else if(u.firstKeyFrame&&u.independent&&a.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const v=this.getMainFwdBufferInfo(),F=(v?v.end:this.getLoadPosition())+this.config.maxBufferHole,x=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!C&&F<x-this.config.maxBufferHole&&!E){this.backtrack(l);return}else E&&(l.gap=!0);l.setElementaryStreamInfo(u.type,l.start,y,l.start,T,!0)}else C&&S>Pn&&(l.gap=!0);l.setElementaryStreamInfo(u.type,S,y,_,T),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,a,C||E)}else if(C||E)l.gap=!0;else{this.backtrack(l);return}}if(p){const{startPTS:m,endPTS:C,startDTS:E,endDTS:S}=p;c&&(c.elementaryStreams[vt.AUDIO]={startPTS:m,endPTS:C,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(vt.AUDIO,m,C,E,S),this.bufferFragmentData(p,l,c,a)}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&&A){const m={id:i,frag:l,details:g,samples:A.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:a,audiovideo:o}=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}]`)}a&&(a.levelCodec=t.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.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,it.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.19"}static isMSESupported(){return rl()}static isSupported(){return jd()}static getMediaSource(){return oi()}static get Events(){return I}static get ErrorTypes(){return rt}static get ErrorDetails(){return M}static get DefaultConfig(){return ni.defaultConfig?ni.defaultConfig:Xd}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,NB(t.debug||!1,"Hls instance");const e=this.config=Rv(ni.DefaultConfig,t);this.userConfig=t,e.progressive&&wv(e);const{abrController:i,bufferController:s,capLevelController:r,errorController:a,fpsController:o}=e,l=new a(this),c=this.abrController=new i(this),h=this.bufferController=new s(this),u=this.capLevelController=new r(this),A=new o(this),d=new FS(this),f=new OS(this),g=e.contentSteeringController,p=g?new g(this):null,m=this.levelController=new Lv(this,p),C=new uT(this),E=new bv(this.config),S=this.streamController=new Gv(this,C,E);u.setStreamController(S),A.setStreamController(S);const y=[d,m,S];p&&y.splice(1,0,p),this.networkControllers=y;const _=[c,h,u,A,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 v=e.subtitleStreamController;v&&y.push(new v(this,C,E)),this.createController(e.timelineController,_),E.emeController=this.emeController=this.createController(e.emeController,_),this.cmcdController=this.createController(e.cmcdController,_),this.latencyController=this.createController(GS,_),this.coreComponents=_,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:rt.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=Ko.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){US(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 a=t[r].attrs["HDCP-LEVEL"];if(a&&a<=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 Uv=Object.freeze(Object.defineProperty({__proto__:null,AbrController:rd,AttrList:bt,AudioStreamController:_d,AudioTrackController:vd,BasePlaylistController:Cr,BaseSegment:Vo,BaseStreamController:yr,BufferController:Rd,CMCDController:Jd,CapLevelController:Br,ChunkMetadata:Ir,ContentSteeringController:zd,DateRange:Yo,EMEController:Ii,ErrorActionFlags:ce,ErrorController:sd,ErrorDetails:M,ErrorTypes:rt,Events:I,FPSController:Ud,Fragment:Dn,Hls:ni,HlsSkip:bs,HlsUrlParameters:Wa,KeySystemFormats:Wt,KeySystems:Bt,Level:Bi,LevelDetails:PA,LevelKey:Xi,LoadStats:$s,MetadataSchema:Ae,NetworkErrorAction:Ht,Part:MA,PlaylistLevelType:it,SubtitleStreamController:xd,SubtitleTrackController:Dd,TimelineController:Od,default:ni,getMediaSource:oi,isMSESupported:rl,isSupported:jd},Symbol.toStringTag,{value:"Module"})),Nv=((n,t)=>typeof window<"u"&&typeof((n=window.document)==null?void 0:n.createElement)=="function"&&typeof((t=window.navigator)==null?void 0:t.userAgent)=="string")();let Ba=null;async function Hv(...n){var t;(t=Ba)!==null&&t!==void 0||(Ba=await IE(()=>Promise.resolve().then(()=>Uv),void 0));const e=Ba.default;return e.isSupported()?new e(...n):null}function Zd(n,{unsuspend:t="loadedmetadata",start:e=!0,hls:i={},crossOrigin:s="anonymous",muted:r=!0,loop:a=!0,playsInline:o=!0,onVideoFrame:l,...c}={}){const h=q(f=>f.gl),u=B.useRef(null),A=ts(()=>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:a,muted:r,playsInline:o,...c});if(g&&Nv&&g.endsWith(".m3u8")){const E=u.current=await Hv(i);E&&(E.on(I.MEDIA_ATTACHED,()=>void E.loadSource(g)),E.attachMedia(m))}const C=new zf(m);"colorSpace"in C?C.colorSpace=h.outputColorSpace:C.encoding=h.outputEncoding,m.addEventListener(t,()=>f(C))}),[n]),d=A.source.data;return Kv(d,l),B.useEffect(()=>(e&&A.image.play(),()=>{u.current&&(u.current.destroy(),u.current=null)}),[A,e]),A}const Sr=B.forwardRef(({children:n,src:t,...e},i)=>{const s=Zd(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))}),Kv=(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 tf={exports:{}};(function(n,t){(function(e,i){n.exports=i()})(EE,function(){var e=function(){function i(d){return a.appendChild(d.dom),d}function s(d){for(var f=0;f<a.children.length;f++)a.children[f].style.display=f===d?"block":"none";r=d}var r=0,a=document.createElement("div");a.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",a.addEventListener("click",function(d){d.preventDefault(),s(++r%a.children.length)},!1);var o=(performance||Date).now(),l=o,c=0,h=i(new e.Panel("FPS","#0ff","#002")),u=i(new e.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var A=i(new e.Panel("MB","#f08","#201"));return s(0),{REVISION:16,dom:a,addPanel:i,showPanel:s,begin:function(){o=(performance||Date).now()},end:function(){c++;var d=(performance||Date).now();if(u.update(d-o,200),d>l+1e3&&(h.update(1e3*c/(d-l),100),l=d,c=0,A)){var f=performance.memory;A.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return d},update:function(){o=this.end()},domElement:a,setMode:s}};return e.Panel=function(i,s,r){var a=1/0,o=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,u=48*c,A=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=u,C.style.cssText="width:80px;height:48px";var E=C.getContext("2d");return E.font="bold "+9*c+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=r,E.fillRect(0,0,h,u),E.fillStyle=s,E.fillText(i,A,d),E.fillRect(f,g,p,m),E.fillStyle=r,E.globalAlpha=.9,E.fillRect(f,g,p,m),{dom:C,update:function(S,y){a=Math.min(a,S),o=Math.max(o,S),E.fillStyle=r,E.globalAlpha=1,E.fillRect(0,0,h,g),E.fillStyle=s,E.fillText(l(S)+" "+i+" ("+l(a)+"-"+l(o)+")",A,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-S/y)*m))}}},e})})(tf);var Yv=tf.exports;const Vv=CE(Yv);function Jv(n,t=[],e){const[i,s]=B.useState();return B.useLayoutEffect(()=>{const r=n();return s(r),()=>void 0},t),i}function zv({showPanel:n=0,className:t,parent:e}){const i=Jv(()=>new Vv,[]);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 a=lo(()=>i.begin()),o=iu(()=>i.end());return()=>{r.length&&i.dom.classList.remove(...r),s==null||s.removeChild(i.dom),a(),o()}}},[e,i,t,n]),null}class $v{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 a=Math.min(1/0,t),o=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} (${a.toFixed(r)}-${parseFloat(o.toFixed(r))})`,this.TEXT_X,this.TEXT_Y),this.context.drawImage(this.canvas,this.GRAPH_X+this.PR,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT,this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT);const l=this.GRAPH_HEIGHT-(1-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 ef=class Gi{constructor({trackGPU:t=!1,logsPerSecond:e=30,samplesLog:i=60,samplesGraph:s=10,precision:r=2,minimal:a=!1,horizontal:o=!0,mode:l=0}={}){this.gl=null,this.ext=null,this.activeQuery=null,this.gpuQueries=[],this.threeRendererPatched=!1,this.frames=0,this.renderCount=0,this.isRunningCPUProfiling=!1,this.totalCpuDuration=0,this.totalGpuDuration=0,this.totalGpuDurationCompute=0,this.totalFps=0,this.gpuPanel=null,this.gpuPanelCompute=null,this.averageFps={logs:[],graph:[]},this.averageCpu={logs:[],graph:[]},this.averageGpu={logs:[],graph:[]},this.averageGpuCompute={logs:[],graph:[]},this.handleClick=c=>{c.preventDefault(),this.showPanel(++this.mode%this.dom.children.length)},this.handleResize=()=>{this.resizePanel(this.fpsPanel,0),this.resizePanel(this.msPanel,1),this.gpuPanel&&this.resizePanel(this.gpuPanel,2),this.gpuPanelCompute&&this.resizePanel(this.gpuPanelCompute,3)},this.mode=l,this.horizontal=o,this.minimal=a,this.trackGPU=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 Gi.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new Gi.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 Gi.Panel("GPU","#ff0","#220"),2),this.gpuPanelCompute=this.addPanel(new Gi.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 Gi.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 a=this.gl.getQueryParameter(t.query,this.gl.QUERY_RESULT)*1e-6;this.totalGpuDuration+=a,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 a=0,o=.01;for(let l=0;l<e.graph.length;l++)a+=e.graph[l],e.graph[l]>o&&(o=e.graph[l]);t&&t.update(s/Math.min(e.logs.length,this.samplesLog),a/Math.min(e.graph.length,this.samplesGraph),r,o,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}};ef.Panel=$v;let qv=ef;const Xv=B.forwardRef(function({className:t,parent:e,id:i,clearStatsGlStyle:s,...r},a){const o=q(c=>c.gl),l=B.useMemo(()=>{const c=new qv({...r});return c.init(o),c},[o]);return B.useImperativeHandle(a,()=>l.domElement,[l]),B.useEffect(()=>{if(l){const c=e&&e.current||document.body;c==null||c.appendChild(l.domElement),l.domElement.querySelectorAll("canvas").forEach(A=>{A.style.removeProperty("position")}),i&&(l.domElement.id=i),s&&l.domElement.removeAttribute("style"),l.domElement.removeAttribute("style");const h=(t??"").split(" ").filter(A=>A);h.length&&l.domElement.classList.add(...h);const u=iu(()=>l.update());return()=>{h.length&&l.domElement.classList.remove(...h),c==null||c.removeChild(l.domElement),u()}}},[e,l,t,i,s]),null});function Wv({size:n=256,frames:t=1/0}={}){const e=q(h=>h.viewport.dpr),{width:i,height:s}=q(h=>h.size),r=n||i*e,a=n||s*e,o=B.useMemo(()=>{const h=new su(r,a);return h.format=nu,h.type=ru,{depthTexture:h}},[r,a]);let l=0;const c=au(r,a,o);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 jv(n,t,e=1){const i=q(a=>a.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 Zv(n,t){const e=q(s=>s.pointer),[i]=B.useState(()=>{const s=new ar;return t&&co(s,t,{}),function(r,a){s.setFromCamera(e,n instanceof $f?n:n.current);const o=this.constructor.prototype.raycast.bind(this);o&&o(s,a)}});return i}function Sa(n,t,e,i){return new(e||(e=Promise))(function(s,r){function a(c){try{l(i.next(c))}catch(h){r(h)}}function o(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(u){u(h)})).then(a,o)}l((i=i.apply(n,[])).next())})}const tx=["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 Nh(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 sf=typeof window>"u",Le=(()=>{if(sf)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 ex(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
|
+
`,u=`
|
|
51
|
+
precision highp float;
|
|
52
|
+
varying float vvv;
|
|
53
|
+
void main() {
|
|
54
|
+
vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv;
|
|
55
|
+
enc = fract(enc);
|
|
56
|
+
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
|
|
57
|
+
gl_FragColor = enc;
|
|
58
|
+
}
|
|
59
|
+
`,A=c.createShader(35633),d=c.createShader(35632),f=c.createProgram();if(!(d&&A&&f))return;c.shaderSource(A,h),c.shaderSource(d,u),c.compileShader(A),c.compileShader(d),c.attachShader(f,A),c.attachShader(f,d),c.linkProgram(f),c.detachShader(f,A),c.detachShader(f,d),c.deleteShader(A),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",a="80162181161",o=Le!=null&&Le.isIpad?[["a7",a,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",a,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=o.filter(([,,c])=>c>=14):(l=o.filter(([,c])=>c===i),l.length||(l=o)),l.map(([c])=>`apple ${c} gpu`)}class Hh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}const Ta=[],Kh=[];function ix(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,a=0;for(;a<i&&n.charCodeAt(a)===t.charCodeAt(a);)a++;if(i-=a,s-=a,i===0)return s;let o,l,c=0,h=0,u=0;for(;h<i;)Kh[h]=n.charCodeAt(a+h),Ta[h]=++h;for(;u<s;)for(r=t.charCodeAt(a+u),o=u++,c=u,h=0;h<i;h++)l=r===Kh[h]?o:o+1,o=Ta[h],c=Ta[h]=o>c?l>c?c+1:l:l>o?o+1:l;return c}function sx(n){return n!=null}const nx=({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.64/dist/benchmarks"}={})=>Sa(void 0,void 0,void 0,function*(){const a={};if(sf)return{tier:0,type:"SSR"};const{isIpad:o=!!(Le!=null&&Le.isIpad),isMobile:l=!!(Le!=null&&Le.isMobile),screenSize:c=window.screen,loadBenchmarks:h=y=>Sa(void 0,void 0,void 0,function*(){const _=yield fetch(`${r}/${y}`).then(T=>T.json());if(parseInt(_.shift().split(".")[0],10)<4)throw new Hh("Detect GPU benchmark data is out of date. Please update to version 4x");return _})}=e;let{renderer:u}=e;const A=(y,_,T,v,F)=>({device:F,fps:v,gpu:T,isMobile:l,tier:y,type:_});let d,f="";if(u)u=Nh(u),d=[u];else{const y=i||function(T,v=!1){const F={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:v,powerPreference:"high-performance",stencil:!1};T&&delete F.powerPreference;const x=window.document.createElement("canvas"),w=x.getContext("webgl",F)||x.getContext("experimental-webgl",F);return w??void 0}(Le==null?void 0:Le.isSafari12,s);if(!y)return A(0,"WEBGL_UNSUPPORTED");const _=Le!=null&&Le.isFirefox?null:y.getExtension("WEBGL_debug_renderer_info");if(u=_?y.getParameter(_.UNMASKED_RENDERER_WEBGL):y.getParameter(y.RENDERER),!u)return A(1,"FALLBACK");f=u,u=Nh(u),d=function(T,v,F){return v==="apple gpu"?ex(T,v,F):[v]}(y,u,l)}const g=(yield Promise.all(d.map(function(y){var _;return Sa(this,void 0,void 0,function*(){const T=(K=>{const D=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const et of D)if(K.includes(et))return et})(y);if(!T)return;const v=`${l?"m":"d"}-${T}${o?"-ipad":""}.json`,F=a[v]=(_=a[v])!==null&&_!==void 0?_:h(v);let x;try{x=yield F}catch(K){if(K instanceof Hh)throw K;return}const w=function(K){var D;const et=(K=K.replace(/\([^)]+\)/,"")).match(/\d+/)||K.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(D=et==null?void 0:et.join("").replace(/\W|amd/g,""))!==null&&D!==void 0?D:""}(y);let U=x.filter(([,K])=>K===w);U.length||(U=x.filter(([K])=>K.includes(y)));const O=U.length;if(O===0)return;const W=y.split(/[.,()\[\]/\s]/g).sort().filter((K,D,et)=>D===0||K!==et[D-1]).join(" ");let Y,[X,,,,Z]=O>1?U.map(K=>[K,ix(W,K[2])]).sort(([,K],[,D])=>K-D)[0][0]:U[0],at=Number.MAX_VALUE;const{devicePixelRatio:V}=window,G=c.width*V*c.height*V;for(const K of Z){const[D,et]=K,ot=D*et,ht=Math.abs(G-ot);ht<at&&(at=ht,Y=K)}if(!Y)return;const[,,H,J]=Y;return[at,H,X,J]})}))).filter(sx).sort(([y=Number.MAX_VALUE,_],[T=Number.MAX_VALUE,v])=>y===T?_-v:y-T);if(!g.length){const y=tx.find(_=>u.includes(_));return y?A(0,"BLOCKLISTED",y):A(1,"FALLBACK",`${u} (${f})`)}const[,p,m,C]=g[0];if(p===-1)return A(0,"BLOCKLISTED",m,p,C);const E=l?n:t;let S=0;for(let y=0;y<E.length;y++)p>=E[y]&&(S=y);return A(S,"BENCHMARK",m,p,C)}),nf=n=>ts(()=>nx(n),["useDetectGPU"]);function rx({children:n,...t}){const e=nf(t);return B.createElement(B.Fragment,null,n==null?void 0:n(e))}function ax(...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 ox(n,t){const e=B.useRef(),[i]=B.useState(()=>t?t instanceof jt?{current:t}:t:e),[s]=B.useState(()=>new qf(void 0));B.useLayoutEffect(()=>{t&&(i.current=t instanceof jt?t:t.current),s._root=i.current});const r=B.useRef({}),a=B.useMemo(()=>{const o={};return n.forEach(l=>Object.defineProperty(o,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:o,names:n.map(l=>l.name),mixer:s}},[n]);return Ot((o,l)=>s.update(l)),B.useEffect(()=>{const o=i.current;return()=>{r.current={},s.stopAllAction(),Object.values(a.actions).forEach(l=>{o&&s.uncacheAction(l,o)})}},[n]),a}const lx=`
|
|
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
|
+
`,cx=`
|
|
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
|
+
`,hx=`
|
|
86
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
87
|
+
worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition );
|
|
88
|
+
#endif
|
|
89
|
+
`,ux=`
|
|
90
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
91
|
+
reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition );
|
|
92
|
+
#endif
|
|
93
|
+
`;function Ax(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>",lx)}`,n.fragmentShader=`
|
|
96
|
+
${cx}
|
|
97
|
+
${n.fragmentShader.replace("#include <envmap_physical_pars_fragment>",Xf.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );",`vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
|
|
98
|
+
${hx}
|
|
99
|
+
`).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );",`reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
|
|
100
|
+
${ux}
|
|
101
|
+
`)}`}function dx(n=new k,t=new k){const[e]=B.useState(()=>({position:new k,size:new k}));co(e,{position:n,size:t});const i=B.useRef(null),s=B.useMemo(()=>({ref:i,onBeforeCompile:r=>Ax(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 fx(n,t,e=.9){return t*e+n*(1-e)}const gx=n=>Math.sqrt(1-Math.pow(n-1,2));class mx{constructor({size:t=256,maxAge:e=750,radius:i=.3,intensity:s=.2,interpolate:r=0,smoothing:a=0,minForce:o=.3,blend:l="screen",ease:c=gx}={}){this.size=t,this.maxAge=e,this.radius=i,this.intensity=s,this.ease=c,this.interpolate=r,this.smoothing=a,this.minForce=o,this.blend=l,this.trail=[],this.force=0,this.initTexture()}initTexture(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=this.size;const 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,a=Math.max(this.minForce,Math.min(r*1e4,1));if(this.force=fx(a,this.force,this.smoothing),this.interpolate){const o=Math.ceil(r/Math.pow(this.radius*.5/this.interpolate,2));if(o>1)for(let l=1;l<o;l++)this.trail.push({x:e.x-i/o*l,y:e.y-s/o*l,age:0,force:a})}}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 rf(n={}){const{size:t,maxAge:e,radius:i,intensity:s,interpolate:r,smoothing:a,minForce:o,blend:l,ease:c}=n,h=B.useMemo(()=>new mx(n),[t,e,i,s,r,a,o,l,c]);Ot((A,d)=>void h.update(d));const u=B.useCallback(A=>h.addTouch(A.uv),[h]);return[h.texture,u]}const px=({children:n,...t})=>{const e=rf(t);return B.createElement(B.Fragment,null,n==null?void 0:n(e))},Ex=B.forwardRef(({font:n,color:t="#cbcbcb",bevelSize:e=.04,debug:i=!1,children:s,...r},a)=>{const[o,l]=B.useState(0),c=B.useCallback((A=1)=>l(o+A),[o]),h=B.useCallback((A=1)=>l(o-A),[o]),u=B.useMemo(()=>({incr:c,decr:h}),[c,h]);return B.useImperativeHandle(a,()=>u,[u]),B.createElement("group",r,B.createElement(B.Suspense,{fallback:null},B.createElement(ou,{top:!0,cacheKey:JSON.stringify({counter:o,font:n})},B.createElement(lu,{bevelEnabled:!0,bevelSize:e,font:n},i?B.createElement("meshNormalMaterial",{wireframe:!0}):B.createElement("meshStandardMaterial",{color:t}),o))),s)});function Cx(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 a=[...s.groups];return s.clearGroups(),i.material.forEach((o,l)=>{l<i.material.length-1&&(o.depthWrite=!1),s.addGroup(0,1/0,l)}),()=>{i.material=r,s.groups=a}}}),B.createElement("group",wt({ref:t},n))}const Ix=B.forwardRef(({mixBlur:n=0,mixStrength:t=.5,resolution:e=256,blur:i=[0,0],args:s=[1,1],minDepthThreshold:r=.9,maxDepthThreshold:a=1,depthScale:o=0,depthToBlurRatioBias:l=.25,mirror:c=0,children:h,debug:u=0,distortion:A=1,mixContrast:d=1,distortionMap:f,...g},p)=>{mo({MeshReflectorMaterial:Wf}),B.useEffect(()=>{console.warn("Reflector has been deprecated and will be removed next major. Replace it with <MeshReflectorMaterial />!")},[]);const m=q(({gl:K})=>K),C=q(({camera:K})=>K),E=q(({scene:K})=>K);i=Array.isArray(i)?i:[i,i];const S=i[0]+i[1]>0,y=B.useRef(null);B.useImperativeHandle(p,()=>y.current,[]);const[_]=B.useState(()=>new Xh),[T]=B.useState(()=>new k),[v]=B.useState(()=>new k),[F]=B.useState(()=>new k),[x]=B.useState(()=>new dt),[w]=B.useState(()=>new k(0,0,-1)),[U]=B.useState(()=>new _e),[O]=B.useState(()=>new k),[W]=B.useState(()=>new k),[Y]=B.useState(()=>new _e),[X]=B.useState(()=>new dt),[Z]=B.useState(()=>new Pt),at=B.useCallback(()=>{if(v.setFromMatrixPosition(y.current.matrixWorld),F.setFromMatrixPosition(C.matrixWorld),x.extractRotation(y.current.matrixWorld),T.set(0,0,1),T.applyMatrix4(x),O.subVectors(v,F),O.dot(T)>0)return;O.reflect(T).negate(),O.add(v),x.extractRotation(C.matrixWorld),w.set(0,0,-1),w.applyMatrix4(x),w.add(F),W.subVectors(v,w),W.reflect(T).negate(),W.add(v),Z.position.copy(O),Z.up.set(0,1,0),Z.up.applyMatrix4(x),Z.up.reflect(T),Z.lookAt(W),Z.far=C.far,Z.updateMatrixWorld(),Z.projectionMatrix.copy(C.projectionMatrix),X.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),X.multiply(Z.projectionMatrix),X.multiply(Z.matrixWorldInverse),X.multiply(y.current.matrixWorld),_.setFromNormalAndCoplanarPoint(T,v),_.applyMatrix4(Z.matrixWorldInverse),U.set(_.normal.x,_.normal.y,_.normal.z,_.constant);const K=Z.projectionMatrix;Y.x=(Math.sign(U.x)+K.elements[8])/K.elements[0],Y.y=(Math.sign(U.y)+K.elements[9])/K.elements[5],Y.z=-1,Y.w=(1+K.elements[10])/K.elements[14],U.multiplyScalar(2/U.dot(Y)),K.elements[2]=U.x,K.elements[6]=U.y,K.elements[10]=U.z+1,K.elements[14]=U.w},[]),[V,G,H,J]=B.useMemo(()=>{const K={type:vs,minFilter:Gn,magFilter:Gn},D=new ul(e,e,K);D.depthBuffer=!0,D.depthTexture=new su(e,e),D.depthTexture.format=nu,D.depthTexture.type=ru;const et=new ul(e,e,K),ot=new jf({gl:m,resolution:e,width:i[0],height:i[1],minDepthThreshold:r,maxDepthThreshold:a,depthScale:o,depthToBlurRatioBias:l}),ht={mirror:c,textureMatrix:X,mixBlur:n,tDiffuse:D.texture,tDepth:D.depthTexture,tDiffuseBlur:et.texture,hasBlur:S,mixStrength:t,minDepthThreshold:r,maxDepthThreshold:a,depthScale:o,depthToBlurRatioBias:l,transparent:!0,debug:u,distortion:A,distortionMap:f,mixContrast:d,"defines-USE_BLUR":S?"":void 0,"defines-USE_DEPTH":o>0?"":void 0,"defines-USE_DISTORTION":f?"":void 0};return[D,et,ot,ht]},[m,i,X,e,c,S,n,t,r,a,o,l,u,A,f,d]);return Ot(()=>{if(!(y!=null&&y.current))return;y.current.visible=!1;const K=m.xr.enabled,D=m.shadowMap.autoUpdate;at(),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),S&&H.render(m,V,G),m.xr.enabled=K,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",J):B.createElement("meshReflectorMaterial",J))});function yx(n){switch(n){case 64:return"-64px";case 128:return"-128px";case 256:return"-256px";case 512:return"-512px";default:return""}}const Bx="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json",Sx="https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d";function af(n=0,t=1024,e){const i=ts(()=>fetch(Bx).then(h=>h.json()),["matcapList"]),s=i[0],r=B.useMemo(()=>Object.keys(i).length,[]),o=`${B.useMemo(()=>typeof n=="string"?n:typeof n=="number"?i[n]:null,[n])||s}${yx(t)}.png`,l=`${Sx}/${t}/${o}`;return[po(l,e),l,r]}const Tx=({children:n,id:t,format:e,onLoad:i})=>{const s=af(t,e,i);return B.createElement(B.Fragment,null,n==null?void 0:n(s))},_x="https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb",vx="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json";function of(n=0,t={},e){const{repeat:i=[1,1],anisotropy:s=1,offset:r=[0,0]}=t,a=ts(()=>fetch(vx).then(A=>A.json()),["normalsList"]),o=B.useMemo(()=>Object.keys(a).length,[]),l=a[0],c=a[n]||l,h=`${_x}/normals/${c}`,u=po(h,e);return B.useLayoutEffect(()=>{u&&(u.wrapS=u.wrapT=Da,u.repeat=new Kt(i[0],i[1]),u.offset=new Kt(r[0],r[1]),u.anisotropy=s)},[u,s,i,r]),[u,h,o]}const xx=({children:n,id:t,onLoad:e,...i})=>{const s=of(t,i,e);return B.createElement(B.Fragment,null,n==null?void 0:n(s))},ai={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
|
+
`},Dx=cu(ai.uniforms,ai.vertex+`
|
|
197
|
+
void main() {
|
|
198
|
+
initWireframe();
|
|
199
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
200
|
+
}
|
|
201
|
+
`,ai.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 Rx(n,t){n.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...t},e.vertexShader=e.vertexShader.replace("void main() {",`
|
|
218
|
+
${ai.vertex}
|
|
219
|
+
void main() {
|
|
220
|
+
initWireframe();
|
|
221
|
+
`),e.fragmentShader=e.fragmentShader.replace("void main() {",`
|
|
222
|
+
${ai.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=Hs,n.transparent=!0}function wx(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 Lx(n){return!!(n!=null&&n.geometry)}function bx(n){return!!(n!=null&&n.isBufferGeometry)}function Fx(n){return!!(n!=null&&n.current)}function Yh(n){return(n==null?void 0:n.current)!==void 0}function Vh(n){return n.type==="WireframeGeometry"}function Mx(){const n={};for(const t in ai.uniforms)n[t]={value:ai.uniforms[t]};return n}function Px(n,t){const i=n.getAttribute("position").count,s=[];for(let r=0;r<i;r++){const a=r%2===0,o=t?1:0;a?s.push(0,0,1,0,1,0,1,0,o):s.push(0,1,0,0,0,1,1,0,o)}return new Ra(Float32Array.from(s),3)}function lf(n){const t=Fx(n)?n.current:n;if(bx(t))return t;{if(Vh(t))throw new Error("Wireframe: WireframeGeometry is not supported.");const e=t.parent;if(Lx(e)){if(Vh(e.geometry))throw new Error("Wireframe: WireframeGeometry is not supported.");return e.geometry}}}function cf(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=Px(n,t);n.setAttribute("barycentric",e)}function kx({geometry:n,simplify:t=!1,...e}){mo({MeshWireframeMaterial:Dx});const[i,s]=B.useState(null);B.useLayoutEffect(()=>{const a=lf(n);if(!a)throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry.");cf(a,t),Yh(n)&&s(a)},[t,n]);const r=Yh(n)?i:n;return B.createElement(B.Fragment,null,r&&B.createElement("mesh",{geometry:r},B.createElement("meshWireframeMaterial",wt({attach:"material",transparent:!0,side:Hs,polygonOffset:!0,polygonOffsetFactor:-4},e,{extensions:{derivatives:!0,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1}}))))}function Qx({simplify:n=!1,...t}){const e=B.useRef(null),i=B.useMemo(()=>Mx(),[ai.uniforms]);return wx(i,t),B.useLayoutEffect(()=>{const s=lf(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 cf(s,n),()=>{s.copy(r),r.dispose()}},[n]),B.useLayoutEffect(()=>{const s=e.current.parent,r=s.material.clone();return Rx(s.material,i),()=>{s.material.dispose(),s.material=r}},[]),B.createElement("object3D",{ref:e})}function Ox({geometry:n,...t}){return n?B.createElement(kx,wt({geometry:n},t)):B.createElement(Qx,t)}function Gx({opacity:n,alphaMap:t}){const e=B.useRef(null),i=B.useRef(null),s=B.useRef({value:1}),r=B.useRef({value:null}),a=B.useRef({value:!1});return B.useLayoutEffect(()=>{e.current.onBeforeCompile=i.current.onBeforeCompile=o=>{const l=o.fragmentShader.indexOf("void main");let c="",h,u=l;for(;h!==`
|
|
237
|
+
`&&u<l+100;)h=o.fragmentShader.charAt(u),c+=h,u++;c=c.trim(),o.vertexShader=o.vertexShader.replace("void main() {",`
|
|
238
|
+
varying vec2 custom_vUv;
|
|
239
|
+
|
|
240
|
+
void main() {
|
|
241
|
+
custom_vUv = uv;
|
|
242
|
+
|
|
243
|
+
`),o.fragmentShader=o.fragmentShader.replace(c,`
|
|
244
|
+
uniform float uShadowOpacity;
|
|
245
|
+
uniform sampler2D uAlphaMap;
|
|
246
|
+
uniform bool uHasAlphaMap;
|
|
247
|
+
|
|
248
|
+
varying vec2 custom_vUv;
|
|
249
|
+
|
|
250
|
+
float bayerDither2x2( vec2 v ) {
|
|
251
|
+
return mod( 3.0 * v.y + 2.0 * v.x, 4.0 );
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
float bayerDither4x4( vec2 v ) {
|
|
255
|
+
vec2 P1 = mod( v, 2.0 );
|
|
256
|
+
vec2 P2 = mod( floor( 0.5 * v ), 2.0 );
|
|
257
|
+
return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
void main() {
|
|
261
|
+
float alpha =
|
|
262
|
+
uHasAlphaMap ?
|
|
263
|
+
uShadowOpacity * texture2D(uAlphaMap, custom_vUv).x
|
|
264
|
+
: uShadowOpacity;
|
|
265
|
+
|
|
266
|
+
if( ( bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ) ) / 16.0 >= alpha ) discard;
|
|
267
|
+
|
|
268
|
+
`),o.uniforms.uShadowOpacity=s.current,o.uniforms.uAlphaMap=r.current,o.uniforms.uHasAlphaMap=a.current}},[]),Ot(()=>{var o;const l=(o=e.current.__r3f)==null?void 0:o.parent;if(l){const c=l.material;c&&(s.current.value=n??c.opacity,t===!1?(r.current.value=null,a.current.value=!1):(r.current.value=t||c.alphaMap,a.current.value=!!r.current.value))}}),B.createElement(B.Fragment,null,B.createElement("meshDepthMaterial",{ref:e,attach:"customDepthMaterial",depthPacking:Zf}),B.createElement("meshDistanceMaterial",{ref:i,attach:"customDistanceMaterial"}))}const Jh=new dt,zh=new tg,_a=new uo,va=new k;function Ux(n,t){const e=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(e.boundingSphere===null&&e.computeBoundingSphere(),_a.copy(e.boundingSphere),_a.applyMatrix4(s),n.ray.intersectsSphere(_a)!==!1&&(Jh.copy(s).invert(),zh.copy(n.ray).applyMatrix4(Jh),!(e.boundingBox!==null&&zh.intersectBox(e.boundingBox,va)===null)&&t.push({distance:va.distanceTo(n.ray.origin),point:va.clone(),object:this})))}const Nx=B.forwardRef(({options:n={video:!0},...t},e)=>{const i=ts(()=>navigator.mediaDevices.getDisplayMedia(n),[]);return B.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),hu([])},[i]),B.createElement(Sr,wt({ref:e},t,{src:i}))}),hf=B.forwardRef(({constraints:n={audio:!1,video:{facingMode:"user"}},...t},e)=>{const i=ts(()=>navigator.mediaDevices.getUserMedia(n),[]);return B.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),hu([])},[i]),B.createElement(Sr,wt({ref:e},t,{src:i}))});function $h(n,t){return n.clone().add(t).multiplyScalar(.5)}function Oi(n,t,e){const i=n.localToWorld(t);return e.worldToLocal(i)}const uf=B.createContext({}),Hx=B.forwardRef(({camera:n,videoTexture:t={start:!0},manualDetect:e=!1,faceLandmarkerResult:i,manualUpdate:s=!1,makeDefault:r,smoothTime:a=.25,offset:o=!0,offsetScalar:l=80,eyes:c=!1,eyesAsOrigin:h=!0,depth:u=.15,debug:A=!1,facemesh:d},f)=>{var g,p;const m=q(ot=>ot.scene),C=q(ot=>ot.camera),E=q(ot=>ot.set),S=q(ot=>ot.get),y=n||C,_=B.useRef(null),[T]=B.useState(()=>new jt),[v]=B.useState(()=>new k),[F]=B.useState(()=>new k),[x]=B.useState(()=>new k),[w]=B.useState(()=>new k),U=B.useCallback(()=>{T.parent=y.parent;const ot=_.current;if(ot){const{outerRef:ht,eyeRightRef:Vt,eyeLeftRef:ne}=ot;if(Vt.current&&ne.current){const{irisDirRef:es}=Vt.current,{irisDirRef:Tr}=ne.current;es.current&&Tr.current&&ht.current&&(v.copy(Oi(es.current,new k(0,0,0),ht.current)),F.copy(Oi(Tr.current,new k(0,0,0),ht.current)),T.position.copy(Oi(ht.current,$h(v,F),y.parent||m)),x.copy(Oi(es.current,new k(0,0,1),ht.current)),w.copy(Oi(Tr.current,new k(0,0,1),ht.current)),T.lookAt(ht.current.localToWorld($h(x,w))))}else ht.current&&(T.position.copy(Oi(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,v,x,m,T]),[O]=B.useState(()=>new jt),W=B.useCallback(function(ot,ht){if(y){var Vt;(Vt=ht)!==null&&Vt!==void 0||(ht=U()),a>0?(zi.damp3(O.position,ht.position,a,ot,void 0,void 0,1e-9),zi.dampE(O.rotation,ht.rotation,a,ot,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,a,O.position,O.rotation]);Ot((ot,ht)=>{s||W(ht)});const Y=B.useRef(null),[X,Z]=B.useState(),at=uu(),V=B.useCallback((ot,ht)=>{const Vt=Y.current;if(!Vt)return;const ne=Vt.source.data,es=at==null?void 0:at.detectForVideo(ne,ot);Z(es)},[at]),G=B.useMemo(()=>Object.assign(Object.create(eg.prototype),{computeTarget:U,update:W,facemeshApiRef:_}),[U,W]);B.useImperativeHandle(f,()=>G,[G]),B.useEffect(()=>{if(r){const ot=S().controls;return E({controls:G}),()=>E({controls:ot})}},[r,G,S,E]);const H=i??X,J=H==null?void 0:H.faceLandmarks[0],K=H==null||(g=H.facialTransformationMatrixes)==null?void 0:g[0],D=H==null||(p=H.faceBlendshapes)==null?void 0:p[0],et={onVideoFrame:V,...t};return B.createElement(uf.Provider,{value:G},!e&&B.createElement(B.Suspense,{fallback:null},"src"in et?B.createElement(Sr,wt({ref:Y},et)):B.createElement(hf,wt({ref:Y},et))),B.createElement(Au,wt({ref:_,children:B.createElement("meshNormalMaterial",{side:Hs})},d,{points:J,depth:u,facialTransformationMatrix:K,faceBlendshapes:D,eyes:c,eyesAsOrigin:h,offset:o,offsetScalar:l,debug:A,"rotation-z":Math.PI,visible:A})))}),Kx=()=>B.useContext(uf),dD=Object.freeze(Object.defineProperty({__proto__:null,AccumulativeShadows:ig,AdaptiveDpr:sg,AdaptiveEvents:ng,ArcballControls:CB,AsciiRenderer:rg,BBAnchor:ag,Backdrop:og,BakeShadows:lg,Billboard:cg,Bounds:hg,Box:ug,Bvh:Ag,CameraControls:vB,CameraShake:dg,Capsule:fg,CatmullRomLine:gg,Caustics:mg,Center:ou,Circle:pg,Clone:go,Cloud:Eg,CloudInstance:Cg,Clouds:Ig,ComputedAttribute:yg,Cone:Bg,ContactShadows:Sg,CubeCamera:Tg,CubeTexture:wB,CubicBezierLine:_g,CurveModifier:vg,CycleRaycast:xg,Cylinder:Dg,Decal:Rg,Detailed:wg,DetectGPU:rx,DeviceOrientationControls:gB,Dodecahedron:Lg,DragControls:DE,Edges:bg,Effects:Fg,Environment:Mg,EnvironmentCube:Pg,EnvironmentMap:kg,EnvironmentPortal:Qg,Example:Ex,Extrude:Og,FaceControls:Hx,FaceLandmarker:Gg,FaceLandmarkerDefaults:Ug,Facemesh:Au,FacemeshDatas:Ng,FacemeshEye:Hg,FacemeshEyeDefaults:Kg,Fbo:Yg,Fbx:LB,FirstPersonControls:BB,Fisheye:Vg,Float:Jg,FlyControls:mB,GizmoHelper:zg,GizmoViewcube:$g,GizmoViewport:qg,Gltf:fB,GradientTexture:Xg,GradientType:Wg,Grid:jg,Helper:Zg,Html:tm,Hud:em,Icosahedron:im,Image:sm,Instance:nm,InstancedAttribute:rm,Instances:am,IsObject:wa,KeyboardControls:qI,Ktx2:bB,Lathe:om,Lightformer:lm,Line:cm,Loader:xE,MapControls:pB,MarchingCube:hm,MarchingCubes:um,MarchingPlane:Am,Mask:dm,MatcapTexture:Tx,Merged:fm,MeshDiscardMaterial:gm,MeshDistortMaterial:mm,MeshPortalMaterial:pm,MeshReflectorMaterial:Em,MeshRefractionMaterial:Cm,MeshTransmissionMaterial:Im,MeshWobbleMaterial:ym,MotionPathControls:RB,MultiMaterial:Cx,NormalTexture:xx,Octahedron:Bm,OrbitControls:Sm,OrthographicCamera:Tm,Outlines:_m,PerformanceMonitor:vm,PerspectiveCamera:xm,PivotControls:Dm,Plane:Rm,Point:wm,PointMaterial:Lm,PointMaterialImpl:bm,PointerLockControls:yB,Points:Fm,PointsBuffer:Mm,Polyhedron:Pm,PositionMesh:km,PositionPoint:Qm,PositionalAudio:Om,Preload:Gm,PresentationControls:JI,Progress:_E,QuadraticBezierLine:Um,RandomizedLight:Nm,Reflector:Ix,RenderCubeTexture:Hm,RenderTexture:Km,Resize:Ym,Ring:Vm,RoundedBox:Jm,Sampler:zm,ScreenQuad:$m,ScreenSizer:dB,ScreenSpace:qm,ScreenVideoTexture:Nx,Scroll:RC,ScrollControls:vC,Segment:Xm,SegmentObject:Wm,Segments:jm,Select:Zm,Shadow:tp,ShadowAlpha:Gx,Shape:ep,Sky:ip,SoftShadows:sp,Sparkles:np,Sphere:rp,Splat:ap,SpotLight:op,SpotLightShadow:lp,SpriteAnimator:cp,Stage:hp,Stars:up,Stats:zv,StatsGl:Xv,Svg:Ap,Tetrahedron:dp,Text:fp,Text3D:lu,Texture:gp,Torus:mp,TorusKnot:pp,TrackballControls:EB,Trail:Ep,TrailTexture:px,TransformControls:IB,Tube:Cp,VideoTexture:Sr,View:Ip,WebcamVideoTexture:hf,Wireframe:Ox,accumulativeContext:yp,calcPosFromAngles:Bp,calculateScaleFactor:tu,checkIfFrameIsEmpty:Sp,createInstances:Tp,getFirstFrame:_p,isWebGL2Available:vp,meshBounds:Ux,shaderMaterial:cu,useAnimations:ox,useAspect:jv,useBVH:xp,useBounds:Dp,useBoxProjectedEnv:dx,useCamera:Zv,useContextBridge:ax,useCubeCamera:Rp,useCubeTexture:Ho,useCursor:yE,useDepthBuffer:Wv,useDetectGPU:nf,useEnvironment:wp,useFBO:au,useFBX:mr,useFaceControls:Kx,useFaceLandmarker:uu,useFont:Lp,useGLTF:zs,useGizmoContext:bp,useHelper:Fp,useIntersect:Mp,useKTX2:pr,useKeyboardControls:XI,useMask:Pp,useMatcapTexture:af,useMotion:LA,useNormalTexture:of,usePerformanceMonitor:kp,useProgress:yo,useScroll:So,useSelect:Qp,useSpriteAnimator:Op,useSpriteLoader:Gp,useSurfaceSampler:Up,useTexture:po,useTrail:Np,useTrailTexture:rf,useVideoTexture:Zd},Symbol.toStringTag,{value:"Module"}));function Af(n,t,e,i){const s=q(r=>r.camera);Ot(()=>{n.current!=null&&t(Hp(s,n.current,e,i))})}function Yx({children:n,direction:t,angle:e=Math.PI/2}){const i=B.useRef(null);return Af(i,s=>{i.current!=null&&(i.current.visible=s)},t,e),Xe.jsx("group",{ref:i,children:n})}function Vx({children:n,direction:t,angle:e=Math.PI/2}){const i=B.useRef(null),[s,r]=B.useState(!1);return Af(i,r,t,e),s?Xe.jsx(Xe.Fragment,{children:n}):null}function Jx({children:n,mode:t}){const e=Eo(t);return Xe.jsx("group",{visible:e,children:n})}function zx({children:n,mode:t}){return Eo(t)?Xe.jsx(Xe.Fragment,{children:n}):null}function $x({children:n}){const t=Co();return Xe.jsx("group",{visible:t==null||t==="visible",children:n})}function qx({children:n}){const t=Co();return t!="visible"&&t!=null?null:Xe.jsx(Xe.Fragment,{children:n})}function Xx(){const n=lr();return B.useMemo(()=>Io.bind(null,n),[n])}function Wx(){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 a=!1;e.current=()=>a=!0;const o=await Io(i,r);if(a){o==null||o.delete();return}return e.current=()=>o==null?void 0:o.delete(),t(o),o},[i]);return B.useEffect(()=>()=>{var r;return void((r=e.current)==null?void 0:r.call(e))},[]),[n,s]}function jx(n,t={},e={},i="left"){const s=lr(),r=B.useMemo(()=>Kp(),[]);Ot((a,o,l)=>r(typeof n=="function"?n:n.current,s,a.camera,o,t,e,i,o,a,l))}function Zx({batchEvents:n,clickThesholdMs:t,contextMenuButton:e,customSort:i,dblClickThresholdMs:s,filter:r,forwardPointerCapture:a,intersectEveryFrame:o,pointerTypePrefix:l}){const c=q(d=>d.gl.domElement),h=q(d=>d.frameloop==="always"),u=q(d=>d.camera),A=q(d=>d.scene);return B.useEffect(()=>{const{destroy:d,update:f}=Yp(c,()=>u,A,{batchEvents:n??h,clickThesholdMs:t,contextMenuButton:e,customSort:i,dblClickThresholdMs:s,filter:r,forwardPointerCapture:a,intersectEveryFrame:o,pointerTypePrefix:l}),g=lo(f);return()=>{g(),d()}},[c,u,A,h,n,t,e,i,s,r,a,o,l]),null}const tD=()=>({enabled:!1,priority:0}),fD=Object.freeze(Object.defineProperty({__proto__:null,ARButton:Vp,CombinedPointer:Jp,DefaultXRController:zp,DefaultXRControllerGrabPointer:$p,DefaultXRGaze:qp,DefaultXRHand:Xp,DefaultXRHandGrabPointer:Wp,DefaultXRHandTouchPointer:jp,DefaultXRInputSourceRayPointer:Zp,DefaultXRInputSourceTeleportPointer:t0,DefaultXRScreenInput:e0,DefaultXRTransientPointer:i0,FallbackXRLayerImplementation:s0,IfFacingCamera:Vx,IfInSessionMode:n0,IfSessionModeSupported:zx,IfSessionVisible:qx,Interactive:r0,PointerCursorModel:a0,PointerEvents:Zx,PointerRayModel:o0,RayGrab:l0,RootCombinedPointer:c0,ShowIfFacingCamera:Yx,ShowIfInSessionMode:h0,ShowIfSessionModeSupported:Jx,ShowIfSessionVisible:$x,TeleportPointerRayModel:u0,TeleportTarget:A0,VRButton:d0,XR:f0,XRButton:g0,XRControllerComponent:m0,XRControllerModel:p0,XRDomOverlay:E0,XRHandJoint:C0,XRHandModel:I0,XRHitTest:y0,XRLayer:B0,XRLayerImplementation:S0,XRMeshModel:T0,XROrigin:_0,XRPlaneModel:v0,XRSpace:x0,createXRHitTestSource:D0,createXRStore:R0,defaultGrabPointerOpacity:w0,defaultRayPointerOpacity:L0,defaultTouchPointerOpacity:b0,isXRInputSourceState:F0,noEvents:tD,privateKeys:M0,requestXRAnchor:Io,requestXRHitTest:P0,useApplyXRSpaceMatrix:k0,useGetXRSpaceMatrix:Q0,useGrabPointer:O0,useHover:G0,useInitRoomCapture:U0,useInteraction:N0,useLayerStore:H0,useLinesPointer:K0,useLoadXRControllerLayout:Y0,useLoadXRControllerModel:V0,usePointerXRInputSourceEvents:J0,useRayPointer:z0,useRequestXRAnchor:Xx,useSessionFeatureEnabled:$0,useSessionModeSupported:Eo,useTouchPointer:q0,useXR:X0,useXRAnchor:Wx,useXRControllerButtonEvent:W0,useXRControllerLocomotion:jx,useXRControllerState:j0,useXREvent:Z0,useXRGazeState:tE,useXRHandState:eE,useXRHitTest:iE,useXRHitTestSource:sE,useXRInputSourceEvent:nE,useXRInputSourceState:rE,useXRInputSourceStateContext:aE,useXRInputSourceStates:oE,useXRMeshGeometry:lE,useXRMeshes:cE,useXRPlaneGeometry:hE,useXRPlanes:uE,useXRReferenceSpace:AE,useXRRequestHitTest:dE,useXRScreenInputState:fE,useXRSessionVisibilityState:Co,useXRSpace:gE,useXRStore:lr,useXRTransientPointerState:mE},Symbol.toStringTag,{value:"Module"}));export{dD as D,fD as X};
|
|
269
|
+
//# sourceMappingURL=chunk-UihyksJm.js.map
|